language
stringclasses 5
values | text
stringlengths 15
988k
|
---|---|
JavaScript | class EventEmitter {
constructor() {
this.__events = {}
}
/**
* Emit the event to all listeners
*
* @param {string} name The name
* @param {object={}} [args] Arguments to pass to
*/
emit(name, args = {}) {
// safeguard
if (!name) {
return
}
// run through the event handlers and call
// it for each one
const handlers = this.__events[name]
if (handlers && handlers.length) {
for (let i = 0, handler; (handler = handlers[i]); i++) {
// kick each handler onto the event loop so that no one blocks the emission
// of the all of the events
// consider: deep clone args so that one handler cannot modify.
// This should be fine if args are simple properties
;(function(h) {
setTimeout(() => h({ ...args }))
})(handler)
}
}
}
/**
* Subscribe to an event
*
* @param {string[]|string} names Name of the event to listen to
* @param {function} handler The handler function
*/
on(names, handler) {
if (!names || typeof handler !== 'function') {
throw new TypeError(
'EventEmitter.prototype.on requires a name (String[]) and handler (Function)'
)
}
if (!Array.isArray(names)) {
names = [names]
}
for (let i = 0, name; (name = names[i]); i++) {
if (!this.__events[name]) {
this.__events[name] = []
}
this.__events[name].push(handler)
}
}
/**
* Un-subscribe from an event
*
* @param {string[]|string} names The event to listen to
* @param {function} handler The event handler to remove
*/
off(names, handler) {
if (!names || typeof handler !== 'function') {
throw new TypeError(
'EventEmitter.prototype.off requires a name (String) and handler (Function)'
)
}
if (!Array.isArray(names)) {
names = [names]
}
for (let i = 0, name; (name = names[i]); i++) {
let handlers = this.__events[name]
if (handlers && handlers.length) {
// filter out the function that was subscribed
handlers = this.__events[name] = handlers.filter(func => func !== handler)
// if there are no longer handlers, remove the memory alotment
if (!handlers.length) {
delete this.__events[name]
}
}
}
}
} |
JavaScript | class XKTMetaObject {
/**
* @private
* @param metaObjectId
* @param propertySetIds
* @param metaObjectType
* @param metaObjectName
* @param parentMetaObjectId
*/
constructor(metaObjectId, propertySetIds, metaObjectType, metaObjectName, parentMetaObjectId) {
/**
* Unique ID of this ````XKTMetaObject```` in {@link XKTModel#metaObjects}.
*
* For a BIM model, this will be an IFC product ID.
*
* If this is a leaf XKTMetaObject, where it is not a parent to any other XKTMetaObject,
* then this will be equal to the ID of an {@link XKTEntity} in {@link XKTModel#entities},
* ie. where {@link XKTMetaObject#metaObjectId} == {@link XKTEntity#entityId}.
*
* @type {String}
*/
this.metaObjectId = metaObjectId;
/**
* Unique ID of one or more property sets that contains additional metadata about this
* {@link XKTMetaObject}. The property sets can be stored in an external system, or
* within the {@link XKTModel}, as {@link XKTPropertySet}s within {@link XKTModel#propertySets}.
*
* @type {String[]}
*/
this.propertySetIds = propertySetIds;
/**
* Indicates the XKTMetaObject meta object type.
*
* This defaults to "default".
*
* @type {string}
*/
this.metaObjectType = metaObjectType;
/**
* Indicates the XKTMetaObject meta object name.
*
* This defaults to {@link XKTMetaObject#metaObjectId}.
*
* @type {string}
*/
this.metaObjectName = metaObjectName;
/**
* The parent XKTMetaObject, if any.
*
* Will be null if there is no parent.
*
* @type {String}
*/
this.parentMetaObjectId = parentMetaObjectId;
}
} |
JavaScript | class ASTGenerator
{
/**
* ASTGenerator returns an instance of ParserData containing a string representing the rendered code of the provided
* AST `node`. In addition Halstead operators and operands are available via ParserData.
*
* @param {object|Array<object>} node - An ESTree or Babylon AST node.
*
* @param {object} options - Optional parameters for source code formatting.
* @property {string} indent - A string to use for indentation (defaults to `\t`)
* @property {string} lineEnd - A string to use for line endings (defaults to `\n`)
* @property {number} startingIndentLevel - indent level to start from (default to `0`)
*
* @returns {ASTData}
*/
static parse(node, options)
{
const state = new ASTState(options);
// Travel through the AST node and generate the code.
if (Array.isArray(node))
{
node.forEach((entry) => { state.generator[entry.type](entry, state); });
}
else if (typeof node === 'object')
{
state.generator[node.type](node, state);
}
else
{
throw new TypeError(`parse error: 'node' is not an 'object' or an 'array'.`);
}
return state.output;
}
/**
* ASTGenerator returns an instance of ParserData containing a string representing the rendered code of the provided
* AST `nodes`. In addition Halstead operators and operands are available via ParserData.
*
* @param {Array<object>} nodes - An array of ESTree or Babylon AST nodes to parse.
*
* @param {object} options - Optional parameters for source code formatting.
* @property {string} indent - A string to use for indentation (defaults to `\t`)
* @property {string} lineEnd - A string to use for line endings (defaults to `\n`)
* @property {number} startingIndentLevel - indent level to start from (default to `0`)
*
* @returns {ASTData}
*/
static parseNodes(nodes, options)
{
if (!Array.isArray(nodes)) { throw new TypeError(`parseNodes error: 'nodes' is not an 'array'.`); }
const state = new ASTState(options);
nodes.forEach((node) =>
{
// Travel through the AST node and generate the code.
if (Array.isArray(node))
{
node.forEach((entry) => { state.generator[entry.type](entry, state); });
}
else if (typeof node === 'object')
{
state.generator[node.type](node, state);
}
else
{
throw new TypeError(`parse error: 'node' is not an 'object' or an 'array'.`);
}
});
return state.output;
}
} |
JavaScript | class StringMatcher {
constructor(strategy){
this.strategy = strategy
}
findMatches(text, term){
if (term === '') return StringMatcher.NoMatches
if (term === null || term === undefined) throw new Error("Invalid term");
return this.strategy.findMatches(text, term);
}
} |
JavaScript | class ProxyHandler extends SameDomainHandler {
/**
* Constructor.
*/
constructor() {
super();
// this is not the best way to get requests
this.score = -10;
}
/**
* @inheritDoc
*/
handles(method, uri) {
/** @type {string} */
var purl = ProxyHandler.PROXY_URL;
if (!purl || purl.indexOf('{url}') == -1) {
log.warning(logger,
'The proxy url is not set properly');
return false;
}
/** @type {Array.<string>} */
var methods = ProxyHandler.METHODS;
if (!methods || methods.indexOf(method) == -1) {
log.fine(logger,
'The ' + method + ' method is not supported by the proxy.');
return false;
}
/** @type {Array.<string>} */
var schemes = ProxyHandler.SCHEMES;
if (!schemes || schemes.indexOf(uri.getScheme()) == -1) {
log.fine(logger,
'The ' + uri.getScheme() + ' scheme is not supported by the proxy');
return false;
}
return !super.handles(method, uri);
}
/**
* @inheritDoc
*/
modUri(uri) {
return ProxyHandler.getProxyUri(uri);
}
/**
* @inheritDoc
*/
getHandlerType() {
return HandlerType.PROXY;
}
/**
* @param {?Object} conf
*/
static configure(conf) {
if (conf) {
if (conf['schemes'] !== undefined) {
ProxyHandler.SCHEMES = /** @type {Array<string>} */ (conf['schemes']);
}
if (conf['methods'] !== undefined) {
ProxyHandler.METHODS = /** @type {Array<string>} */ (conf['methods']);
}
if (conf['encode'] !== undefined) {
ProxyHandler.ENCODE = /** @type {boolean} */ (conf['encode']);
}
if (conf['url'] !== undefined) {
ProxyHandler.PROXY_URL = /** @type {string} */ (conf['url']);
}
}
}
/**
* Get the proxy URI with the encoded url parameter set.
*
* @param {goog.Uri|string} uri The URI parameter
* @return {string} The proxy URI
*/
static getProxyUri(uri) {
uri = ProxyHandler.ENCODE ? encodeURIComponent(uri.toString()) : uri.toString();
return ProxyHandler.PROXY_URL.replace('{url}', uri);
}
} |
JavaScript | class SearchResultsPanel extends AbstractMvuContentPanel {
/**
*
*/
createView() {
return html`
<div class="search-results-panel">
${unsafeHTML(`<${LocationResultsPanel.tag}/>`)}
${unsafeHTML(`<${GeoResourceResultsPanel.tag}/>`)}
${unsafeHTML(`<${CpResultsPanel.tag}/>`)}
</div>
`;
}
static get tag() {
return 'ba-search-results-panel';
}
} |
JavaScript | class ScaleProvider {
/**
* @return {number} - The ratio by which an image will be scaled.
*/
getScaleRatio() {}
} |
JavaScript | class App extends React.Component {
render() {
return <RootComponent />;
}
} |
JavaScript | class AddUser extends Component {
constructor(props) {
super(props);
this.state = {
permissionData: '',
singleUserData: {},
rows: [],
is_email_valid: '',
checkboxpermission: false
};
this.permissionsData = this.permissionsData.bind(this)
}
permissionData = '';
/**
* @function append checked permission names to permissionData variable
* @param permissionData
*/
permissionsData(permissionData) {
this.permissionData = '';
for (let permission of permissionData)
if (permission.isPermissionChecked) this.permissionData += ',' + permission.permission_name;
}
componentWillMount = () => {
let headers = {
'authorization': handleLocalStorage("get", "employerLogin"),
'Content-Type': 'application/json',
};
this.getPermissionsData(headers)
};
/**
* @function to get subuser data from the backend and check subuser permissions
* @param headers: token and
*/
getSingleUserData(headers) {
if (this.props.match.params.userId) {
let apiUrl = SUB_USER_LIST + this.props.match.params.userId + '/';
apiCall('get', null, apiUrl, headers).then(res => {
this.setState({
singleUserData: res.data
}, () => {
const {rows} = this.state;
for (let permission of this.state.singleUserData.permissions.split(',')) {
let row = rows.find(row => row.permission_name === permission);
if (row) row.isPermissionChecked = true
}
this.setState({ rows })
})
})
}
}
/**
* @function to get the permissions of a user from backend
* @param headers: token and content-type as headers
*/
getPermissionsData(headers) {
apiCall('get', null, GET_PERMISSIONS, headers).then(res => {
for (let permission of res.data) {
permission.isPermissionChecked = false
}
this.setState({
rows: res.data
}, () => {
this.getSingleUserData(headers)
})
})
}
/**
* @function to send updated subuser data to the backend and
* if response status true redirect it to subusers list page
* @param method: http method
* @param dataToBeSend: request body
* @param apiUrl: api end point
* @param headers: headers for the api call
*/
saveOrUpdatedSubUserData(method, dataToBeSend, apiUrl, headers) {
apiCall(method, dataToBeSend, apiUrl, headers).then(res => {
if (res.status) {
this.props.history.push({ pathname: '/subuser' })
}
})
}
/**
* @function to validate permissions and create request body before make an api call
*/
saveUserData = () => {
// checking permissions change
if (!this.permissionData) {
if (this.props.match.params.userId) {
toast("Permission is same as before, kindly Edit it or click on Cancel", {});
} else {
toast("Kindly specify atleast one permission", {});
}
return;
}
let dataToBeSend;
if (this.props.formData) {
dataToBeSend = {email_id: this.props.formData.values.email, permissions: this.permissionData.slice(1)}
}
let headers = {
'authorization': handleLocalStorage("get", "employerLogin"),
'Content-Type': 'application/json',
};
let apiUrl = SUB_USER_LIST;
if (this.props.match.params.userId) {
apiUrl = apiUrl + this.props.match.params.userId + '/';
this.saveOrUpdatedSubUserData('patch', dataToBeSend, apiUrl, headers)
} else {
this.saveOrUpdatedSubUserData('post', dataToBeSend, apiUrl, headers)
}
};
/**
* redirect to subusers list page, if user doesn't want to change or create subuser.
*/
cancelUser = () => this.props.history.push({pathname: '/subuser'});
/**
* @function to handle email input field and permission checkboxes enable or disable
* @param emailError: email error
* @param allowed: flag to enable or disable checkboxes
*/
isEmaildisabled = (emailError, allowed) => {
this.setState({
is_email_valid: emailError,
checkboxpermission: allowed
})
};
render() {
return (
<div className="sub-user-page">
<EmployerSideNav history={history} selected={4}>
<div style={{
overflow: 'auto',
height: '700px',
paddingLeft: '40px',
paddingRight: '40px',
paddingBottom: '40px'
}}>
<div className="sub-user-container add-sub-user-responsive-container">
<div>
<div className="sub-user-text">Add Sub User</div>
<div className="sub-user-nav">
<Breadcrumbs
separator={<NavigateNextIcon fontSize="small"/>}
arial-label="Breadcrumb"
>
<Link color="inherit" href="#" onClick={this.handleNavigationClick}>
Profile
</Link>
<Link color="inherit" href="/subuser" onClick={this.handleNavigationClick}>
Sub Users
</Link>
<Link color="inherit" href="#" onClick={this.handleNavigationClick}>
<CustomIcon text="Add Sub User" className="nav-create-a-job-text"/>
</Link>
</Breadcrumbs>
</div>
</div>
<div className="btn-wrapper">
<button className="shenzyn-btn outline-primary-button px-40 py-8" onClick={this.cancelUser}> Cancel
</button>
{this.props.formData && this.props.formData.syncErrors || this.state.checkboxpermission ? <Fab
variant="extended"
size="medium"
className="disable-button">Save{this.state.checkboxpermission}</Fab> : <Fab
variant="extended"
size="medium"
className="submit-button"
onClick={this.saveUserData}
disabled={this.props.formData && this.props.formData.syncErrors || this.state.checkboxpermission == true}>
{this.props.match.params.userId ? 'Update' : 'Save'}
</Fab>}
</div>
</div>
<div className="profile-section">
<ProfileSection match={this.props.match} singleUserData={this.state.singleUserData}
isEmailValid={this.isEmaildisabled} cancelPopup={this.cancelUser}/>
<Permission savedData={this.permissionsData} permissionData={this.state.rows}
checkboxEnable={this.state.checkboxpermission} isEmailValidCheck={this.state.is_email_valid}
isEmailValidUpdateCheck={this.props.formData && this.props.formData.syncErrors}/>
</div>
</div>
</EmployerSideNav>
</div>
);
}
} |
JavaScript | class PerspectiveController extends CanvasController {
constructor($cb, controller) {
super(
$cb, controller,
new Three.PerspectiveCamera(45, 1, 1, -1));
this.mCamera.position.set(0, 0, 10);
this.mCamera.up.set(0, 0, 1);
this.mCamera.aspect = this.mAspectRatio;
this.mControls = new OrbitControls(
this.mCamera, this.mRenderer.domElement);
this.mControls.target.set(0, 0, 0);
this.mControls.update();
this.mConstructed = true;
this.animate();
}
// @Override CanvasController
show() {
super.show();
this.mSceneController.addMeshToScene();
}
hide() {
super.hide();
this.mSceneController.removeMeshFromScene();
}
// @Override CanvasController
fit() {
if (!this.mConstructed)
return;
let bounds = this.mSceneController.boundingBox;
let sz = bounds.getSize(new Three.Vector3());
let viewSize = Math.max(sz.x, sz.y, sz.z)
this.mSceneController.resizeHandles(viewSize);
// Look at the centre of the scene
this.mControls.target = bounds.getCenter(new Three.Vector3());
this.mCamera.position.set(bounds.max.x, bounds.max.y, bounds.max.z);
}
animate() {
this.mControls.update();
super.animate();
}
} |
JavaScript | class SubjectManager {
constructor() {
this._observers = {};
}
addObserver(eventType, observer) {
if(!this._observers[eventType]) {
this._observers[eventType] = [];
}
this._observers[eventType].push(observer);
}
removeObserver(eventType, observer) {
const idx = this._observers[eventType].indexOf(observer);
if(idx > -1){
this._observers[eventType].splice(idx);
}
}
notify(eventType, data) {
this._observers[eventType].forEach(observer => observer.update(data));
}
} |
JavaScript | class Collidable {
constructor(type, x, y, width, height) {
this.type = type;
this.x = x; // x location of collidable in game space
this.y = y; // y location of collidable in game space
this.height = height; // height of object
this.width = width; // width of object
}
} |
JavaScript | class PieChart extends React.Component {
constructor() {
super();
this.state = {
response1: "",
response2: "",
response3: "",
response4: "",
count1: null,
count2: null,
count3: null,
count4: null,
complete: false,
loading: true
// date: null
};
}
// componentWillMount() {
// this.setState({ complete: false });
// this.count = 0;
// this.response1 = "";
// this.response2 = "";
// this.response3 = "";
// this.response4 = "";
// this.complete = false;
// if (this.props.survey.length > 0 && this.props.singleSurvey.length !== 0) {
// const responses = this.props.singleSurvey.data.map(
// response => (this.count += 1)
// );
// console.log(responses, "responses");
// // for (let i = 0; i < this.count; i++) {
// // let data = this.props.singleSurvey.data;
// // let testText = data[i].feeling_text;
// // let breakTest = testText.split(" ");
// // this.result = [];
// // for (let i = 0; i < breakTest.length; i++) {
// // if (breakTest[i].indexOf(":") === -1) {
// // let textP = breakTest[i] + " ";
// // this.result.push(textP);
// // } else if (breakTest[i].indexOf(":") > -1) {
// // let textE = <Emoji emoji={breakTest[i]} size={16} />;
// // this.result.push(textE);
// // }
// // }
// // }
// if (this.count < 4) {
// for (let i = 0; i < this.count; i++) {
// let data = this.props.singleSurvey.data;
// for (let i = 0; i < this.count; i++) {
// let testText = data[i].feeling_text;
// let breakTest = testText.split(" ");
// this.result = [];
// for (let i = 0; i < breakTest.length; i++) {
// if (breakTest[i].indexOf(":") === -1) {
// let textP = breakTest[i] + " ";
// this.result.push(textP);
// } else if (breakTest[i].indexOf(":") > -1) {
// let textE = <Emoji emoji={breakTest[i]} size={16} />;
// this.result.push(textE);
// }
// }
// }
// let temp = data[i].feeling_text;
// if (this.response1 === "") {
// this.response1 = temp;
// if (this.count === 1) {
// this.complete = true;
// }
// } else if (this.response1 === temp && this.response2 === "") {
// this.response2 = temp;
// if (this.count === 2) {
// this.complete = true;
// }
// } else if (
// this.response1 === temp &&
// this.response3 === "" &&
// this.response2 === temp
// ) {
// this.response3 = temp;
// if (this.count === 3) {
// this.complete = true;
// }
// } else if (
// this.response1 === temp &&
// this.response4 === "" &&
// this.response2 === temp &&
// this.response3 === temp
// ) {
// this.response4 = temp;
// this.complete = true;
// } else {
// this.complete = true
// }
// }
// }
// for (let i = 0; i < this.count; i++) {
// let data = this.props.singleSurvey.data;
// let temp = data[i].feeling_text;
// if (this.response1 === "") {
// this.response1 = temp;
// } else if (this.response1 !== temp && this.response2 === "") {
// this.response2 = temp;
// } else if (
// this.response1 !== temp &&
// this.response3 === "" &&
// this.response2 !== temp
// ) {
// this.response3 = temp;
// } else if (
// this.response1 !== temp &&
// this.response4 === "" &&
// this.response2 !== temp &&
// this.response3 !== temp
// ) {
// this.response4 = temp;
// this.complete = true;
// }
// }
// // this.responsesEmojis = []
// // for(let i=1; i<=4; i++) {
// // let testText = this.response[i]
// // let breakTest = testText.split(" ");
// // let result = [];
// // for (let i = 0; i < breakTest.length; i++) {
// // if (breakTest[i].indexOf(":") === -1) {
// // let textP = breakTest[i] + " ";
// // result.push(textP);
// // } else if (breakTest[i].indexOf(":") > -1) {
// // let textE = <Emoji emoji={breakTest[i]} size={16} />;
// // result.push(textE);
// // }
// // }
// // this.responsesEmojis = result;
// // }
// // console.log(this.responsesEmojis)
// // }
// }
// if (
// this.props.survey.length > 0 &&
// this.props.singleSurvey.length !== 0 &&
// this.complete === true
// ) {
// this.emoji1 = [];
// this.emoji2 = [];
// this.emoji3 = [];
// this.emoji4 = [];
// for (let i = 0; i < this.result.length; i++) {
// if (this.emoji1.length === 0) {
// if (typeof this.result[i] === "string") {
// this.emoji1.push(this.result[i]);
// this.emoji1.push(this.result[i + 1]);
// i = i + 2;
// } else {
// this.emoji1 = this.result[i];
// i = i + 1;
// }
// } else if (
// this.emoji1[0] !== this.result[i] &&
// this.emoji2.length === 0
// ) {
// if (typeof this.result[i] === "string") {
// this.emoji2.push(this.result[i]);
// this.emoji2.push(this.result[i + 1]);
// i = i + 2;
// } else {
// this.emoji2 = this.result[i];
// i = i + 1;
// }
// } else if (
// this.emoji1[0] !== this.result[i] &&
// this.emoji2[0] !== this.result[i] &&
// this.emoji3.length === 0
// ) {
// if (typeof this.result[i] === "string") {
// this.emoji3.push(this.result[i]);
// this.emoji3.push(this.result[i + 1]);
// i = i + 2;
// } else {
// this.emoji3 = this.result[i];
// i = i + 1;
// }
// } else if (
// this.emoji1[0] !== this.result[i] &&
// this.emoji2[0] !== this.result[i] &&
// this.emoji3[0] !== this.result[i] &&
// this.emoji4.length === 0
// ) {
// if (typeof this.result[i] === "string") {
// this.emoji4.push(this.result[i]);
// this.emoji4.push(this.result[i + 1]);
// i = i + 2;
// } else {
// this.emoji4 = this.result[i];
// i = i + 1;
// }
// }
// }
// console.log(this.emoji1, this.emoji2);
// }
// this.responseArray = [];
// for (let i = 0; i < this.count; i++) {
// let temp = this.props.singleSurvey.data[i].feeling_text;
// this.responseArray.push(temp);
// }
// let counts = {};
// this.responseArray.forEach(function(x) {
// counts[x] = (counts[x] || 0) + 1;
// });
// // if(this.props.singleSurvey.response.length === 0) {
// // this.date = new Date();
// // } else {
// // this.date = new Date(`${this.props.singleSurvey.response[0].created_at}`);
// // }
// this.setState({
// response1: this.response1,
// response2: this.response2,
// response3: this.response3,
// response4: this.response4,
// count1: counts[this.response1],
// count2: counts[this.response2],
// count3: counts[this.response3],
// count4: counts[this.response4],
// complete: this.complete,
// loading: false
// // date: this.date
// });
// }
componentDidMount() {
this.props.getSingleTeamMembers(localStorage.getItem("email"));
this.props.getSurvey(localStorage.getItem('id'));
this.props.getSingleTeam(localStorage.getItem('team_id'));
this.props.getFeelings(localStorage.getItem('id'));
if (this.props.survey.length > 0 && this.props.singleSurvey.length === 0) {
this.props.fetchSingleSurvey(this.props.survey[0].survey_time_stamp);
// this.setState({
// loading: false
// })
}
// this.setState({
// loading: false
// })
// }
}
componentDidUpdate(prevProps) {
if (this.props.surveyIsFetching !== prevProps.surveyIsFetching) {
if (this.props.survey.length !== prevProps.survey.length) {
this.props.fetchSingleSurvey(this.props.survey[0].survey_time_stamp)
}
this.setState({ complete: false });
this.count = 0;
this.response1 = "";
this.response2 = "";
this.response3 = "";
this.response4 = "";
this.complete = false;
if (this.props.survey.length > 0 && this.props.singleSurvey.length !== 0) {
const responses = this.props.singleSurvey.data.map(
response => (this.count += 1)
);
console.log(responses, "responses");
// for (let i = 0; i < this.count; i++) {
// let data = this.props.singleSurvey.data;
// let testText = data[i].feeling_text;
// let breakTest = testText.split(" ");
// this.result = [];
// for (let i = 0; i < breakTest.length; i++) {
// if (breakTest[i].indexOf(":") === -1) {
// let textP = breakTest[i] + " ";
// this.result.push(textP);
// } else if (breakTest[i].indexOf(":") > -1) {
// let textE = <Emoji emoji={breakTest[i]} size={16} />;
// this.result.push(textE);
// }
// }
// }
if (this.count < 4) {
for (let i = 0; i < this.count; i++) {
let data = this.props.singleSurvey.data;
this.result = [];
for (let i = 0; i < this.count; i++) {
let testText = data[i].feeling_text;
let breakTest = testText.split(" ");
for (let i = 0; i < breakTest.length; i++) {
if (breakTest[i].indexOf(":") === -1) {
let textP = breakTest[i] + " ";
this.result.push(textP);
} else if (breakTest[i].indexOf(":") > -1) {
let textE = <Emoji emoji={breakTest[i]} size={16} />;
this.result.push(textE);
}
}
}
let temp = data[i].feeling_text;
if (this.response1 === "") {
this.response1 = temp;
if (this.count === 1) {
this.complete = true;
}
} else if (this.response1 !== temp && this.response2 === "") {
this.response2 = temp;
if (this.count !== 2) {
this.complete = true;
}
} else if (
this.response1 !== temp &&
this.response3 === "" &&
this.response2 !== temp
) {
this.response3 = temp;
if (this.count === 3) {
this.complete = true;
}
} else if (
this.response1 !== temp &&
this.response4 === "" &&
this.response2 !== temp &&
this.response3 !== temp
) {
this.response4 = temp;
this.complete = true;
} else {
this.complete = true
}
}
}
for (let i = 0; i < this.count; i++) {
let data = this.props.singleSurvey.data;
this.result = [];
for (let i = 0; i < this.count; i++) {
let testText = data[i].feeling_text;
let breakTest = testText.split(" ");
for (let i = 0; i < breakTest.length; i++) {
if (breakTest[i].indexOf(":") === -1) {
let textP = breakTest[i] + " ";
this.result.push(textP);
} else if (breakTest[i].indexOf(":") > -1) {
let textE = <Emoji emoji={breakTest[i]} size={16} />;
this.result.push(textE);
}
}
}
let temp = data[i].feeling_text;
if (this.response1 === "") {
this.response1 = temp;
} else if (this.response1 !== temp && this.response2 === "") {
this.response2 = temp;
} else if (
this.response1 !== temp &&
this.response3 === "" &&
this.response2 !== temp
) {
this.response3 = temp;
} else if (
this.response1 !== temp &&
this.response4 === "" &&
this.response2 !== temp &&
this.response3 !== temp
) {
this.response4 = temp;
this.complete = true;
} else {
this.complete = true
}
}
// this.responsesEmojis = []
// for(let i=1; i<=4; i++) {
// let testText = this.response[i]
// let breakTest = testText.split(" ");
// let result = [];
// for (let i = 0; i < breakTest.length; i++) {
// if (breakTest[i].indexOf(":") === -1) {
// let textP = breakTest[i] + " ";
// result.push(textP);
// } else if (breakTest[i].indexOf(":") > -1) {
// let textE = <Emoji emoji={breakTest[i]} size={16} />;
// result.push(textE);
// }
// }
// this.responsesEmojis = result;
// }
// console.log(this.responsesEmojis)
// }
}
if (
this.props.survey.length > 0 &&
this.props.singleSurvey.length !== 0 &&
this.complete === true
) {
this.emoji1 = [];
this.emoji2 = [];
this.emoji3 = [];
this.emoji4 = [];
for (let i = 0; i < this.result.length; i += 2) {
if (this.emoji1.length === 0) {
this.emoji1.push(this.result[i]);
this.emoji1.push(this.result[i + 1]);
// console.log(i, 'i at 440', this.result[i], this.emoji1)
// console.log(this.result)
// } else if (this.emoji1[1].props.emoji === this.result[i+1].props.emoji) {
// this.emoji1.shift()
// this.emoji1.shift()
// this.emoji1.push(this.result[i]);
// this.emoji1.push(this.result[i + 1]);
} else if (this.emoji1[1].props.emoji !== this.result[i+1].props.emoji &&
this.emoji2.length === 0){
this.emoji2.push(this.result[i]);
this.emoji2.push(this.result[i + 1]);
// console.log(i, 'i at 466', this.result[i], this.emoji2)
} else if (
this.emoji1[1].props.emoji !== this.result[i+1].props.emoji &&
this.emoji2[1].props.emoji !== this.result[i+1].props.emoji &&
this.emoji3.length === 0
) {
this.emoji3.push(this.result[i]);
this.emoji3.push(this.result[i + 1]);
} else if (
this.emoji1[1].props.emoji !== this.result[i+1].props.emoji &&
this.emoji2[1].props.emoji !== this.result[i+1].props.emoji &&
this.emoji3[1].props.emoji !== this.result[i+1].props.emoji &&
this.emoji4.length === 0
) {
this.emoji4.push(this.result[i]);
this.emoji4.push(this.result[i + 1]);
}
// break
}
// console.log(this.emoji1, this.emoji2);
}
this.responseArray = [];
for (let i = 0; i < this.count; i++) {
let temp = this.props.singleSurvey.data[i].feeling_text;
this.responseArray.push(temp);
}
let counts = {};
this.responseArray.forEach(function (x) {
counts[x] = (counts[x] || 0) + 1;
});
// if(this.props.singleSurvey.response.length === 0) {
// this.date = new Date();
// } else {
// this.date = new Date(`${this.props.singleSurvey.response[0].created_at}`);
// }
this.setState({
response1: this.response1,
response2: this.response2,
response3: this.response3,
response4: this.response4,
count1: counts[this.response1],
count2: counts[this.response2],
count3: counts[this.response3],
count4: counts[this.response4],
complete: this.complete,
loading: false
// date: this.date
});
}
// if(this.props.singleSurvey.response === undefined) {
// this.date = new Date();
// } else if(this.props.singleSurvey.response !== undefined && this.props.singleSurvey.length !== 0) {
// this.date = new Date(`${this.props.singleSurvey.response[0].created_at}`)
// }
}
render() {
// if (localStorage.getItem('i')) {
// setTimeout(function () {
// localStorage.removeItem('i')
// }, 1200)
// return <p>Loading...</p>
// }
if (this.state.complete === false || this.props.loading === true || this.props.surveyIsFetching === true) {
return (<><Link className="btn-feel-4" to={"/profile"}>Create Survey</Link>{/*<img className="loadinggif report-gif" src={loadinggif} alt="loading" />*/}</>)
} else if (
this.props.surveyIsFetching === false &&
this.props.survey.length === 0 &&
this.props.singleSurvey.length === 0 &&
this.state.complete === false
) {
return <p>Make surveys to display data</p>;
} else if (
this.props.survey.length > 0 &&
this.props.surveyIsFetching === false &&
this.props.singleSurvey.length === 0 &&
this.state.complete === false
) {
return <p>Make surveys to display data</p>
} else if (this.props.singleSurvey.length === 0) {
return <p>Make surveys to display data</p>
} else if (typeof this.props.singleSurvey.response.length === undefined) {
return <p>Make surveys to display data</p>
} else {
const data = {
labels: ["", "", "", ""],
datasets: [
{
data: [
this.state.count1,
this.state.count2,
this.state.count3,
this.state.count4
],
backgroundColor: ["#FF6384", "#36A2EB", "#FFCE56"],
hoverBackgroundColor: ["#FF6384", "#36A2EB", "#FFCE56"]
}
]
};
let date = new Date(`${this.props.singleSurvey.response[0].created_at}`)
const canvas = {
height: "400px",
width: "350px"
};
return (
<>
{this.state.complete === false ? (
<div>Create Surveys to see results!</div>
) : (
<div className="pie-chart-main" style={canvas}>
<div className="pie-chart-words">
<h2>{this.props.singleSurvey.response[0].description}</h2>
{date === undefined ? (
<p>This has no responses yet</p>
) : (
<h3>Created on {date.toDateString()}.</h3>
)}
<p>
{this.count} {this.count < 2 ? "response" : "responses"} to
this survey
</p>
</div>
<div className="responses">
<p className="response1">Response 1:</p>
{this.state.response1 === "" ? (<p></p>) : (this.state.response1[0] === ":" ? (
<Emoji
className="emoji1"
emoji={this.state.response1}
size={16}
/>
) : (
<p>
{this.emoji1[0]}
{this.emoji1[1]}
</p>
))}{" "}
<p className="response2">Response 2:</p>
{this.state.response2 === "" ? (<p></p>) : (this.state.response2[0] === ":" ? (
<Emoji
className="emoji1"
emoji={this.state.response2}
size={16}
/>
) : (
<p>
{this.emoji2[0]}
{this.emoji2[1]}
</p>
))}{" "}
<p className="response3">Response 3:</p>
{this.state.response3 === "" ? (<p></p>) : (this.state.response3[0] === ":" ? (
<Emoji
className="emoji1"
emoji={this.state.response3}
size={16}
/>
) : (
<p>
{this.emoji3[0]}
{this.emoji3[1]}
</p>
))}{" "}
<p className="response4">Response 4:</p>
{this.state.response4 === "" ? (<p></p>) : (this.state.response4[0] === ":" ? (
<Emoji
className="emoji1"
emoji={this.state.response4}
size={16}
/>
) : (
<p>
{this.emoji4[0]}
{this.emoji4[1]}
</p>
))}
</div>
<Pie
className="piepie"
data={data}
// width={10}
height={10}
options={{
maintainAspectRatio: false,
responsive: true
}}
/>
</div>
)}
{/* <Select options={surveyList} /> */}
</>
);
}
}
} |
JavaScript | class MultiMessageGame extends MessageGame {
constructor(context, players, options) {
super(context, players, options);
for (let player of this.players) {
if (player.bot) continue;
player.liveMessage = new LiveMessage(player.id);
}
}
async startGame(client) {
let playerInterface = this.constructor.CONFIG.player.interface || [];
for (let player of this.players) {
if (player.liveMessage) {
await player.liveMessage.setupReactionInterface(client, playerInterface);
}
}
return super.startGame(client);
}
updateEmbed() {
for (let player of this.players) {
if (player.liveMessage) {
player.liveMessage.updateEmbed(this);
}
}
return this.embed;
}
} |
JavaScript | class ReviewTasksDashboard extends Component {
state = {
showType: ReviewTasksType.toBeReviewed,
showSubType: "reviewer",
filterSelected: {},
}
componentDidMount() {
this.props.subscribeToReviewMessages()
}
componentDidUpdate(prevProps) {
if (_isUndefined(_get(this.props, 'match.params.showType')) &&
this.state.showType !== ReviewTasksType.toBeReviewed ) {
this.setState({showType:ReviewTasksType.toBeReviewed})
}
else if (_get(this.props, 'match.params.showType') !== this.state.showType &&
!_isUndefined(_get(this.props, 'match.params.showType'))) {
this.setState({showType: _get(this.props, 'match.params.showType')})
}
if (!this.state.filterSelected[this.state.showType]) {
if (_get(this.props.history, 'location.search')) {
this.setSelectedFilters(
buildSearchCriteriafromURL(this.props.history.location.search)
)
return
}
if (!_isEmpty(_get(this.props.history, 'location.state.filters'))) {
// We already have filters set in our history, so let's just move
// on to the table.
return
}
return
}
// If our path params have changed we need to update the default filters
if (!_isEqual(this.props.location.search, prevProps.location.search)) {
this.setSelectedFilters(
buildSearchCriteriafromURL(this.props.history.location.search), true
)
return
}
if (this.props.location.pathname !== prevProps.location.pathname &&
this.props.location.search !== prevProps.location.search) {
window.scrollTo(0, 0)
}
}
componentWillUnmount() {
this.props.unsubscribeFromReviewMessages()
}
setSelectedFilters = (filters, clearPrevState = false) => {
const filterSelected = _cloneDeep(this.state.filterSelected)
filterSelected[this.state.showType] = clearPrevState ?
_merge({filters:{}}, filters) :
_merge({filters:{}}, filterSelected[this.state.showType], filters)
if (filters.challengeName) {
filterSelected[this.state.showType].filters.challenge = filters.challengeName
}
if (filters.projectName) {
filterSelected[this.state.showType].filters.project = filters.projectName
}
// Remove any undefined filters
filterSelected[this.state.showType] = _omitBy(
filterSelected[this.state.showType], f => _isUndefined(f)
)
// Check for a valid challenge id
const challengeId = filterSelected[this.state.showType].filters.challengeId
if (challengeId) {
if (!_isFinite(_parseInt(challengeId))) {
filterSelected[this.state.showType] = _omit(
filterSelected[this.state.showType], ['challengeId', 'challenge', 'challengeName'])
}
}
// Check for a valid project id
const projectId = filterSelected[this.state.showType].filters.projectId
if (projectId) {
if (!_isFinite(_parseInt(projectId))) {
filterSelected[this.state.showType] = _omit(
filterSelected[this.state.showType], ['projectId', 'project', 'projectName'])
}
}
this.setState({filterSelected})
}
setSelectedChallenge = (challengeId, challengeName) => {
this.setSelectedFilters({filters: {challengeId, challengeName}})
}
setSelectedProject = (projectId, projectName) => {
this.setSelectedFilters({filters: {projectId, projectName}})
}
clearSelected = () => {
const filterSelected = _cloneDeep(this.state.filterSelected)
filterSelected[this.state.showType] = null
this.setState({filterSelected})
this.props.history.push({
pathname: `/review/${this.state.showType}`
})
}
changeTab = (tab) => {
this.props.history.push({
pathname: `/review/${tab}`
})
}
render() {
// The user needs to be logged in.
const user = AsEndUser(this.props.user)
if (!user.isLoggedIn()) {
return (
<div className="mr-flex mr-justify-center mr-py-8 mr-w-full mr-bg-blue">
<SignInButton {...this.props} longForm />
</div>
)
}
const metaReviewEnabled = process.env.REACT_APP_FEATURE_META_QC === 'enabled'
const showType = !user.isReviewer() ? ReviewTasksType.myReviewedTasks : this.state.showType
const reviewerTabs =
<div>
{!!this.state.filterSelected[showType] && user.isReviewer() &&
<div className="mr-mb-4">
<button
className="mr-text-green-lighter mr-text-sm hover:mr-text-white"
onClick={() => this.clearSelected()}
>
← <FormattedMessage {...messages.goBack} />
</button>
</div>
}
<ol className="mr-list-reset mr-text-md mr-leading-tight mr-flex">
<li>
<button
className={classNames(
this.state.showType === 'tasksToBeReviewed' ? "mr-text-white" : "mr-text-green-lighter"
)}
onClick={() => this.changeTab(ReviewTasksType.toBeReviewed)}
>
{this.props.intl.formatMessage(messages.tasksToBeReviewed)}
</button>
</li>
<li className="mr-ml-4 mr-border-l mr-pl-4 mr-border-green">
<button
className={classNames(
this.state.showType === ReviewTasksType.reviewedByMe ? "mr-text-white" : "mr-text-green-lighter"
)}
onClick={() => this.changeTab(ReviewTasksType.reviewedByMe)}
>
{this.props.intl.formatMessage(messages.tasksReviewedByMe)}
</button>
</li>
<li className="mr-ml-4 mr-border-l mr-pl-4 mr-border-green">
<button
className={classNames(
this.state.showType === ReviewTasksType.myReviewedTasks ? "mr-text-white" : "mr-text-green-lighter"
)}
onClick={() => this.changeTab(ReviewTasksType.myReviewedTasks)}
>
{this.props.intl.formatMessage(messages.myReviewTasks)}
</button>
</li>
<li className="mr-ml-4 mr-border-l mr-pl-4 mr-border-green">
<button
className={classNames(
this.state.showType === ReviewTasksType.allReviewedTasks ? "mr-text-current" : "mr-text-green-lighter"
)}
onClick={() => this.changeTab(ReviewTasksType.allReviewedTasks)}
>
{this.props.intl.formatMessage(messages.allReviewedTasks)}
</button>
</li>
{metaReviewEnabled &&
<li className="mr-ml-4 mr-border-l mr-pl-4 mr-border-green">
<button
className={classNames(
this.state.showType === ReviewTasksType.metaReviewTasks ? "mr-text-current" : "mr-text-green-lighter"
)}
onClick={() => this.changeTab(ReviewTasksType.metaReviewTasks)}
>
{this.props.intl.formatMessage(messages.metaReviewTasks)}
</button>
</li>
}
</ol>
{this.state.showType === ReviewTasksType.reviewedByMe && metaReviewEnabled &&
<ol className="mr-list-reset mr-text-md mr-leading-tight mr-flex mr-mt-6">
<li className="mr-text-yellow">
{this.props.intl.formatMessage(messages.role)}
</li>
<li className="mr-ml-4 mr-pl-4 mr-border-green">
<button
className={classNames(
this.state.showSubType === "reviewer" ? "mr-text-white" : "mr-text-green-lighter"
)}
onClick={() => this.setState({showSubType: "reviewer"})}
>
{this.props.intl.formatMessage(messages.asReviewer)}
</button>
</li>
<li className="mr-ml-4 mr-pl-4 mr-border-green">
<button
className={classNames(
this.state.showSubType === "meta-reviewer" ? "mr-text-white" : "mr-text-green-lighter"
)}
onClick={() => this.setState({showSubType: "meta-reviewer"})}
>
{this.props.intl.formatMessage(messages.asMetaReviewer)}
</button>
</li>
</ol>
}
</div>
const notReviewerTabs = (
<div>
<ol className="mr-list-reset mr-text-md mr-leading-tight mr-flex mr-links-green-lighter">
<li>
{this.props.intl.formatMessage(messages.myReviewTasks)}
</li>
<li className="mr-ml-4 mr-border-l mr-pl-4 mr-border-green">
<Link to="/user/profile">
{this.props.intl.formatMessage(messages.volunteerAsReviewer)}
</Link>
</li>
</ol>
</div>
)
return (
<div className='review-pane'>
{!this.state.filterSelected[showType] && user.isReviewer() &&
<div className={classNames("mr-widget-workspace",
"mr-py-8 mr-bg-gradient-r-green-dark-blue mr-text-white mr-cards-inverse")}>
<Header
className="mr-px-8"
eyebrow={this.props.workspaceEyebrow}
title={''}
info={user.isReviewer()? reviewerTabs : notReviewerTabs}
actions={null}
/>
<div>
<TasksReviewChallenges
reviewTasksType={this.state.showType}
selectChallenge={this.setSelectedChallenge}
selectProject={this.setSelectedProject}
/>
</div>
</div>
}
{(!!this.state.filterSelected[showType] || !user.isReviewer()) &&
<ReviewWidgetWorkspace
{...this.props}
className="mr-py-8 mr-bg-gradient-r-green-dark-blue mr-text-white mr-cards-inverse"
workspaceTitle={null}
workspaceInfo={user.isReviewer()? reviewerTabs : notReviewerTabs}
reviewTasksType={showType}
reviewTasksSubType={this.state.showSubType}
defaultFilters={this.state.filterSelected[showType]}
clearSelected={this.clearSelected}
pageId={showType}
metaReviewEnabled={metaReviewEnabled}
/>
}
<MediaQuery query="(max-width: 1023px)">
<ScreenTooNarrow />
</MediaQuery>
</div>
)
}
} |
JavaScript | class CheckReportCustomData {
constructor() {
/**
* @type {import('../metrics/metrics').CustomMetric[]}
*/
this.metrics = [];
}
} |
JavaScript | class GetSavingsSummary {
/**
* Constructs a new <code>GetSavingsSummary</code>.
* @alias module:model/GetSavingsSummary
*/
constructor() {
GetSavingsSummary.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>GetSavingsSummary</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/GetSavingsSummary} obj Optional instance to populate.
* @return {module:model/GetSavingsSummary} The populated <code>GetSavingsSummary</code> instance.
*/
static constructFromObject(data, obj) {
if (data) {
obj = obj || new GetSavingsSummary();
if (data.hasOwnProperty('currency')) {
obj['currency'] = GetSavingsCurrency.constructFromObject(data['currency']);
}
if (data.hasOwnProperty('accountBalance')) {
obj['accountBalance'] = ApiClient.convertToType(data['accountBalance'], 'Number');
}
}
return obj;
}
} |
JavaScript | class TodoModel {
constructor() {
this.todos = [{
id: 1,
title: 'Some stuff',
completed: false
},
{
id: 2,
title: 'Send pictures',
completed: true
},
{
id: 3,
title: 'Finish todo project',
completed: false
}
]
}
todos_all() {
return this.todos;
}
todos_create(title, completed = false) {
this.todos.push({
id: this.todos.length + 1,
title,
completed
});
}
} |
JavaScript | class Console extends EventEmitter {
/**
* @type {Object} List of options for the console
*/
options;
/**
* @type {DOM} Jquery element for the window part of the console
*/
windowElement;
/**
* @type {DOM} Jquery element for the input part of the console
*/
inputElement;
/**
* @type {GremlinClient} The driver client class from jbmusso/gremlin-javascript
*/
client;
/**
* @type {Parser} This is a Parser object that can be used to parse responses from the DB. Mostly useful for custom serializers.
* The Console mostly holds onto this to pass id down to the Clients
*/
parser;
/**
* @var {Array} this holds all query and response history in the form of:
* [
* {query: String, err: String|null, JSONresponse: String|null, TextResponse: String|null},
* {query: "g.V(1)", err: null, JSONresponse: "[{id: 1, etc...}]", TextResponse: "==>v[1]"},
* ...
* ]
*/
history = [];
/**
* @var {Integer} the current pointer in the history array
*/
historyPointer = 0;
/**
* Builds the Console
*
* @param {String|DOM} element This can be a jquery selector (String) or a dom element
* @param {Object} options The options array.
* @return {Void}
*/
constructor(windowElement, inputElement, options = {}) {
super();
this.windowElement = Console._getElement(windowElement);
this.inputElement = Console._getElement(inputElement);
//set window params
this.windowElement.css({overflowY: "auto"});
this.options = {
port: 8182,
host: 'localhost',
driverOptions: {
session: true
},
visualizerOptions: {
},
...options
}
this._attachHandlers();
//set default parser up
this.parser = new Parser();
//lets set up events
this.on('error', (err)=>{
console.log(err);
});
this.on('results', (query, parser)=>{
this.handleResults(query, parser);
});
}
/**
* Opens a connection with the client
* This is seperated and only called on query so that the user can interact and change settings/plugins
* after initializing the Console and still affect the client with those changes.
*
* This also has the potential to reconnect a disconnected client.
*
* @return {Void}
*/
initClient() {
if(!this.client) {
//lets init the client
this.client = new Client(this.options.host, this.options.port, this.options.driverOptions, this.parser);
//lets set up events
this.client.onError((err)=>{ // bubble up errors
this.emit('error', err);
});
this.client.onOpen(()=>{ // bubble up errors
this.emit('open');
});
}
}
/**
* Runs a gremlin query against gremlin-server
*
* @param {String} query the gremlin query
* @return {Void}
*/
executeQuery(query) {
this.initClient();
this.client.execute(query, (parser) => {
this.emit('results', query, parser);
});
}
/**
* Applies logic based on results
*
* @param {String} query The query run against db
* @param {Parser} parser The database parser object
* @param {Boolean} recordHistory Whether or not we should record this request in the history
* @return {Void}
*/
handleResults(query, parser, recordHistory = true) {
//add results to window
let response = $('<div>').addClass('port-section');
response.append($('<div>').addClass("port-query").html('gremlin> ' + Html.htmlEncode(query)));
if(!parser.getError()) {
response.append(parser.getHtmlResults());
} else {
response.append(parser.getHtmlError());
}
this.windowElement.append(response);
this.windowElement.animate({ scrollTop: this.windowElement[0].scrollHeight }, "slow");
//add results to history
if(recordHistory) {
this.populateHistory(query, parser);
}
}
/**
* Populate the history array
*
* @param {String} query The query that was sent to the database
* @param {Parser} parser The parser sent back from the database.
* @return {Void}
*/
populateHistory(query, parser) {
if(query != "" // not an empty query
&& (
!parser.getError()
|| (
typeof this.history[this.history.length - 1] == 'undefined' // if error then don't save the same query multiple
|| query != this.history[this.history.length - 1].query // times.
)
)
) {
this.history.push($.extend({query: query}, parser.getHistory()));
}
this.historyPointer = this.history.length;
}
/**
* Private : attaches keypress/down events to the input
*
* @return {Void}
*/
_attachHandlers() {
const widget = this;
//Lets attach the enter key down handler
this.inputElement.keypress(function(e) {
if(e.which == 13) {
widget.executeQuery($(this).val());
$(this).val('');
}
});
//Lets attach up and down arrows to navigate history
this.inputElement.keydown(function(e) {
if(e.which == 38) { // on up arrow
if( typeof widget.history[widget.historyPointer - 1] !== 'undefined' ) {
widget.historyPointer -= 1;
$(this).val(widget.history[widget.historyPointer].query);
}
}else if(e.which == 40) { // on down arrow
if( typeof widget.history[widget.historyPointer + 1] !== 'undefined' ) {
widget.historyPointer += 1;
$(this).val(widget.history[widget.historyPointer].query);
} else {
widget.historyPointer = widget.history.length;
$(this).val('');
}
}
})
}
/**
* Simple method to get/set elements from jquery selector strings
*
* @param {String|DOM} element the elementwe want to get/set
* @return {DOM} the dom element (translated from string if necessary)
*/
static _getElement(element) {
if(typeof element == "string") {
return $(element);
} else {
return element;
}
}
/**
* Registers a plugin for the console
* Plugins follow a specific interface documented in the README.md
*
* @param {Plugin} plugin the plugin to register
* @return {Void}
*/
register(plugin) {
plugin.load(this);
}
/**
* Populates the state of the graph from the provided history.
* This essentially re-runs all the history queries so that all session variables and graph state exist.
*
* @param {Array} history the history we want to re-run.
* @return {Void}
*/
populateDbFromHistory(history = []) {
//lets populate history properly if it isn't empty
if(history.length > 0 && this.history.length < 1) {
this.history = history;
this.historyPointer = history.length;
this.populateDbFromHistory();
if(typeof this.history[0].query !== 'undefined') {
this.initClient();
//lets take all queries and bunch them together to recreate env
let query = '';
for (let i = 0; (i < this.history.length - 1); i++) {
let parser = this.parser.create(this.history[i].error, this.history[i].results); // creates a Parser
this.handleResults(this.history[i].query, parser, false); // don't emit('results') as some plugins may generate viz on each call.
if(typeof parser.getError() === 'undefined' || parser.getError() == '' || parser.getError() == null)
query += this.history[i].query + ";";
}
//add typing to avoid strange db errors due to sandboxing
query = this._addTyping(query);
//execute the bundled query
this.client.execute(query, (parser) => {
if(!parser.getError())
{
if(this.history.length > 0) {
//here we need to remove the last history item since we are going to apply it again.
var lastHistory = this.history.splice(-1,1);
this.executeQuery(lastHistory[0].query);
}
} else {
this.emit('error', new Error( "Your initializing script produced an error : \n" + Html.htmlEncode(parser.getError())));
}
});
}
}
}
/**
* Adds typing and defs for query.
* This is used internaly to allow the system to issue a long query string of queries that may not have
* been required to use typing because they were sent individualy. (sandboxing caveats)
*
* @param {String} groovy The query that potentially doesn't have correct typing
* @return {String} a query with correct typing.
*/
_addTyping(groovy) {
const regex = /(?:"[^"]*?")|(?:^|\;) ?(\w+) ?(?=\=)/gmi;
let pointer = 0, pointerIncr = 0, result, variables = {}, output = groovy;
while ( (result = regex.exec(groovy)) ) {
if(typeof variables[result[1]] != "undefined" || (result[1] != "graph" && result[1] != "g" && typeof result[1] != "undefined"))
{
pointer = result.index + pointerIncr + result[0].indexOf(result[1]);
output = [output.slice(0, pointer), "def ", output.slice(pointer)].join('');
pointerIncr += 4;
variables[result[1]] = true; // this means we've already def this variable.
}
}
return output;
}
} |
JavaScript | class EarthQuakeList extends Component {
static propTypes = {
showEarthQuakeOnMap: React.PropTypes.func,
show: React.PropTypes.bool,
onClose: React.PropTypes.func,
selectedID: React.PropTypes.string,
earthquakes: React.PropTypes.array
};
//use below method if we expect data change after mounting the component
componentWillReceiveProps(nextProps) {
}
render() {
const {earthquakePlaces} = window;
const {show, showEarthQuakeOnMap, onClose, selectedID, earthquakes} = this.props;
return (
<RightDrawer show={show} onClose={onClose}>
<Header >Showing all {earthquakes.length} earthquakes</Header>
<Content>
{earthquakes.map( (earthquake, index) => {
const {coords1, coords2, id} = earthquake;
const cardStyle = (id == selectedID) ? appStyle.infoCardSelected : appStyle.infoCard;
return (
<div key={index} className={cardStyle} onClick={() => showEarthQuakeOnMap(id)}>
<div><span className="glyphicon glyphicon-map-marker" aria-hidden="true"></span>{earthquake.place}</div>
<div><span className={appStyle.title}>Magnitude: </span>{earthquake.magnitude}</div>
<div><span className={appStyle.title}>Time: </span>{toDateTime(earthquake.time)}</div>
</div>
);
})}
</Content>
</RightDrawer>
);
}
} |
JavaScript | class Manager extends Employee {
// Manager constructor
constructor(employeeObject) {
super(employeeObject);
this.officeNumber = employeeObject.managerOffice;
this.role = "Manager";
}
// ______________________
// Manager Object Methods
// ______________________
getRole() {
return this.role;
}
} |
JavaScript | class UcdlibIconset extends Mixin(LitElement)
.with(MainDomElement) {
static get properties() {
return {
name: {type: String},
size: {type: Number},
label: {type: String},
_iconMap: {type: Object, state: true}
};
}
constructor() {
super();
this.mutationObserver = new MutationObserverController(this, {subtree: true, childList: true});
this.name = "";
this.label = "";
this.size = 24;
this._iconMap = {};
this.style.display = "none";
}
/**
* @method updated
* @description Lit lifecyle method called after element updates
* @param {Map} props - Updated properties
* @private
*/
updated( props ){
if (props.has('name') && this.name ) {
this.dispatchEvent(
new CustomEvent('ucdlib-iconset-added', {bubbles: true, composed: true})
);
}
}
/**
* @method getIconNames
* @description Returns a list of icon names for this set
* @returns {Array}
*/
getIconNames(){
return Object.keys(this._iconMap);
}
/**
* @method getLabel
* @description Returns a friendly label of iconset
* @returns {String}
*/
getLabel(){
if ( this.label ) return this.label;
return this.name.replace(/-/g, " ");
}
/**
* @method applyIcon
* @description Adds icon to ucdlib-icon element from iconset
* @param {Element} element - A ucdlib-icon element
* @param {String} iconName - The icon identifier
* @returns {Boolean}
*/
applyIcon(element, iconName){
this.removeIcon(element);
let svg = this._cloneIcon(iconName);
if ( svg ) {
let eleRoot = this._getElementRoot(element);
eleRoot.insertBefore(svg, eleRoot.childNodes[0]);
return element._svgIcon = svg;
}
return null;
}
/**
* @method removeIcon
* @description Remove an icon from the given element by undoing the changes effected by `applyIcon`.
*
* @param {Element} element The element from which the icon is removed.
*/
removeIcon(element){
if (element._svgIcon) {
this._getElementRoot(element).removeChild(element._svgIcon);
element._svgIcon = null;
}
}
/**
* @method _cloneIcon
* @description Produce installable clone of the SVG element matching `id` in this
* iconset, or `undefined` if there is no matching element.
* @param {String} id - Icon id
* @returns {Element} - an SVG element
* @private
*/
_cloneIcon(id){
if ( !this._iconMap ) this._updateIconMap();
if ( this._iconMap[id] ){
let content = this._iconMap[id].cloneNode(true),
svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg'),
viewBox =
content.getAttribute('viewBox') || '0 0 ' + this.size + ' ' + this.size,
cssText =
'pointer-events: none; display: block; width: 100%; height: 100%;';
svg.setAttribute('viewBox', viewBox);
svg.setAttribute('preserveAspectRatio', 'xMidYMid meet');
svg.setAttribute('focusable', 'false');
svg.style.cssText = cssText;
svg.appendChild(content).removeAttribute('id');
return svg;
}
return null;
}
/**
* @method _getElementRoot
* @description Returns shadowroot if exists
* @param {Element} element
* @returns {Object}
* @private
*/
_getElementRoot(element){
if ( element.renderRoot ) {
return element.renderRoot;
}
if ( element.shadowRoot ) {
return element.shadowRoot;
}
return element;
}
/**
* @method _onChildListMutation
* @description Fires when element child list changes
* @private
*/
_onChildListMutation(){
this._updateIconMap();
}
/**
* @method _updateIconMap
* @description Sets the _iconMap property with object: {icon_id: icon}
* @private
*/
_updateIconMap(){
let iconMap = {};
this.querySelectorAll('g[id]').forEach(icon => {
iconMap[icon.id] = icon;
});
if ( !Object.keys(iconMap).length ) {
console.warn('No g elements with an id attribute found!.');
}
this._iconMap = iconMap;
}
} |
JavaScript | class Test extends Component {
state = {
projects: [],
message: `Tiles haven't loaded`
};
componentDidMount() {
this.getCarouselProjects()
};
getCarouselProjects = () => {
API.getCarouselProjects()
.then(res =>{
// console.log(res.data);
this.setState({
projects: res.data
})
}
).catch(() =>
this.setState({
projects:[],
message: `Your search hasn't worked`
})
);
};
render() {
return (
<div>
<Container>
<Row>
{this.state.projects.map(project => (
<Col size='md-4'>
<TestTile
key={project.id}
title={project.title}
date = {project.date}
photo_url = {project.photo_url}
category={project.Category.name}
/>
</Col>
))}
</Row>
</Container>
</div>
)
}
} |
JavaScript | class MenuScreen {
constructor(containerElement, _showflashcard) {
this.containerElement = containerElement;
this._showflashcard = _showflashcard;
this._goto = this._goto.bind(this);
const choices = containerElement.querySelector('#choices');
for (var val of FLASHCARD_DECKS) {
const title = document.createElement('div');
title.textContent = val.title;
title.addEventListener('click', this._goto);
choices.append(title);
}
}
_goto(event) {
// const eventInfo = {
// titleName: event.target.textContent,
// answer : null
// };
// document.dispatchEvent( new CustomEvent('title-clicked', { detail: eventInfo }) );
this._showflashcard(event.target.textContent, null);
}
show() {
this.containerElement.classList.remove('inactive');
}
hide() {
this.containerElement.classList.add('inactive');
}
} |
JavaScript | class ListButton extends Component {
render () {
const listItem = (
<ListItem button
disabled={this.props.disabled}
onClick={this.props.onClick}
style={this.props.style ? this.props.style : {}}
>
{
this.props.icon
? <ListItemIcon>
{this.props.icon}
</ListItemIcon>
: null
}
<ListItemText
primary={this.props.displayText}
inset={this.props.inset ? this.props.inset : false}
primaryTypographyProps={
this.props.primaryTypographyProps
? this.props.primaryTypographyProps
: {}
} />
</ListItem>
)
return (
<Fragment>
{
this.props.toolTip
? (
<Tooltip title={this.props.toolTip} placement="right">
{listItem}
</Tooltip>
)
: listItem
}
</Fragment>
)
}
} |
JavaScript | class CategoryPageTemplate extends React.Component {
componentDidMount() {
triggerAnalytics("CategoryPage");
}
render() {
// All queries defined at PageQuery are available here as this.props.data
const category = this.props.data.contentfulCategory;
return (
<Layout>
<SEO title={category.name} />
<h1>{category.name}</h1>
<Img fixed={category.image.fixed}/>
</Layout>
)
}
} |
JavaScript | class Node {
constructor(data, parent = null) {
this.data = data;
this._parent = parent;
this._children = [];
this._id = Utils.generateID();
this.constructorName = this.constructor.name;
}
get children() {
return this._children;
}
get hasChildren() {
return this._children.length > 0;
}
replaceChildren(arr) {
this._children.length = 0;
for (let child of arr) {
this._children.push(child);
}
}
/**
* Gets an identifier for this object that is unique across the entire graph. Multiple nodes may
* share a key if they represent the same object
*/
get key() {
// default implementation - should be overriden if a node can occur in multiple graphs
return this._id;
}
/**
* Gets an identifier for this node that is unique across the entire graph. Nodes do NOT share
* an id.
* @returns {*}
*/
get id() {
return this._id;
}
get parent() {
return this._parent;
}
get neighbors() {
let arr = this.children.slice();
if (!this.isRoot) {
arr.push(this.parent);
}
return arr;
}
get isLeaf() {
return !this.children.length;
}
get isRoot() {
return !this.parent;
}
get descendantsAndThis() {
return [this].concat(this.descendants);
}
get descendants() {
if (!this.hasChildren) {
return [];
}
return Array.concat.apply(null, this.children.map(node => node.descendantsAndThis));
}
get innerNodes() {
return this.descendants.filter(node => !node.isLeaf);
}
/**
* Gets the label to be shown on hover
*/
get label() {
return '';
}
/**
* Gets the label to be shown inside the node
*/
get shortLabel() {
return this.label;
}
/**
* Determines at which position a child node occurs
*/
indexOfChild(node) {
return this.children.indexOf(node);
}
/**
* Determines the position of this node in its parent
*/
get indexInParent() {
if (this.isRoot) {
return 0;
}
return this.parent.indexOfChild(this);
}
/**
* Sets the globalIndex property of this node and all its children
* @param offset the globalIndex of this node, omit if called on the root node
*/
calculateGlobalIndices(offset = 0) {
this.globalIndex = offset;
if (this.isLeaf) {
return offset + 1;
}
for (var child of this.children) {
offset = child.calculateGlobalIndices(offset);
}
return offset;
}
/**
* Gets the length of the longest path from the root to any leaf (including root and leaf)
* @returns {number}
*/
get height() {
if (!this.children.length) {
return 1;
}
return 1 + Math.max.apply(null, this.children.map(c => c.height));
}
/**
* Finds the root node
*/
get root() {
if (this.isRoot) {
return this;
}
return this.parent.root;
}
/**
* Gets a value that should be used for this node when sorting a tree recursively
*/
get sortOrder() {
if (this._overriddenSortOrder) {
return this._overriddenSortOrder;
}
return this.globalIndex;
}
/**
* Gets a set of the keys of leaf nodes
*/
get leafKeys() {
if (!this._leafKeys) {
this._leafKeys = this._generateLeafKeySet();
}
return this._leafKeys;
}
_generateLeafKeySet() {
var result = new Set();
for (var child of this.children) {
for (var leafKey of child.leafKeys) {
result.add(leafKey);
}
}
return result;
}
/**
* Gets the leaf nodes of this node as Set
*/
get leaves() {
if (!this._leaves) {
this._leaves = this._generateLeafSet();
}
return this._leaves;
}
get leavesInOrder() {
if (!this._leavesInOrder) {
this._leavesInOrder = this._generateLeafArray();
}
return this._leavesInOrder;
}
_generateLeafSet() {
var result = new Set();
if (this.isLeaf) {
result.add(this);
}
for (var child of this.children) {
for (var leaf of child.leaves) {
result.add(leaf);
}
}
return result;
}
_generateLeafArray() {
var result = [];
if (this.isLeaf) {
result.push(this);
}
for (var child of this.children) {
for (var leaf of child.leavesInOrder) {
result.push(leaf);
}
}
return result;
}
/**
* Generates a map of a node key to the node object
*/
_generateKeyMap() {
var result = new Map();
for (let child of this.children) {
result.set(child.key, child);
for (let [key, value] of child.keyMap) {
result.set(key, value);
}
}
return result;
}
/**
* Gets a Map that maps node keys of descendants to node objects
*/
get keyMap() {
if (!this._keyMap) {
this._keyMap = this._generateKeyMap();
}
return this._keyMap;
}
/**
* Finds a node that is a descendant of this node by key
*/
getDescendantByKey(key) {
return this.keyMap.get(key);
}
/**
* Gets all descendants
*/
get nodes() {
if (!this._nodes) {
this._nodes = [this];
for (var child of this.children) {
this._nodes = this._nodes.concat(child.nodes);
}
}
return this._nodes;
}
bary(pi1Fn) {
return average(Array.from(this.leaves).map(c => pi1Fn(c)));
}
/**
* Sorts the descendants of this node to most closely match the given other tree
*/
recursiveHierarchySort(otherRoot) {
this._overriddenSortOrder = this.bary(n => {
let otherNode = otherRoot.getDescendantByKey(n.key);
if (otherNode) {
return otherNode.globalIndex;
}
return 0;
});
for (let child of this.children) {
child.recursiveHierarchySort(otherRoot);
}
this.children.sort((a, b) => a.sortOrder - b.sortOrder);
}
} |
JavaScript | class EditorImageBuilder extends BaseImageBuilder { // eslint-disable-line no-unused-vars
/**
* Build image from json data
* @override
* @param {string} root File root path
* @param {JSON} image Image json data
* @return {GameImage} Maked image
*/
build(root, image) {
return new EditorImage(super.build(root, image), root);
}
} |
JavaScript | class Enemy {
constructor(level = 1, health = 10, isBoss = false) {
this.level = level
this.health = health
this.isBoss = isBoss
}
attack() {
return this.level * 3 * Math.floor(Math.random() + 2) * (this.isBoss ? 3 : 1)
}
} |
JavaScript | class MetricsCollector {
constructor(server, config) {
// NOTE we need access to config every time this is used because uuid is managed by the kibana core_plugin, which is initialized AFTER kbn_server
this._getBaseStats = () => ({
name: config.get('server.name'),
uuid: config.get('server.uuid'),
version: {
number: config.get('pkg.version').replace(matchSnapshot, ''),
build_hash: config.get('pkg.buildSha'),
build_number: config.get('pkg.buildNum'),
build_snapshot: matchSnapshot.test(config.get('pkg.version'))
}
});
this._stats = Metrics.getStubMetrics();
this._metrics = new Metrics(config, server); // TODO: deprecate status API that uses Metrics class, move it this module, fix the order of its constructor params
}
/*
* Accumulate metrics by summing values in an accumulutor object with the next values
*
* @param {String} property The property of the objects to roll up
* @param {Object} accum The accumulator object
* @param {Object} next The object containing next values
*/
static sumAccumulate(property, accum, next) {
const accumValue = accum[property];
const nextValue = next[property];
if (nextValue === null || nextValue === undefined) {
return; // do not accumulate null/undefined since it can't be part of a sum
} else if (nextValue.constructor === Object) { // nested structure, object
const newProps = {};
for (const innerKey in nextValue) {
if (nextValue.hasOwnProperty(innerKey)) {
const tempAccumValue = accumValue || {};
newProps[innerKey] = MetricsCollector.sumAccumulate(innerKey, tempAccumValue, nextValue);
}
}
return { // merge the newly summed nested values
...accumValue,
...newProps,
};
} else if (nextValue.constructor === Number) {
// leaf value
if (nextValue || nextValue === 0) {
const tempAccumValue = accumValue || 0; // treat null / undefined as 0
const tempNextValue = nextValue || 0;
return tempAccumValue + tempNextValue; // perform sum
}
} else {
return; // drop unknown type
}
}
async collect(event) {
const capturedEvent = await this._metrics.capture(event); // wait for cgroup measurement
const { process, os, ...metrics } = capturedEvent;
const stats = {
// guage values
...metrics,
process,
os,
// accumulative counters
response_times: MetricsCollector.sumAccumulate('response_times', this._stats, metrics),
requests: MetricsCollector.sumAccumulate('requests', this._stats, metrics),
concurrent_connections: MetricsCollector.sumAccumulate('concurrent_connections', this._stats, metrics),
sockets: MetricsCollector.sumAccumulate('sockets', this._stats, metrics),
event_loop_delay: MetricsCollector.sumAccumulate('event_loop_delay', this._stats, metrics),
};
this._stats = stats;
return stats;
}
getStats() {
return {
...this._getBaseStats(),
...this._stats
};
}
} |
JavaScript | class Notifications extends Core {
constructor(options) {
super(options);
this.flyout = new Flyout();
this._render(Template, options);
this.initialOptions = options;
}
_componentDidMount() {
this.mountPartialToComment('FLYOUT', this.flyout, this.el);
this.flyout.setAnchorPoint('top-left');
this.shortcut = new Shortcut({
icon: 'notification',
title: this.initialOptions.title
});
this.list = new List();
this.flyout.addTarget(this.shortcut);
this.flyout.addSlot(this.list);
this.flyout.setAnchorPoint('top-left');
window.addEventListener('resize', this._adjustFlyoutMaxHeight.bind(this));
this.unreadCount = this._findDOMEl(
'.hig__notifications__unread-messages-count',
this.el
);
}
setUnseenCount(unreadCount) {
this._findDOMEl(
'.hig__notifications__unread-messages-count',
this.el
).textContent = unreadCount;
}
open() {
this.flyout.open();
this._adjustFlyoutMaxHeight();
}
close() {
this.flyout.close();
}
addNotification(notification) {
this.list.addItem(notification);
}
onClickOutside(fn) {
return this.flyout.onClickOutside(fn);
}
onClick(fn) {
return this.shortcut.onClick(fn);
}
onScroll(fn) {
return this.list.onScroll(fn);
}
setLoading() {
this.list.setLoading();
}
setNotLoading() {
this.list.setNotLoading();
}
setTitle(title) {
if (this.list) {
this.list.setTitle(title);
}
}
_adjustFlyoutMaxHeight() {
const bufferFromBottom = 80;
const { bottom } = this.list.titleElement.getBoundingClientRect();
// Distance between the bottom of the notifications title and 80px from the bottom of the screen
const calculatedMaxHeight = window.innerHeight - bufferFromBottom - bottom;
this.flyout.flyoutContent.style.maxHeight = 'inherit'; // Override flyout's default max height
this.list.setContentMaxHeight(calculatedMaxHeight);
}
hideNotificationsCount() {
this.unreadCount.classList.add(
'hig__notifications__unread-messages-count--hide'
);
}
showNotificationsCount() {
this.unreadCount.classList.remove(
'hig__notifications__unread-messages-count--hide'
);
}
} |
JavaScript | class Node {
constructor(key, val) {
this.key = key || null
this.val = val || null
this.prev = null
this.next = null
}
} |
JavaScript | class CreateExperimentFormComponent extends Component {
static propTypes = {
validator: PropTypes.func,
intl: PropTypes.shape({ formatMessage: PropTypes.func.isRequired }).isRequired,
innerRef: PropTypes.any.isRequired,
};
render() {
return (
<Form ref={this.props.innerRef} layout='vertical'>
<Form.Item
label={this.props.intl.formatMessage({
defaultMessage: 'Experiment Name',
description: 'Label for create experiment modal to enter a valid experiment name',
})}
name={EXP_NAME_FIELD}
rules={[
{
required: true,
message: this.props.intl.formatMessage({
defaultMessage: 'Please input a new name for the new experiment.',
description: 'Error message for name requirement in create experiment for MLflow',
}),
validator: this.props.validator,
},
]}
>
<Input
placeholder={this.props.intl.formatMessage({
defaultMessage: 'Input an experiment name',
description: 'Input placeholder to enter experiment name for create experiment',
})}
autoFocus
/>
</Form.Item>
<Form.Item
name={ARTIFACT_LOCATION}
label={this.props.intl.formatMessage({
defaultMessage: 'Artifact Location',
description: 'Label for create experiment modal to enter a artifact location',
})}
rules={[
{
required: false,
},
]}
>
<Input
placeholder={this.props.intl.formatMessage({
defaultMessage: 'Input an artifact location (optional)',
description: 'Input placeholder to enter artifact location for create experiment',
})}
/>
</Form.Item>
</Form>
);
}
} |
JavaScript | class SurfaceBuffer extends MeshBuffer {
constructor() {
super(...arguments);
this.isSurface = true;
}
} |
JavaScript | class DateCB{
dayOfWeekString = ['Minggu','Senin','Selasa','Rabu','Kamis','Jumat','Sabtu'];
monthOfYearString = ['Januari','Februari','Maret','April','Mei','Juni','Juli','Agustus','September','Oktober','November','Desember'];
/**
*
* @param {*} date = type string example: 1996-12-12, 1996-11-10 etc
*/
constructor(year,month = 0,day = 0){
this.year = year;
this.month = month;
this.day = day;
this.date = new Date(year,month,day);
}
getMonthString(){
let monthString = "";
for(let m in this.monthOfYearString){
if(m == this.date.getMonth()){
monthString = this.monthOfYearString[m]
}
}
return monthString;
}
setDayString(year,month,day){
this.date = new Date(year,month,day);
}
getDayString(){
let dayString = "";
for(let m in this.dayOfWeekString){
if(m == this.date.getDay()){
dayString = this.dayOfWeekString[m]
}
}
return dayString;
}
/**
* get semua hari di persatu bulan,
*
*/
getAllDayOfMonth(){
let newDate = new Date(this.year,this.month + 1,0);
let lastDay = newDate.getDate();
let dayArray = [];
for (let index = 0; index < lastDay; index++) {
this.date = new Date(this.year,this.month,index + 1);
dayArray[index] = this.getDayString();
}
return dayArray;
}
/**
* get semua hari di persatu tahun,
*
*/
getAllDayOfYear(){
let monthObject = {};
let monthArray = [];
let dayArray = [];
for (let indexMonth = 0; indexMonth < this.monthOfYearString.length; indexMonth++) {
let newDate = new Date(this.year,indexMonth + 1,0);
let lastDay = newDate.getDate();
dayArray = [];
for (let index = 0; index < lastDay; index++) {
this.date = new Date(this.year,indexMonth,index + 1);
dayArray[index] = this.getDayString();
}
monthArray.push(dayArray);
Object.assign(monthObject,{[this.monthOfYearString[indexMonth]]:dayArray})
}
return {
array:monthArray,
object:monthObject
}
}
} |
JavaScript | class DrawingCanvas{
constructor(){
}
} |
JavaScript | class TextureVideo extends TextureInterface {
/**
* Constructor
*
* @param {string} path Path to the video file
*/
constructor(path = null) {
super();
/**
* Video.
* @type {HTMLVideoElement}
* @private
*/
this.data = document.createElement('video');
if (path) {
this.loadFromFile(path);
}
}
/**
* Load the video from a file
*
* @param {string} path Path to the video file
*/
loadFromFile(path) {
// Detect when video is ready
this.data.addEventListener('canplaythrough', () => {
this.ready = true;
}, true);
// Load
this.data.preload = 'auto';
this.data.crossOrigin = 'anonymous';
this.data.src = path;
this.data.muted = 'muted';
}
/**
* Pause the video
*/
pause() {
this.data.pause();
}
/**
* Play the video
*/
play() {
this.data.play();
}
/**
* Set video's playback speed
*
* @param {number} [value] 0.5 is half speed, 1.0 is normal speed, 2.0 is double speed
*/
setSpeed(value = 1.0) {
this.data.playbackRate = value;
}
/**
* Get video's duration
*
* @return {number} The duration property returns the length of the current audio/video, in seconds
*/
getDuration() {
return this.data.duration;
}
/**
* Get video's data
*
* @return {HTMLVideoElement} The HTML video element
*/
getVideoData() {
return this.data;
}
} |
JavaScript | class ArgumentChecker {
static notEmpty(arg, argName) {
if (!arg || arg instanceof Array && arg.length === 0) {
throw Errors.IgniteClientError.illegalArgumentError(Util.format('"%s" argument should not be empty', argName));
}
}
static notNull(arg, argName) {
if (arg === null || arg === undefined) {
throw Errors.IgniteClientError.illegalArgumentError(Util.format('"%s" argument should not be null', argName));
}
}
static hasType(arg, argName, isArray, ...types) {
if (arg === null) {
return;
}
if (isArray && arg instanceof Array) {
for (let a of arg) {
ArgumentChecker.hasType(a, argName, false, ...types);
}
}
else {
for (let type of types) {
if (arg instanceof type) {
return;
}
}
throw Errors.IgniteClientError.illegalArgumentError(Util.format('"%s" argument has incorrect type', argName));
}
}
static hasValueFrom(arg, argName, isArray, values) {
if (isArray && arg instanceof Array) {
for (let a of arg) {
ArgumentChecker.hasValueFrom(a, argName, false, values);
}
}
else {
if (!Object.values(values).includes(arg)) {
throw Errors.IgniteClientError.illegalArgumentError(Util.format('"%s" argument has incorrect value', argName));
}
}
}
static isInteger(arg, argName) {
if (arg === null || arg === undefined || !Number.isInteger(arg)) {
throw Errors.IgniteClientError.illegalArgumentError(Util.format('"%s" argument should be integer', argName));
}
}
static invalidArgument(arg, argName, type) {
if (arg !== null && arg !== undefined) {
throw Errors.IgniteClientError.illegalArgumentError(
Util.format('"%s" argument is invalid for %s', argName, type.constructor.name));
}
}
} |
JavaScript | class UADiscreteAlarmImpl extends ua_alarm_condition_impl_1.UAAlarmConditionImpl {
static instantiate(namespace, discreteAlarmTypeId, options, data) {
const addressSpace = namespace.addressSpace;
const discreteAlarmType = addressSpace.findEventType(discreteAlarmTypeId);
/* istanbul ignore next */
if (!discreteAlarmType) {
throw new Error(" cannot find Condition Type for " + discreteAlarmType);
}
const discreteAlarmTypeBase = addressSpace.findObjectType("DiscreteAlarmType");
(0, node_opcua_assert_1.assert)(discreteAlarmTypeBase, "expecting DiscreteAlarmType - please check you nodeset xml file!");
/* eventTypeNode should be subtypeOf("DiscreteAlarmType"); */
/* istanbul ignore next */
if (!discreteAlarmType.isSupertypeOf(discreteAlarmTypeBase)) {
throw new Error("UADiscreteAlarm.instantiate : event found is not subType of DiscreteAlarmType");
}
const alarmNode = ua_alarm_condition_impl_1.UAAlarmConditionImpl.instantiate(namespace, discreteAlarmType.nodeId, options, data);
Object.setPrototypeOf(alarmNode, UADiscreteAlarmImpl.prototype);
return alarmNode;
}
} |
JavaScript | class WordReader {
constructor(words) {
this.index = 0
this.words = words
}
read(n, pad) {
let response = []
let val = 0
for (let i = 0; i < n; i++) {
let wordIndex = Math.floor(this.index / 5)
let bitIndex = 4 - this.index % 5
let word = this.words[wordIndex]
let pow = (1 << (7 - i%8)) * (word >> bitIndex & 1)
val += pow
if(i%8==7) {
response.push(val)
val = 0
}
this.index++
}
if(pad) {
const bits = n % 8
if (bits > 0) {
response.push((this.words.slice(-1) << (8 - bits)) & 255)
}
}
return response
}
readInt(n) {
let val = 0
for (let i = 0; i < n; i++) {
let wordIndex = Math.floor(this.index / 5)
let bitIndex = 4 - this.index % 5
let word = this.words[wordIndex]
let pow = (1 << (n - i - 1)) * (word >> bitIndex & 1)
val += pow
this.index++
}
return val
}
readWords(n) {
let wordIndex = this.index / 5
this.index += n*5
return this.words.slice(wordIndex, wordIndex+n)
}
remaining() {
return 5 * this.words.length - this.index
}
} |
JavaScript | class GraphicEQHTMLElement extends HTMLElement {
// plugin = the same that is passed in the DSP part. It's the instance
// of the class that extends WebAudioModule. It's an Observable plugin
constructor(plugin) {
super();
this.root = this.attachShadow({ mode: 'open' });
this.root.innerHTML = `<style>${style}</style>${template}`;
// MANDATORY for the GUI to observe the plugin state
this.plugin = plugin;
this.setResources();
this.setKnobs();
this.setSwitchListener();
this.gridColor = "rgb(235,235,235)";
this.textColor = "rgb(235, 235, 235)";
this.nyquist = 0.5 * this.plugin.audioContext.sampleRate;
this.noctaves = 11;
this.setSwitchListener();
this.setCanvas();
this.draw();
window.requestAnimationFrame(this.handleAnimationFrame);
}
get properties() {
this.boundingRect = {
dataWidth: {
type: Number,
value: 480
},
dataHeight: {
type: Number,
value: 350
}
};
return this.boundingRect;
}
updateStatus = (status) => {
this.shadowRoot.querySelector('#switch1').value = status;
}
handleAnimationFrame = () => {
/*
const {
lowGain,
midLowGain,
midHighGain,
highGain,
enabled,
} = this.plugin.audioNode.getParamsValues();
this.shadowRoot.querySelector('#knob1').value = lowGain;
this.shadowRoot.querySelector('#knob2').value = midLowGain;
this.shadowRoot.querySelector('#knob3').value = midHighGain;
this.shadowRoot.querySelector('#knob4').value = highGain;
this.shadowRoot.querySelector('#switch1').value = enabled;
*/
this.draw();
window.requestAnimationFrame(this.handleAnimationFrame);
}
/**
* Change relative URLS to absolute URLs for CSS assets, webaudio controls spritesheets etc.
*/
setResources() {
// Setting up the switches imgs, those are loaded from the assets
this.root.querySelector("webaudio-switch").setAttribute('src', getAssetUrl(switchImg));
}
setKnobs() {
}
setSwitchListener() {
console.log("GraphicEQ : set switch listener");
const { plugin } = this;
// by default, plugin is disabled
plugin.audioNode.setParamsValues({ enabled: 1 });
this.shadowRoot
.querySelector('#switch1')
.addEventListener('change', function onChange() {
plugin.audioNode.setParamsValues({ enabled: +!!this.checked });
});
}
setCanvas() {
// canvas
this.canvas = document.createElement("canvas");
// get dimensions, by default the ones from the parent element
this.canvas.classList.add("graphicEQ");
this.canvas.width = this.width = 430;
this.canvas.height = this.height = 250;
this.canvas.style.position = "absolute";
this.ctx = this.canvas.getContext("2d");
this.canvasParent = this.root.querySelector("#DivFilterBank");
this.canvasParent.appendChild(this.canvas);
this.canvas2 = document.createElement("canvas");
this.canvas2.classList.add("frequencyMeasure");
this.canvas2.style.position = "relative";
this.canvas2.style.top = 0;
this.canvas2.style.left = 0;
this.canvas2.width = this.canvas.width;
this.canvas2.height = this.canvas.height;
this.canvas2.style.zIndex = -1;
this.canvasParent.appendChild(this.canvas2);
this.ctx2 = this.canvas2.getContext("2d");
this.dbScale = 60;
//TODO:
this.pixelsPerDb = (0.5 * this.height) / this.dbScale;
// listeners
this.canvas.addEventListener("mousemove", this.processMouseMove.bind(this));
this.canvas.addEventListener("mousedown", this.processMouseDown.bind(this));
this.canvas.addEventListener("mouseup", this.processMouseUp.bind(this));
requestAnimationFrame(this.drawFrequencies.bind(this));
this.canvas.addEventListener('mouseenter', this.setFocus, false);
this.canvas.addEventListener('mouseleave', this.unsetFocus, false);
/*window.addEventListener('resize',
(evt) => {
console.log("resize canvasParent:" + this.canvasParent.clientWidth + " " + this.canvasParent.clientHeight);
this.resize(this.canvasParent.clientWidth,
this.canvasParent.clientHeight);
});*/
}
setFocus(){
this.focus();
this.tabIndex=1;
}
unsetFocus(){
this.blur();
this.tabIndex=-1;
}
draw() {
let ctx = this.ctx;
ctx.save();
ctx.clearRect(0, 0, this.width, this.height);
this.sumCurveParallel = []; // curves of (x, y) pixels thats sums all filter curves
this.sumCurveSerie = [];
for (let x = 0; x < this.width; x++) {
this.sumCurveParallel[x] = 0;
this.sumCurveSerie[x] = 0;
}
this.plugin.audioNode.filters.forEach((filt) => {
this.drawFilterCurves(filt);
// draw control point
this.drawControlPoint(filt);
});
this.drawGrid();
if (this.plugin.audioNode.filters.length > 0) {
//this.drawSumOfAllFilterCurveParallel();
this.drawSumOfAllFilterCurveSerie();
}
if (this.mode === "dragControlPoint")
this.drawTooltip();
ctx.restore();
}
//TODO: how to manipulate this function about the zoom of pedalboard
resize(w, h) {
//console.log("resize");
let r = this.canvasParent.getBoundingClientRect();
let rc = this.canvas.getBoundingClientRect();
//this.canvas.width = this.width = this.canvasParent.clientWidth - (r.left + rc.left) / 2;
//this.canvas.height = this.height = this.canvasParent.clientHeight - (r.top + rc.top) / 2;
this.canvas.width = this.width =window.innerWidth;
this.canvas.heigth = this.height = window.innerHeight;
this.canvas2.width = this.canvas.width;
this.canvas2.height = this.canvas.height;
this.pixelsPerDb = (0.5 * this.height) / this.dbScale;
//this.clearCanvas();
this.draw();
}
drawFilterCurves(filt) {
let frequencyHz = new Float32Array(this.canvas.width);
let magResponse = new Float32Array(this.canvas.width);
let phaseResponse = new Float32Array(this.canvas.width);
let ctx = this.ctx;
ctx.save();
ctx.globalAlpha = 0.3
ctx.strokeStyle = "white";
ctx.fillStyle = filt.color;
ctx.lineWidth = 3;
ctx.beginPath();
ctx.moveTo(0, 0);
// First get response.
for (let i = 0; i < this.width; i++) {
let f = i / this.width;
// Convert to log frequency scale (octaves).
f = this.nyquist * Math.pow(2.0, this.noctaves * (f - 1.0));
frequencyHz[i] = f;
}
filt.getFrequencyResponse(frequencyHz, magResponse, phaseResponse);
/*
var magResponseOfFilter = new Float32Array(width);
filt.getFrequencyResponse(frequencyHz, magResponseOfFilter, phaseResponse);
// sum it to magResponse
for(var l = 0; l < width; l++) {
magResponse[l] = magResponseOfFilter[l];
}
*/
// Draw filters curves
for (let i = 0; i < this.width; i++) {
let f = magResponse[i];
let response = magResponse[i];
let dbResponse = 2 * (10.0 * Math.log(response) / Math.LN10);
let x = i;
let y = this.dbToY(dbResponse);
// curve that sums all filter responses
this.sumCurveParallel[x] += response;
this.sumCurveSerie[x] += dbResponse;
if (i === 0)
ctx.moveTo(x, y);
else
ctx.lineTo(x, y);
}
//ctx.lineTo(this.width, this.height);
ctx.lineTo(this.width, this.height / 2);
ctx.lineTo(0, this.height / 2);
ctx.fill();
//ctx.stroke();
ctx.restore();
}
drawControlPoint(filter) {
let q = filter.Q.value; // unit = db
let f = filter.frequency.value;
let gain = filter.gain.value;
let x, y;
//TODO: See this function to know X
x = this.fToX(f);
switch (filter.type) {
case "lowpass":
case "highpass":
y = this.dbToY(q);
break;
case "lowshelf":
case "highshelf":
y = this.dbToY(gain / 2);
break;
case "peaking":
y = this.dbToY(gain);
break;
case "notch":
case "bandpass":
if (q > 0.16) {
y = this.dbToY(q);
}
break;
}
filter.controlPoint = {
x: x,
y: y,
}
this.drawControlPointAsColoredCircle(x, y, filter.color)
}
drawControlPointAsColoredCircle(x, y, color) {
let ctx = this.ctx;
ctx.save();
ctx.fillStyle = color;
ctx.beginPath();
ctx.arc(x + 1, y, 5, 0, Math.PI * 2);
ctx.fill();
ctx.restore();
}
getFontSizeDependingOnWidth() {
return this.width / 45;
}
getFontSizeDependingOnHeight() {
return this.height / 35;
}
drawGrid() {
let ctx = this.ctx;
ctx.save();
let fontSize = this.getFontSizeDependingOnWidth();
ctx.beginPath();
ctx.lineWidth = 1;
ctx.font = "300 " + fontSize + 'px OpenSans, sans-serif';
// Draw frequency scale.
for (let octave = 0; (octave+1) <= this.noctaves; octave++) {
let x = octave * this.width / this.noctaves;
ctx.strokeStyle = this.gridColor;
ctx.moveTo(x, 30);
ctx.lineTo(x, this.height);
ctx.stroke();
let f = this.nyquist * Math.pow(2.0, octave - this.noctaves);
let value = f.toFixed(0);
let unit = 'Hz';
if (f > 1000) {
unit = 'KHz';
value = (f / 1000).toFixed(1);
}
ctx.textAlign = "center";
ctx.fillStyle = this.textColor;
if(octave !== 0)
ctx.fillText(value + unit, x, 20);
else
ctx.fillText(value + unit, 10, 20);
}
// Draw 0dB line.
fontSize = this.getFontSizeDependingOnHeight();
ctx.font = "300 " + fontSize + 'px OpenSans, sans-serif';
ctx.beginPath();
ctx.moveTo(0, 0.5 * this.height);
ctx.lineTo(this.width, 0.5 * this.height);
ctx.stroke();
// Draw decibel scale.
let dbIncrement = this.dbScale * 10 / 60;
for (let db = -this.dbScale; (db+dbIncrement) < this.dbScale; db += dbIncrement) {
let y = this.dbToY(db);
ctx.fillStyle = this.textColor;
ctx.fillText(db.toFixed(0) + "dB", this.width - this.width / 25, y-2);
ctx.strokeStyle = this.gridColor;
ctx.beginPath();
ctx.moveTo(0, y);
ctx.lineTo(this.width, y);
ctx.stroke();
}
ctx.restore();
}
drawSumOfAllFilterCurveSerie() {
//console.log("draw sum")
let ctx = this.ctx;
ctx.save();
ctx.strokeStyle = "white";
ctx.beginPath();
for (let x = 0; x < this.width; x++) {
//let y = this.dbToY(0) -
let dbResponse = this.sumCurveSerie[x];
let y = this.dbToY(dbResponse);
//drawControlPointAsColoredCircle(x, y, "red");
if (y !== NaN) {
if (x === 0)
ctx.moveTo(x, y);
else
ctx.lineTo(x, y);
}
//console.log("x = " + x + " y = " + y)
}
ctx.stroke();
ctx.restore();
}
map(value, istart, istop, ostart, ostop) {
return ostart + (ostop - ostart) * ((value - istart) / (istop - istart));
}
fToX(f) {
// logarithmic scale
var logf = Math.log2(f);
var logmaxf = Math.log2(this.nyquist); // 24Khz for 11 octaves at 48Khz
var logminf = Math.log2(10); // min freq value in our graphic
var x = this.map(logf, logminf, logmaxf, -this.width / 50, this.width);
return x;
}
dbToY(db) {
var y = (0.5 * this.height) - this.pixelsPerDb * db;
return y;
};
processMouseMove(e) {
this.mousePos = this.getMousePos(e);
e.stopPropagation();
//console.log(this.mousePos);
//console.log(this.canvasParent.clientWidth);
switch (this.mode) {
case "none":
// color each control point in red
this.plugin.audioNode.filters.forEach((f) => {
this.drawControlPointAsColoredCircle(f.controlPoint.x, f.controlPoint.y, f.color);
});
// if mouse close to a control point color it in green
if (this.selectedFilter = this.findClosestFilterControlPoint(this.mousePos.x, this.mousePos.y)) {
this.drawControlPointAsColoredCircle(this.selectedFilter.controlPoint.x, this.selectedFilter.controlPoint.y, "red");
}
break;
case "dragControlPoint":
this.dy = (this.clickedY - this.mousePos.y);
this.changeFilterParameters(this.selectedFilter, this.mousePos.x, this.mousePos.y, this.shiftPressed, this.dy);
break;
}
return false;
}
processMouseDown(e) {
e.stopPropagation();
if (this.selectedFilter) {
this.selectedFilter.originalQValue = this.selectedFilter.Q.value;
this.mode = "dragControlPoint";
this.shiftPressed = (e.shiftKey);
this.clickedY = this.getMousePos(e).y;
this.drawTooltip();
}
// console.log("mode=START DRAGGING");
}
processMouseUp(e) {
this.mode = "none";
this.selectedFilter = null;
this.shiftPressed = false;
this.dy = 0;
this.draw();
}
drawFrequencies() {
//clear the canvas
this.ctx2.clearRect(0, 0, this.canvas2.width, this.canvas2.height);
// Get analyser data
this.plugin.audioNode.analyser.getFloatFrequencyData(this.plugin.audioNode.dataArray);
var barWidth = [];
var barHeight;
var x = 0;
var analyserRange = this.plugin.audioNode.analyser.maxDecibels - this.plugin.audioNode.analyser.minDecibels;
// ration between analyser range and our range
var range = this.dbScale * 2;
var dbRatio = range / analyserRange;
for (var i = 0; i < this.plugin.audioNode.bufferLength; i++) {
// values are all negative
barHeight = this.dbToY(-this.plugin.audioNode.dataArray[i]);
barHeight *= dbRatio;
//this.ctx2.fillStyle = 'rgb(' + (barHeight+100) + ',0,0)';
this.ctx2.fillStyle = 'red';
barWidth[i] = (Math.log(i + 2) - Math.log(i + 1)) * this.canvas2.width / Math.log(this.plugin.audioNode.bufferLength - 80);
this.ctx2.fillRect(x, this.canvas2.height - barHeight, barWidth[i], barHeight);
// 2 is the number of pixels between bars
x += barWidth[i] + 1;
}
// call again the visualize function at 60 frames/s
requestAnimationFrame(this.drawFrequencies.bind(this));
}
getMousePos(e) {
let rect = this.canvas.getBoundingClientRect();
//console.log("cx= " + e.clientX + " lx= " + e.layerX);
let mouseX = e.clientX - rect.left;
let mouseY = e.clientY - rect.top;
return {
x: mouseX,
y: mouseY
}
}
findClosestFilterControlPoint(x, y) {
for (let i = 0; i < this.plugin.audioNode.filters.length; i++) {
let f = this.plugin.audioNode.filters[i];
let cp = f.controlPoint;
if (this.distance(x, y, cp.x, cp.y) < 5) {
// mouse cursor is over a control point
return f;
}
//console.log(x, y);
//console.log(cp.x, cp.y);
};
return null;
}
dyToQ(dy) {
let q;
if (dy < 0) {
q = this.map(dy, 0, -100, this.selectedFilter.originalQValue, 0.1);
} else {
q = this.map(dy, 0, 100, this.selectedFilter.originalQValue, 15);
}
return q;
}
distance(x1, y1, x2, y2) {
let dx = x1 - x2;
let dy = y1 - y2;
return Math.sqrt(dx * dx + dy * dy);
}
drawTooltip() {
if (this.mousePos === undefined) return;
let tooltipWidth = 50, tooltipHeight;
let displayQ = false, displayGain = false;
switch (this.selectedFilter.type) {
case "lowpass":
case "highpass":
case "bandpass":
case "notch":
displayQ = true;
displayGain = false;
tooltipHeight = 44;
break;
case "peaking":
displayQ = true;
displayGain = true;
tooltipHeight = 55;
break;
case "highshelf":
case "lowshelf":
displayQ = false;
displayGain = true;
tooltipHeight = 44;
break;
}
let ctx = this.ctx;
ctx.save();
if (this.mousePos.x < (this.canvas.width - tooltipWidth))
ctx.translate(this.mousePos.x, this.mousePos.y);
else
ctx.translate(this.mousePos.x - tooltipWidth, this.mousePos.y);
ctx.fillStyle = "rgba(200, 200, 200, 0.3)";
ctx.strokeStyle = "rgba(153, 153, 153)";
ctx.beginPath();
ctx.rect(10, 0, tooltipWidth, tooltipHeight);
ctx.fill();
ctx.stroke()
ctx.fillStyle = "rgba(255, 255, 255, 0.7)";
ctx.font = "11px OpenSans, sanserif";
let xText = 12;
ctx.fillText(this.selectedFilter.type, 15, xText);
xText += 13;
ctx.fillText(this.selectedFilter.frequency.value.toFixed(0) + "Hz", 15, xText);
xText += 13;
if (displayGain) {
ctx.fillText(this.selectedFilter.gain.value.toFixed(0) + "dB/Oct", 15, 38);
xText += 13;
}
if (displayQ)
ctx.fillText(this.selectedFilter.Q.value.toFixed(3), 15, xText);
ctx.restore();
}
changeFilterParameters(filter, x, y, shiftPressed, dy) {
// x = frequency, y = Db
let db = this.yToDb(y);
let f = this.xToF(x);
//console.log("f = " + f + " db = " + db);
const index = this.plugin.audioNode.filters.indexOf(filter);
this.plugin.audioNode.setParamValue(`${filter.type}_${index}_frequency`, f);
// filter.frequency.value = f;
switch (filter.type) {
case "lowpass":
case "highpass":
// Here important! Do not code with this.plugin.audioNode.Q = but instead use the exposed param names
// and setParamValue from CompositeAudioNode if you want getState/setState + automation to work
this.plugin.audioNode.setParamValue(`${filter.type}_${index}_Q`, db);
// filter.Q.value = db;
this.draw();
break;
case "lowshelf":
case "highshelf":
this.plugin.audioNode.setParamValue(`${filter.type}_${index}_gain`, 2 * db);
// filter.gain.value = 2 * db;
this.draw();
break;
case "peaking":
if (!shiftPressed)
this.plugin.audioNode.setParamValue(`${filter.type}_${index}_gain`, db);
// filter.gain.value = db;
else {
this.plugin.audioNode.setParamValue(`${filter.type}_${index}_Q`, this.dyToQ(dy));
// filter.Q.value = this.dyToQ(dy);
}
this.draw();
break;
case "notch":
if (!shiftPressed)
this.plugin.audioNode.setParamValue(`${filter.type}_${index}_gain`, db);
// filter.gain.value = db;
else {
this.plugin.audioNode.setParamValue(`${filter.type}_${index}_Q`, this.dyToQ(dy));
// filter.Q.value = this.dyToQ(dy);
}
this.draw();
break;
case "bandpass":
if (db >= 0.16)
this.plugin.audioNode.setParamValue(`${filter.type}_${index}_Q`, db);
// filter.Q.value = db;
this.draw();
break;
}
}
yToDb(y) {
var db = ((0.5 * this.height) - y) / this.pixelsPerDb;
return db;
};
xToF(x) {
// x corresponds to a freq in log scale
// logarithmic scale
var logmaxf = Math.log2(this.nyquist); // 24Khz for 11 octaves at 48Khz
var logminf = Math.log2(10); // min freq value in our graphic
var flog = this.map(x, -this.width / 50, this.width, logminf, logmaxf);
return Math.pow(2, flog); // reverse of a log function is 2^logf
}
/*
bypass() {
this.plugin.params.state = "disable";
this.plugin.audioNode.connectNodes();
}
reactivate() {
this.plugin.params.state = "enable";
this.plugin.audioNode.connectNodes();
}
*/
letDrag() {
this.root.querySelector("#DivFilterBank").draggable = true;
}
// name of the custom HTML element associated
// with the plugin. Will appear in the DOM if
// the plugin is visible
static is() {
return 'wasabi-graphic-eq';
}
} |
JavaScript | class MyTimer extends group_1.MyGroup {
constructor() {
super(...arguments);
// vars
this.nameList = [];
this.resultsList = [];
this.slackUrl = secrets_1.SLACK_HOOK_URL;
// initialize timerdata
this.timerData = {
startTime: 0,
endTime: 0,
min: 0,
sec: 0,
name: this.nameList[0],
index: 0,
html: "",
totals: {}
};
}
setStartTime() {
this.timerData.startTime = this.getTime();
// console.log("Set Start Time");
// console.log(this.timerData);
}
setStopTime() {
if (this.timerData.endTime == 0) {
this.timerData.endTime = this.getTime();
this.elapsedTime(this.timerData.startTime, this.timerData.endTime);
this.timerData.totals = this.setTotals(this.timerData.name, this.timerData.min, this.timerData.sec);
// console.log("Set Stop Time");
// console.log(this.timerData);
}
}
setUser(inc) {
this.timerData.name = this.nameList[inc];
this.timerData.index = inc;
// console.log("Set User");
// console.log(this.timerData);
}
setTotals(user, min, sec) {
// min, sec, and name all to a single string -
const minSec = min + ":" + sec;
const fullTotal = user + " " + minSec;
this.resultsList.push(fullTotal);
// console.log("Set Totals");
// console.log(this.timerData);
return this.resultsList;
}
skip(nameToSkip) {
Object.defineProperty(this.timerData.totals, nameToSkip, { value: 0 });
}
// This resets the timer and group order
nextUser(cnt) {
this.resetTimer();
// get length for the names array : minus one to offset index vs length
const endIng = this.nameList.length - 1;
// console.log("Get Next User");
// check if array length vs current position in user list
const inc = cnt + 1;
if (inc > endIng) {
// this.timerData.name = this.nameList[0];
this.timerData.name = "Open";
// this.timerData.index = 0;
// console.log(this.timerData.index + " " + this.timerData.name);
}
else {
this.timerData.name = this.nameList[inc];
this.timerData.index = inc;
// console.log(this.timerData.index + " " + this.timerData.name);
}
// console.log(this.timerData);
}
getTime() {
// console.log("Get Time");
// console.log(this.timerData);
return Date.now();
}
returnTimerData() {
// console.log("Return Timer Data");
// console.log(this.timerData);
// possibly use app.locals.siteDate
return this.timerData;
}
// get's start/end time difference in ms
// formats to get from ms to mm and s.sssssss
elapsedTime(startedAt, stoppedAt) {
const diff = stoppedAt - startedAt;
this.timerData.min = this.formatMinSec(diff).minutes;
this.timerData.sec = this.formatMinSec(diff).seconds;
// console.log("Get Elapsed Time");
// console.log(this.timerData);
}
// converts ms to combined min sec
formatMinSec(ms) {
const sec = Math.floor((ms / 1000) % 60);
// const secCalc = (ms / 1000) % 60;
const min = ((ms / 1000) - ((ms / 1000) % 60)) / 60;
// const sec = Math.trunc(secCalc * Math.pow(10, 3)) / 100;
const results = { seconds: sec, minutes: 0 };
if (min < 1) {
results.minutes = 0;
}
else {
results.minutes = min;
}
// console.log("Formatting Time");
// console.log(this.timerData);
return results;
}
// Clear times and user only
resetTimer() {
this.timerData.startTime = 0;
this.timerData.endTime = 0;
this.timerData.min = 0;
this.timerData.sec = 0;
// this.setUser(0);
// console.log("Reset Timer");
// console.log(this.timerData);
}
// reset name needs to be called seperate of resettimer
resetName() {
this.nameList = this.getNames();
// this.nameList.push("Open");
// console.log(this.nameList);
this.setUser(0);
}
// clear result totals only
resetResults() {
this.timerData.totals = {};
// this.timerData.totals = 0;
this.resultsList = [];
// console.log("Reset Results");
// console.log(this.timerData);
}
// post a web hook/request to slack channel - sending the time totals
copyToSlack(data) {
const body = {
"channel": "#dev-team",
"username": "Standup_Times",
"text": data,
"icon_url": "https://pbs.twimg.com/profile_images/76277472/bender.jpg"
};
// console.log("Send to Slack");
// console.log(this.timerData);
request_1.default({
url: "https://hooks.slack.com/services/" + this.slackUrl,
method: "POST",
json: true,
body: body,
headers: {
"content-type": "application/json",
}
}, function (err, resp, body) {
if (err) {
// console.log(err, err.stack);
}
else {
// console.log(resp.statusCode);
// console.log(resp.statusMessage);
// console.log(body);
}
});
}
} |
JavaScript | class UsersForm extends Component {
constructor() {
super();
this.state = {
password: null,
BareUsersForm: Components.Loading,
};
}
storePassword = data => {
this.setState({ password: data._password });
};
setPassword = ({ _id }) => {
Meteor.call(
"users.setPassword",
{
_id,
password: this.state.password
},
(err, res) => {
if (err) {
toast.error("Impossible de mettre à jour le mot de passe");
} else {
toast.success("Mot de passe mis à jour");
}
}
);
};
componentDidMount() {
if (BareUsersFormOriginal === null) {
BareUsersFormOriginal = getComponent('UsersForm');
if (!BareUsersForm) throw new Error('Error: UsersForm component is not defined. vulcan:users-manager needs a backoffice to be set using vulcan:backoffice-builder.');
}
this.setState({ BareUsersForm: BareUsersFormOriginal });
}
render() {
// TODO: setup callbacks
const { BareUsersForm } = this.state;
return (
<BareUsersForm
submitCallback={this.storePassword}
successCallback={this.setPassword}
// enhance the schema with a dummy password field
// that is not stored in the db
//schema={{
// _password: {
// type: String,
// label: "Password",
// optional: true,
// canRead: [],
// canCreate: ["admins"],
// canUpdate: ["admins"],
// //onCreate: ({ newDocument, currentUser }) => {
// // delete newDocument._password; // not sure if needed
// // return ""; // SHOULD NEVER BE ACTUALLY STORED
// //},
// inputProperties: {
// type: "password"
// }
// //min: Accounts.ui._options.minimumPasswordLength
// }
//}}
{...this.props}
/>
);
}
} |
JavaScript | class IndefiniteObservable {
/**
* The provided function should receive an observer and connect that
* observer's `next` method to an event source (for instance,
* `element.addEventListener('click', observer.next)`).
*
* It must return a function that will disconnect the observer from the event
* source.
*/
constructor(connect) {
this._connect = connect;
}
/**
* `subscribe` uses the function supplied to the constructor to connect an
* observer to an event source. Each observer is connected independently:
* each call to `subscribe` calls `connect` with the new observer.
*
* To disconnect the observer from the event source, call `unsubscribe` on the
* returned subscription.
*
* Note: `subscribe` accepts either a function or an object with a
* next method.
*/
subscribe(observerOrNext) {
const observer = _wrapWithObserver(observerOrNext);
let disconnect = this._connect(observer);
return {
unsubscribe() {
if (disconnect) {
disconnect();
disconnect = undefined;
}
}
};
}
/**
* Tells other libraries that know about observables that we are one.
*
* https://github.com/tc39/proposal-observable#observable
*/
[$observable]() {
return this;
}
} |
JavaScript | class SimpleColorsSharedStyles extends LitElement{// render function
render(){return html`
<style>
:host {
display: block; }
:host([hidden]) {
display: none; }
</style>
<slot></slot>`}// properties available to the custom element for data binding
static get properties(){return{}}/**
* Store the tag name to make it easier to obtain directly.
* @notice function name must be here for tooling to operate correctly
*/tag(){return"simple-colors-shared-styles"}// life cycle
constructor(){super();this.tag=SimpleColorsSharedStyles.tag;// map our imported properties json to real props on the element
// @notice static getter of properties is built via tooling
// to edit modify src/simple-colors-shared-styles-properties.json
let obj=SimpleColorsSharedStyles.properties;for(let p in obj){if(obj.hasOwnProperty(p)){if(this.hasAttribute(p)){this[p]=this.getAttribute(p)}else{this.setAttribute(p,obj[p].value);this[p]=obj[p].value}}}}/**
* life cycle, element is afixed to the DOM
*/connectedCallback(){super.connectedCallback()}// static get observedAttributes() {
// return [];
// }
// disconnectedCallback() {}
// attributeChangedCallback(attr, oldValue, newValue) {}
} |
JavaScript | class MatchApi {
// #
// #
// ### ## ###
// # # # ## #
// ## ## #
// # ## ##
// ###
/**
* Processes the request.
* @param {Express.Request} req The request.
* @param {Express.Response} res The response.
* @returns {Promise} A promise that resolves when the request is complete.
*/
static async get(req, res) {
return res.json(await Match.getBySeason(req.query.season, req.query.page));
}
} |
JavaScript | class AddDeckView extends Component {
state = {
text: ''
}
handleTextChange = (input) => {
this.setState(() => ({
text: input
}))
}
createDeck = () => {
const deck = this.state.text
if (deck === '') {
Alert.alert('Deck name must have a value')
} else {
this.props.dispatch(addDeck({
deck
}))
saveDeckTitle(deck)
this.setState(() => ({
text: ''
}))
this.props.navigation.navigate(
'DeckView',
{ deck }
)
}
}
render() {
const { text } = this.state
return (
<KeyboardAvoidingView behavior='padding' style={styles.container}>
<Text style={{ fontSize: 20 }}>What is the title of your deck?</Text>
<TextInput
style={styles.deckNameInput}
value={text}
onChangeText={this.handleTextChange}
placeholder='Deck name'
/>
<CreateDeckBtn
onPress={this.createDeck}
/>
</KeyboardAvoidingView>
)
}
} |
JavaScript | class Suffix extends Component {
render() {
const html = { __html: this.props.source }
return (
<p className={this.props.className} dangerouslySetInnerHTML={html} />
)
}
} |
JavaScript | class Schema {
/**
* @method createUserSchema
* @description Validates the user object from a post request
* @param {object} user - The user object to be validated
* @returns {object} An object specifying weather the input was valid or not.
*/
static createUserSchema(user) {
const schema = {
firstName: Joi.string().lowercase().trim().required()
.regex(/^[a-zA-Z]+$/)
.error((errors) => {
errors.forEach((err) => {
switch (err.type) {
case 'string.regex.base':
err.message = 'firstName can only contain letters';
break;
default:
break;
}
});
return errors;
}),
lastName: Joi.string().lowercase().trim().required()
.regex(/^[a-zA-Z]+$/)
.error((errors) => {
errors.forEach((err) => {
switch (err.type) {
case 'string.regex.base':
err.message = 'lastName can only contain letters';
break;
default:
break;
}
});
return errors;
}),
email: Joi.string().trim().lowercase().email({ minDomainAtoms: 2 })
.required(),
password: Joi.string().min(8).required(),
};
return Joi.validate(user, schema, { abortEarly: false });
}
/**
* @method superUserSchema
* @description Validates the user object from a post request
* @param {object} user - The user object to be validated
* @returns {object} An object specifying weather the input was valid or not.
*/
static superUserSchema(user) {
const schema = {
firstName: Joi.string().lowercase().trim().required()
.regex(/^[a-zA-Z]+$/)
.error((errors) => {
errors.forEach((err) => {
switch (err.type) {
case 'string.regex.base':
err.message = 'firstName can only contain letters';
break;
default:
break;
}
});
return errors;
}),
lastName: Joi.string().lowercase().trim().required()
.regex(/^[a-zA-Z]+$/)
.error((errors) => {
errors.forEach((err) => {
switch (err.type) {
case 'string.regex.base':
err.message = 'lastName can only contain letters';
break;
default:
break;
}
});
return errors;
}),
email: Joi.string().trim().lowercase().email({ minDomainAtoms: 2 })
.required(),
password: Joi.string().min(8).required(),
isAdmin: Joi.boolean().required(),
};
return Joi.validate(user, schema, { abortEarly: false });
}
/**
* @method loginSchema
* @description Validates the login details from a post request
* @param {object} login - The login object to be validated
* @returns {object} An object specifying weather the input was valid or not.
*/
static loginSchema(login) {
const schema = {
email: Joi.string().trim().lowercase().email({ minDomainAtoms: 2 })
.required(),
password: Joi.string().min(8).required(),
};
return Joi.validate(login, schema, { abortEarly: false });
}
/**
* @method createAccountSchema
* @description Validates the account details from a post request
* @param {object} account - The account object to be validated
* @returns {object} An object specifying weather the input was valid or not.
*/
static createAccountSchema(account) {
const schema = {
type: Joi.string().trim().lowercase().valid('savings', 'current', 'loan')
.required(),
initialDeposit: Joi.number().min(5000).required(),
};
return Joi.validate(account, schema, { abortEarly: false });
}
/**
* @method editAccountSchema
* @description Validates the account status from a patch request
* @param {object} account - The account object to be validated
* @returns {object} An object specifying weather the input was valid or not.
*/
static editAccountSchema(account) {
const schema = {
status: Joi.string().trim().lowercase().valid('active', 'dormant')
.required(),
};
return Joi.validate(account, schema, { abortEarly: false });
}
/**
* @method transactionSchema
* @description Validates the amount from a post request
* @param {object} amount - The figure to be validated
* @returns {object} An object specifying weather the input was valid or not.
*/
static transactionSchema(amount) {
const schema = {
amount: Joi.number().positive().required()
.error((errors) => {
errors.forEach((err) => {
switch (err.type) {
case 'number.positive':
err.message = 'Invalid amount';
break;
default:
break;
}
});
return errors;
}),
};
return Joi.validate(amount, schema, { abortEarly: false });
}
/**
* @method accountSchema
* @description Validates account numbers from the req.params object
* @param {integer} accountNumber - The account number to be validated
* @returns {object} An object specifying weather the input was valid or not.
*/
static accountSchema(accountNumber) {
const schema = {
accountNumber: Joi.string().required()
.regex(/^[0-9]{10}$/)
.error((errors) => {
errors.forEach((err) => {
switch (err.type) {
case 'string.regex.base':
err.message = 'Invalid account number, please provide a valid account number (10 digit integer)';
break;
default:
break;
}
});
return errors;
}),
};
const value = {
accountNumber,
};
return Joi.validate(value, schema, { abortEarly: false });
}
/**
* @method idSchema
* @description Validates ids from the req.params object
* @param {integer} id - The id to be validated
* @returns {object} An object specifying weather the input was valid or not.
*/
static idSchema(id) {
const schema = {
id: Joi.string().required()
.regex(/^[1-9][0-9]*$/)
.error((errors) => {
errors.forEach((err) => {
switch (err.type) {
case 'string.regex.base':
err.message = 'Invalid ID, please provide a valid id (digit from 1 and above)';
break;
default:
break;
}
});
return errors;
}),
};
const value = {
id,
};
return Joi.validate(value, schema, { abortEarly: false });
}
/**
* @method emailSchema
* @description Validates email addresses from the req.params object
* @param {string} email - The email to be validated
* @returns {object} An object specifying weather the input was valid or not.
*/
static emailSchema(email) {
const schema = {
email: Joi.string().trim().lowercase().email({ minDomainAtoms: 2 })
.required(),
};
const value = {
email,
};
return Joi.validate(value, schema, { abortEarly: false });
}
/**
* @method querySchema
* @description the query from the req.query object
* @param {string} query - The query object to be validated
* @returns {object} An object specifying weather the input was valid or not.
*/
static querySchema(query) {
const schema = {
status: Joi.string().trim().lowercase().valid('active', 'dormant', 'draft'),
};
return Joi.validate(query, schema, { abortEarly: true });
}
} |
JavaScript | class IconBoxTable extends React.Component {
actionFirst = (boxes) => {
const action = boxes.filter((item) =>
item.title.toLowerCase().includes("action")
)[0];
if (action) {
var rest = boxes.filter((item) => item.title !== action.title);
var newB = [action, ...rest];
return newB;
}
return boxes;
};
renderBoxes(boxes) {
// for now we won't want to do this because of issue:
// https://github.com/massenergize/frontend-admin/issues/226
// boxes = this.actionFirst(boxes);
if (!boxes) {
return <div>No Icon Boxes to Display</div>;
}
return Object.keys(boxes).map((key, index) => {
var box = boxes[key];
var iconLink = `${this.props.prefix}/${box.link}`.replace('//', '/')
if (box.link.startsWith("http")) {
iconLink = box.link
}
return (
<div
className="col-lg-3 col-6 d-flex flex-row"
key={index}
>
<IconBox
key={index}
title={box.title}
description={box.description}
icon={box.icon}
link={iconLink}
/>
</div>
);
});
}
render() {
const boxes = this.props.boxes;
return (
<section className="service mob-icon-white-fix pc-icon-div-container-fix">
<div className="container">
<div className="section-title center ">
{/* <h4 className="phone-vanish text-white cool-font m-service-title" >{boxes.length ===0?'': this.props.title}</h4> */}
</div>
<div className="row d-flex flex-row">{this.renderBoxes(boxes)}</div>
</div>
</section>
);
}
} |
JavaScript | class Handler {
constructor(props) {
if(!props.name) {
throw new Error("Missing handler name in properties");
}
this.name = props.name;
[
'init',
'newBlock',
'purgeBlock'
].forEach(fn=>this[fn]=this[fn].bind(this));
}
/**
* Initialize the handler with the given context resources
*
* @param {context containing shared resources for all handlers} ctx
* @param {function to invoke next handler} next
*/
async init(ctx, next) {
return next();
}
/**
* Process a new block
*
* @param {context containing shared resources} ctx
* @param {new block to process} block
* @param {function to invoke next handler} next
* @param {function to reject current block and not call downstream handlers} reject
*/
async newBlock(ctx, block, next, reject) {
return next();
}
/**
* During pipeline processing, it is inevitable that state will be preserved somewhere.
* In these cases, it's useful to be able to purge that state when the system decides
* that some threshold of persistence has been met. This function allows all handlers
* to remove any persisted state about the given blocks.
*
* @param {context contianing shared resources} ctx
* @param {block to purge} block
* @param {function to invoke next handler} next
* @param {function to reject removal of current block and not call downstream handlers} reject
*/
async purgeBlock(ctx, block, next, reject) {
return next();
}
} |
JavaScript | class ValueColormaker extends Colormaker {
constructor(params) {
super(params);
this.valueScale = this.getScale();
}
/**
* return the color for a volume cell
* @param {Integer} index - volume cell index
* @return {Integer} hex cell color
*/
volumeColor(index) {
return this.valueScale(this.parameters.volume.data[index]); // TODO
}
} |
JavaScript | class ServoController {
constructor() {
this.active = false;
this.servoUpdateHandler = (angle0, angle1) => {throw "Cannot set servo before handler is attached"};
this.goalOrientation = {x: undefined, y: undefined, z: undefined};
this.currentOrientation = {x: undefined, y: undefined, z: undefined};
this.panLimits = {
center: 80,
min: 30,
max: 129
};
this.tiltLimits = {
center: 73,
min: 30,
max: 105
};
this.servoStretching = 0.55;
}
onServoUpdate(callback) {
this.servoUpdateHandler = callback;
this.setGoal({x: 0, y: 0});
}
setGoal(orientation) {
function mod180(x) {
while (x >= 180) {
x -= 360;
}
while (x < -180) {
x += 360;
}
return x;
}
function limitTo(x, min, max) {
if (x > max) {
return max;
}
else if (x < min) {
return min;
}
return x;
}
this.goalOrientation = {
x: mod180(orientation.x),
y: mod180(orientation.y)
}
let panAngle = limitTo(this.panLimits.center - (this.goalOrientation.y) * this.servoStretching, this.panLimits.min, this.panLimits.max);
let tiltAngle = limitTo(this.tiltLimits.center + (this.goalOrientation.x) * this.servoStretching, this.tiltLimits.min, this.tiltLimits.max);
this._setServos(panAngle, tiltAngle);
// console.log(`Goal: ${Math.round(this.goalOrientation.y)}, ${Math.round(this.goalOrientation.x)} | Servos: ${Math.round(panAngle)}, ${Math.round(tiltAngle)}`);
}
setState(angle0, angle1) {
this.currentOrientation = {
x: angle1,
y: angle0,
z: 0
};
}
_setServos(angle0, angle1) {
// Convert to int, then send to device
this.servoUpdateHandler(Math.round(angle0), Math.round(angle1));
}
} |
JavaScript | class Model extends EventEmitter {
/**
* Create a new model instance
* @example
* const model = new Model({
* folder: 'path/to/model'
* })
*
* @constructor
* @param {ModelConstructorOptions} options
*/
constructor({
folder = defaults.folder,
rules = null
} = {}) {
super()
this.folder = path.resolve(folder, '.file')
this.filename = '_m_.json'
this.metaFile = path.resolve(folder, this.filename)
this.meta = null
this.isNew = false
this.rules = rules
this.__init()
}
__init() {
// Create folder if not existed
fs2.ensureDirSync(this.folder)
// Load meta data if existed
this.meta = fs2.pathExistsSync(this.metaFile) && fs2.readJsonSync(this.metaFile)
if (!this.meta) {
this.meta = defaultMeta()
this.isNew = true
this.__save_meta_file()
} else {
// Migrated data of older version to folder .file
// TODO
}
}
__save_meta_file() {
if (!this.meta || !this.metaFile) throw new TypeError('Model not yet initialized')
this.meta.version = (new Date()).toISOString()
fs2.outputJsonSync(this.metaFile, this.meta)
}
__key_validator(key) {
if (typeof key !== 'string') return false
const keys = [
'_m_',
'_s_',
'model',
'schema',
path.basename(this.filename, '.json')
]
return /^[\w\-]+$/i.test(key) && !keys.includes(key.toLowerCase().trim())
}
__key__(key) {
if (!this.__key_validator(key)) throw new TypeError(`Invalid Key: ${key}`)
return key.toLowerCase().trim()
}
__get_file_path(key) {
return path.resolve(this.folder, `${this.__key__(key)}.json`)
}
/**
* Check existence of a model with specific key.
* @example
* const model = new Model()
* model.on('missed', key => console.log(`${key} is missing`))
* model.has('test')
*
* @param {string} key
* @param {ModelHasOptions} options
*
* @returns {boolean}
*/
has(key, {
event = true
} = {}) {
if (!this.meta) throw new Error('Model not yet initialized')
key = this.__key__(key)
const exists = this.meta.total > 0 && this.meta.data && !!this.meta.data[key] || false
if (!exists && event) this.emit('missed', key)
return exists
}
/**
* Get count of the objects
* @example
* const model = new Model()
* console.log(model.count())
*
* @returns {int}
*/
count() {
return this.meta && this.meta.total || 0
}
/**
* Get all keys of the objects
* @example
* const model = new Model()
* console.log(model.keys())
*
* @returns {Array}
*/
keys() {
const data = this.meta && this.meta.data || {}
return Object.keys(data)
}
/**
* Get version of the model
* @example
* const model = new Model()
* console.log(model.version())
*
* @returns {string}
*/
version() {
return this.meta && this.meta.version || (new Date()).toISOString()
}
/**
* Get object with specific key, null will be returned if object not existed
* @example
* const model = new Model()
* model.on('error', (func, err, { key } = {}) => console.log(func, key, err))
* const data = model.get('key1')
* console.log(data)
*
* @param {string} key - ID of an object
* @param {ModelGetOptions} options
*
* @returns {object | null}
*/
get(key, {
event = true,
housekeep = false
} = {}) {
const __funcname = 'get'
let data = null
try {
key = this.__key__(key)
const file = this.__get_file_path(key)
if (this.has(key, { event })) {
data = fs2.pathExistsSync(file) && fs2.readJsonSync(file) || null
} else if (housekeep && fs2.pathExistsSync(file)) {
this.del(key, { event: false, real: true })
}
} catch (error) {
if (event) {
this.emit('error', error, { method: __funcname, key })
} else {
throw new Error(error && error.message || 'Fatal Error')
}
}
return data
}
/**
* Delete object with specific key
* @example
* const model = new Model()
* model.on('deleted', (key, data) => console.log('deleted', key, data))
* model.on('error', (func, err, { key } = {}) => console.log(func, key, err))
* model.del('key1')
*
* @param {string} key - ID of an object
* @param {ModelDelOptions} options
*/
del(key, {
event = true,
real = true
} = {}) {
const __funcname = 'del'
try {
key = this.__key__(key)
const file = this.__get_file_path(key)
// Update meta
if (this.has(key, { event })) {
delete this.meta.data[key]
this.meta.total--
this.__save_meta_file()
}
// Delete file
if (real && fs2.pathExistsSync(file)) {
const data = fs2.readJsonSync(file)
if (event) {
fs2.removeSync(file)
this.emit('deleted', key, data)
} else {
fs2.removeSync(file)
return { key, data }
}
} else {
if (event) {
this.emit('deleted', key, null)
} else {
return { key }
}
}
} catch (error) {
if (event) {
this.emit('error', error, { method: __funcname, key })
} else {
throw new Error(error && error.message || 'Fatal Error')
}
}
}
/**
* Create of update an object with specific key
* @example
* const model = new Model()
* model.on('error', (func, err, { key, value, index } = {}) => console.log(func, key, err, value, index))
* model.on('set', (key, value, index, old) => console.log(key, value, index, old))
* model.set('key1', { name: 'Ben' })
*
* @param {string} key - ID of an object
* @param {object} value - Data to be saved in the JSON file
* @param {object | undefined} index - Data to be saved in meta
* @param {ModelSetOptions} options
*/
set(key, value = {}, index = undefined, {
override = true,
event = true,
saveMeta = true,
rules,
promise = false,
callback
} = {}) {
const __funcname = 'set'
try {
key = this.__key__(key)
const file = this.__get_file_path(key)
const isNew = !this.has(key, { event})
const old = !isNew && fs2.pathExistsSync(file) && fs2.readJsonSync(file) || null
// Save file
let data = Object.assign({
createdAt: old && old.createdAt || Date.now()
}, value, {
updatedAt: Date.now()
})
if (!override && old) data = Object.assign({}, old, value, {
updatedAt: Date.now()
})
if (isNew) data.createdAt = data.updatedAt
const save = () => {
fs2.outputJsonSync(file, data)
// Update meta
if (isNew) {
this.meta.data[key] = index || { id: key }
this.meta.total++
if (saveMeta) this.__save_meta_file()
} else if (!!index) {
this.meta.data[key] = index
if (saveMeta) this.__save_meta_file()
}
if (event) this.emit('set', key, value, index, old)
if (callback) callback(null, data)
}
if (rules || this.rules) {
const validator = new ValidateSchema(rules || this.rules)
if (promise) {
return new Promise((resolve, reject) => {
validator.validate(data).then(() => {
save()
resolve(data)
}).catch(reject)
})
} else {
validator.validate(data).then(() => {
save()
}).catch((errors, fields) => {
if (callback) {
callback(errors)
} else {
throw new Error('test')
}
})
}
} else {
if (promise) {
return new Promise((resolve, reject) => {
try {
save()
resolve(data)
} catch (error) {
reject(error)
}
})
} else {
save()
}
}
} catch (error) {
if (event) {
this.emit('error', error, { method: __funcname, key, value, index })
} else {
throw new Error(error && error.message || 'Fatal Error')
}
}
}
/**
* Get the first object which the comparator returns true
* @example
* const model = new Model()
* const data = model.find(item => item.id === 'key1')
* console.log(data)
*
* @param {function} comparator
*
* @returns {ModelFindReturns | null}
*/
find(comparator = (obj) => { return false }, {
loadData = true
} = {}) {
let result = null
if (this.meta && this.meta.data) {
for (const [key, index = {}] of Object.entries(this.meta.data)) {
const file = this.__get_file_path(key)
if (comparator(index)) {
const data = loadData && fs2.pathExistsSync(file) && fs2.readJsonSync(file) || undefined
result = { id: key, data, options: index }
break
}
}
}
return result
}
/**
* Get all objects which the comparator returns true
* @example
* const model = new Model()
* const data = model.findAll(item => item.role === 'admin')
* console.log(data)
*
* @param {function} comparator
* @param {PaginateOptions} options
*
* @returns {ModelFindReturns[]}
*/
findAll(comparator = (obj) => { return true }, {
offset = 0,
limit = 0
} = {}) {
if (!this.meta) throw new Error('Model not yet initialized')
offset = parseInt(offset) || 0
limit = parseInt(limit) || 0
const result = []
let match = 0
let valid = 0
for (const [key, index = {}] of Object.entries(this.meta.data || {})) {
const file = this.__get_file_path(key)
if (comparator(index)) {
match += 1
if (match > offset) {
const data = fs2.pathExistsSync(file) && fs2.readJsonSync(file) || null
if (data) {
result.push({ id: key, data, options: index })
valid += 1
if (limit > 0 && valid === limit) break
}
}
}
}
return result
}
/**
* Bulk create or update objects
* @example
* const model = new Model()
* model.mset({
* 'key1': {
* value: { id: 'key1' }
* },
* 'key2': {
* value: { id: 'key2', name: 'Ben', role: 'admin' }
* index: { role: 'admin' }
* }
* })
*
* @param {object} data
* @param {ModelSetOptions} options
*/
mset(data, {
override = true,
event = true,
saveMeta = true
} = {}) {
const __funcname = 'mset'
const debug = CreateLogger(`${__logname}:${__funcname}`)
try {
if (!data || Array.isArray(data) || typeof data !== 'object') throw new TypeError('Invalid Data')
for (const [id, { value = {}, index = { id }}] of Object.entries(data)) {
this.set(id, value, index, {
override,
saveMeta: false,
event: false
})
}
if (saveMeta) this.__save_meta_file()
} catch (error) {
debug(`Error occurred, message: ${error && error.message}`)
if (event) {
this.emit('error', error, { method: __funcname, data })
} else {
throw new Error(error && error.message || 'Fatal Error')
}
}
}
/**
* Delete all objects
* @example
* const model = new Model()
* model.delAll()
*
* @param {ModelDelOptions} options
*/
delAll({
event = true,
real = true
} = {}) {
if (!this.meta) throw new Error('Model not yet initialized')
if (real) {
Object.keys(this.meta.data).forEach(key => this.del(key, { event, real }))
} else {
this.meta = defaultMeta()
this.__save_meta_file()
}
}
} |
JavaScript | class MasterEndpoint extends NodeMultiCoreCPUBase.MasterEndpoint
{
constructor(classReverseCallsClient)
{
console.log(`Fired up cluster ${cluster.isWorker ? "worker" : "master"} with PID ${process.pid}`);
if(!cluster.isMaster)
{
throw new Error("MasterEndpoint can only be instantiated in the master process.");
}
super(classReverseCallsClient);
}
async _configureBeforeStart()
{
cluster.on(
"fork",
async (worker) => {
try
{
this.objWorkerIDToState[worker.id] = {
client: null,
ready: false
};
console.log("Adding worker ID " + worker.id + " to BidirectionalWorkerRouter.");
const nConnectionID = await this._bidirectionalWorkerRouter.addWorker(worker, /*strEndpointPath*/ this.path, 120 * 1000 /*Readiness timeout in milliseconds*/);
this.objWorkerIDToState[worker.id].client = this._bidirectionalWorkerRouter.connectionIDToSingletonClient(nConnectionID, this.ReverseCallsClientClass);
this.emit("workerReady", this.objWorkerIDToState[worker.id].client);
}
catch(error)
{
console.error(error);
console.error("Cluster master process, on fork event handler unexpected error. Don't know how to handle.");
process.exit(1);
}
}
);
cluster.on(
"exit",
async (worker, nExitCode, nKillSignal) => {
try
{
console.log(`Worker with PID ${worker.process.pid} died. Exit code: ${nExitCode}. Signal: ${nKillSignal}.`);
this.arrFailureTimestamps.push(new Date().getTime());
this.arrFailureTimestamps = this.arrFailureTimestamps.filter((nMillisecondsUnixTime) => {
return nMillisecondsUnixTime >= new Date().getTime() - (60 * 2 * 1000);
});
if(this.arrFailureTimestamps.length / Math.max(os.cpus().length, 1) > 4)
{
await this.gracefulExit(null);
}
else
{
if(!this.bShuttingDown)
{
await sleep(500);
cluster.fork();
}
}
}
catch(error)
{
console.error(error);
console.error("Cluster master process, on worker exit event handler unexpected error. Don't know how to handle. Exiting...");
process.exit(1);
}
}
);
}
async _addWorker()
{
cluster.fork();
}
/**
* @param {JSONRPC.Client} reverseCallsClient
*
* @returns {{plugin:JSONRPC.ClientPluginBase, workerID:number, worker:cluster.Worker}}
*/
async _transportPluginFromReverseClient(reverseCallsClient)
{
const workerTransportPlugin = reverseCallsClient.plugins.filter(plugin => plugin.worker && plugin.worker.id && plugin.worker.on)[0];
if(!workerTransportPlugin)
{
throw new Error("bFreshlyCachedWorkerProxyMode needs to know the worker ID of the calling worker from incomingRequest.reverseCallsClient.plugins[?].worker.id (and it must be of type number.");
}
return {
plugin: workerTransportPlugin,
// Must uniquely identify a worker.
workerID: workerTransportPlugin.worker.id,
// Has to emit an "exit" event.
worker: workerTransportPlugin.worker
};
}
/**
* @param {JSONRPC.Server} jsonrpcServer
*
* @returns {JSONRPC.RouterBase}
*/
async _makeBidirectionalRouter(jsonrpcServer)
{
return new JSONRPC.BidirectionalWorkerRouter(this._jsonrpcServer);
}
} |
JavaScript | class Welcome extends Component {
constructor(props) {
super(props)
}
async componentDidMount() {
// await this.checkeUser();
console.log(this.props)
setTimeout(() => {
SplashScreen.hide();
}, 500);
}
go = async()=>{
console.log('过',NavigationActions)
this.props.navigation.dispatch(
StackActions.reset({
index: 0,
actions: [NavigationActions.navigate({ routeName: "Login" })]
})
);
}
render() {
return (
<ImageBackground
style={styles.container}
source={require('../images/1080.png')}
resizeMode="cover"
>
<StatusBar
animated
translucent={versionFlg}
backgroundColor="rgba(0,0,0,0)"
/>
<Text style={[styles.textCommon, styles.text2]}>系统正在初始化···</Text>
<Text style={[styles.textCommon, styles.text2]}>当前版本:</Text>
{/* 点击跳转 */}
<TouchableOpacity activeOpacity={activeOpacity} style={styles.btn} onPress={this.go}>
<Text >退进入首页</Text>
</TouchableOpacity>
</ImageBackground>
)
}
} |
JavaScript | class ThCell extends React.Component {
state = {};
handleClick = value => e => {
e.stopPropagation();
let { fixed } = this.props;
const maps = {
topLeft: 'left',
topRight: 'right',
};
const { index, onColumnFixChange } = this.props;
fixed = fixed ? undefined : maps[value];
this.setState(
{
[value]: !this.state[value],
// show: false
},
() => {
onColumnFixChange && onColumnFixChange(index, fixed);
},
);
};
render() {
const { show, children, classes, ...other } = this.props;
const { topRight, topLeft } = this.state;
const leftClassName = classNames(classes.actionTopLeft, { [classes.active]: true });
const rightClassName = classNames(classes.actionTopRight, { [classes.active]: true });
return show ? (
<React.Fragment>
<div onClick={this.handleClick('topLeft')} className={leftClassName} />
<div onClick={this.handleClick('topRight')} className={rightClassName} />
</React.Fragment>
) : null;
}
} |
JavaScript | class SessionCache extends BaseCache {
/**
* Constructs an instance.
*
* @param {Logger} log Logger instance to use.
*/
constructor(log) {
super(log.withAddedContext('session'));
}
/** @override */
get _impl_cachedClass() {
return BaseSession;
}
/** @override */
get _impl_maxLruSize() {
return 10;
}
/** @override */
get _impl_maxRejectionAge() {
// Valid value so that the constructor won't complain, but note that this
// class isn't used asynchronously, so the actual value shouldn't matter.
return 1000;
}
/** @override */
_impl_idFromObject(session) {
return session.getCaretId();
}
/** @override */
_impl_isValidId(id) {
return CaretId.isInstance(id);
}
} |
JavaScript | class CurveComparator {
constructor (sampleCurve, targetCurve) {
this.sampleCurve = sampleCurve;
this.targetCurve = targetCurve;
let interp = this.#transformToCommonAbscissa();
this.areaMetric = this.compareByAreaMetric(interp.newX, interp.newSampleY, interp.newTargetY);
this.sumOfSquaresMetric = this.compareBySumOfSquaresMetric(interp.newX, interp.newSampleY, interp.newTargetY);
this.maxDeviationMetric = this.compareByMaximumDeviationMetric(interp.newX, interp.newSampleY, interp.newTargetY);
}
/**
* Function finds common abscissa values of two curves
* Creates modified curves with common abscissa domain
* Assuming that each curve x-arrays are sorted in ascending order
*/
#transformToCommonAbscissa() {
const sampleCurveLength = this.sampleCurve.x.length;
const targetCurveLength = this.targetCurve.x.length;
let commonXmin = Math.max(this.sampleCurve.x[0], this.targetCurve.x[0]);
let commonXmax = Math.min(this.sampleCurve.x[sampleCurveLength - 1], this.targetCurve.x[targetCurveLength - 1]);
// create new abscissa array over common domain
const commonNewLength = Math.max(sampleCurveLength, targetCurveLength) * 2;
let step = (commonXmax - commonXmin)/(commonNewLength - 1);
let commonAbscissa = linspace(commonXmin, commonXmax, step);
// interpolate ordinate values to new abscissa
let interpolatedsampleOrdinate = evaluateLinear(commonAbscissa, this.sampleCurve.x, this.sampleCurve.y);
let interpolatedTargetOrdinate = evaluateLinear(commonAbscissa, this.targetCurve.x, this.targetCurve.y);
return {
newX: commonAbscissa,
newSampleY: interpolatedsampleOrdinate,
newTargetY: interpolatedTargetOrdinate
}
}
compareByAreaMetric(commonX, sampleY, targetY) {
let sampleAreaMetric = 0;
for (let i = 1; i < commonX.length; i++) {
sampleAreaMetric += Math.pow((commonX[i] - commonX[i - 1]) * (sampleY[i] + sampleY[i - 1]) * 0.5, 2);
}
let targetAreaMetric = 0;
for (let i = 1; i < commonX.length; i++) {
targetAreaMetric += Math.pow((commonX[i] - commonX[i - 1]) * (targetY[i] + targetY[i - 1]) * 0.5, 2);
}
return {
sampleAreaMetric: sampleAreaMetric,
targetAreaMetric: targetAreaMetric,
sampleToTargetAreaRatio: (sampleAreaMetric - targetAreaMetric) / targetAreaMetric
};
}
compareBySumOfSquaresMetric(commonX, sampleY, targetY) {
let sumOfSquaresMetric = 0;
for (let i = 0; i < commonX.length; i++) {
let delta = sampleY[i] - targetY[i];
sumOfSquaresMetric += Math.pow(delta, 2);
}
return sumOfSquaresMetric;
}
compareByMaximumDeviationMetric(commonX, sampleY, targetY) {
let maxDeviationMetric = 0;
for (let i = 0; i < commonX.length; i++) {
let delta = Math.abs(sampleY[i] - targetY[i]);
if (delta > maxDeviationMetric) {
maxDeviationMetric = delta;
}
}
return maxDeviationMetric;
}
} |
JavaScript | class Logger {
constructor(debug, echo) {
this.debug = debug;
this.echo = echo;
this.browser = typeof window !== 'undefined';
}
dbug(text) {
if (this.debug) {
this.print('debug ', text, c.debug);
}
}
err(text) {
this.print('error ', text, c.error);
}
stdin(text) {
if (this.echo) {
this.print('stdin ', text, c.stdin);
}
}
stdout(text) {
if (this.echo) {
this.print('stdout ', text, c.stdout);
}
}
stderr(text) {
if (this.echo) {
this.print('stderr ', text, c.stderr);
}
}
sendosc(text) {
if (this.echo) {
this.print('sendosc', text, c.sendosc);
}
}
rcvosc(text) {
if (this.echo) {
this.print('rcvosc ', text, c.rcvosc);
}
}
print(label, text, color) {
if (this.browser) {
console.log('%c' + label, 'font-size: 10px; color:' + color, text);
} else {
// terminal
if (typeof text !== 'string') {
text = JSON.stringify(text, undefined, 2);
}
var
lines = text.split('\n'),
clean = [label + ': ' + lines[0]],
rest = lines.slice(1),
colorFn = chalk[color];
rest = rest.filter(function(s) { return s.length > 0; });
rest = rest.map(function(s) {
return ' ' + s;
});
clean = clean.concat(rest);
console.log(colorFn(clean.join('\n')));
}
}
} |
JavaScript | class SuspendableResource {
constructor (loader, isModule = false) {
this._isModule = isModule
this._loader = loader
this._promise = null
this._result = null
this._error = null
}
/**
* Triggers loading of the resource.
* Will check if we already have a result; could happen when router triggers load during route
* warming and this resolves before triggering the second load when committing navigation action.
* Also checks if we already have a promise; in case load had already been invoked on the resource.
* This effectively ensures we don't dispatch multiple network requests to fetch the resource.
*/
load = () => {
if (this._result) return this._result // we have already a result, nothing else to do
if (this._promise) return this._promise // we have already set a promise, hence initialised loading
this._promise = this._loader()
.then(result => {
// if a js module has default export, we return that
const returnValue = this._isModule ? result.default || result : result
this._result = returnValue
})
.catch(error => {
this._error = error
})
return this._promise
}
/**
* This is the key method for integrating with React Suspense. Read will:
* - "Suspend" if the resource loading has not been triggered or is still pending
* - Throw an error if the resource failed to load
* - Return the data of the resource if available
*/
read = () => {
if (this._result) return this._result
if (this._error) throw this._error
if (this._promise) throw this._promise
// we don't expect reaching this line since the router should always initialise 'load' before
// attempting to 'read'. Should aything go wrong we will initialise 'load' here which returns the promise
throw this.load()
}
} |
JavaScript | class Font {
/**
* Creates a new instance of Font
* @param {String} font Holds the font name
* @param {Object} styles Holds the font styles as object properties
*/
constructor ( font, styles ) {
/**
* Holds the font name
* @type {String}
* @private
*/
this.__font = font
/**
* Holds the font styles as object properties
* @type {Object}
* @private
*/
this.__styles = styles
}
/**
* Returns a new instance of Font
* @param {String} font Holds the font name
* @param {Object} styles Holds the font styles as object properties
* @return {Font} The newly created Font instance
*/
static create ( font, styles ) {
return new Font( font, styles )
}
/**
* Loads the font into the html document
* @param {Array} srcs An array of sources pointing to the font file ( ttf, otf, etc )
* @return {Font} Returns the current instance of the class
*/
get ( srcs ) {
/**
* Holds the fontfile css source
* @type {HTMLElement}
* @private
*/
this.__fontfile = html( '<style></style>' )
document.head.appendChild( this.__fontfile )
let data = 'src: ' + srcs.join( ', ' ) + ';\n'
loop( this.__styles, ( value, key ) => {
data += key + ': ' + value + ';\n'
} )
this.__fontfile.innerHTML = `
@font-face {
font-family: '` + this.__font + `';
` + data + `
}
`
return this
}
/**
* Destroy font related tags
*/
destroy () {
if ( this.__fontfile ) {
this.__fontfile.remove()
}
}
/**
* A method to check if a font has been loaded
* @param {Number} [attempts=-1] The number of attempts before the promise is rejected. Default is infinite.
* @param {Number} [interval=100] The time in milliseconds it takes to retry the load
* @return {Promise} A promise that is resolved when the font is loaded
*/
load ( attempts, interval ) {
attempts = attempts || -1
let blankFontStyle = html( '<style></style>' )
document.head.appendChild( blankFontStyle )
blankFontStyle.innerHTML = AdobeBlankCss
let container = createContainer( this.__font )
document.body.appendChild( container )
container.style.fontFamily = '"' + this.__font + '", "AdobeBlank"'
loop( this.__styles, ( value, key ) => {
container.style[ key ] = value
} )
let count = 0
return new Promise( ( resolve, reject ) => {
let cleanUp = () => {
container.parentNode.removeChild( container )
blankFontStyle.remove()
}
let timer = () => {
if ( container.offsetWidth > 0 ) {
cleanUp()
resolve()
} else {
count++
if ( count === attempts ) {
cleanUp()
reject()
} else {
setTimeout( timer, interval || 100 )
}
}
}
setTimeout( () => {
timer()
}, interval || 100 )
} )
}
} |
JavaScript | class ContextProvider extends React.Component
{
constructor(props)
{
super(props);
this.state = this.props.state;
if (providerCallback) providerCallback(this);
if (loadCallback) loadCallback(this.state);
this.dispatch = this.dispatch.bind(this);
}
/** @override */
componentDidMount()
{
if (mountCallback) mountCallback(this);
}
/** @override */
componentWillUnmount()
{
if (unmountCallback) unmountCallback(this);
if (unloadCallback) unloadCallback(this.state);
}
dispatch(action)
{
let result;
switch(action.type)
{
case 'setState':
result = action.value;
break;
default:
if (reducer)
{
result = reducer(this.state, action);
}
else
{
result = action;
}
}
if (result)
{
this.setState(result);
}
}
/** @override */
render()
{
const props = this.props;
return React.createElement(
StateContext.Provider, { value: this.state },
React.createElement(
DispatchContext.Provider, { value: this.dispatch },
props.children
)
);
}
} |
JavaScript | class ShapeMixin {
constructor(pos) {
if(!(pos instanceof Vector2))
throw TypeError("Position on a shape was expected to be an instance of Vector2");
this.pos = pos;
this._color0 = undefined;
this._color1 = undefined;
this._rotation = 0;
}
set fillStyle(v) { this._color1 = v; }
get fillStyle() {
if(this._color1 instanceof Color)
return this._color1.toString();
return this._color1;
}
set strokeStyle(v) { this._color0 = v; }
get strokeStyle() {
if(this._color0 instanceof Color)
return this._color0.toString();
return this._color0;
}
get rotation() { this._rotation; }
} |
JavaScript | class Lexeme extends Model {
/**
* Create a new Lexeme
* @param {Object} [data] The raw data for the lexeme. See the [DLx specification for a Lexeme]{@link http://developer.digitallinguistics.io/spec/schemas/Lexeme.html} for more information on formatting Lexeme data.
* @param {Array} [data.allomorphs] An array of allomorphs. You can use the [Allomorph class]{@link dlx.module:models.Allomorph} to ensure the data is formatted correctly.
* @param {Object} [data.citationForm] The citation form for this lexeme, formatted as a [Transcription]{@link http://developer.digitallinguistics.io/spec/schemas/Transcription.html}
* @param {Array} [data.components] An array of Lexeme References to other lexemes that are components of the current lexeme. Each item must be formatted as a [LexemeReference object]{@link http://developer.digitallinguistics.io/spec/schemas/LexemeReference.html}.
* @param {String|Date} [data.dateCreated] A date string or date object representing the time this lexeme was originally created. If none is supplied, dateCreated will be set to the current date-time.
* @param {String|Date} [data.dateModified] A date string or date object representing the time this lexeme was last modified. If none is supplied, dateModified will be set to the current date-time.
* @param {String} [data.defaultAnalysisLanguage=eng] The default analysis language for this language, as an [Abbreviation]{@link http://developer.digitallinguistics.io/spec/schemas/Abbreviation.html}.
* @param {String} [data.defaultOrthography=ipa] The default orthography for this language, as an [Abbreviation]{@link http://developer.digitallinguistics.io/spec/schemas/Abbreviation.html}.
* @param {Array} [data.examples] An array of example sentences illustrating this lexeme's uses. Each item must be formatted as a [Sentence]{@link http://developer.digitallinguistics.io/spec/schemas/Sentence.html}.
* @param {Object|Array} [data.features] An object containing grammatical features and their values. May also be a Map object.
* @param {Array} [data.includedIn] An Array of references to lexemes that have the current lexeme as a component. Each item should be formatted as a [LexemeReference]{@link http://developer.digitallinguistics.io/spec/schemas/LexemeReference.html}.
* @param {String} [data.key] A human-readable key that uniquely identifies this lexeme or variant within its lexicon. Best practice is for the key to consist of the lemma form of the word in the default orthography, and if the word is a homonym, the homonym number. However, any value is acceptable as long as it is unique within the lexicon. (Keys do not need to be unique across lexicons.) Must be formatted as an [Abbreviation]{@link http://developer.digitallinguistics.io/spec/schemas/abbreviation.html}.
* @param {Object} data.lemma The lemma form of this lexeme. A lemma is the particular form conventionally used to represent a particular lexeme. It may differ drastically from the citation form or headword form. For example, the form be is typically used as the lemma form of the English verb to be, with its variants am, are, is, etc. Lemmas may be represented in multiple orthographies. Do not include any leading or trailing tokens (e.g. hyphens, equal signs). Must be in the format of a [Transcription object]{@link http://developer.digitallinguistics.io/spec/schemas/Transcription.html}.
* @param {Array} [data.lexicalRelations] An array of objects formatted as a [LexemeReference]{@link http://developer.digitallinguistics.io/spec/schemas/LexemeReference.html}, with an additional required "relation" property. See the [Lexeme format]{@link http://developer.digitallinguistics.io/spec/schemas/Lexeme.html} for more details.
* @param {Object} [data.literalMeaning] The literal meaning of the lexeme, optionally in multiple languages. Must be formatted as a [MultiLangString]{@link http://developer.digitallinguistics.io/spec/schemas/MultiLangString.html}.
* @param {Object} [data.morphemeType] The type of morpheme or complex construction that this lexeme is, optionally in multiple languages. Examples: root, stem, bipartite stem, enclitic, prefix, inflected word, sentence, circumfix. Must be formatted as a [MultiLangString]{@link http://developer.digitallinguistics.io/spec/schemas/MultiLangString.html}.
* @param {Array} [data.notes] An array of notes about this lexeme. Each note should adhere to the [Note format]{@link http://developer.digitallinguistics.io/spec/schemas/Note.html}.
* @param {Array} [data.references] An array of bibliographic references about this lexeme. Each item should adhere to the [Reference format]{@link http://developer.digitallinguistics.io/spec/schemas/Reference.html}.
* @param {Array} data.senses An array of senses for this lexeme. Each item should be formatted as a Sense object. See the [Lexeme schema]{@link http://developer.digitallinguistics.io/spec/schemas/Lexeme.html} for more details.
* @param {Array} [data.sources] An array of attested sources for this lexeme, as strings. This will often be the initials of a speaker, but could also be the abbreviation of the story the lexeme was found it, or other types of sources.
* @param {String} [data.syllableStructure] An abstract representation of the syllable structure of this form, as a string, e.g. `CVC`.
* @param {Object|Array} [data.tags] An object containing tags and their values. May also be an iterable object, whose items are arrays of tags and their values (in other words, the standard method for instantiating a new Map object; see [MDN's Map documentation]{@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map} for more details).
* @param {String} [data.tone] A string representing the tonal pattern of this lexeme or variant. Examples: `HLH`, `323`, etc.
* @param {String} [data.url] A URI where this lexeme can be accessed, as a string.
* @param {Object} [data.variantOf] When this lexeme is a variant of another lexeme, this field should contain a reference (formatted as a [LexemeReference]{@link http://developer.digitallinguistics.io/spec/schemas/LexemeReference.html}) to the other Lexeme. Lexemes may only be variants of one other Lexeme.
* @param {Array} [data.variants] An array of variants of this lexeme. Each item should be formatted as a [LexemeReference]{@link http://developer.digitallinguistics.io/spec/schemas/LexemeReference.html}, and must also have the "variantType" property specified.
* @param {Object} [data.variantType] If this lexeme is a variant of another lexeme or sense, this field can be used to specify the type of variant. Possible values might be a person's name (representing an idiolectal variant), or simply `idiolectal`, or `dialectal`, or the name of the dialect, or `rapid speech`, etc. Must be in the format of a [MultiLangString]{@link http://developer.digitallinguistics.io/spec/schemas/MultiLangString.html}.
*/
constructor(data = {}) {
// VALIDATION
if (data instanceof Lexeme) return data;
if (typeof data !== `object`) {
throw new TypeError(`The data passed to the Lexeme constructor must be an object.`);
}
// INSTANTIATION
super();
Object.assign(this, data);
addAbbreviation(this, `defaultAnalysisLanguage`, data.defaultAnalysisLanguage || `eng`);
addAbbreviation(this, `defaultOrthography`, data.defaultOrthography || `ipa`);
addAbbreviation(this, `key`, data.key);
addType(this, `Lexeme`);
addURL(this, `url`, data.url);
defineProp(this, `citationForm`, Transcription, data.citationForm);
defineProp(this, `dateCreated`, Date, data.dateCreated || new Date);
defineProp(this, `dateModified`, Date, data.dateModified || new Date);
defineProp(this, `lemma`, Transcription, data.lemma || {});
defineProp(this, `literalMeaning`, MultiLangString, data.literalMeaning);
defineProp(this, `features`, Features, data.features || {});
defineProp(this, `morphemeType`, MultiLangString, data.morphemeType || {});
defineProp(this, `syllableStructure`, String, data.syllableStructure);
defineProp(this, `tags`, Tags, data.tags || {});
defineProp(this, `tone`, String, data.tone);
defineProp(this, `variantOf`, LexemeReference, data.variantOf);
defineProp(this, `variantType`, MultiLangString, data.variantType);
defineArray(this, `allomorphs`, Allomorph, data.allomorphs);
defineArray(this, `components`, LexemeReference, data.components);
defineArray(this, `examples`, Sentence, data.examples);
defineArray(this, `includedIn`, LexemeReference, getUniqueReferences(data.includedIn || []));
defineArray(this, `lexicalRelations`, LexicalRelation, getUniqueReferences(data.lexicalRelations || []));
defineArray(this, `notes`, Note, data.notes);
defineArray(this, `references`, Reference, data.references);
defineArray(this, `senses`, Sense, data.senses);
defineArray(this, `sources`, String, data.sources);
defineArray(this, `variants`, Variant, getUniqueReferences(data.variants || []));
aliasLanguage(this, `literalMeaning`, `$literalMeaning`);
aliasLanguage(this, `morphemeType`, `$morphemeType`);
aliasLanguage(this, `variantType`, `$variantType`);
aliasTranscription(this, `citationForm`, `$citationForm`);
aliasTranscription(this, `lemma`, `$lemma`);
// VALIDATION FOR SETTERS
const handler = {
set(target, prop, val, proxy) {
target.dateModified = new Date;
return Reflect.set(target, prop, val, proxy);
},
};
return new Proxy(this, handler);
}
toJSON() {
return simplify(this, [
`lemma`,
`senses`,
]);
}
} |
JavaScript | class Catalog extends Component {
constructor(props) {
super(props);
this.state = {
loading: false,
totalItemsCount: null,
items: []
};
this.updateQueryStr = this.updateQueryStr.bind(this);
}
async fetchData(url) {
this.setState({ loading: true });
// Parse the query string
let qsAsObject = queryString.parse(this.props.location.search);
let results;
await Api.searchItems(url, qsAsObject).then(data => {
console.log(data);
results = data;
});
this.setState({
items: results.data,
loading: false,
totalItemsCount: results.totalLength
});
}
imageUrl = "";
async deleteProduct(id) {
let baseUrl = document.querySelector("meta[property='base-url']").getAttribute("content");
await Api.deleteItem(baseUrl + Constants.PRODUCTS_URL + "/" + id).then(res => {
alert(res.data);
});
}
componentDidMount() {
let baseUrl = document.querySelector("meta[property='base-url']").getAttribute("content");
this.imageUrl = document.querySelector("meta[property='image-url']").getAttribute("content");
this.fetchData(baseUrl);
}
updateQueryStr(newValues) {
let current = queryString.parse(this.props.location.search);
this.props.history.push(
"/?" + queryString.stringify({ ...current, ...newValues })
);
}
componentDidUpdate(prevProps, prevState, snapshot) {
let currentQueryStr = queryString.parse(this.props.location.search);
let oldQueryStr = queryString.parse(prevProps.location.search);
let areSameObjects = (a, b) => {
if (Object.keys(a).length !== Object.keys(b).length) return false;
for (let key in a) {
if (a[key] !== b[key]) return false;
}
return true;
};
// We will refetch products only when query string changes.
if (!areSameObjects(currentQueryStr, oldQueryStr)) {
this.fetchData();
}
}
render() {
let parsedQueryStr = queryString.parse(this.props.location.search);
if (this.state.loading) {
return <CircularProgress className="circular" />;
}
return (
<div style={{ height: "100%", display: "flex", flexDirection: "column" }}>
<Table>
<TableHead>
<TableRow>
<TableCell><Button
style={{ width: 170, marginTop: 5 }}
color="primary"
variant="contained"
onClick={() => {
if (this.props.showMenu)
this.props.dispatch(toggleMenu());
this.props.history.push("/manage-catalog-add");
}}
>
Add Product
</Button></TableCell>
<TableCell></TableCell>
<TableCell></TableCell>
<TableCell></TableCell>
<TableCell></TableCell>
<TableCell></TableCell>
<TableCell></TableCell>
</TableRow>
<TableRow>
<TableCell>Item image</TableCell>
<TableCell>Item name</TableCell>
<TableCell>Item description</TableCell>
<TableCell>Item category</TableCell>
<TableCell>Price</TableCell>
<TableCell>Quantity</TableCell>
<TableCell>Action</TableCell>
</TableRow>
</TableHead>
<TableBody>
{this.state.items.map(item => {
return <CatalogItem key={item.id} item={item} deleteItem={this.deleteProduct} path={this.imageUrl} />;
})}
</TableBody>
</Table>
<Paging
parsedQueryStr={parsedQueryStr}
updateQueryStr={this.updateQueryStr}
totalItemsCount={this.state.totalItemsCount}
/>
</div>
);
}
} |
JavaScript | class JSONAPISource extends Source {
constructor(options = {}) {
assert('JSONAPISource\'s `schema` must be specified in `options.schema` constructor argument', options.schema);
assert('JSONAPISource\'s `keyMap` must be specified in `options.keyMap` constructor argument', options.keyMap);
assert('JSONAPISource requires Orbit.Promise be defined', Orbit.Promise);
assert('JSONAPISource requires Orbit.ajax be defined', Orbit.ajax);
super(options);
this.name = options.name || 'jsonapi';
this.namespace = options.namespace;
this.host = options.host;
this.headers = options.headers || { Accept: 'application/vnd.api+json' };
this.maxRequestsPerFetch = options.maxRequestsPerFetch;
this.maxRequestsPerTransform = options.maxRequestsPerTransform;
const SerializerClass = options.SerializerClass || JSONAPISerializer;
this.serializer = new SerializerClass({ schema: options.schema, keyMap: options.keyMap });
assert('Serializer must be an instance of OC.Serializer', this.serializer instanceof Serializer);
}
/////////////////////////////////////////////////////////////////////////////
// Transformable interface implementation
/////////////////////////////////////////////////////////////////////////////
_transform(transform) {
const requests = getTransformRequests(transform);
if (this.maxRequestsPerTransform && requests.length > this.maxRequestsPerTransform) {
return Orbit.Promise.resolve()
.then(() => {
throw new TransformNotAllowed(
`This transform requires ${requests.length} requests, which exceeds the specified limit of ${this.maxRequestsPerTransform} requests per transform.`,
transform);
});
}
return this._processRequests(requests, TransformRequestProcessors)
.then(transforms => {
transforms.unshift(transform);
return transforms;
});
}
/////////////////////////////////////////////////////////////////////////////
// Fetchable interface implementation
/////////////////////////////////////////////////////////////////////////////
_fetch(query) {
const requests = getFetchRequests(query);
if (this.maxRequestsPerFetch && requests.length > this.maxRequestsPerFetch) {
return Orbit.Promise.resolve()
.then(() => {
throw new FetchNotAllowed(
`This query requires ${requests.length} fetch requests, which exceeds the specified limit of ${this.maxRequestsPerFetch} requests per query.`,
query);
});
}
return this._processRequests(requests, FetchRequestProcessors);
}
/////////////////////////////////////////////////////////////////////////////
// Publicly accessible methods particular to JSONAPISource
/////////////////////////////////////////////////////////////////////////////
ajax(url, method, settings = {}) {
return new Orbit.Promise((resolve, reject) => {
settings.url = url;
settings.type = method;
settings.dataType = 'json';
settings.context = this;
if (settings.data && method !== 'GET') {
if (!settings.contentType) {
settings.contentType = this.ajaxContentType(settings);
}
settings.data = JSON.stringify(settings.data);
}
if (!settings.headers) {
settings.headers = this.ajaxHeaders(settings);
}
settings.success = function(json) {
resolve(json);
};
settings.error = function(jqXHR) {
if (jqXHR) {
jqXHR.then = null;
}
reject(jqXHR);
};
Orbit.ajax(settings);
});
}
ajaxContentType(/* settings */) {
return 'application/vnd.api+json; charset=utf-8';
}
ajaxHeaders(/* settings */) {
return this.headers;
}
resourceNamespace(/* type */) {
return this.namespace;
}
resourceHost(/* type */) {
return this.host;
}
resourcePath(type, id) {
let path = [this.serializer.resourceType(type)];
if (id) {
let resourceId = this.serializer.resourceId(type, id);
if (resourceId) {
path.push(resourceId);
}
}
return path.join('/');
}
resourceURL(type, id) {
let host = this.resourceHost(type);
let namespace = this.resourceNamespace(type);
let url = [];
if (host) { url.push(host); }
if (namespace) { url.push(namespace); }
url.push(this.resourcePath(type, id));
url = url.join('/');
if (!host) { url = '/' + url; }
return url;
}
resourceRelationshipURL(type, id, relationship) {
return this.resourceURL(type, id) +
'/relationships/' + this.serializer.resourceRelationship(type, relationship);
}
relatedResourceURL(type, id, relationship) {
return this.resourceURL(type, id) +
'/' + this.serializer.resourceRelationship(type, relationship);
}
/////////////////////////////////////////////////////////////////////////////
// Private methods
/////////////////////////////////////////////////////////////////////////////
_processRequests(requests, processors) {
let transforms = [];
let result = Orbit.Promise.resolve();
requests.forEach(request => {
let processor = processors[request.op];
result = result.then(() => {
return processor(this, request)
.then(additionalTransforms => {
if (additionalTransforms) {
Array.prototype.push.apply(transforms, additionalTransforms);
}
});
});
});
return result.then(() => transforms);
}
} |
JavaScript | class destructuringAssignment{
newOne(){
const list = [1,2,3];
const [x,,y] = list;
console.log(x,y);
const obj = {foo: 2, bar:40, fooBar:true}
const {fooBar, foo, bar} = obj;
console.log(bar, fooBar, foo);
}
oldOne(){
const list = [1,2,3];
const x = list[0];
const y = list[2];
console.log(x,y);
const obj = {foo: 2, bar:40, fooBar:true}
const foo = obj.foo;
const bar = obj.bar;
const fooBar = obj.fooBar;
console.log(bar, fooBar, foo);
}
} |
JavaScript | class Xml2Json {
constructor(options) {
this.currentLevel = 0;
this._pojo = {};
this.state_stack = [];
this.current_state = null;
if (!options) {
this.state_stack = [];
this.current_state = null;
this._promote(exports.json_extractor, 0);
return;
}
const state = (options instanceof ReaderState)
? options : new ReaderState(options);
state.root = this;
this.state_stack = [];
this.current_state = null;
this._promote(state, 0);
}
parseString(xml_text, callback) {
const parser = this._prepareParser(callback);
parser.write(xml_text);
parser.end();
}
parse(xmlFile, callback) {
if (!callback) {
throw new Error("internal error");
}
const readWholeFile = true;
if (readWholeFile) {
// slightly faster but require more memory ..
fs.readFile(xmlFile, (err, data) => {
if (err) {
return callback(err);
}
if (data[0] === 0xEF && data[1] === 0xBB && data[2] === 0xBF) {
data = data.slice(3);
}
const dataAsString = data.toString();
const parser = this._prepareParser(callback);
parser.write(dataAsString);
parser.end();
});
}
else {
const Bomstrip = require("bomstrip");
const parser = this._prepareParser(callback);
fs.createReadStream(xmlFile, { autoClose: true, encoding: "utf8" })
.pipe(new Bomstrip())
.pipe(parser);
}
}
/**
* @param new_state
* @param name
* @param attr
* @private
* @internal
*/
_promote(new_state, level, name, attr) {
attr = attr || {};
this.state_stack.push({
backup: {},
state: this.current_state
});
const parent = this.current_state;
this.current_state = new_state;
this.current_state._on_init(name || "???", attr, parent, level, this);
}
/**
*
* @private
* @internal
*/
_demote(cur_state, level, elementName) {
/// assert(this.current_state === cur_state);
const { state, backup } = this.state_stack.pop();
this.current_state = state;
if (this.current_state) {
this.current_state._on_endElement2(level, elementName);
}
}
_prepareParser(callback) {
node_opcua_assert_1.assert(callback instanceof Function);
const parser = new LtxParser();
this.currentLevel = 0;
parser.on("startElement", (name, attrs) => {
const tag_ns = resolve_namespace(name);
this.currentLevel += 1;
if (this.current_state) {
this.current_state._on_startElement(this.currentLevel, tag_ns.tag, attrs);
}
});
parser.on("endElement", (name) => {
const tag_ns = resolve_namespace(name);
if (this.current_state) {
this.current_state._on_endElement(this.currentLevel, tag_ns.tag);
}
this.currentLevel -= 1;
if (this.currentLevel === 0) {
parser.emit("close");
}
});
parser.on("text", (text) => {
text = text.trim();
if (text.length === 0) {
return;
}
if (this.current_state) {
this.current_state._on_text(text);
}
});
parser.on("close", () => {
if (callback) {
callback(null, this._pojo);
}
});
return parser;
}
} |
JavaScript | class App extends React.Component {
constructor(props) {
super(props);
}
// shouldComponentUpdate(nextProps){
// return !Immutable.is(this.props.state, nextProps.state);
// }
render() {
return (
<div>
{this.props.state.getIn(["monitor","enable"]).toString()}
<br/>
{this.props.state.get("count")}
<button type="button"
onClick={()=> this.props.actions.changeIncAsync()}
>PATTERN_BASIC</button>
</div>
)
}
} |
JavaScript | class PersistentSocket {
constructor(destination) {
this.destination = destination;
this.ws = makeSocket(this.destination);
}
send(data) {
if (this.ws.readyState == 1) {
this.ws.send(data);
}
}
} |
JavaScript | class Rewind {
constructor(element, options) {
this.isAdjusting = false;
// validate element
// options...
const defaults = {
onTimeChange: () => {},
onPreviewTimeChange: () => {},
onVolumeChange: () => {},
onClick: () => {},
volumeSpeed: 1,
timeSpeed: 0.01,
};
this.options = {
...defaults,
...options,
};
// set initial helper values
this.element = element;
this.startVolume = null;
this.startTime = null;
// dragger instance
this.dragger = new Dragger({
...this.options,
element: element,
onDragStart: this.onDragStart,
onDragEnd: this.onDragEnd,
onDrag: this.onDrag,
onClick: (event) => {
this.options.onClick(this.isAdjusting);
},
});
};
onDragStart = () => {
this.startVolume = parseInt(this.element.volume * 100);
this.startTime = parseInt(this.element.currentTime);
};
onDragEnd = (event) => {
if (this.dragger.currentlyAdjusting === 'x') {
this.element.currentTime = this.currentTime;
this.options.onTimeChange({time: this.currentTime});
}
setTimeout(() => this.isAdjusting = false);
this.currentTime = null;
this.startVolume = null;
this.startTime = null;
};
onDrag = (distance, absoluteDistance, direction, event) => {
this.isAdjusting = true;
if (direction === "x") {
let currentTime = null;
const time = parseInt(distance * this.options.timeSpeed + this.startTime);
if (time < 0) {
currentTime = 0;
} else if (time > this.element.duration) {
currentTime = this.element.duration;
} else {
currentTime = time;
}
this.currentTime = currentTime;
this.options.onPreviewTimeChange({time: this.currentTime});
return toMMSS(currentTime);
} else {
let volume = null;
const volumeToSet = parseInt((this.startVolume) - distance * this.options.volumeSpeed / 2);
if (volumeToSet < 0) {
volume = 0;
} else if (volumeToSet > 100) {
volume = 100;
} else {
volume = volumeToSet;
}
this.element.volume = volume / 100;
this.options.onVolumeChange({volume});
return volume;
}
};
destroy = () => {
//
};
} |
JavaScript | class KernelRidge {
/**
* @param {number} lambda
* @param {'gaussian'} kernel
*/
constructor(lambda = 0.1, kernel = null) {
this._w = null
this._x = null
this._lambda = lambda
this._kernel = null
if (kernel === 'gaussian') {
this._kernel = (x, y, sigma = 1.0) => {
const s = x.copySub(y).reduce((acc, v) => acc + v * v, 0)
return Math.exp(-s / sigma ** 2)
}
}
}
/**
* Fit model.
* @param {Array<Array<number>>} x
* @param {Array<Array<number>>} y
*/
fit(x, y) {
x = Matrix.fromArray(x)
y = Matrix.fromArray(y)
const K = new Matrix(x.rows, x.rows)
this._x = []
for (let i = 0; i < x.rows; i++) {
this._x.push(x.row(i))
K.set(i, i, this._kernel(this._x[i], this._x[i]) + this._lambda)
for (let j = 0; j < i; j++) {
const v = this._kernel(this._x[i], this._x[j])
K.set(i, j, v)
K.set(j, i, v)
}
}
this._w = K.solve(y)
}
/**
* Returns predicted values.
* @param {Array<Array<number>>} x
* @returns {Array<Array<number>>}
*/
predict(x) {
x = Matrix.fromArray(x)
const K = new Matrix(x.rows, this._x.length)
for (let i = 0; i < x.rows; i++) {
const xi = x.row(i)
for (let j = 0; j < this._x.length; j++) {
const v = this._kernel(xi, this._x[j])
K.set(i, j, v)
}
}
return K.dot(this._w).toArray()
}
/**
* Returns importances of the features.
* @returns {number[]}
*/
importance() {
return this._w.value
}
} |
JavaScript | class ForkedVinylStream extends stream_1.Transform {
constructor() {
super({ objectMode: true });
}
_transform(file, enc, callback) {
callback(null, file.clone({ deep: true, contents: true }));
}
} |
JavaScript | class Attachable {
/// Default constructor.
constructor() {}
/**
* Static Abstract function: meant to guide other attachable
* objects to use a common function to attach their properties
* to the input 'obj'. Utilize Attachable's add and append
* functions here.
*
* @param {object} obj object attaching things to
* @param {object} [data] attachment details
*/
static attach(obj, data) {
//... attach new properties to obj (override)
}
/**
* Static function: Attaches a getter/setter property.
*
* @param {object} obj object that we are attaching this new propery to
* @param {String} name name of property
* @param {Function} get_f getter function
* @param {Function} set_f setter function
*/
static add_prop(obj, name, get_f, set_f) {
Object.defineProperty(obj, name, {get: get_f, set: set_f});
}
/**
* Static function: Attaches a variable/function.
*
* @param {object} obj object that we are attaching this new variable to
* @param {String} name name of variable
* @param {object} val value of new variable
*/
static add_var(obj, name, val) {
obj[name] = val;
}
/**
* @todo look for a less dependable method of function addition.
* Static function: Attaches a new function to an existing function.
* via an array. No arguments are passed into the function.
*
* @requires 'lst' must be a list of functions called inside some other function
*
* @param {Array} lst list of functions called within some other function
* @param {Function} new_f function to append to function list
*/
static append_func(lst, new_f) {
lst.push(new_f);
}
}//end Attachable |
JavaScript | class AttributeSets extends PlantWorksBaseMiddleware {
// #region Constructor
constructor(parent, loader) {
super(parent, loader);
}
// #endregion
// #region startup/teardown code
/**
* @async
* @function
* @override
* @instance
* @memberof AttributeSets
* @name _setup
*
* @returns {null} Nothing.
*
* @summary Sets up the broker to manage API exposed by other modules.
*/
async _setup() {
try {
await super._setup();
const dbSrvc = this.$dependencies.DatabaseService;
const self = this; // eslint-disable-line consistent-this
Object.defineProperty(this, '$TenantModel', {
'__proto__': null,
'configurable': true,
'value': dbSrvc.Model.extend({
'tableName': 'tenants',
'idAttribute': 'tenant_id',
'hasTimestamps': true,
'tenantFeatures': function() {
return this.hasMany(self.$TenantFeatureModel, 'tenant_id');
}
})
});
Object.defineProperty(this, '$TenantFeatureModel', {
'__proto__': null,
'configurable': true,
'value': dbSrvc.Model.extend({
'tableName': 'tenants_features',
'idAttribute': 'tenant_feature_id',
'hasTimestamps': true,
'tenant': function() {
return this.belongsTo(self.$TenantModel, 'tenant_id');
},
'attributeSets': function() {
return this.hasMany(self.$AttributeSetModel, 'tenant_feature_id');
}
})
});
Object.defineProperty(this, '$AttributeSetModel', {
'__proto__': null,
'configurable': true,
'value': dbSrvc.Model.extend({
'tableName': 'attribute_sets',
'idAttribute': 'attribute_set_id',
'hasTimestamps': true,
'tenantFeature': function() {
return this.belongsTo(self.$TenantFeatureModel, 'tenant_feature_id');
},
'properties': function() {
return this.hasMany(self.$AttributeSetPropertyModel, 'attribute_set_id');
},
'functions': function() {
return this.hasMany(self.$AttributeSetFunctionModel, 'attribute_set_id');
}
})
});
Object.defineProperty(this, '$AttributeSetPropertyModel', {
'__proto__': null,
'configurable': true,
'value': dbSrvc.Model.extend({
'tableName': 'attribute_set_properties',
'idAttribute': 'attribute_set_property_id',
'hasTimestamps': true,
'tenant': function() {
return this.belongsTo(self.$TenantModel, 'tenant_id');
},
'attributeSet': function() {
return this.belongsTo(self.$AttributeSetModel, 'attribute_set_id');
}
})
});
Object.defineProperty(this, '$AttributeSetFunctionModel', {
'__proto__': null,
'configurable': true,
'value': dbSrvc.Model.extend({
'tableName': 'attribute_set_functions',
'idAttribute': 'attribute_set_function_id',
'hasTimestamps': true,
'tenant': function() {
return this.belongsTo(self.$TenantModel, 'tenant_id');
},
'attributeSet': function() {
return this.belongsTo(self.$AttributeSetModel, 'attribute_set_id');
}
})
});
return null;
}
catch(err) {
throw new PlantWorksMiddlewareError(`${this.name}::_setup error`, err);
}
}
/**
* @async
* @function
* @override
* @instance
* @memberof AttributeSets
* @name _teardown
*
* @returns {undefined} Nothing.
*
* @summary Deletes the broker that manages API.
*/
async _teardown() {
try {
delete this.$AttributeSetFunctionModel;
delete this.$AttributeSetPropertyModel;
delete this.$AttributeSetModel;
delete this.$TenantFeatureModel;
delete this.$TenantModel;
await super._teardown();
return null;
}
catch(err) {
throw new PlantWorksMiddlewareError(`${this.name}::_teardown error`, err);
}
}
// #endregion
// #region Protected methods
async _registerApis() {
try {
const ApiService = this.$dependencies.ApiService;
await super._registerApis();
await ApiService.add(`${this.name}::getAttributeSets`, this._getAttributeSets.bind(this));
await ApiService.add(`${this.name}::createAttributeSet`, this._createAttributeSet.bind(this));
await ApiService.add(`${this.name}::updateAttributeSet`, this._updateAttributeSet.bind(this));
await ApiService.add(`${this.name}::deleteAttributeSet`, this._deleteAttributeSet.bind(this));
return null;
}
catch(err) {
throw new PlantWorksMiddlewareError(`${this.name}::_registerApis`, err);
}
}
async _deregisterApis() {
try {
const ApiService = this.$dependencies.ApiService;
await ApiService.remove(`${this.name}::deleteAttributeSet`, this._deleteAttributeSet.bind(this));
await ApiService.remove(`${this.name}::updateAttributeSet`, this._updateAttributeSet.bind(this));
await ApiService.remove(`${this.name}::createAttributeSet`, this._createAttributeSet.bind(this));
await ApiService.remove(`${this.name}::getAttributeSets`, this._getAttributeSets.bind(this));
await super._deregisterApis();
return null;
}
catch(err) {
throw new PlantWorksMiddlewareError(`${this.name}::_registerApis`, err);
}
}
// #endregion
// #region API
async _getAttributeSets(ctxt) {
try {
let attributeSetData = await this.$AttributeSetModel
.query(function(qb) {
qb
.where('tenant_feature_id', '=', ctxt.query['tenant-feature-id'])
.andWhere({ 'tenant_id': ctxt.state.tenant.tenant_id });
})
.fetchAll({
'withRelated': (ctxt.query.include && ctxt.query.include.length) ? ctxt.query.include.split(',').map((related) => { return related.trim(); }) : ['tenantFeature', 'properties', 'functions']
});
attributeSetData = this.$jsonApiMapper.map(attributeSetData, 'common/attribute-set', {
'typeForModel': {
'tenantFeature': 'tenant-administration/feature-manager/tenant-feature',
'properties': 'common/attribute-set-property',
'functions': 'common/attribute-set-function'
},
'enableLinks': false
});
delete attributeSetData.included;
return attributeSetData;
}
catch(err) {
throw new PlantWorksMiddlewareError(`${this.name}::_getAttributeSets`, err);
}
}
async _createAttributeSet(ctxt) {
try {
const attributeSet = ctxt.request.body;
const jsonDeserializedData = await this.$jsonApiDeserializer.deserializeAsync(attributeSet);
jsonDeserializedData['attribute_set_id'] = jsonDeserializedData['id'];
delete jsonDeserializedData.id;
delete jsonDeserializedData.created_at;
delete jsonDeserializedData.updated_at;
Object.keys(attributeSet.data.relationships || {}).forEach((relationshipName) => {
if(!attributeSet.data.relationships[relationshipName].data) {
delete jsonDeserializedData[relationshipName];
return;
}
if(!attributeSet.data.relationships[relationshipName].data.id) {
delete jsonDeserializedData[relationshipName];
return;
}
jsonDeserializedData[`${relationshipName}_id`] = attributeSet.data.relationships[relationshipName].data.id;
});
const savedRecord = await this.$AttributeSetModel
.forge()
.save(jsonDeserializedData, {
'method': 'insert',
'patch': false
});
return {
'data': {
'type': attributeSet.data.type,
'id': savedRecord.get('attribute_set_id')
}
};
}
catch(err) {
throw new PlantWorksMiddlewareError(`${this.name}::_createAttributeSet`, err);
}
}
async _updateAttributeSet(ctxt) {
try {
const attributeSet = ctxt.request.body;
const jsonDeserializedData = await this.$jsonApiDeserializer.deserializeAsync(attributeSet);
jsonDeserializedData['attribute_set_id'] = jsonDeserializedData['id'];
delete jsonDeserializedData.id;
delete jsonDeserializedData.created_at;
delete jsonDeserializedData.updated_at;
Object.keys(attributeSet.data.relationships || {}).forEach((relationshipName) => {
if(!attributeSet.data.relationships[relationshipName].data) {
delete jsonDeserializedData[relationshipName];
return;
}
if(!attributeSet.data.relationships[relationshipName].data.id) {
delete jsonDeserializedData[relationshipName];
return;
}
jsonDeserializedData[`${relationshipName}_id`] = attributeSet.data.relationships[relationshipName].data.id;
});
const savedRecord = await this.$AttributeSetModel
.forge()
.save(jsonDeserializedData, {
'method': 'update',
'patch': true
});
return {
'data': {
'type': attributeSet.data.type,
'id': savedRecord.get('attribute_set_id')
}
};
}
catch(err) {
throw new PlantWorksMiddlewareError(`${this.name}::_updateAttributeSet`, err);
}
}
async _deleteAttributeSet(ctxt) {
try {
const attributeSet = await new this.$AttributeSetModel({
'tenant_id': ctxt.state.tenant['tenant_id'],
'attribute_set_id': ctxt.params['attributeSetId']
})
.fetch();
if(!attributeSet) throw new Error('Unknown Attribute Set');
await attributeSet.destroy();
return null;
}
catch(err) {
throw new PlantWorksMiddlewareError(`${this.name}::_deleteAttributeSet`, err);
}
}
// #endregion
// #region Properties
/**
* @override
*/
get basePath() {
return __dirname;
}
// #endregion
} |
JavaScript | class Switch {
/**
* Constructor
* @param {Object} options
- Component options
* @return {Object} Class instance
*/
constructor (options) {
this.options = Object.assign({}, defaults, options || {})
Object.assign(this, emitter, attach, dataset)
this.value = this.options.value
this.build()
this.setup()
this.attach()
return this
}
/**
* build method
* @return {Object} The class instance
*/
build () {
var tag = this.options.tag || 'span'
this.root = document.createElement(tag)
this.root.classList.add('switch')
if (this.options.class !== 'switch') {
addClass(this.root, this.options.class)
}
this.layout = new Layout(this.options.layout, this.root)
this.ui = this.layout.component
// console.log('ui', this.ui)
this.styleAttributes()
this.buildIcon()
this.buildLabel()
if (this.options.container) {
this.options.container.appendChild(this.root)
}
}
setup () {
if (this.options.data) {
dataset(this.root, this.options.data)
}
// console.log('attribute', this.ui.input, this.options)
attributes(this.ui.input, this.options)
if (this.options.checked) {
this.check(true)
}
if (this.value) {
this.element.input.setAttribute('checked', 'checked')
}
if (this.options.tooltip) {
this.root.setAttribute('data-tooltip', this.options.tooltip)
}
this.ui.input.setAttribute('aria-label', this.options.name)
if (this.options.case) {
this.root.classList.add(this.options.case + '-case')
}
}
buildLabel () {
// console.log('buildLabel', this.options.label)
if (!this.options.label) return
this.ui.label = document.createElement('label')
this.ui.label.classList.add('label')
this.ui.label.innerHTML = this.options.label
if (this.options.name) {
this.ui.label.setAttribute('for', this.options.name)
}
this.root.insertBefore(this.ui.label, this.ui.input)
}
buildIcon () {
if (!this.options.icon) return
this.ui.icon = document.createElement('i')
this.ui.icon.classList.add('icon')
this.ui.icon.innerHTML = this.options.icon
this.root.insertBefore(this.ui.icon, this.ui.input)
}
styleAttributes () {
if (this.options.style) {
this.root.classList.add('style-' + this.options.style)
}
if (this.options.size) {
this.root.classList.add(this.options.size + '-size')
}
if (this.options.color) {
this.root.classList.add('color-' + this.options.color)
}
if (this.options.bold) {
this.root.classList.add('bold')
}
}
/**
* Setter
* @param {string} prop
* @param {string} value
* @return {Object} The class instance
*/
set (prop, value, silent) {
switch (prop) {
case 'value':
this.setValue(value, silent)
break
case 'text':
this.setValue(value)
break
case 'disabled':
if (value === true) {
this.disable()
} else if (value === false) {
this.enable()
}
break
default:
this.setValue(prop, value)
}
return this
}
setLabel (value) {
// console.log('setLabel', value)
if (this.ui.label) {
this.ui.label.innerHTML = value
}
}
setText (value) {
this.setLabel(value)
}
get () {
return this.value
}
/**
* set switch value
* @param {boolean} value [description]
*/
getValue () {
return this.value
}
/**
* set switch value
* @param {boolean} value [description]
*/
setValue (value, silent) {
// console.log('setValue', value, typeof silent, silent)
this.check(value, silent)
}
/**
* [toggle description]
* @return {Object} The class instance
*/
toggle () {
// console.log('toggle')
if (this.disabled) return
this.focus()
if (this.checked) {
this.check(false)
} else {
this.check(true)
}
return this
}
/**
* Set checkbox value
* @param {boolean} value [description]
*/
check (checked, silent) {
// console.log('check', checked, silent)
if (checked === true) {
this.root.classList.add('is-checked')
this.ui.input.checked = true
this.checked = true
this.value = true
if (!silent) {
this.emit('change', this.checked)
}
} else {
this.root.classList.remove('is-checked')
this.ui.input.checked = false
this.checked = false
this.value = false
if (!silent) {
this.emit('change', this.checked)
}
}
return this
}
/**
* [_onInputFocus description]
* @return {?} [description]
*/
focus () {
if (this.disabled === true) return this
this.root.classList.add('is-focused')
if (this.ui.input !== document.activeElement) { this.ui.input.focus() }
return this
}
/**
* [_onInputBlur description]
* @return {?} [description]
*/
blur () {
this.root.classList.remove('is-focused')
return this
}
} |
JavaScript | class ImageInfoStore
{
/**
* Full config.
* @member {Config}
*/
config = null;
/**
* The actual store.
* @member {object}
*/
store = {bySrc: {}, byPage: {}};
/**
* Constructor.
*
* @param {Config} config Configs.
*
* @return {ImageInfostore}
*/
constructor(config)
{
this.config = config;
}
/**
* Load a cache from disk.
*
* @return {FileCache}
*/
load()
{
let cp = path.join(this.config.sitePath, '_cache', 'imageInfoCache.json');
if (!fs.existsSync(cp)) {
debug(`No saved file cache found at ${cp}. This may be okay, but just saying.`);
this.store.bySrc = {};
} else {
debug(`Loading file cache from ${cp}.`);
let serialised = fs.readFileSync(cp, 'utf8');
this.store.bySrc = JSON.parse(serialised);
}
return this;
}
/**
* Save a cache to disk.
*
* @return {void}
*/
save()
{
let cp = path.join(this.config.sitePath, '_cache', 'imageInfoCache.json');
if (!fs.existsSync(path.dirname(cp))) {
fs.mkdirSync(path.dirname(cp), {recurse: true});
let serialised = JSON.stringify(this.store.bySrc);
fs.writeFileSync(cp, serialised, 'utf8');
} else {
let serialised = JSON.stringify(this.store.bySrc);
fs.writeFileSync(cp, serialised, 'utf8');
}
}
/**
* Add some metadata by source AND page.
*
* @param {string} src Base source name.
* @param {string} page Page name.
* @param {object} info Info metadata.
*
* @return {ImageInfoStore}
*/
addBySrcAndPage(src, page, info)
{
if (!this.hasBySrc(src)) {
this.addBySrc(src, info);
}
this.addByPage(page, src);
return this;
}
/**
* Add some metadata by source.
*
* @param {string} src Base source name.
* @param {object} info Info metadata.
*
* @return {ImageInfoStore}
*/
addBySrc(src, info)
{
if (!this.hasBySrc(src)) {
this.store.bySrc[src] = info;
}
return this;
}
/**
* See if we have something by source.
*
* @param {string} src Source to test.
*
* @return {boolean}
*/
hasBySrc(src)
{
return Object.keys(this.store.bySrc).includes(src);
}
/**
* Get image info by source.
*
* @param {string} src Source to retrieve.
* @param {boolean} mustExist Must this exist?
*
* @return {object}
*
* @throws {GfImageInfoStoreError}
*/
getBySrc(src, mustExist = true)
{
if (!this.hasBySrc(src)) {
if (mustExist) {
throw new GfImageInfoStoreError(`Could not retrieve image by source: ${src}`);
} else {
return null;
}
}
return this.store.bySrc[src];
}
/**
* Get the source's image of specified type that's closest to the size given.
*
* @param {string} src Source to get image for.
* @param {string} type Type of image.
* @param {number} size Size we're looking for.
*
* @return {object}
*/
getSpecificBySrc(src, type, size)
{
if (!this.hasBySrc(src)) {
return null;
}
let saved = null;
let savedDiff = 999999;
let found = this.getBySrc(src);
for (let idx in found) {
if (!Object.keys(found[idx]).includes(type)) {
continue;
}
for (let item of found[idx][type]) {
if (item.width === size) {
return item;
} else {
if (Math.abs(item.width - savedDiff) < Math.abs(size - savedDiff)) {
saved = item;
savedDiff = Math.abs(item.width - savedDiff);
}
}
}
}
return saved;
}
//
// ==============================================================================================
//
/**
* Add some metadata by page.
*
* @param {string} page Page URL.
* @param {string} src Source name to store.
*
* @return {ImageInfoStore}
*/
addByPage(page, src)
{
page = GfPath.removeBothSlashes(page);
if (!this.store.byPage[page]) {
this.store.byPage[page] = [];
}
this.store.byPage[page].push(src);
return this;
}
/**
* See if we have something by page.
*
* @param {string} page Page to test.
*
* @return {boolean}
*/
hasByPage(page)
{
page = GfPath.removeBothSlashes(page);
return Object.keys(this.store.byPage).includes(page);
}
/**
* Get image info by page.
*
* @param {string} page Page to retrieve.
* @param {boolean} mustExist Must this exist?
*
* @return {object}
*
* @throws {GfImageInfoStoreError}
*/
getByPage(page, mustExist = false)
{
page = GfPath.removeBothSlashes(page);
if (!this.hasByPage(page)) {
if (mustExist) {
throw new GfImageInfoStoreError(`Could not retrieve image by page: ${page}`);
} else {
return null;
}
}
let ret = [];
for (let src of this.store.byPage[page]) {
ret.push(this.getBySrc(src));
}
return ret;
}
/**
* Get the page's image of specified type that's closest to the size given.
*
* @param {string} page Page to get image for.
* @param {string} type Type of image.
* @param {number} size Size we're looking for.
*
* @return {object}
*/
getSpecificByPage(page, type, size)
{
page = GfPath.removeBothSlashes(page);
if (!this.hasByPage(page)) {
return null;
}
let saved = null;
let savedDiff = 999999;
let forPage = this.getByPage(page);
for (let item of forPage) {
for (let t in item) {
if (t === type) {
for (let file of item[t].files) {
if (file.width === size) {
return file;
} else {
debugdev(`Checking ${Math.abs(file.width - savedDiff)} < ${Math.abs(size - savedDiff)}`)
if (Math.abs(file.width - savedDiff) < Math.abs(size - savedDiff)) {
saved = file;
savedDiff = Math.abs(file.width - savedDiff);
}
}
}
}
}
}
return saved;
}
} |
JavaScript | class Character extends Container {
constructor() {
super();
this.name = 'character';
this._charBody = new Sprite.from('char-body');
this._charBody.name = 'char-body';
this._charEye = new Sprite.from('char-eye');
this._charEye.name = 'char-eye';
this._charLidBottom = new Sprite.from('char-lid-bottom');
this._charLidBottom.name = 'char-lid-bottom';
this._charLidTop = new Sprite.from('char-lid-top');
this._charLidTop.name = 'char-lid-top';
this._init();
}
/**
* Sets the elements up
* @private
*/
_init() {
this._charBody.anchor.set(0.5);
this._charEye.anchor.set(0.5);
this._charLidBottom.anchor.set(0.5, 1);
this._charLidTop.anchor.set(0.5, 0);
this._charEye.position.y = -20;
this._charLidTop.position.y = -60;
this._charLidBottom.position.y = 20;
this.addChild(
this._charBody,
this._charEye,
this._charLidBottom,
this._charLidTop,
);
this.tl = new gsap.timeline();
}
/**
* Plays the blinking nimation
*/
blink() {
const eyelidsScale = [this._charLidTop, this._charLidBottom].map((c) => c.scale);
this.tl.to(eyelidsScale, {
y: 1.4,
yoyo: true,
repeat: 1,
duration: 0.1,
ease: 'linear'
});
}
/**
* Eyes widening animation
*/
openEyesWide() {
const eyelidsScale = [this._charLidTop, this._charLidBottom].map((c) => c.scale);
this.tl
.to(eyelidsScale, {
y: 0.3,
x: 0.6,
duration: 0.1,
ease: 'power1.in',
})
.to(eyelidsScale, {
y: 1,
x: 1,
duration: 0.3,
}, '+=0.5');
}
/**
* Starts the hover animation.
* @param {number | string} y the y property for the tween
* @param {number} duration tween duration
* @returns {Character}
*/
hover(y, duration) {
gsap.to(this.position, {
y,
duration,
repeat: -1,
yoyo: true,
ease: 'power1.inOut',
});
return this;
}
/**
* Hook called whenever the pointer moves.
* @param {Event} e event
* @private
*/
_onPointerMove(e) {
const bounds = this.getBounds();
const eyeMiddlePos = {
x: bounds.x + (bounds.width / 2),
y: bounds.y + (bounds.height / 2),
};
const eyePos = {
x: -(eyeMiddlePos.x - e.pageX) / 120,
y: -(eyeMiddlePos.y - e.pageY) / 120 - 20,
};
this._charEye.position.x = eyePos.x;
this._charEye.position.y = eyePos.y;
}
/**
* Eyes start following the pointer.
* @returns {Character}
*/
followMouse() {
this.pointerHandler = this._onPointerMove.bind(this);
window.addEventListener('pointermove', this.pointerHandler);
return this;
}
/**
* Eyes stop following the cursor.
* @returns {Character}
*/
unfollowMouse() {
window.removeEventListener('pointermove', this.pointerHandler);
return this;
}
/**
* Makes the eyelid sprites invisible
* @returns {Character}
*/
openEyes() {
this._charLidBottom.visible = false;
this._charLidTop.visible = false;
return this;
}
/**
* Makes eyelid sprites visible
* @returns {Character}
*/
closeEyes() {
this._charLidBottom.visible = true;
this._charLidTop.visible = true;
return this;
}
} |
JavaScript | class TurtleMessageConsumer extends Writable {
constructor(turtle, options) {
super(options);
this.turtle = turtle;
this.previousChunks = [];
this.incompleteMsg = '';
}
/**
* Transforms a chunk of json msgs to json and applies the it
* on the turtle canvas. Takes care of incomplete messages at
* the end of a chunk.
*
* @param {any} str
*/
transformChunk (str) {
var newStr = str;
// Append the incompleteMsgs from last the last chunk to the new one
if (this.incompleteMsg !== '') {
newStr = this.incompleteMsg.concat(str);
this.incompleteMsg = ''; // Reset incompleteMsgs
}
// Now split the msgs by \n\r see turtle.py sendPickle
let msgs = newStr.split('\n\r');
var length = msgs.length;
// Check if chunk contains an incomplete message at the end
if (str.endsWith('\n\r') === false) {
debug('Incomplete TurtleMessage - buffering now');
this.incompleteMsg = msgs[length - 1];
length = length - 1; // Ignore last incomplete message in processing
}
// Iterate over all msgs and try to parse and apply them
for (let i = 0; i < length; i++) {
if (msgs[i].length === 0 || (msgs[i].length === 1 && msgs[i].charCodeAt(0) === 13)) {
// Skip those empty lines
} else {
try {
let chunkJson = JSON.parse(msgs[i]);
this.turtle.onStreamMessage(chunkJson);
} catch (e) {
if (e instanceof SyntaxError) {
// We might recover from those
console.warn(`Invalid json message:`);
} else {
// Those can lead to some serious problems.
// How can we access the std.out to output our error here
// ToDo: add stdout access and print error
console.error(e);
this.emit('error', e);
}
}
}
}
}
_write (chunk, encoding, callback) {
let chunkStr = chunk.toString();
// Pass Chunk to our transform method
debug('Received TurtleMessage:', chunkStr);
this.transformChunk(chunkStr);
callback();
}
} |
JavaScript | class Turtle extends EventEmitter {
constructor(streams, project) {
super();
this.project = project;
this.canvas; // jQuery object
this.items = [];
this.streams = streams;
debug('Created Instance');
// The MessageConsumer parses the JSON messages and applies them
const turtleMessageConsumer = new TurtleMessageConsumer(this, {
objectMode: true
});
turtleMessageConsumer.on('error', e => {
console.warn('TurtleMessageConsumer:', e);
if (streams.stdout) {
streams.stdout.write('Unser Server ist etwas aus dem Tritt gekommen. Bitte starte das Beispiel erneut.');
}
});
// Now pipe the incoming messages to our consumer/transformer
this.streams.fromServer.pipe(turtleMessageConsumer, { end: true });
this.debugChars = [];
this.canvasClickHandler = this.canvasClickHandler.bind(this);
this.canvasReleaseHandler = this.canvasReleaseHandler.bind(this);
}
// ToDo: handle different events, may require changes in turtle.py
// https://docs.python.org/3.1/library/turtle.html#turtle.onclick
// https://docs.python.org/3.1/library/turtle.html#turtle.onkey
// http://openbookproject.net/thinkcs/python/english3e/events.html
getMouseEventData(e) {
let dx;
let dy;
let xpos;
let ypos;
let eventX;
let eventY;
if (e.eventPhase !== 2) {
return;
}
e.stopPropagation();
dx = this.canvas.width / 2;
dy = this.canvas.height / 2;
if (e.offsetX == undefined) {
xpos = e.pageX - this.canvas.offsetLeft;
ypos = e.pageY - this.canvas.offsetTop;
} else {
xpos = e.offsetX;
ypos = e.offsetY;
}
eventX = xpos - dx;
eventY = ypos - dy;
// Turtle uses Left, Middle, Right => 1, 2, 3
// Browsers use 0, 1, 2, 3, 4...
let button = e.button != null ? e.button : 0;
button += 1; // Add 1 to match turtle num
return {
eventX,
eventY,
button
};
}
canvasReleaseHandler(e) {
let eventData = this.getMouseEventData(e);
this.streams.toServer.write(JSON.stringify({
'cmd': 'canvasevent',
'type': `<Button${eventData.button}-ButtonRelease>`,
'x': eventData.eventX,
'y': eventData.eventY
}));
this.streams.toServer.write('\n');
}
canvasClickHandler(e) {
let eventData = this.getMouseEventData(e);
this.streams.toServer.write(JSON.stringify({
'cmd': 'canvasevent',
'type': `<Button-${eventData.button}>`,
'x': eventData.eventX,
'y': eventData.eventY
}));
this.streams.toServer.write('\n');
}
canvasDragHandler(e) {
// ToDo:
// Add handler in mouseclick
// Remove handler in mouserelease
// always remove in addCanvasClickHandler
}
// ToDo: add click, release and key handlers
addCanvasClickHandler() {
this.canvas.removeEventListener('mousedown', this.canvasClickHandler);
this.canvas.addEventListener('mousedown', this.canvasClickHandler);
this.canvas.removeEventListener('mouseup', this.canvasReleaseHandler);
this.canvas.addEventListener('mouseup', this.canvasReleaseHandler);
}
/**
* Create or get a canvas
*/
getOrCreateCanvas () {
if (this.canvas == null) {
this.canvas = document.createElement('canvas');
this.canvas.width = 800;
this.canvas.height = 600;
// add a new tab with the turtle canvas
// Delete all old/previous turtle tabs
this.project.tabManager.closeTabByType('turtle');
let tabIndex = this.project.tabManager.addTab('turtle', {item: this, active: false});
this.project.tabManager.hideTabsByType('file');
// Now only show the turtle tab
this.project.tabManager.toggleTab(tabIndex);
this.tab = this.project.tabManager.getTabs()[tabIndex]; // Get Tab Reference
this.addCanvasClickHandler();
}
return this.canvas;
}
onStreamMessage (msg) {
switch (msg.cmd) {
case 'turtle':
this.handleTurtleCommand(msg);
break;
case 'turtlebatch':
this.handleTurtleBatchCommand(msg);
break;
case 'debug':
// ignore (ToDo)
debug('Received debug message: %s', msg);
break;
default:
debug('Received unhandled turtle msg: %s', msg.cmd);
}
}
handleTurtleCommand (msg) {
if (msg.action in this) {
let result = this[msg.action].apply(this, msg.args);
console.info('handleTurtleCommand', msg, result);
this.streams.toServer.write(JSON.stringify({cmd: 'result', 'result': result}) + '\n');
} else {
this.streams.toServer.write(JSON.stringify({cmd: 'exception', exception: 'AttributeError', message: msg.action}) + '\n');
}
}
handleTurtleBatchCommand (msg) {
for (let i = 0; i < msg.batch.length; i++) {
let cmd = msg.batch[i];
this[cmd[0]].apply(this, cmd[1]);
}
}
update() {
var i, k, canvas, ctx, dx, dy, item, c, length;
canvas = this.getOrCreateCanvas();
ctx = canvas.getContext('2d');
// clear canvas for redrawing
ctx.clearRect(0, 0, canvas.width, canvas.height);
length = this.items.length;
dx = canvas.width / 2;
dy = canvas.height / 2;
for (i = 0; i < length; i += 1) {
item = this.items[i];
c = item.coords;
switch (item.type) {
case 'line':
ctx.beginPath();
ctx.moveTo(c[0] + dx, c[1] + dy);
for (k = 2; k < c.length; k += 2) {
ctx.lineTo(c[k] + dx, c[k + 1] + dy);
}
// add some logic to handle pencolor and fillcolor
if (item.fill && item.fill !== "") {
ctx.strokeStyle = item.fill;
ctx.fillStyle = item.fill;
} else if (item.outline && item.outline !== "") {
ctx.strokeStyle = item.outline;
} else if (this.fill) {
ctx.strokeStyle = this.fill;
}
ctx.stroke();
break;
case 'polygon':
ctx.beginPath();
ctx.moveTo(c[0] + dx, c[1] + dy);
for (k = 2; k < c.length; k += 2) {
ctx.lineTo(c[k] + dx, c[k + 1] + dy);
}
ctx.closePath();
if (item.fill !== "") {
ctx.fillStyle = item.fill;
ctx.strokeStyle = item.fill;
ctx.fill();
}
ctx.stroke();
break;
case 'dot':
ctx.beginPath();
ctx.arc(c[0] + dx, c[1] + dy, item.radius, 0, 2 * Math.PI);
ctx.fillStyle = item.fill;
ctx.fill();
break;
case 'image':
// ToDo: Support images here
break;
case 'write':
// ctx write text
ctx.fillStyle = item.fill;
ctx.font = `${item.font[2]} ${item.font[1]}px ${item.font[0]}`;
ctx.textAlign = ANCHOR_LUT[item.anchor];
ctx.textBaseline = 'middle';
ctx.fillText(item.text, item.x+dx, item.y+dy);
break;
}
}
}
get_width() {
return this.getOrCreateCanvas().width;
}
get_height() {
return this.getOrCreateCanvas().height;
}
winfo_width() {
return this.get_width();
}
winfo_height() {
return this.get_height();
}
delete (item) {
if (item == 'all') {
this.items = [];
} else {
delete this.items[item];
}
}
create_text (item) {
this.items.push(item);
return this.items.length - 1;
}
create_image (image) {
debug('Received create_image message: %s', image.toString());
this.items.push({ type: 'image', image: image });
return this.items.length - 1;
}
create_dot(item) {
this.items.push({type: 'dot', coords: item.pos, fill: item.color, radius: item.size / 2});
return this.items.length - 1;
}
create_line () {
this.items.push({
type: 'line',
fill: '',
coords: [0, 0, 0, 0],
width: 2,
capstyle: 'round'
});
return this.items.length - 1;
}
create_polygon () {
this.items.push({
type: 'polygon',
// fill: "" XXX
// outline: "" XXX
coords: [0, 0, 0, 0, 0, 0]
});
return this.items.length - 1;
}
coords (item, coords) {
if (coords === undefined) {
return this.items[item].coords;
}
this.items[item].coords = coords;
}
itemconfigure (item, key, value) {
this.items[item][key] = value;
}
css (key, value) {
if (value !== undefined) {
let canvas = this.getOrCreateCanvas();
canvas.style[key] = value; // tuples of values
}
}
title(title) {
this.emit('title', title);
}
} |
JavaScript | class ResponseFormatter {
constructor() {
if (this.constructor.name === 'ResponseFormatter') {
throw Error('Cannot instantiate an interface');
}
if (!this.format) {
throw Error('Missing interface method `format`');
}
const formatFn = this.format;
this.format = data => formatFn(data);
}
} |
JavaScript | class IovPlayer {
static EVENT_NAMES = [
'metric',
'unsupportedMimeCodec',
'firstFrameShown',
'videoReceived',
'videoInfoReceived',
];
static METRIC_TYPES = [
'sourceBuffer.bufferTimeEnd',
'video.currentTime',
'video.drift',
'video.driftCorrection',
'video.segmentInterval',
'video.segmentIntervalAverage',
];
static factory (
logId,
videoElement,
onConduitMessageError,
onPlayerError,
) {
return new IovPlayer(
logId,
videoElement,
onConduitMessageError,
onPlayerError,
);
}
constructor (
logId,
videoElement,
onConduitMessageError = this.onConduitMessageError,
onPlayerError = this.onPlayerError,
) {
this.logId = logId;
this.logger = Logger().factory(`Iov Player ${this.logId}`);
this.logger.debug('constructor');
this.metrics = {};
// @todo - there must be a more proper way to do events than this...
this.events = {};
for (let i = 0; i < IovPlayer.EVENT_NAMES.length; i++) {
this.events[IovPlayer.EVENT_NAMES[i]] = [];
}
this.videoElement = videoElement;
this.conduitCount = 0;
this.conduit = null;
this.streamConfiguration = null;
this.onConduitMessageError = onConduitMessageError;
this.onPlayerError = onPlayerError;
this.firstFrameShown = false;
this.stopped = false;
// Used for determining the size of the internal buffer hidden from the MSE
// api by recording the size and time of each chunk of video upon buffer append
// and recording the time when the updateend event is called.
this.LogSourceBuffer = false;
this.LogSourceBufferTopic = null;
this.latestSegmentReceived = null;
this.segmentIntervalAverage = null;
this.segmentInterval = null;
this.segmentIntervals = [];
this.mseWrapper = null;
this.moov = null;
// These can be configured manually after construction
this.ENABLE_METRICS = DEFAULT_ENABLE_METRICS;
this.SEGMENT_INTERVAL_SAMPLE_SIZE = DEFAULT_SEGMENT_INTERVAL_SAMPLE_SIZE;
this.DRIFT_CORRECTION_CONSTANT = DEFAULT_DRIFT_CORRECTION_CONSTANT;
}
on (name, action) {
this.logger.debug(`Registering Listener for ${name} event...`);
if (!IovPlayer.EVENT_NAMES.includes(name)) {
throw new Error(`"${name}" is not a valid event."`);
}
if (this.destroyed) {
return;
}
this.events[name].push(action);
}
trigger (name, value) {
const sillyMetrics = [
'metric',
'videoReceived',
];
if (sillyMetrics.includes(name)) {
this.logger.silly(`Triggering ${name} event...`);
}
else {
this.logger.debug(`Triggering ${name} event...`);
}
if (this.destroyed) {
return;
}
if (!IovPlayer.EVENT_NAMES.includes(name)) {
throw new Error(`"${name}" is not a valid event."`);
}
for (let i = 0; i < this.events[name].length; i++) {
this.events[name][i](value, this);
}
}
metric (type, value) {
if (!this.ENABLE_METRICS) {
return;
}
if (!IovPlayer.METRIC_TYPES.includes(type)) {
// @todo - should this throw?
return;
}
switch (type) {
case 'video.driftCorrection': {
if (!this.metrics[type]) {
this.metrics[type] = 0;
}
this.metrics[type] += value;
break;
}
default: {
this.metrics[type] = value;
}
}
this.trigger('metric', {
type,
value: this.metrics[type],
});
}
_onError (
type,
message,
error,
) {
this.logger.warn(
type,
':',
message,
);
this.logger.error(error);
}
generateConduitLogId () {
return `${this.logId}.conduit:${++this.conduitCount}`;
}
onConduitReconnect = (error) => {
if (error) {
this.logger.error(error);
// @todo - should we do anything else on error?
return;
}
// @todo - is there a more performant way to do this?
this.restart();
};
onPlayerError = (error) => {
this.logger.error('Player Error!');
this.logger.error(error);
};
onConduitMessageError = (error) => {
this.logger.error('Conduit Message Error!');
this.logger.error(error);
};
async initialize (streamConfiguration = this.streamConfiguration) {
if (!StreamConfiguration.isStreamConfiguration(streamConfiguration)) {
throw new Error('streamConfiguration is not valid');
}
this.logger.debug(`Initializing with ${streamConfiguration.streamName}`);
this.streamConfiguration = streamConfiguration;
// This MUST be globally unique! The CLSP server will broadcast the stream
// to a topic that contains this id, so if there is ANY other client
// connected that has the same id anywhere in the world, the stream to all
// clients that use that topic will fail. This is why we use guids rather
// than an incrementing integer.
// It is now prefixed with `clsp-plugin-` to differentiate requests that
// come from this plugin from others.
// Note - this must not contain the '+' character
// @todo - the caller should be able to provide a prefix or something
this.clientId = `clsp-plugin-${utils.version.replace('+', '-build-')}-${uuidv4()}`;
this.videoElement.id = this.clientId;
this.videoElement.dataset.name = streamConfiguration.streamName;
this.conduit = await ConduitCollection.asSingleton().create(
this.generateConduitLogId(),
this.clientId,
this.streamConfiguration,
this.videoElement.parentNode,
this.onConduitReconnect,
this.onConduitMessageError,
);
await this.conduit.initialize();
}
_html5Play () {
// @see - https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/play
try {
const promise = this.videoElement.play();
if (typeof promise !== 'undefined') {
promise.catch((error) => {
this._onError(
'play.promise',
'Error while trying to play clsp video',
error,
);
});
}
}
catch (error) {
this._onError(
'play.notPromise',
'Error while trying to play clsp video - the play operation was NOT a promise!',
error,
);
}
}
async reinitializeMseWrapper (mimeCodec) {
if (this.mseWrapper) {
await this.mseWrapper.destroy();
}
this.mseWrapper = MSEWrapper.factory(this.videoElement);
this.mseWrapper.on('metric', ({
type,
value,
}) => {
this.trigger('metric', {
type,
value,
});
});
this.mseWrapper.initializeMediaSource({
onSourceOpen: async () => {
this.logger.debug('on mediaSource sourceopen');
await this.mseWrapper.initializeSourceBuffer(mimeCodec, {
onAppendStart: (byteArray) => {
this.logger.silly('On Append Start...');
// onAppendStart
this.conduit.segmentUsed(byteArray);
},
onAppendFinish: (info) => {
this.logger.silly('On Append Finish...');
if (!this.firstFrameShown) {
this.firstFrameShown = true;
this.trigger('firstFrameShown');
}
this.drift = info.bufferTimeEnd - this.videoElement.currentTime;
this.metric('sourceBuffer.bufferTimeEnd', info.bufferTimeEnd);
this.metric('video.currentTime', this.videoElement.currentTime);
this.metric('video.drift', this.drift);
if (this.drift > ((this.segmentIntervalAverage / 1000) + this.DRIFT_CORRECTION_CONSTANT)) {
this.metric('video.driftCorrection', 1);
this.videoElement.currentTime = info.bufferTimeEnd;
}
if (this.videoElement.paused === true) {
this.logger.debug('Video is paused!');
this._html5Play();
}
},
onRemoveFinish: (info) => {
this.logger.debug('onRemoveFinish');
},
onAppendError: async (error) => {
// internal error, this has been observed to happen the tab
// in the browser where this video player lives is hidden
// then reselected. 'ex' is undefined the error is bug
// within the MSE C++ implementation in the browser.
this._onError(
'sourceBuffer.append',
'Error while appending to sourceBuffer',
error,
);
await this.reinitializeMseWrapper(mimeCodec);
},
onRemoveError: (error) => {
if (error.constructor.name === 'DOMException') {
// @todo - every time the mseWrapper is destroyed, there is a
// sourceBuffer error. No need to log that, but you should fix it
return;
}
// observed this fail during a memry snapshot in chrome
// otherwise no observed failure, so ignore exception.
this._onError(
'sourceBuffer.remove',
'Error while removing segments from sourceBuffer',
error,
);
},
onStreamFrozen: async () => {
this.logger.debug('stream appears to be frozen - reinitializing...');
await this.reinitializeMseWrapper(mimeCodec);
},
onError: async (error) => {
this._onError(
'mediaSource.sourceBuffer.generic',
'mediaSource sourceBuffer error',
error,
);
await this.reinitializeMseWrapper(mimeCodec);
},
});
this.trigger('videoInfoReceived');
this.mseWrapper.appendMoov(this.moov);
},
onSourceEnded: async () => {
this.logger.debug('on mediaSource sourceended');
await this.stop();
},
onError: (error) => {
this._onError(
'mediaSource.generic',
'mediaSource error',
// @todo - sometimes, this error is an event rather than an error!
// If different onError calls use different method signatures, that
// needs to be accounted for in the MSEWrapper, and the actual error
// that was thrown must ALWAYS be the first argument here. As a
// shortcut, we can log `...args` here instead.
error,
);
},
});
if (!this.mseWrapper.mediaSource || !this.videoElement) {
throw new Error('The video element or mediaSource is not ready!');
}
this.mseWrapper.reinitializeVideoElementSrc();
}
async restart () {
this.logger.debug('restart');
// @todo - this has not yet been tested for memory leaks
// If the src attribute is missing, it means we must reinitialize. This can
// happen if the video was loaded while the page was not visible, e.g.
// document.hidden === true, which can happen when switching tabs.
// @todo - is there a more "proper" way to do this?
const needToReinitialize = !this.videoElement.src;
await this.stop();
if (needToReinitialize) {
if (this.conduit) {
ConduitCollection.asSingleton().remove(this.clientId);
}
await this.initialize();
}
const playError = await this.play();
if (playError) {
return playError;
}
if (needToReinitialize) {
this._html5Play();
}
}
onMoof = (clspMessage) => {
// @todo - this seems like a hack...
if (this.stopped) {
return;
}
this.trigger('videoReceived');
this.getSegmentIntervalMetrics();
// Sometimes, the first moof arrives before the mseWrapper has finished
// being initialized, so we will need to drop those frames
if (!this.mseWrapper) {
return;
}
this.mseWrapper.append(clspMessage.payloadBytes);
};
/**
* Note that if an error is thrown during play, the IovPlayer instance should
* be destroyed to free resources.
*/
async play () {
this.logger.debug('play');
this.stopped = false;
if (!this.streamConfiguration) {
this.logger.error('Cannot play a stream without a stream configuration');
return;
}
let mimeCodec;
let moov;
try {
({
// guid,
mimeCodec,
moov,
} = await this.conduit.play(this.onMoof));
}
catch (error) {
this.onPlayerError(error);
// Don't throw here, since the error was handled. Return the error to the
// caller.
return error;
}
if (!MSEWrapper.isMimeCodecSupported(mimeCodec)) {
this.trigger('unsupportedMimeCodec', `Unsupported mime codec: ${mimeCodec}`);
throw new Error(`Unsupported mime codec: ${mimeCodec}`);
}
this.moov = moov;
await this.reinitializeMseWrapper(mimeCodec);
this.conduit.resyncStream(() => {
// console.log('sync received re-initialize media source buffer');
this.reinitializeMseWrapper(mimeCodec);
});
}
/**
* @returns {Promise}
*/
stop () {
this.logger.debug('stop...');
if (this.stopped) {
return Promise.resolve();
}
this.stopped = true;
this.moov = null;
this.logger.debug('stop about to finish synchronous operations and return promise...');
// The logic above MUST be run synchronously when called, therefore,
// we cannot use async to define the stop method, and must return a
// promise here rather than using await. We return this promise so
// that the caller has the option of waiting, but is not forced to
// wait.
return new Promise(async (resolve, reject) => {
try {
try {
await this.conduit.stop();
}
catch (error) {
this.logger.error('failed to stop the conduit');
this.logger.error(error);
}
if (!this.mseWrapper) {
this.logger.debug('stop succeeded asynchronously...');
return resolve();
}
// Don't wait until the next play event or the destruction of this player
// to clear the MSE
await this.mseWrapper.destroy();
this.mseWrapper = null;
this.logger.debug('stop succeeded asynchronously...');
resolve();
}
catch (error) {
this.logger.error('stop failed asynchronously...');
reject(error);
}
});
}
getSegmentIntervalMetrics () {
const previousSegmentReceived = this.latestSegmentReceived;
this.latestSegmentReceived = Date.now();
if (previousSegmentReceived) {
this.segmentInterval = this.latestSegmentReceived - previousSegmentReceived;
}
if (this.segmentInterval) {
if (this.segmentIntervals.length >= this.SEGMENT_INTERVAL_SAMPLE_SIZE) {
this.segmentIntervals.shift();
}
this.segmentIntervals.push(this.segmentInterval);
let segmentIntervalSum = 0;
for (let i = 0; i < this.segmentIntervals.length; i++) {
segmentIntervalSum += this.segmentIntervals[i];
}
this.segmentIntervalAverage = segmentIntervalSum / this.segmentIntervals.length;
this.metric('video.segmentInterval', this.segmentInterval);
this.metric('video.segmentIntervalAverage', this.segmentIntervalAverage);
}
}
enterFullscreen () {
if (!window.document.fullscreenElement) {
// Since the iov and player take control of the video element and its
// parent, ask the parent for fullscreen since the video elements will be
// destroyed and recreated when changing sources
this.videoElement.parentNode.requestFullscreen();
}
}
exitFullscreen () {
if (window.document.exitFullscreen) {
window.document.exitFullscreen();
}
}
toggleFullscreen () {
if (!window.document.fullscreenElement) {
this.enterFullscreen();
}
else {
this.exitFullscreen();
}
}
_freeAllResources () {
this.logger.debug('_freeAllResources...');
ConduitCollection.asSingleton().remove(this.clientId);
this.conduit = null;
// The caller must destroy the streamConfiguration
this.streamConfiguration = null;
this.firstFrameShown = null;
this.events = null;
this.metrics = null;
this.LogSourceBuffer = null;
this.LogSourceBufferTopic = null;
this.latestSegmentReceived = null;
this.segmentIntervalAverage = null;
this.segmentInterval = null;
this.segmentIntervals = null;
this.moov = null;
this.logger.debug('_freeAllResources finished...');
}
/**
* @returns {Promise}
*/
destroy () {
this.logger.debug('destroy...');
if (this.destroyed) {
return;
}
this.destroyed = true;
// Note that we DO NOT wait for the stop command to finish execution,
// because this destroy method MUST be treated as a synchronous operation
// to ensure that the caller is not forced to wait on destruction. This
// allows us to properly support client side libraries and frameworks that
// do not support asynchronous destruction. See the comments in the destroy
// method on the MSEWrapper for a more detailed explanation.
this.logger.debug('about to stop...');
const stopPromise = this.stop();
// Setting the src of the video element to an empty string is
// the only reliable way we have found to ensure that MediaSource,
// SourceBuffer, and various Video elements are properly dereferenced
// to avoid memory leaks
// @todo - should these occur after stop? is there a reason they're done
// in this order?
this.videoElement.src = '';
this.videoElement.parentNode.removeChild(this.videoElement);
this.videoElement.remove();
this.videoElement = null;
this.logger.debug('exiting destroy, asynchronous destroy logic in progress...');
return stopPromise
.then(() => {
this.logger.debug('stopped successfully...');
this._freeAllResources();
this.logger.debug('destroy successfully finished...');
})
.catch((error) => {
this.logger.debug('stopped unsuccessfully...');
this.logger.error('Error while destroying the iov player!');
this.logger.error(error);
this._freeAllResources();
this.logger.debug('destroy unsuccessfully finished...');
});
}
} |
JavaScript | class RedditPostCreater {
constructor() {
// The list of post creater functions we have for Reddit. Functions should
// return null if it cannot create a post from the thing. The first post returned
// from these functions will be used as the post for that thing. At least one post
// must be returned by these functioins.
this.postCreaters = [
this.createImagePost.bind(this),
this.createDefaultPost.bind(this),
];
}
/**
* Create a list of Post from a list of things
* @param {List} things A list of Reddit things
* @return {List} A list of Post
*/
createPosts(things) {
// Avoids having to call `.bind`
return things.map(thing => this.createPost(thing));
}
/**
* Create a post from a thing by going through all the creaters.
* @param {Thing} thing A Reddit thing
* @return {Post} The Post this thing maps to
*/
createPost(thing) {
for (let createPostFn of this.postCreaters) {
const post = createPostFn(thing);
if (post !== null) {
return post;
}
}
}
/**
* Default post to create when none of the custom post creations work.
* TODO: iframe is to risky, change default to open in new tab.
* @param {Thing} thing A Reddit thing
* @return {Post} The default iframe post pointing to the url.
*/
createDefaultPost(thing) {
const data = thing.data;
return new PostBuilder(data.id, data.title, Post.VIEWS.IFRAME)
.iframe(data.url)
.secondaryText(data.url)
.build();
}
/**
* Attempts to create an image post
* @param {Thing} thing A Reddit thing
* @return {Post} A Post if possible
*/
createImagePost(thing) {
if (this.isRawImagePost(thing)) {
const data = thing.data;
return new PostBuilder(data.id, data.title, Post.VIEWS.IMAGE)
.image(data.url)
.secondaryText(data.url)
.build();
}
return null;
}
/**
* Checks whether a thing is a raw image post.
* @param {Thing} thing A Reddit thing
* @return {Boolean} Whether this post is an image
*/
isRawImagePost(thing) {
const data = thing.data;
if (!data && !data.url) {
return false;
}
const url = URI(data.url);
const domain = url.domain();
const subdomain = url.subdomain();
const suffix = url.suffix();
// TODO: is this complete?
const imageSuffixes = ['jpg', 'png', 'gif'];
const containsSuffix = imageSuffixes.indexOf(suffix) > -1;
// i.imgur.com rule
if (containsSuffix && subdomain === 'i' && domain === 'imgur.com') {
return true;
}
// i.redd.it rule
if (containsSuffix && subdomain === 'i' && domain === 'redd.it') {
return true;
}
}
} |
JavaScript | class ModeCTR extends Mode {
/**
* Creates this mode for encryption.
*
* @param {BlockCipherProcessor} cipher A block cipher instance.
* @param {Array<number>} iv The IV words.
*
* @returns {ModeProcessor}
*/
createEncryptor(cipher, iv) {
return new ModeCTRProcessor(cipher, iv);
}
/**
* Creates this mode for encryption.
*
* @param {BlockCipherProcessor} cipher A block cipher instance.
* @param {Array<number>} iv The IV words.
*
* @returns {ModeProcessor}
*/
createDecryptor(cipher, iv) {
return new ModeCTRProcessor(cipher, iv);
}
} |
JavaScript | class Spline {
constructor(mat_size,radiusx,radiusy,cx,cy) {
this._internal = {
inverseMatrix : null,
controlpoints : null,
nodepoints : null,
numpoints : 0,
};
this.ellipse(mat_size ,radiusx ,radiusy ,cx ,cy);
}
/** initialize class using a points arrray matrix
* @param {Matrix} points - a 2d array created using numericjs
*/
initialize(points) {
points = points || null;
if (points!==null)
this._internal.nodepoints=numeric.clone(points);
this._internal.numpoints=numeric.dim(this._internal.nodepoints)[0];
this._internal.controlpoints = splineutil.zero(this._internal.numpoints,2);
this.createInverseMatrix(this._internal.numpoints);
this.updatecontrolpoints();
}
/** get number of points
* @returns {number} n - number of points
*/
getnumpoints() {
return this._internal.numpoints;
}
/** get the nodepoints as a numericjs matrix
* @returns {Matrix} m - numeric js N*2 matrix
*/
getnodepoints() {
return this._internal.nodepoints;
}
/** create an ellipse (called by constructor)
* @param {number} mat_size - number of control points
* @param {number} radiusx,radiusy - x and y radii of ellipse
* @param {number} cx,cy - x and y position of ellipse centroid
*/
ellipse(np,radiusx,radiusy,centerx,centery) {
centerx=centerx||50.0;
centery=centery||50.0;
radiusx=radiusx||10.0;
radiusy=radiusy||10.0;
var n = splineutil.range(np|| DEFAULTPOINTS ,4,MAXPOINTS);
this._internal.nodepoints = splineutil.zero(n,2);
for (var i=0;i<n;i++) {
var t=(i/n)*2.0*Math.PI;
this._internal.nodepoints[i][0]=radiusx*Math.cos(t)+centerx;
this._internal.nodepoints[i][1]=radiusy*Math.sin(t)+centery;
}
this.initialize();
}
/** update the control points if nodepoints have changed */
updatecontrolpoints() {
this.inPlaceMultiply(this._internal.inverseMatrix,
this._internal.nodepoints,
this._internal.controlpoints);
}
/** Get position in array pos at arclength s
* @param {number} s - arclength in range 0..1
* @param {array} pos - output array [ x,y] (passed in to save on memory alloc/dealloc in loops)
*/
position(s,pos) {
var reals=s*this._internal.numpoints;
var index=Math.floor(reals);
var t=reals-index;
pos[0]=0.0; pos[1]=0.0;
for (var i=0;i<=3;i++) {
var b=splineutil.value(i,t);
var c=splineutil.cyclicrange(index+i-1,this._internal.numpoints);
for (var j=0;j<=1;j++)
pos[j]+=b*this._internal.controlpoints[c][j];
}
}
/** Get derivative of curve at arclength s
* @param {number} s - arclength in range 0..1
* @param {array} pos - output array [ x,y] (passed in to save on memory alloc/dealloc in loops)
* @returns {array} d - a 2-array containing dx/ds and dy/ds
*/
derivative(s) {
var reals=s*this._internal.numpoints;
var index=Math.floor(reals);
var t=reals-index;
var dpos = [ 0.0,0.0 ];
for (var i=0;i<=3;i++) {
var b=splineutil.der(i,t);
var c=splineutil.cyclicrange(index+i-1,this._internal.numpoints);
for (var j=0;j<=1;j++)
dpos[j]+=b*this._internal.controlpoints[c][j];
}
return dpos;
}
/** Get sampled curve from b-spline
* @param {number} ds - arclength spacing in range 0.005 to 0.5
* @returns {Matrix} d - an N*2-array containing x,y coordinates of each output point
*/
createcurve(ds) {
ds=splineutil.range(ds,0.005,0.5);
var np=1.0/ds;
var pts= splineutil.zero(np,2);
var pos=[0.0,0.0];
for (var i=0;i<np;i++) {
var s=i*ds;
this.position(s,pos);
pts[i][0]=pos[0];
pts[i][1]=pos[1];
}
return pts;
}
/** get the length of the curve (after sampling at ds=0.05)
* @returns {number} l - arclength of curve
*/
length(spacing) {
var ds = spacing || 0.05;
var pts=this.createcurve(ds);
var n=numeric.dim(pts)[0];
var d=0.0;
for (var i=0;i<n;i++) {
var ip=i+1;
if (ip===n)
ip=0;
d+=Math.sqrt( Math.pow(pts[i][0]-pts[ip][0],2.0)+
Math.pow(pts[i][1]-pts[ip][1],2.0));
}
return d;
}
/** resample spline to have a new number of points (DESTRUCTIVE)
* @param {number} newnumpoints - new number of points
*/
resample(newnumpoints) {
var n = splineutil.range( newnumpoints || DEFAULTPOINTS ,4,MAXPOINTS);
this._internal.nodepoints=this.createcurve(1.0/n);
this.initialize();
}
/** a complex test function -- used for testing
* @param {boolean} silent - if true print debug messages
* @returns {boolean} out - true or false
*/
// A complex test function
test(silent) {
silent=silent || false;
var mat = numeric.identity(this._internal.numpoints);
var x=splineutil.zero(this._internal.numpoints,2);
var i=0;
for (i=0;i<this._internal.numpoints;i++) {
var ip=i+1;
if (ip>(this._internal.numpoints-1)) ip=0;
var im=i-1;
if (im<0) im=this._internal.numpoints-1;
mat[i][im]=splineutil.value(0,0.0);
mat[i][i]=splineutil.value(1,0.0);
mat[i][ip]=splineutil.value(2,0.0);
x[i][0]=this._internal.controlpoints[i][0];
x[i][1]=this._internal.controlpoints[i][1];
}
var y=numeric.dot(mat,x);
if (!silent)
console.log('\t +++++ Check difference nodepoints size=',
this._internal.numpoints,'*',this._internal.numpoints,',',
numeric.norm2(numeric.sub(y,this._internal.nodepoints)));
var m2=numeric.inv(mat);
var z=numeric.dot(m2,y);
var err=numeric.norm2(numeric.sub(x,z));
if (!silent)
console.log('\t +++++ Check difference inverse=',
this._internal.numpoints,'*',this._internal.numpoints,',',err);
return (err<0.001);
}
/** create internal inverse matrix for nump control points
* this maps nodepoints to controlpoints
* @param {number} nump - number of points
*/
createInverseMatrix(nump) {
var forwardMatrix= splineutil.zero(nump,nump);
for (var i=0;i<nump;i++) {
var ip=splineutil.cyclicrange(i+1,nump);
var im=splineutil.cyclicrange(i-1,nump);
forwardMatrix[i][im]=1.0/6.0;
forwardMatrix[i][i]=2.0/3.0;
forwardMatrix[i][ip]=1.0/6.0;
}
this._internal.inverseMatrix=numeric.inv(forwardMatrix);
return true;
}
/** in place matrix multiply to save on memory alloc/dealloc A*x=B
* this maps nodepoints to controlpoints
* @param {Matrix} A - input matrix 1
* @param {Matrix} x - input matrix 2
* @param {Matrix} B - output
*/
inPlaceMultiply(A,X,B) {
var d=numeric.dim(A);
var matrows=d[0],
matcols=d[1],
veccols=numeric.dim(X)[1],
row=0,
col=0,
index=0;
for (row=0;row<matrows;row++) {
for (col=0;col<veccols;col++) {
B[row][col]=0.0;
for (index=0;index<matcols;index++)
B[row][col]+=A[row][index]*X[index][col];
}
}
}
} |
JavaScript | class Lexer {
/**
* Constructor.
*/
constructor() {
/**
* @type {RegExp}
*
* @private
*/
this._spaces = new RegExp('^[' + Lexer.SPACES + ']+$', 'g');
/**
* @type {RegExp}
*
* @private
*/
this._reservedKeywords = new RegExp('^' + Lexer.RESERVED_WORDS + '$', 'g');
/**
* @type {RegExp}
*
* @private
*/
this._identifiers = new RegExp('^#?' + Lexer.IDENTIFIER + '$', 'g');
/**
* @type {RegExp}
*
* @private
*/
this._numbers = new RegExp('^' + Lexer.NUMBERS + '$', 'g');
/**
* @type {RegExp}
*
* @private
*/
this._regexes = new RegExp('(?<=((?:^|[\\n;`=<>!~+\\-/%*&,?|:()[\\]{}]|' + Lexer.RESERVED_WORDS + ')\\s*))\\/((?![*+?])(?:[^\\r\\n\\[/\\\\]|\\\\.|\\[(?:[^\\r\\n\\]\\\\]|\\\\.)*\\])+)\\/w*', 'g');
/**
* @type {Object}
*
* @private
*/
this._last = undefined;
/**
* @type {string}
*
* @private
*/
this._input = undefined;
}
/**
* Reset the lexer
*/
reset() {
this.token = undefined;
this.lookahead = undefined;
this._peek = 0;
this._position = 0;
}
/**
* Resets the peek pointer to 0.
*/
resetPeek() {
this._peek = 0;
}
/**
* Gets the current position.
*
* @returns {int}
*/
get position() {
return this._position;
}
/**
* Resets the lexer position on the input to the given position.
*
* @param {int} position Position to place the lexical scanner.
*/
resetPosition(position = 0) {
this._position = position;
this.moveNext();
}
/**
* Retrieve the original lexer's input until a given position.
*
* @param {int} position
*
* @returns {string}
*/
getInputUntilPosition(position) {
return this._input.substr(0, position);
}
/**
* Checks whether a given token matches the current lookahead.
*
* @param {int|string} token
*
* @returns {boolean}
*/
isNextToken(token) {
return undefined !== this.lookahead && this.lookahead.type === token;
}
/**
* Checks whether any of the given tokens matches the current lookahead.
*
* @param {Array} tokens
*
* @returns {boolean}
*/
isNextTokenAny(tokens) {
return undefined !== this.lookahead && -1 !== tokens.indexOf(this.lookahead.type);
}
/**
* Moves to the next token in the input string.
*
* @returns {boolean}
*/
moveNext() {
this._peek = 0;
this.token = this._tokens[this._position];
this.lookahead = this._tokens[this._position + 1];
this._position++;
return this.token !== undefined && Lexer.T_EOF !== this.token.type;
}
/**
* Tells the lexer to skip input tokens until it sees a token with the given value.
*
* @param {string} type The token type to skip until.
*/
skipUntil(type) {
while (this.lookahead && this.lookahead.type !== type) {
this.moveNext();
}
}
/**
* Checks if given value is identical to the given token.
*
* @param {*} value
* @param {int} token
*
* @returns {boolean}
*/
isA(value, token) {
return this.getType(value) === token;
}
/**
* Checks if current token is of a given type.
*
* @param {int} token
*
* @returns {boolean}
*/
isToken(token) {
return this.token && this.token.type === token;
}
/**
* Moves the lookahead token forward.
*
* @returns {Object|undefined} The next token or undefined if there are no more tokens ahead.
*/
peek() {
if (this._tokens[this._position + this._peek]) {
return this._tokens[this._position + this._peek++];
}
return undefined;
}
/**
* Peeks at the next token, returns it and immediately resets the peek.
*
* @returns {Object|undefined} The next token or undefined if there are no more tokens ahead.
*/
glimpse() {
const peek = this.peek();
this._peek = 0;
return peek;
}
/**
* Gets the literal for a given token.
*
* @param {int} token
*
* @returns {string}
*/
getLiteral(token) {
const reflClass = new ReflectionClass(this);
const constants = reflClass.constants;
for (const [ name, value ] of __jymfony.getEntries(constants)) {
if (value === token) {
return name;
}
}
return token.toString();
}
/**
* Gets the original input data.
*
* @returns {string}
*/
get input() {
return this._input;
}
/**
* Sets the input data to be tokenized.
*
* The Lexer is immediately reset and the new input tokenized.
* Any unprocessed tokens from any previous input are lost.
*
* @param {string} input The input to be tokenized.
*/
set input(input) {
this._input = input;
this._tokens = [];
this.reset();
this._scan(input);
}
/**
* Re-scans a single token.
*
* @param {Token} token
* @param {Error} err
*/
rescan(token, err) {
this._last = undefined;
const regex = new RegExp('((?:' + this.getPatterns().join(')|(?:') + '))', 'g');
const tokens = this._tokens.slice(0, token.index);
let match, value = token.value, offset = token.position;
if (err instanceof NotARegExpException || err instanceof WrongAssignmentException) {
tokens.push({
value: value[0],
type: this.getType(new ValueHolder(value[0])),
position: offset,
index: 0,
});
value = this._input.substr(++offset);
} else {
throw new Exception('Unknown rescan reason');
}
while ((match = regex.exec(value))) {
const holder = new ValueHolder(match[0]);
const type = this.getType(holder);
tokens.push({
value: holder.value,
type: type,
position: match.index + offset,
index: 0,
});
}
tokens.push({
value: 'end-of-file',
type: Lexer.T_EOF,
position: this._input.length,
index: tokens.length,
});
this._tokens = tokens;
for (const [ index, tok ] of __jymfony.getEntries(this._tokens)) {
tok.index = index;
}
}
/**
* Scans the input string for tokens.
*
* @param {string} input A query string.
* @param {int} offset
*/
_scan(input, offset = 0) {
this._last = undefined;
const regex = new RegExp('((?:' + this.getPatterns().join(')|(?:') + '))', 'g');
let match;
while ((match = regex.exec(input))) {
const holder = new ValueHolder(match[0]);
const type = this.getType(holder);
this._tokens.push({
value: holder.value,
type: type,
position: match.index + offset,
index: this._tokens.length,
});
}
this._tokens.push({
value: 'end-of-file',
type: Lexer.T_EOF,
position: input.length,
index: this._tokens.length,
});
}
/**
* Iterates through the tokens
*/
* [Symbol.iterator]() {
yield * this._tokens;
}
/**
* @returns {string[]}
*/
getPatterns() {
return [
'#!.+[\\r\\n]',
'\\.\\.\\.',
'\\?\\.',
Lexer.NUMBERS,
'`(?:[^`\\\\$]|\\\\[\\s\\S]|\\$(?!\\{)|\\$\\{(?:`(?:[^`\\\\$]|\\\\[\\s\\S]|\\$(?!\\{)|\\$\\{(?:`(?:[^`\\\\$]|\\\\[\\s\\S]|\\$(?!\\{)|\\$\\{(?:`(?:[^`\\\\$]|\\\\[\\s\\S]|\\$(?!\\{)|\\$\\{(?:`(?:[^`\\\\$]|\\\\[\\s\\S]|\\$(?!\\{)|\\$\\{(?:`(?:[^`\\\\$]|\\\\[\\s\\S]|\\$(?!\\{)|\\$\\{(?:`(?:[^`\\\\$]|\\\\[\\s\\S]|\\$(?!\\{)|\\$\\{(?:`(?:[^`\\\\$]|\\\\[\\s\\S]|\\$(?!\\{)|\\$\\{(?:`(?:[^`\\\\$]|\\\\[\\s\\S]|\\$(?!\\{)|\\$\\{(?:`(?:[^`\\\\$]|\\\\[\\s\\S]|\\$(?!\\{)|\\$\\{(?:`(?:[^`\\\\$]|\\\\[\\s\\S]|\\$(?!\\{)|\\$\\{(?:[^}])*\\}?)*?[`]|[^}])*\\}?)*?[`]|[^}])*\\}?)*?[`]|[^}])*\\}?)*?[`]|[^}])*\\}?)*?[`]|[^}])*\\}?)*?[`]|[^}])*\\}?)*?[`]|[^}])*\\}?)*?[`]|[^}])*\\}?)*?[`]|[^}])*\\}?)*?[`]|[^}])*\\}?)*?[`]',
'[\'](?:\\\\(?=\\n|\\r|\\r\\n|\u2028|\u2029)[\\r\\n\u2028\u2029]*|[^\\\'\\\\\\r\\n]|\\\\.)*?[\']',
'["](?:\\\\(?=\\n|\\r|\\r\\n|\u2028|\u2029)[\\r\\n\u2028\u2029]*|[^"\\\\\\r\\n]|\\\\.)*?["]',
'(\\/\\*([^*]|[\\r\\n]|(\\*+([^*\\/]|[\\r\\n])))*\\*+\\/)|(\\/\\/.*)|(?:<!--.*)|((?<=^|\\s+)-->.*)',
'(?<=((?:^|[\\n;`=<>!~+\\-/%*&,?|:()[\\]{}\'"]|'+Lexer.RESERVED_WORDS+')\\s*))\\/((?![*+?])(?:[^\\r\\n\\[/\\\\]|\\\\.|\\[(?:[^\\r\\n\\]\\\\]|\\\\.)*\\])+)\\/\\w*',
'(?:\\s|^)'+Lexer.RESERVED_WORDS+'(?!'+Lexer.IDENTIFIER+')',
'[\\(\\)\\[\\]\\.\\{\\};]',
'[`=<>!~+\\-/%*&?|:^]+(?=\\/((?![*+?\\s])(?:[^\\r\\n\\[/\\\\]|\\\\.|\\[(?:[^\\r\\n\\]\\\\]|\\\\.)*\\])+)\\/w*)',
'(?:`|\\|\\||&&|>>>=|<<=|>>=|=>|[<>~+\\-/%*&|^]=|\\|>|>>>|\\*\\*=|\\*\\*|\\+\\+|--|<<|>>|!==|!=|===|==|=|[!~<>!~+\\-/%*&|^\'""]|\\?|:)',
',',
'[' + Lexer.SPACES + ']+',
'(?:[^' + Lexer.SPACES + '\\\\\\(\\)\\[\\]\\.\\{\\};`=<>!~+\\-/%*&,?|:^\'"]|\\\\u[\\dA-Fa-f]{4}|\\\\u\\{[\\dA-Fa-f]+\\})+',
];
}
/**
* @param {Object} holder
*
* @returns {int}
*/
getType(holder) {
if (holder.value.match(this._spaces)) {
return Lexer.T_SPACE;
}
switch (holder.value.charAt(0)) {
case '"':
case '\'':
case '`':
return Lexer.T_STRING;
case '@':
return Lexer.T_DECORATOR_IDENTIFIER;
case '<':
if (holder.value.startsWith('<!--')) {
return Lexer.T_COMMENT;
}
break;
case '-':
if (holder.value.startsWith('-->')) {
return Lexer.T_COMMENT;
}
break;
case '/':
if (holder.value.startsWith('/**')) {
return Lexer.T_DOCBLOCK;
} else if (holder.value.startsWith('//') || holder.value.startsWith('/*')) {
return Lexer.T_COMMENT;
} else if (holder.value.match(this._regexes)) {
return Lexer.T_REGEX;
}
break;
case '#':
if (holder.value.startsWith('#!')) {
return Lexer.T_SHEBANG;
}
}
switch (holder.value) {
case '.':
case '?.':
return Lexer.T_DOT;
case '...':
return Lexer.T_SPREAD;
case '(':
return Lexer.T_OPEN_PARENTHESIS;
case ')':
return Lexer.T_CLOSED_PARENTHESIS;
case '[':
return Lexer.T_OPEN_SQUARE_BRACKET;
case ']':
return Lexer.T_CLOSED_SQUARE_BRACKET;
case '{':
return Lexer.T_CURLY_BRACKET_OPEN;
case '}':
return Lexer.T_CURLY_BRACKET_CLOSE;
case ';':
return Lexer.T_SEMICOLON;
case ':':
return Lexer.T_COLON;
case ',':
return Lexer.T_COMMA;
case '===':
case '!==':
case '==':
case '!=':
case '<=':
case '>=':
case '<':
case '>':
return Lexer.T_COMPARISON_OP;
case '+':
case '-':
case '*':
case '/':
case '%':
case '**':
case '!':
case '~':
case '&':
case '|':
case '^':
case '++':
case '--':
case '<<':
case '>>':
case '>>>':
case '|>':
case 'instanceof':
case 'in':
case 'delete':
case 'void':
case 'typeof':
return Lexer.T_OPERATOR;
case '&&':
case '||':
case '??':
return Lexer.T_LOGICAL_OPERATOR;
case '=>':
return Lexer.T_ARROW;
case '?':
return Lexer.T_QUESTION_MARK;
case '=':
case '+=':
case '=+':
case '-=':
case '=-':
case '*=':
case '=*':
case '/=':
case '=/':
case '%=':
case '=%':
case '**=':
case '=**':
case '~=':
case '&=':
case '|=':
case '^=':
case '<<=':
case '=<<':
case '>>=':
case '>>>=':
case '=>>':
case '=>>>':
return Lexer.T_ASSIGNMENT_OP;
}
if (holder.value.match(this._reservedKeywords)) {
if (Lexer.T_DOT === this._last) {
return Lexer.T_IDENTIFIER;
}
switch (holder.value) {
case 'class':
return Lexer.T_CLASS;
case 'extends':
return Lexer.T_EXTENDS;
case 'function':
return Lexer.T_FUNCTION;
case 'decorator':
return Lexer.T_DECORATOR;
case 'static':
return Lexer.T_STATIC;
case 'async':
return Lexer.T_ASYNC;
case 'await':
return Lexer.T_AWAIT;
case 'true':
return Lexer.T_TRUE;
case 'false':
return Lexer.T_FALSE;
case 'throw':
return Lexer.T_THROW;
case 'new':
return Lexer.T_NEW;
case 'if':
return Lexer.T_IF;
case 'else':
return Lexer.T_ELSE;
case 'return':
return Lexer.T_RETURN;
case 'this':
return Lexer.T_THIS;
case 'super':
return Lexer.T_SUPER;
case 'null':
return Lexer.T_NULL;
case 'yield':
return Lexer.T_YIELD;
case 'arguments':
return Lexer.T_ARGUMENTS;
default:
return Lexer.T_KEYWORD;
}
}
if (holder.value.match(this._identifiers)) {
switch (holder.value) {
case 'get':
return Lexer.T_GET;
case 'set':
return Lexer.T_SET;
}
return Lexer.T_IDENTIFIER;
}
if (holder.value.match(this._numbers)) {
return Lexer.T_NUMBER;
}
return Lexer.T_OTHER;
}
} |
JavaScript | class TxInputs extends SerialBuffer {
/**
* The array of inputs managed here.
* @type TxInput[]
*/
//_inputs
/**
* @param {TxInput[]} inputs - An array of inputs.
*/
constructor(inputs = []) {
super()
this._inputs = inputs
}
/**
* Read inputs from a SerialReader
* @param {SerialReader}
* @return {TxInputs}
*/
static read(reader) {
const inCount = reader.meta.inputsLength || VarInt.read(reader) // SegWit transactions
reader.meta.inputsLength = inCount // inCount is also witnessCount
const inputs = []
for (let i = 0; i < inCount; i++) {
const input = TxInput.read(reader)
inputs.push(input)
}
return new TxInputs(inputs)
}
/**
* @override
*/
write(writer) {
// 1 - Write the inputs count
this.inputsCount.write(writer)
// 2 - Write every input
this._inputs.forEach(input => input.write(writer))
}
/**
* @override
*/
byteLength() {
return this.inputsCount.byteLength() +
this._inputs.reduce((sum, input) => sum + input.byteLength(), 0)
}
/**
* The number of inputs as VarInt.
* @return {VarInt}
*/
get inputsCount() {
return new VarInt(this._inputs.length)
}
/**
*
* Add an input to spend in this transaction.
*
* @param {string} prevTxOutHash - hash of the transaction that created the input.
* @param {number} prevTxOutIndex - Output index within the transaction that created the input.
* @param {string} scriptSig - The signature script to unlock the input.
* @param {Uint32?} sequence - The sequence number.
*/
add(prevTxOutHash, prevTxOutIndex, scriptSig, sequence) {
const input = TxInput.fromHex(prevTxOutHash, prevTxOutIndex, scriptSig, sequence)
this._inputs.push(input)
}
/**
* Sets all inputs' scripts to be empty scripts.
*/
emptyScripts() {
this._inputs.forEach(input => input.setEmptyScript())
}
/**
* @param {number} inputIndex - The index of the input to set the script.
* @param {Script} script - The script to set.
*/
setScript(inputIndex, script) {
this._inputs[inputIndex].scriptSig = script
}
/**
*
* Add a witness to unlock an input.
*
* @param {number} inputIndex - The index of the input to add a witness to.
* @param {Buffer} publicKey - The public key which corresponds to the input's address.
* @param {BitcoinSignature} signature - The signature unlocking the input.
*/
addWitness(inputIndex, publicKey, signature) {
const input = this._inputs[inputIndex]
input.scriptSig.add(signature.toBuffer())
input.scriptSig.add(publicKey)
}
} |
JavaScript | class PluginWithRuntimes extends Plugin {
get runtimes() {
return [runtime1, runtime2, runtime2v2];
}
} |
JavaScript | class Worker extends EventEmitter {
constructor (options={}) {
super();
options = Object.assign({
name: "Worker",
heart: {},
heartbeat: 10000,
action: () => { Config.logger.debug("[Worker] Triggered action from 'anonymous'."); }
}, options);
Object.assign(this, options);
}
// methods
start() {
Config.logger.info(`[${this.name}] Starting worker.`);
this.heart = Timer.setInterval(this.action, this.heartbeat);
this.action();
}
stop() {
let Timeout = Timer.setInterval(() => {}, 0).constructor; // feed the next 'instanceof'
if (this.heart instanceof Timeout) {
Config.logger.info(`[${this.name}] Stopping worker.`);
Timer.clearInterval( this.heart );
} else {
Config.logger.info(`[${this.name}] Worker is not running; ignoring stop request.`);
}
}
} |
JavaScript | class CalendarSite extends React.Component {
constructor() {
super()
this.state = {
events: []
}
BigCalendar.momentLocalizer(moment)
}
componentDidMount() {
getCalendarEvents()
.then(events => {
this.setState({
events
})
})
}
render() {
return (
<div className='site-container'>
<div className='site-content'>
<div className='row'>
<div className='col-xs-12 margin-1'>
<h1>Tapahtumakalenteri</h1>
</div>
</div>
<div className='row'>
<div className='col-xs-12'>
<BigCalendar
style={{ height: '420px' }}
events={this.state.events}
culture='fi'
/>
</div>
</div>
</div>
</div >
)
}
} |
JavaScript | class SomeView extends Marionette.ItemView {
constructor() {
// do something here
}
} |
JavaScript | class BilibiliRest {
/**
* Send request, gets json as response
* 发送请求,获取json返回
*
* @param {Request} req - Request details
* @returns {Promise} resolve(JSON) reject(Error)
*/
static request(req) {
const acceptedCode = [ 200 ];
const noRetryCode = [ 412 ];
const requestUntilDone = async () => {
let success = false;
let tries = 3;
let result = null;
let err = null;
while (success === false && tries > 0) {
--tries;
try {
const response = await xhr.request(req);
const statusCode = response.status_code;
const statusMsg = response.status_message;
if (acceptedCode.includes(statusCode)) {
result = response.json();
err = null;
success = true;
} else if (noRetryCode.includes(statusCode)) {
result = response;
err = new Error(`Http status ${statusCode}: ${statusMessage}`);
tries = 0;
} else {
err = new Error(`Http status ${statusCode}: ${statusMessage}`);
}
} catch (error) {
err = error;
cprint(`\n${error.stack}`, colors.red);
}
}
if (err) {
throw err;
} else {
return result;
}
};
return requestUntilDone();
}
/** app端获取房间内抽奖信息 */
static appGetRaffleInRoom(roomid) {
const params = {};
Object.assign(params, appCommon);
params['roomid'] = roomid;
params['ts'] = Number.parseInt(0.001 * new Date());
const request = (RequestBuilder.start()
.withHost('api.live.bilibili.com')
.withPath('/xlive/lottery-interface/v1/lottery/getLotteryInfo')
.withMethod('GET')
.withHeaders(appHeaders)
.withParams(params)
.build()
);
return BilibiliRest.request(request);
}
/** Check for lottery in room ``roomid``
*
*/
static getRaffleInRoom(roomid) {
const params = { 'roomid': roomid, };
const request = (RequestBuilder.start()
.withHost('api.live.bilibili.com')
.withPath('/xlive/lottery-interface/v1/lottery/Check')
.withMethod('GET')
.withHeaders(webHeaders)
.withParams(params)
.build()
);
return BilibiliRest.request(request);
}
/** 查取视频cid */
static getVideoCid(aid) {
const jsonp = 'jsonp';
const params = {
aid,
jsonp,
};
const request = (RequestBuilder.start()
.withHost('api.bilibili.com')
.withPath('/x/player/pagelist')
.withMethod('GET')
.withHeaders(webHeaders)
.withParams(params)
.build()
);
return Bilibili.request(request);
}
static appSign(string) {
return crypto.createHash('md5').update(string+appSecret).digest('hex');
}
static parseAppParams(params) {
const pre_paramstr = BilibiliRest.formatForm(params);
const sign = BilibiliRest.appSign(pre_paramstr);
const paramstr = `${pre_paramstr}&sign=${sign}`;
return paramstr;
}
static formatCookies(cookies) {
const options = {
'encodeURIComponent': querystring.unescape,
};
const formattedCookies = querystring.stringify(cookies, '; ', '=', options);
return formattedCookies;
}
static formatForm(form) {
const formattedForm = querystring.stringify(form, '&', '=');
return formattedForm;
}
} |
JavaScript | class BaseN {
/**
* Encrypts a message, given a key and two charsets.
*
* ```baseCharset``` must include all symbols used in both *msg* and *key*.
* @param {string} msg
* @param {string} key
* @param {string} baseCharset
* @param {string} newCharset
*/
static encrypt(msg,key,baseCharset,newCharset){let t=msg,e=key,r=baseCharset,n=newCharset;const l=_B(r.length),s=_B(n.length);let i,c=_B(0),o="",h=[];for(let e=0;e<t.length;e++)c+=l**_B(t.length-1-e)*_B(r.indexOf(t[e]));for(let t=_B(e.length-1);t>=0;t--){const n=r.indexOf(e[Number(t)]);c+=l**t*_B(n),h.push(n)}if(c<0)return"";for(i=_B(0);s**i<=c&&s**(i+_B(1))<c;i++);for(;i>=0;i--)for(let t=_B(0);t<s;t++){const e=s**i,r=e*t;if(r<=c&&r+e>c){c-=r,o+=n[(Number(t)+h.reduce((t,e)=>t+e))%Number(s)];for(let t=0;t<h.length&&(h[t]+=1,h[t]>=l);t++)h[t]=0}}return o}
/**
* Decrypts a message, given a key and two charsets.
* @param {string} msg
* @param {string} key
* @param {string} baseCharset
* @param {string} newCharset
*/
static decrypt(msg,key,baseCharset,newCharset){let t=msg,e=key,r=baseCharset,n=newCharset;const l=_B(r.length),s=_B(n.length);let i,c=_B(0),o="",h=[];for(let t=_B(e.length-1);t>=0;t--){const r=n.indexOf(e[Number(t)]);c-=s**t*_B(r),h.push(r)}for(let e=0;e<t.length;e++){let n=_B(h.reduce((t,e)=>t+e)+r.indexOf(t[e]));for(let e=2;e<l;e++)n-=_B(r.indexOf(t[e]))*l-_B(h.reduce((t,e)=>t+e));for(let t=0;t<h.length&&(h[t]+=1,h[t]>=s);t++)h[t]=0;c+=l**_B(t.length-1-e)*(n%l)}if(c<_B(0))return"";for(i=_B(0);s**i<=c&&s**(i+_B(1))<=c;i++);for(;i>=0;i--)for(let t=_B(0);t<s;t++){const e=s**i,r=e*t;r<=c&&r+e>c&&(c-=r,o+=n[Number(t)])}return o}
/**
* Returns all characters contained in input, without duplicates.
* @param {string} msg
* @returns {string}
*/
static extractCharset(msg){let e="";for(let r=0;r<msg.length;r++)e.includes(msg[r])||(e+=msg[r]);return e}
/**
* Returns a safe charset for both the msg and the key.
*
* ```substringLength``` affects only the ```msg```.
* @param {string} msg
* @param {string} key
* @param {number} [substringLength=0]
*/
static charsetFromMsgAndKey(msg,key,substringLength){return this.extractCharset(this.extractAndRandomize(msg,substringLength)+this.extractAndRandomize(key))}
/**
* This function extracts the charset of the message and shuffles it randomly.
* It attempts to shuffle it in a way no substring of ```msg``` will start with the first letter of the charset (if not possible an error will be thrown).
* If ```substringLength=0``` the input will be treated as a whole word.
*
* @param {string} msg
* @param {number} [substringLength=0] the length of a single subdivision of the string **msg**.
*/
static extractAndRandomize(msg,substringLength){const r=0===(substringLength=void 0===substringLength?0:substringLength)?"":this.extractCharset(msg.match(new RegExp(`.{1,${substringLength}}`,"g")).map(v=>v[0]));let n=this.extractCharset(msg),l=n,s="",i=n.length;for(;n.length!==i-1;){const i=Math.floor(Math.random()*l.length);if(0===substringLength&&msg[0]===l[i]||r.includes(l[i])){l=l.slice(0,i)+l.slice(i+1);continue}if(0===l.length)throw"Impossible to create a safe charset";const c=n.indexOf(l[i]);s+=n[c],n=n.slice(0,c)+n.slice(c+1)}for(;s.length!==i;){const t=Math.floor(Math.random()*n.length);s+=n[t],n=n.slice(0,t)+n.slice(t+1)}return s}
/**
* works exactly like ```.encrypt()``` but treats the input as segments, given a valid ```substringLength``` value.
* @param {string} msg
* @param {string} key
* @param {string} baseCharset
* @param {string} newCharset
* @param {number} substringLength the length of a single substring of **msg**.
* @param {string|string[]} [inBetween=" "] a string or a serie of strings that stitches the substrings together.
*/
static encryptSubstrings(msg,key,baseCharset,newCharset,substringLength,inBetween){let t=msg,e=key,r=baseCharset,n=newCharset,l=substringLength,s=inBetween;s=void 0===s?" ":s;let i="";if("number"!=typeof l)throw"substringLength must be a number!";for(let c=0;c<t.length;c+=l)i+=this.encrypt(t.slice(c,c+l),e,r,n),c+l<t.length&&(i+=Array.isArray(s)?s[c%s.length]:s);return i}
/**
* works exactly like ```.decrypt()``` but treats the input as segments.
* @param {string} msg
* @param {string} key
* @param {string} baseCharset
* @param {string} newCharset
* @param {string|string[]} [inBetween=" "] needed to split the input into substrings.
*/
static decryptSubstrings(msg,key,baseCharset,newCharset,inBetween){let t=msg,e=key,r=baseCharset,n=newCharset,l=inBetween;l=void 0===l?" ":l;let s=[],i="";if(Array.isArray(l)){l=[...new Set(l)];for(let e=0;e<l.length;e++)t=t.replaceAll(l[e],"{{{{{{SPLIT--POINT}}}}}}");s=t.split("{{{{{{SPLIT--POINT}}}}}}")}else s=t.split(l);for(let t=0;t<s.length;t++)i+=this.decrypt(s[t],e,r,n);return i}
} |
JavaScript | class Header extends React.Component {
//after logout button is clicked this function is called,it
//removes jwt and user data from local storage and redirects user to
//login page
signout = () => {
localStorage.removeItem('userData');
localStorage.removeItem('jwt');
this.props.history.push('/login');
console.log('signed out');
};
render() {
const name = localStorage.getItem('userData');
const buttonStyle= {
position:'fixed',
fontFamily:"Serif",
right:"3%",
marginRight:"20px",
background: '#cc2900',
padding:'12px 70px',
fontSize:'16px',
border: 'none',
borderRadius:'4px',
color: 'white'
};
return (
<div>
{/* name && <div className="welcoming">Welcome {name}</div> */}
<div className="user_authorization">
{name && (
<div>
<button onClick={this.signout} style={buttonStyle}>Logout</button>
</div>
)}
</div>
</div>
);
}
} |
JavaScript | class Text extends Object {
/**
* @constructor
*
* @param {Object} settings - object settings.
* @param {String} settings.name - object name.
*
* @param {Object} settings.settings - object settings for only this type.
* @param {String} settings.settings.text - object's text.
* @param {String} settings.settings.font - object's font.
* @param {Number} settings.settings.size - object's size.
* @param {String} settings.settings.color - object color.
*
* @param {Number[]} settings.coords - object coordinations. First value - x coord, second value - y coord, third value - width, fourth value - height. If width and/or height are not defined - they will be taken automatically.
* @param {String} settings.type - object type. For this object type it is "rectangle".
* @param {Number} [settings.layer=1] - object layer.
* @param {Boolean} [settings.isVisible=true] - show object in the playground.
*/
constructor(settings) {
super(settings);
}
/**
* Drawing object on the playground.
*/
draw() {
if(this._settings.type === 'text') {
const textSettings = this._settings.settings;
this._context.fillStyle = textSettings.color;
this._context.font = `${textSettings.size}px "${textSettings.font}"`;
this._context.textAlign = 'left';
this._context.textBaseline = 'top';
this._context.fillText(textSettings.text, this._settings.coords[0]+this._camera.x, this._settings.coords[1]+this._camera.y)
}
}
/**
* Drawing object borders and their central points. Works only if debug mode in World class is turned on.
*/
drawInDebug() {
super.drawInDebug();
}
} |
JavaScript | class Level extends Phaser.Scene {
/**
* Constructor de la escena
*/
constructor() {
super({ key: 'host' });
}
create() {
// Loads the map
this.map = this.make.tilemap({
key: 'tilemap'
})
let tileset = this.map.addTilesetImage('tileset','tileset');
this.groundLayer = this.map.createLayer('ground', tileset);
this.wallsLayer = this.map.createLayer('walls', tileset);
// Store empty cells
this.cells = new Set();
for (let i = 0; i < 625; i++) this.cells.add(i);
// Mark walls as occupied cells
this.map.forEachTile((wall) => this.cells.delete(wall.x + wall.y * 25), this, 0, 0, 25, 25, { isNotEmpty: true })
// Create players
this.snakesGroup = this.physics.add.group();
this.snakes = new Map();
this.player = new PlayerSnake(this, this.snakesGroup, this.getEmptyCell(), PLAYERSKIN, USERSESSIONAME);
this.snakes.set(USERSESSIONAME, this.player);
PLAYERS.forEach((p) => {
if (p[0] !== USERSESSIONAME) {
this.snakes.set(p[0], new PlayerSnake(this, this.snakesGroup, this.getEmptyCell(), p[1], p[0]));
}
});
this.results = [];
this.counter = NPLAYERS;
this.texts = [];
//Create Texts
// Create food
this.food = new Food(this, this.getEmptyCell());
let topScoreText = this.add.text(390, 0, "Top Scores", {
color: '#FFFFFF',
fontStyle: 'italic',
fontSize: 14
});
topScoreText.setDepth(1);
let cont = 0;
this.snakes.forEach(snake => {
let texto = this.add.text(370,(cont+1) * 15, snake.gamePosition + " " + snake.username + " " + snake.score, {
color: '#FFFFFF',
fontStyle: 'italic',
fontSize: 14
});
texto.setDepth(1);
this.texts.push(texto);
cont++;
});
// Cursors
this.cursors = this.input.keyboard.createCursorKeys();
this.cursors.up.on('down', () => this.player.setDir(0), this);
this.cursors.right.on('down', () => this.player.setDir(1), this);
this.cursors.down.on('down', () => this.player.setDir(2), this);
this.cursors.left.on('down', () => this.player.setDir(3), this);
// Add key to toggle game fullscreen
this.input.keyboard.addKey('F').on('down', () => this.scale.toggleFullscreen(), this);
// Set level collisions
this.wallsLayer.setCollisionFromCollisionGroup();
this.wallsLayer.setTileIndexCallback(2, this.onCollision, this);
// Delay game start and then set timers
this.timer = this.time.addEvent({
delay: 3000,
callback: () => {
this.timer = this.time.addEvent({
delay: 500,
callback: this.processTick,
callbackScope: this,
loop: true
})
this.finishGameTimer = this.time.addEvent({
delay: 1000,
callback: this.processSecond,
callbackScope: this,
loop: true
})
},
callbackScope: this,
loop: false
})
this.timeToFinish = 90;
let remainingTimeText = this.add.text(190, 0, "Remaining Time", {
color: '#FFFFFF',
fontStyle: 'italic',
fontSize: 14
});
remainingTimeText.setDepth(1);
this.timeText = this.add.text(230, 15, this.timeInMinutesSeconds(this.timeToFinish), {
color: '#FFFFFF',
fontStyle: 'italic',
fontSize: 14
});
this.timeText.setDepth(1);
// Let some logic be delayed
this.ticked = false;
this.events.on('update', () => this.postTick(), this);
this.startTime = Date.now();
ws.subscribe("/topic/match" + MATCH, (text) => {
if (text.type == "Move") this.onMoveRequest(text.message);
if (text.type == "finishMatch"){
let toastHTML = document.getElementById('finishGameToast');
let finishGameToastBody = document.getElementById('finishGameToastBody');
let topScoresDiv = document.getElementById('topScoresDiv');
finishGameToastBody.innerHTML = '';
finishGameToastBody.appendChild(topScoresDiv);
text.message.forEach(r => {
let divR = document.createElement('div');
divR.setAttribute("class", "row justify-content-around");
let p1 = document.createElement('p');
let p2 = document.createElement('p');
switch(text.message.indexOf(r)){
case 0:
p1.style.color = 'gold';
break;
case 1:
p1.style.color = 'silver';
break;
case 2:
p1.style.color = 'brown';
break;
default:
p1.style.color = 'grey';
}
p1.setAttribute("class", "col-4 text-center fs-5");
p2.setAttribute("class", "col-4 text-center fs-5");
p1.innerHTML = (text.message.indexOf(r) + 1) + ". " + r.playerName;
p2.innerHTML = r.score;
divR.appendChild(p1);
divR.appendChild(p2);
finishGameToastBody.appendChild(divR);
});
let backButton = document.createElement("button");
backButton.setAttribute("class", "w-50 btn btn-outline-danger text-center fs-5");
backButton.innerHTML = 'Go Back To Room';
backButton.onclick = () => {
window.location.replace("/rooms/" + ROOM);
}
finishGameToastBody.appendChild(backButton);
toastHTML.style.display = '';
let toast = new bootstrap.Toast(toastHTML);
toast.show();
}
});
// Broadcast initial game state
this.broadcastState();
go("/rooms/start_match/" + MATCH, 'POST', {})
.then(d => console.log("Success", d))
.catch(e => console.log("Error", e))
}
/**
* Handles a movement request from a remote player
* @param request The received request
*/
onMoveRequest(request) {
let snake = this.snakes.get(request.user);
if (snake !== undefined) snake.setDir(request.dir);
}
/**
* Handles collision for two given GameObjects
* If the objects are Snakes they are killed
* @param {Phaser.GameObjects.GameObject} o1
* @param {Phaser.GameObjects.GameObject} o2
*/
onCollision(o1, o2) {
if (o1 instanceof SnakePart) {
o1.snake.die(o2);
} else if (o2 instanceof SnakePart) {
o2.snake.die(o1);
}
}
/**
* Calls the tick processing method of all the snakes
*/
processTick() {
this.snakes.forEach(snake => snake.processTick());
this.food.processTick();
this.ticked = true;
}
postTick() {
if (this.ticked) {
this.ticked = false;
this.snakes.forEach(snake => snake.handleDeath());
this.actualizeGameState();
this.broadcastState();
}
}
actualizeGameState(){
let alivePlayers = 0;
let snakeScores = [];
this.snakes.forEach(snake => {
snakeScores.unshift({
playerName: snake.username,
score: snake.score,
lastSecondLive: snake.lastSecondLive
})
if (!snake.dead) {
alivePlayers++;
snake.lastSecondLive = this.timeToFinish;
}
else {
if(!snake.putInResult){
this.results.unshift({
playerName: snake.username,
score: snake.score,
lastSecondLive: this.timeToFinish
});
snake.putInResult = true;
snake.lastSecondLive = this.timeToFinish;
}
}
});
this.sortPlayersData(snakeScores);
snakeScores.forEach(snakeScore => {
let index = snakeScores.indexOf(snakeScore);
this.texts[index].setText((index + 1) + " " + snakeScore.playerName + " " + snakeScore.score);
});
if (alivePlayers <= 1) {
if(alivePlayers==1){
this.snakes.forEach(snake => {
if(!snake.dead && !snake.putInResult){
if(this.timeToFinish > 0){
this.results.unshift({
playerName: snake.username,
score: snake.score,
lastSecondLive: this.timeToFinish - 1
});
snake.putInResult = true;
snake.lastSecondLive = this.timeToFinish;
}
}
})
}
this.sortPlayersData(this.results);
this.finishGame();
}
}
sortPlayersData(list){
list.sort(function(a,b){
if(a.lastSecondLive < b.lastSecondLive){
return -1;
}
if(a.lastSecondLive > b.lastSecondLive){
return 1;
}
if(a.score < b.score){
return 1;
}
if(a.score > b.score){
return -1;
}
if(a.playerName < b.playerName){
return -1;
}
if(a.playerName > b.playerName){
return 1;
}
return 0;
});
}
completeResults(){
this.snakes.forEach(snake => {
if(!snake.dead && !snake.putInResult){
this.results.unshift({
playerName: snake.username,
score: snake.score,
lastSecondLive: this.timeToFinish
});
snake.putInResult = true;
snake.lastSecondLive = this.timeToFinish;
}
})
this.sortPlayersData(this.results);
this.finishGame();
}
timeInMinutesSeconds(seconds){
//Minutes
var minutes = Math.floor(seconds/60);
// Seconds
var partInSeconds = seconds%60;
// Adds left zeros to seconds
partInSeconds = partInSeconds.toString().padStart(2,'0');
return `${minutes}:${partInSeconds}`;
}
processSecond(){
this.timeToFinish-=1;
this.timeText.setText(this.timeInMinutesSeconds(this.timeToFinish));
if(this.timeToFinish==0){
this.completeResults();
}
}
finishGame(){
go("/rooms/finish_match/" + MATCH, 'POST', {
message: this.results
})
.then(d => console.log("Success", d))
.catch(e => console.log("Error", e))
this.timer.destroy();
this.finishGameTimer.destroy();
this.timer = undefined;
this.finishGameTimer = undefined;
}
/**
* Shares current gamestate over websocket
*/
broadcastState() {
const body = JSON.stringify({type: "GameState", message: this.toJSON()});
ws.stompClient.send("/topic/match" + MATCH, ws.headers, body);
}
/**
* Checks if the snake would crash when moving to the new position
* @param pos The position to check
* @returns True if the position is occupied. False otherwise
*/
isOccupied(pos) {
return (pos.x < 0 || pos.x >= 25) || (pos.y < 0 || pos.y >= 25) || this.isSnake(pos) || this.isWall(pos);
}
/**
* Checks if there is a snake at the given position
* @param pos The position to check
* @returns True if there is a snake at the given position. False otherwise
*/
isSnake(pos) {
return this.physics.overlapRect(pos.x * 20 + 10, pos.y * 20 + 10, 0, 0, true, false).length > 0;
}
/**
* Checks if there is a wall at the given position
* @param pos The position to check
* @returns True if there is a wall at the given position. False otherwise
*/
isWall(pos) {
return this.map.getTileAt(pos.x, pos.y) !== null;
}
/**
* Gets a cell that is not occupied and is not a wall
* @returns The position of the empty cell
*/
getEmptyCell() {
let cell = [...this.cells][Math.floor(Math.random() * this.cells.size)];
return cell === undefined ? null : { x: cell % 25, y: ~~(cell / 25) };
}
/**
* Changes the state of the given position to be empty or not
* @param pos The position of which to change the state of
* @param {boolean} empty If is empty or not
*/
setCellState(pos, empty) {
if (empty) {
this.cells.add(pos.x + pos.y * 25);
} else {
this.cells.delete(pos.x + pos.y * 25);
}
}
/**
* Creates a JSON object representing the current state
* @returns JSON object containing current state
*/
toJSON() {
let snakes = {};
let texts =[];
this.snakes.forEach((v, k) => snakes[k] = v.toJSON());
this.texts.forEach(t => {
texts.push(t.text);
})
return { food: this.food.toJSON(), snakes: snakes, time: this.startTime, texts: texts, timeText: this.timeText.text};
}
} |
JavaScript | class rule_choice{
constructor(x, y, type){
this.x = x;
this.y = y;
this.type = type;
}
get rule(){
return this.calculate();
}
calculate(){
var arr_type;
if(this.type === 1){
arr_type = graph.state_1;
}
else if(this.type === 0){
arr_type = graph.state_0;
}
var _state_ = arr_type[this.x][this.y];
var _n0 = 0, _n1 = 0, _n2 = 0, _n3 = 0, _n4 = 0, _n5 = 0, _n6 = 0, _n7 = 0;
if(this.x > 0){
_n0 = arr_type[this.x - 1][this.y];
}
if(this.x < graph.size.width - 1){
_n1 = arr_type[this.x + 1][this.y];
}
if(this.y > 0){
_n2 = arr_type[this.x][this.y - 1];
}
if(this.y < graph.size.height - 1){
_n3 = arr_type[this.x][this.y + 1];
}
if(this.x > 0 && this.y > 0){
_n4 = arr_type[this.x - 1][this.y - 1];
}
if(this.x < graph.size.width - 1 && this.y < graph.size.height - 1){
_n5 = arr_type[this.x + 1][this.y + 1];
}
if(this.x > 0 && this.y < graph.size.height - 1){
_n6 = arr_type[this.x - 1][this.y + 1];
}
if(this.x < graph.size.width - 1 && this.y > 0){
_n7 = arr_type[this.x + 1][this.y - 1];
}
var _sum = _n0 + _n1 + _n2 + _n3 + _n4 + _n5 + _n6 + _n7;
// current cell is dead
if(!_state_){
if(_sum === 3){
// cell alive code
return 1;
}
else{
// error code
return -1;
}
}
else{
if(_sum < 2){
// cell dead code
return 0;
}
else if(_sum === 2 || _sum === 3){
return 1;
}
else if(_sum > 3){
return 0;
}
else{
return -1;
}
}
}
} |
JavaScript | class Azure_NoSql {
/**
*
* @param {module} azureRestSdk Azure Rest SDK
*/
constructor(azureRestSdk) {
this._azureRestSdk = azureRestSdk;
}
/**
* Trigers the createUpdateTable function of cosmosdb
* @param {StringKeyword} resourceGroupName - Mandatory parameter
* @param {StringKeyword} accountName - Mandatory parameter
* @param {StringKeyword} tableName - Mandatory parameter
* @param {TypeReference} createUpdateTableParameters - Mandatory parameter
* @param {TypeReference} [options] - Optional parameter
* @returns {Promise<createUpdateTableResponse>}
*/
createCollection(
resourceGroupName,
accountName,
tableName,
createUpdateTableParameters,
options = undefined
) {
return new Promise((resolve, reject) => {
this._azureRestSdk
.loginWithServicePrincipalSecretWithAuthResponse(
process.env.AZURE_CLIENT_ID,
process.env.AZURE_CLIENT_SECRET,
process.env.AZURE_TENANT_ID
)
.then(authres => {
const client = new CosmosDBManagementClient(
authres.credentials,
process.env.AZURE_SUBSCRIPTION_ID
);
client.tableResources
.createUpdateTable(
resourceGroupName,
accountName,
tableName,
createUpdateTableParameters,
options
)
.then(result => {
resolve(result);
});
})
.catch(err => {
reject(err);
});
});
}
/**
* Trigers the deleteTable function of cosmosdb
* @param {StringKeyword} resourceGroupName - Mandatory parameter
* @param {StringKeyword} accountName - Mandatory parameter
* @param {StringKeyword} tableName - Mandatory parameter
* @param {TypeReference} [options] - Optional parameter
* @returns {Promise<deleteTableResponse>}
*/
deleteCollection(
resourceGroupName,
accountName,
tableName,
options = undefined
) {
return new Promise((resolve, reject) => {
this._azureRestSdk
.loginWithServicePrincipalSecretWithAuthResponse(
process.env.AZURE_CLIENT_ID,
process.env.AZURE_CLIENT_SECRET,
process.env.AZURE_TENANT_ID
)
.then(authres => {
const client = new CosmosDBManagementClient(
authres.credentials,
process.env.AZURE_SUBSCRIPTION_ID
);
client.tableResources
.deleteTable(resourceGroupName, accountName, tableName, options)
.then(result => {
resolve(result);
});
})
.catch(err => {
reject(err);
});
});
}
/**
* Trigers the listTables function of cosmosdb
* @param {StringKeyword} resourceGroupName - Mandatory parameter
* @param {StringKeyword} accountName - Mandatory parameter
* @param {TypeReference} [options] - Optional parameter
* @returns {Promise<listTablesResponse>}
*/
listCollections(resourceGroupName, accountName, options = undefined) {
return new Promise((resolve, reject) => {
this._azureRestSdk
.loginWithServicePrincipalSecretWithAuthResponse(
process.env.AZURE_CLIENT_ID,
process.env.AZURE_CLIENT_SECRET,
process.env.AZURE_TENANT_ID
)
.then(authres => {
const client = new CosmosDBManagementClient(
authres.credentials,
process.env.AZURE_SUBSCRIPTION_ID
);
client.tableResources
.listTables(resourceGroupName, accountName, options)
.then(result => {
resolve(result);
});
})
.catch(err => {
reject(err);
});
});
}
/**
* Trigers the updateTableThroughput function of cosmosdb
* @param {StringKeyword} resourceGroupName - Mandatory parameter
* @param {StringKeyword} accountName - Mandatory parameter
* @param {StringKeyword} tableName - Mandatory parameter
* @param {TypeReference} updateThroughputParameters - Mandatory parameter
* @param {TypeReference} [options] - Optional parameter
* @returns {Promise<updateTableThroughputResponse>}
*/
setAttribute(
resourceGroupName,
accountName,
tableName,
updateThroughputParameters,
options = undefined
) {
return new Promise((resolve, reject) => {
this._azureRestSdk
.loginWithServicePrincipalSecretWithAuthResponse(
process.env.AZURE_CLIENT_ID,
process.env.AZURE_CLIENT_SECRET,
process.env.AZURE_TENANT_ID
)
.then(authres => {
const client = new CosmosDBManagementClient(
authres.credentials,
process.env.AZURE_SUBSCRIPTION_ID
);
client.tableResources
.updateTableThroughput(
resourceGroupName,
accountName,
tableName,
updateThroughputParameters,
options
)
.then(result => {
resolve(result);
});
})
.catch(err => {
reject(err);
});
});
}
/**
* Trigers the getTable function of cosmosdb
* @param {StringKeyword} resourceGroupName - Mandatory parameter
* @param {StringKeyword} accountName - Mandatory parameter
* @param {StringKeyword} tableName - Mandatory parameter
* @param {TypeReference} [options] - Optional parameter
* @returns {Promise<getTableResponse>}
*/
getAttributes(
resourceGroupName,
accountName,
tableName,
options = undefined
) {
return new Promise((resolve, reject) => {
this._azureRestSdk
.loginWithServicePrincipalSecretWithAuthResponse(
process.env.AZURE_CLIENT_ID,
process.env.AZURE_CLIENT_SECRET,
process.env.AZURE_TENANT_ID
)
.then(authres => {
const client = new CosmosDBManagementClient(
authres.credentials,
process.env.AZURE_SUBSCRIPTION_ID
);
client.tableResources
.getTable(resourceGroupName, accountName, tableName, options)
.then(result => {
resolve(result);
});
})
.catch(err => {
reject(err);
});
});
}
} |
JavaScript | class Track {
constructor(url, name) {
this.url = url;
this.name = name || url.split('/').pop();
}
get duration() {
return '--:--'; // TODO: calculate the song duration
}
toString() {
return this.name.replace(/\.(mp3|wav|ogg)$/,'');
}
read() {
return fs.createReadStream(this.url);
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.