language
stringclasses 5
values | text
stringlengths 15
988k
|
---|---|
JavaScript | class TokenUser {
get createdOstStatus() {
return 'CREATED';
}
get activatingOstStatus() {
return 'ACTIVATING';
}
get activatedOstStatus() {
return 'ACTIVATED';
}
get ostStatuses() {
const oThis = this;
return {
'1': oThis.createdOstStatus,
'2': oThis.activatingOstStatus,
'3': oThis.activatedOstStatus
};
}
get invertedOstStatuses() {
const oThis = this;
if (invertedOstStatuses) {
return invertedOstStatuses;
}
invertedOstStatuses = util.invert(oThis.ostStatuses);
return invertedOstStatuses;
}
get airdropDoneProperty() {
return 'AIRDROP_DONE';
}
get airdropStartedProperty() {
return 'AIRDROP_STARTED';
}
get airdropFailedProperty() {
return 'AIRDROP_FAILED';
}
get tokenHolderDeployedProperty() {
return 'TOKEN_HOLDER_DEPLOYED';
}
get properties() {
const oThis = this;
if (!propertiesHash) {
propertiesHash = {
'1': oThis.tokenHolderDeployedProperty,
'2': oThis.airdropStartedProperty,
'4': oThis.airdropDoneProperty,
'8': oThis.airdropFailedProperty
};
}
return propertiesHash;
}
get validPropertiesArray() {
const oThis = this;
return [
oThis.tokenHolderDeployedProperty,
oThis.airdropStartedProperty,
oThis.airdropDoneProperty,
oThis.airdropFailedProperty
];
}
get invertedProperties() {
const oThis = this;
if (!invertedPropertiesHash) {
invertedPropertiesHash = util.invert(oThis.properties);
}
return invertedPropertiesHash;
}
} |
JavaScript | class RegisterBlock extends Component {
constructor(props){
super(props);
this.state = {
User: {},
usernameState: STATUS.NO_INPUT,
emailState: STATUS.NO_INPUT,
passwordState: STATUS.NO_INPUT,
passwordSuggestState: {
status: STATUS.VALID,
eightCharacters: STATUS.NO_INPUT,
oneUpperCase: STATUS.NO_INPUT,
oneLowerCase: STATUS.NO_INPUT,
oneNumber: STATUS.NO_INPUT,
oneSpecial: STATUS.NO_INPUT
},
confirmState: STATUS.NO_INPUT,
verifyState: STATUS.NO_INPUT,
recaptchaState: STATUS.NO_INPUT,
verify: false,
username: "",
email: "",
password: "",
passwordConfirm: "",
recaptcha: "",
registrationStatus: STATUS.WAITING,
store_in_keystore: true
}
this.register = this.register.bind(this);
this.updateUsername = this.updateUsername.bind(this);
this.updateEmail = this.updateEmail.bind(this);
this.updatePassword = this.updatePassword.bind(this);
this.updatePasswordConfirm = this.updatePasswordConfirm.bind(this);
this.updateVerify = this.updateVerify.bind(this);
this.recaptcha = this.recaptcha.bind(this);
this.loginClick = this.loginClick.bind(this);
this.handleStorageClick = this.handleStorageClick.bind(this)
}
componentWillUnmount(){
this.showRecaptcha = false;
}
componentDidMount(){
this.showRecaptcha = true;
}
handleStorageClick(e) {
this.setState({store_in_keystore: ((e.target.name === "keystore"))})
}
register(){
this.setState({registrationStatus: STATUS.PENDING});
let abort = false;
if (this.state.usernameState !== STATUS.VALID){
abort = true;
this.setState({usernameState: STATUS.INVALID});
}
if (this.state.emailState !== STATUS.VALID){
abort = true;
this.setState({emailState: STATUS.INVALID});
}
if (this.state.passwordState !== STATUS.VALID){
abort = true;
this.setState({passwordState: STATUS.INVALID});
}
if (this.state.confirmState !== STATUS.VALID){
abort = true;
this.setState({confirmState: STATUS.INVALID});
}
if (!this.state.verify){
abort = true;
this.setState({verifyState: STATUS.INVALID});
}
if (this.state.recaptcha === ""){
abort = true;
this.setState({verifyState: STATUS.INVALID});
}
// If we are not ready, abort.
if (abort){
this.setState({registrationStatus: STATUS.WAITING});
}
this.props.accountRegister(this.state.email, this.state.password, {store_in_keystore: this.state.store_in_keystore})
}
updateUsername(){
let newState = STATUS.VALID;
if (this.username.value === "")
newState = STATUS.NO_INPUT;
this.setState({username: this.username.value, usernameState: newState});
}
updateEmail(){
let newState = this.state.emailState;
let isEmail = validator.isEmail(this.email.value);
newState = isEmail ? STATUS.VALID : STATUS.INVALID;
if (this.email.value === "")
newState = STATUS.NO_INPUT;
this.setState({email: this.email.value, emailState: newState});
}
updatePassword(){
let newState = STATUS.VALID;
if (this.password.value === "")
newState = STATUS.NO_INPUT;
function hasDigit(str) {
return (/^(?=.*\d)/.test(str));
}
function hasLowerCase(str) {
return (/^(?=.*[a-z])/.test(str));
}
function hasUpperCase(str) {
return (/^(?=.*[A-Z])/.test(str));
}
function hasSpecialCharacter(str) {
return (/[^A-Za-z0-9]/.test(str));
}
function isAtLeastEight(str){
return str.length >= 8;
}
var uppercase = hasUpperCase(this.password.value);
var lowercase = hasLowerCase(this.password.value);
var number = hasDigit(this.password.value);
var specialCharacter = hasSpecialCharacter(this.password.value);
var atLeastEight = isAtLeastEight(this.password.value);
var newStatus = STATUS.INVALID;
// If we are all good, or if there is no input, then hide the suggester
if ((uppercase && lowercase && number && specialCharacter && atLeastEight) || newState === STATUS.NO_INPUT)
newStatus = STATUS.VALID
this.setState({password: this.password.value, passwordState: newState, passwordSuggestState: {
status: newStatus,
eightCharacters: atLeastEight ? STATUS.VALID : STATUS.INVALID,
oneUpperCase: uppercase ? STATUS.VALID : STATUS.INVALID,
oneLowerCase: lowercase ? STATUS.VALID : STATUS.INVALID,
oneNumber: number ? STATUS.VALID : STATUS.INVALID,
oneSpecial: specialCharacter ? STATUS.VALID : STATUS.INVALID
}});
// Only set password confirm to "invalid" if the user has typed anything in.
if (this.state.passwordConfirm !== "")
this.updatePasswordConfirm();
}
updatePasswordConfirm(){
let newState = STATUS.INVALID;
if (this.passwordConfirm.value === this.password.value)
newState = STATUS.VALID;
if (this.passwordConfirm.value === "")
newState = STATUS.NO_INPUT;
this.setState({passwordConfirm: this.passwordConfirm.value, confirmState: newState});
}
updateVerify(verify_state){
this.setState({verify: verify_state });
}
recaptcha(response){
if (response)
this.setState({recaptcha: response, recaptchaState: STATUS.VALID})
else
this.setState({recaptcha: response, recaptchaState: STATUS.INVALID})
}
loginClick(){
this.setState({redirectToLogin: true})
}
render() {
var RegisterBtnTxt = "Register";
if (this.props.Account.registerFetching){
RegisterBtnTxt = "Registering..."
} else if (this.props.Account.registerSuccess){
RegisterBtnTxt = "Register Success!"
} else if (this.props.Account.registerFailure){
RegisterBtnTxt = "Register Error!"
}
return (
<div>
<h2>Please Register</h2>
<hr className="" />
<div className="form-group">
<input ref={username => this.username = username} onInput={this.updateUsername} type="text" className={"form-control input-lg" + (this.state.usernameState === STATUS.INVALID ? " is-invalid" : "") + (this.state.usernameState === STATUS.VALID ? " is-valid" : "")} placeholder="Username*" tabIndex="1" />
{this.state.usernameState === STATUS.INVALID ? <div className="invalid-feedback" id="feedback_username">
Please choose a Username
</div> : ""}
</div>
<div className="form-group">
<input ref={email => this.email = email} onInput={this.updateEmail} type="email" className={"form-control input-lg" + (this.state.emailState === STATUS.INVALID ? " is-invalid" : "") + (this.state.emailState === STATUS.VALID ? " is-valid" : "")} placeholder="Email Address" tabIndex="2" />
{this.state.emailState === STATUS.INUSE ? <div className="invalid-feedback">
That email is already in use, please try another one
</div> : ""}
{this.state.emailState === STATUS.INVALID ? <div className="invalid-feedback">
That email does not seem valid, please try another one
</div> : ""}
</div>
<div className="row">
<div className="col-xs-12 col-sm-6 col-md-6">
<div className="form-group">
<input ref={password => this.password = password} onInput={this.updatePassword} type="password" className={"form-control input-lg" + (this.state.passwordState === STATUS.INVALID ? " is-invalid" : "") + (this.state.passwordState === STATUS.VALID ? " is-valid" : "")} placeholder="Password*" tabIndex="3" />
</div>
</div>
<div className="col-xs-12 col-sm-6 col-md-6">
<div className="form-group">
<input ref={passwordConfirm => this.passwordConfirm = passwordConfirm} onInput={this.updatePasswordConfirm} type="password" className={"form-control input-lg" + (this.state.confirmState === STATUS.INVALID ? " is-invalid" : "") + (this.state.confirmState === STATUS.VALID ? " is-valid" : "")} placeholder="Confirm Password*" tabIndex="4" />
{this.state.confirmState === STATUS.INVALID ? <div className="invalid-feedback" id="feedback_password_confirmation">
Your passwords do not match
</div> : ""}
</div>
</div>
<div className="col-12">
{this.state.passwordSuggestState.status === STATUS.INVALID ?
<div className="warning-feedback">
We suggest your password contain a minimum of:
<ul style={{listStyle: "none"}}>
<li className={
this.state.passwordSuggestState.eightCharacters === STATUS.VALID ? "text-success" :
this.state.passwordSuggestState.eightCharacters === STATUS.INVALID ? "text-danger" : "text-warning"
}>
<span className={this.state.passwordSuggestState.eightCharacters === STATUS.VALID ? "fa fa-check" : "fa fa-times"}></span> 8 Characters
</li>
<li className={
this.state.passwordSuggestState.oneUpperCase === STATUS.VALID ? "text-success" :
this.state.passwordSuggestState.oneUpperCase === STATUS.INVALID ? "text-danger" : "text-warning"
}>
<span className={this.state.passwordSuggestState.oneUpperCase === STATUS.VALID ? "fa fa-check" : "fa fa-times"}></span> 1 Uppercase Letter
</li>
<li className={
this.state.passwordSuggestState.oneLowerCase === STATUS.VALID ? "text-success" :
this.state.passwordSuggestState.oneLowerCase === STATUS.INVALID ? "text-danger" : "text-warning"
}>
<span className={this.state.passwordSuggestState.oneLowerCase === STATUS.VALID ? "fa fa-check" : "fa fa-times"}></span> 1 Lowercase Letter
</li>
<li className={
this.state.passwordSuggestState.oneNumber === STATUS.VALID ? "text-success" :
this.state.passwordSuggestState.oneNumber === STATUS.INVALID ? "text-danger" : "text-warning"
}>
<span className={this.state.passwordSuggestState.oneNumber === STATUS.VALID ? "fa fa-check" : "fa fa-times"}></span> 1 Number
</li>
<li className={
this.state.passwordSuggestState.oneSpecial === STATUS.VALID ? "text-success" :
this.state.passwordSuggestState.oneSpecial === STATUS.INVALID ? "text-danger" : "text-warning"
}>
<span className={this.state.passwordSuggestState.oneSpecial === STATUS.VALID ? "fa fa-check" : "fa fa-times"}></span> 1 Special Character
</li>
</ul>
</div> : ""}
</div>
</div>
<div className="row d-flex justify-content-center">
<button name="local" type="button" onClick={this.handleStorageClick} className={"btn btn" + (this.state.store_in_keystore ? "-outline-success" : "-success") + " btn-sm m-2"}>Store locally</button>
<button name="keystore" type="button" onClick={this.handleStorageClick} className={"btn btn" + (this.state.store_in_keystore ? "-info" : "-outline-info") + " btn-sm m-2"}>Store in keystore</button>
</div>
<div className="row">
<div className="col-12 text-center" style={{fontSize: "13.5px", padding: "0px"}}>
<p>
Save your password now!
<br />
<strong>Password recovery is NOT possible</strong>
<br />
(We never see your password!)
</p>
</div>
<div className="col-12" style={{margin: "0px 0px"}}>
<center>
<ButtonCheckbox color={"secondary"} onChange={this.updateVerify} text={"I have taken responsibility for my password"} style={{fontSize: "12px", width: "300px", height: "50px"}} iconStyle={{fontSize: "25px", verticalAlign: "-5px"}} />
{this.state.verifyState === STATUS.INVALID ?
<p id="passwordResponsibilityCheckbox" style={{color: "#dc3545", fontSize: "13.5px", marginTop: "5px", marginBottom: "0px"}}>Please agree that you have saved your password safely!</p>
: ""}
</center>
</div>
</div>
<div className="row">
<div style={{margin: "0px auto", marginTop: "10px", marginBottom: "-5px"}}>
{this.showRecaptcha ? <ReCAPTCHA sitekey="6LdZnGgUAAAAALEwTXUJ9xzm30Ny_jqmgtKDYBo6" onChange={this.recaptcha} /> : ""}
{this.state.recaptchaState === STATUS.INVALID ?
<p style={{color: "#dc3545", fontSize: "13.5px", marginTop: "5px", marginBottom: "0px"}}>Your recaptcha is invalid!</p>
: ""}
</div>
</div>
<br />
<div className="row">
<div className="col-12" style={{fontSize: "13.5px", margin: "0px 0px", marginBottom: "-10px"}}>
By <strong>Registering</strong>, you agree to the <a href="/terms_and_conditions" data-toggle="modal" data-target="#t_and_c_m" data-ytta-id="-">Terms and Conditions</a>, including our Cookie Use.<p></p>
</div>
</div>
<hr className="" />
{this.props.Account.registerFailure ? this.props.Account.registerErrorMessage : null}
<div className="row">
<div className="col-xs-12 col-md-3 order-2 order-sm-1"><button className="btn btn-outline-secondary btn-block btn-lg" onClick={this.props.onLoginClick}>Login</button></div>
<div className="col-xs-12 col-md-9 order-1 order-sm-2"><button id="register" className={"btn btn" + (this.props.Account.registerFailure ? "-danger" : "-success") + " btn-block btn-lg"} onClick={this.register} tabIndex="5">{RegisterBtnTxt}</button></div>
</div>
</div>
);
}
} |
JavaScript | class MatRowHarness extends _MatRowHarnessBase {
constructor() {
super(...arguments);
this._cellHarness = MatCellHarness;
}
/**
* Gets a `HarnessPredicate` that can be used to search for a table row with specific attributes.
* @param options Options for narrowing the search
* @return a `HarnessPredicate` configured with the given options.
*/
static with(options = {}) {
return new HarnessPredicate(MatRowHarness, options);
}
} |
JavaScript | class MatHeaderRowHarness extends _MatRowHarnessBase {
constructor() {
super(...arguments);
this._cellHarness = MatHeaderCellHarness;
}
/**
* Gets a `HarnessPredicate` that can be used to search for
* a table header row with specific attributes.
* @param options Options for narrowing the search
* @return a `HarnessPredicate` configured with the given options.
*/
static with(options = {}) {
return new HarnessPredicate(MatHeaderRowHarness, options);
}
} |
JavaScript | class MatFooterRowHarness extends _MatRowHarnessBase {
constructor() {
super(...arguments);
this._cellHarness = MatFooterCellHarness;
}
/**
* Gets a `HarnessPredicate` that can be used to search for
* a table footer row cell with specific attributes.
* @param options Options for narrowing the search
* @return a `HarnessPredicate` configured with the given options.
*/
static with(options = {}) {
return new HarnessPredicate(MatFooterRowHarness, options);
}
} |
JavaScript | class Cursor {
// DOM elements
DOM = {
// Main element (.cursor)
el: null,
}
// Properties that will change
renderedStyles = {
// With interpolation, we can achieve a smooth animation effect when moving the cursor.
// The "previous" and "current" values are the values that will interpolate.
// The returned value will be one between these two (previous and current) at a specific increment.
// The "amt" is the amount to interpolate.
// As an example, the following formula calculates the returned translationX value to apply:
// this.renderedStyles.tx.previous = lerp(this.renderedStyles.tx.previous, this.renderedStyles.tx.current, this.renderedStyles.tx.amt);
// Cursor translation in the x-axis
tx: {previous: 0, current: 0, amt: 0.4},
// Cursor translation in the y-axis
ty: {previous: 0, current: 0, amt: 0.4},
// Scale up the cursor
scale: {previous: 1, current: 1, amt: 0.2},
// Fade out the cursor
opacity: {previous: 1, current: 1, amt: 0.3}
};
// Size and position
bounds;
/**
* Constructor.
* @param {Element} DOM_el - The .cursor element
* @param {String} triggerSelector - Selector for all the elements that when hovered trigger the cursor enter/leave methods. Default is all <a>.
*/
constructor(DOM_el, triggerSelector = 'a') {
this.DOM = {el: DOM_el};
// Hide initially
this.DOM.el.style.opacity = 0;
// Calculate size and position
this.bounds = this.DOM.el.getBoundingClientRect();
// Mousemove event:
// Start tracking the cursor position as soon as the user moves the cursor and fede in the cursor element.
this.onMouseMoveEv = () => {
// Set up the initial values to be the same
this.renderedStyles.tx.previous = this.renderedStyles.tx.current = cursor.x - this.bounds.width/2;
this.renderedStyles.ty.previous = this.renderedStyles.ty.previous = cursor.y - this.bounds.height/2;
// Fade in
gsap.to(this.DOM.el, {duration: 0.9, ease: 'Power3.easeOut', opacity: 1});
// Start loop
requestAnimationFrame(() => this.render());
// Remove the mousemove event
window.removeEventListener('mousemove', this.onMouseMoveEv);
};
window.addEventListener('mousemove', this.onMouseMoveEv);
[...document.querySelectorAll(triggerSelector)].forEach(link => {
link.addEventListener('mouseenter', () => this.enter());
link.addEventListener('mouseleave', () => this.leave());
});
}
/**
* Mouseenter event
* Scale up and fade out.
*/
enter() {
this.renderedStyles['scale'].current = 2;
this.renderedStyles['opacity'].current = 0.8;
}
/**
* Mouseleave event
* Reset scale and opacity.
*/
leave() {
this.renderedStyles['scale'].current = 1;
this.renderedStyles['opacity'].current = 1;
}
/**
* Shows the cursor
*/
show() {
this.renderedStyles['opacity'].current = 1;
}
/**
* Hides the cursor
*/
hide() {
this.renderedStyles['opacity'].current = 0;
}
/**
* Loop
*/
render() {
// New cursor positions
this.renderedStyles['tx'].current = cursor.x - this.bounds.width/2;
this.renderedStyles['ty'].current = cursor.y - this.bounds.height/2;
// Interpolation
for (const key in this.renderedStyles ) {
this.renderedStyles[key].previous = lerp(this.renderedStyles[key].previous, this.renderedStyles[key].current, this.renderedStyles[key].amt);
}
// Apply interpolated values (smooth effect)
this.DOM.el.style.transform = `translateX(${(this.renderedStyles['tx'].previous)}px) translateY(${this.renderedStyles['ty'].previous}px) scale(${this.renderedStyles['scale'].previous})`;
this.DOM.el.style.opacity = this.renderedStyles['opacity'].previous;
// loop...
requestAnimationFrame(() => this.render());
}
} |
JavaScript | class HttpMethod {
/**
* Instance an object
* @param methods array to list all avaiable http methods
* @param checked determines the current selected http methods by user
* @param subPrefix DOM id, needed to access the sub contents from the current method.
*/
constructor(methods, checked, subPrefix) {
$.each(methods, function (index, value) {
value = value.toUpperCase();
});
this.methods = methods;
this.subPrefix = subPrefix;
this.methodString = checked.toUpperCase();
}
/**
* httpMethod.method = "text"
* Trying to set the method property (methodString) of httpMethod with String "text".
* If "text" does not match with the kown methods (set by constructor) the set attempt will be ignored.
* If "text" is the same as last time, the sub content for that methods is toogled
* else the new set methods subcontent will be visible and the replaced one will be hidden.
* @param input should be a value from listed methods
*/
set method(input) {
input = input.toUpperCase();
var i;
for (i = 0; i < this.methods.length; i++) {
if (input == this.methods[i]) {
if (input == this.methodString) {
this.toggleMethod();
} else {
this.hideMethod();
this.methodString = input;
this.showMethod();
}
break;
}
}
}
/**
* xyz = httpMethod.method
* @return methodString value will be returned as the method property
*/
get method() {
return this.methodString;
}
/**
* Hides the outer div container from the subcontent for the current method property.
*/
hideMethod() {
if (this.methodString != "") {
$("#" + this.subPrefix + this.methodString.substring(0, 1).toUpperCase() + this.methodString.substring(1).toLowerCase()).hide();
}
}
/**
* Shows the outer div container from the subcontent for the current method property.
*/
showMethod() {
if (this.methodString != "") {
$("#" + this.subPrefix + this.methodString.substring(0, 1).toUpperCase() + this.methodString.substring(1).toLowerCase()).show();
}
}
/**
* Toggles the outer div container from the subcontent for the current method property.
*/
toggleMethod() {
if (this.methodString != "") {
$("#" + this.subPrefix + this.methodString.substring(0, 1).toUpperCase() + this.methodString.substring(1).toLowerCase()).toggle();
}
}
} |
JavaScript | class ModelSet extends BaseClass {
constructor(iterable) {
this._size = 0;
if(iterable) {
this.addObjects(iterable);
}
}
get size() {
return this._size;
}
/**
Clears the set. This is useful if you want to reuse an existing set
without having to recreate it.
```javascript
var models = new ModelSet([post1, post2, post3]);
models.size; // 3
models.clear();
models.size; // 0
```
@method clear
@return {ModelSet} An empty Set
*/
clear() {
var len = this._size;
if (len === 0) { return this; }
var guid;
for (var i=0; i < len; i++){
guid = guidFor(this[i]);
delete this[guid];
delete this[i];
}
this._size = 0;
return this;
}
add(obj) {
var guid = guidFor(obj),
idx = this[guid],
len = this._size;
if (idx>=0 && idx<len && (this[idx] && this[idx].isEqual(obj))) {
// overwrite the existing version
if(this[idx] !== obj) {
this[idx] = obj;
}
return this; // added
}
len = this._size;
this[guid] = len;
this[len] = obj;
this._size = len+1;
return this;
}
delete(obj) {
var guid = guidFor(obj),
idx = this[guid],
len = this._size,
isFirst = idx === 0,
isLast = idx === len-1,
last;
if (idx>=0 && idx<len && (this[idx] && this[idx].isEqual(obj))) {
// swap items - basically move the item to the end so it can be removed
if (idx < len-1) {
last = this[len-1];
this[idx] = last;
this[guidFor(last)] = idx;
}
delete this[guid];
delete this[len-1];
this._size = len-1;
return true;
}
return false;
}
has(obj) {
return this[guidFor(obj)]>=0;
}
copy(deep=false) {
var C = this.constructor, ret = new C(), loc = this._size;
ret._size = loc;
while(--loc>=0) {
ret[loc] = deep ? this[loc].copy() : this[loc];
ret[guidFor(this[loc])] = loc;
}
return ret;
}
forEach(callbackFn, thisArg = undefined) {
for (var i=0; i < this._size; i++) {
callbackFn.call(thisArg, this[i], this[i], this);
}
}
toString() {
var len = this.size, idx, array = [];
for(idx = 0; idx < len; idx++) {
array[idx] = this[idx];
}
return `ModelSet<${array.join(',')}>`;
}
get(model) {
var idx = this[guidFor(model)];
if(idx === undefined) return;
return this[idx];
}
getForClientId(clientId) {
var idx = this[clientId];
if(idx === undefined) return;
return this[idx];
}
*values() {
for (var i=0; i < this._size; i++) {
yield this[i];
}
}
/**
Adds the model to the set or overwrites the existing
model.
*/
addData(model) {
var existing = this.getModel(model);
var dest;
if(existing) {
dest = existing.copy();
model.copyTo(dest);
} else {
// copy since the dest could be the model in the session
dest = model.copy();
}
this.add(dest);
return dest;
}
//
// Backwards compat. methods
//
addObjects(iterable) {
if(typeof iterable.forEach === 'function') {
iterable.forEach(function(item) {
this.add(item);
}, this);
} else {
for (var item of iterable) {
this.add(item);
}
}
return this;
}
removeObjects(iterable) {
if(typeof iterable.forEach === 'function') {
iterable.forEach(function(item) {
this.delete(item);
}, this);
} else {
for (var item of iterable) {
this.delete(item);
}
}
return this;
}
toArray() {
return array_from(this);
}
} |
JavaScript | class XwInvalidStateError extends Error {
/**
* @constructor
* @param {string} [reason] Reason related to the invalid state
*/
constructor(reason) {
const _reason = xw.defaultable(reason);
super(_formatMessage(_reason));
this.reason = _reason;
}
} |
JavaScript | class ReservedInstances {
/**
* Constructs a new <code>ReservedInstances</code>.
* Describes a Reserved Instance.
* @alias module:model/ReservedInstances
*/
constructor() {
ReservedInstances.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>ReservedInstances</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/ReservedInstances} obj Optional instance to populate.
* @return {module:model/ReservedInstances} The populated <code>ReservedInstances</code> instance.
*/
static constructFromObject(data, obj) {
if (data) {
obj = obj || new ReservedInstances();
if (data.hasOwnProperty('AvailabilityZone')) {
obj['AvailabilityZone'] = ApiClient.convertToType(data['AvailabilityZone'], 'String');
}
if (data.hasOwnProperty('CurrencyCode')) {
obj['CurrencyCode'] = CurrencyCodeValues.constructFromObject(data['CurrencyCode']);
}
if (data.hasOwnProperty('Duration')) {
obj['Duration'] = ApiClient.convertToType(data['Duration'], 'Number');
}
if (data.hasOwnProperty('End')) {
obj['End'] = ApiClient.convertToType(data['End'], 'Date');
}
if (data.hasOwnProperty('FixedPrice')) {
obj['FixedPrice'] = ApiClient.convertToType(data['FixedPrice'], 'Number');
}
if (data.hasOwnProperty('InstanceCount')) {
obj['InstanceCount'] = ApiClient.convertToType(data['InstanceCount'], 'Number');
}
if (data.hasOwnProperty('InstanceTenancy')) {
obj['InstanceTenancy'] = Tenancy.constructFromObject(data['InstanceTenancy']);
}
if (data.hasOwnProperty('InstanceType')) {
obj['InstanceType'] = InstanceType.constructFromObject(data['InstanceType']);
}
if (data.hasOwnProperty('OfferingClass')) {
obj['OfferingClass'] = OfferingClassType.constructFromObject(data['OfferingClass']);
}
if (data.hasOwnProperty('OfferingType')) {
obj['OfferingType'] = OfferingTypeValues.constructFromObject(data['OfferingType']);
}
if (data.hasOwnProperty('ProductDescription')) {
obj['ProductDescription'] = RIProductDescription.constructFromObject(data['ProductDescription']);
}
if (data.hasOwnProperty('RecurringCharges')) {
obj['RecurringCharges'] = ApiClient.convertToType(data['RecurringCharges'], [RecurringCharge]);
}
if (data.hasOwnProperty('ReservedInstancesId')) {
obj['ReservedInstancesId'] = ApiClient.convertToType(data['ReservedInstancesId'], 'String');
}
if (data.hasOwnProperty('Scope')) {
obj['Scope'] = Scope.constructFromObject(data['Scope']);
}
if (data.hasOwnProperty('Start')) {
obj['Start'] = ApiClient.convertToType(data['Start'], 'Date');
}
if (data.hasOwnProperty('State')) {
obj['State'] = ReservedInstanceState.constructFromObject(data['State']);
}
if (data.hasOwnProperty('Tags')) {
obj['Tags'] = ApiClient.convertToType(data['Tags'], [Tag]);
}
if (data.hasOwnProperty('UsagePrice')) {
obj['UsagePrice'] = ApiClient.convertToType(data['UsagePrice'], 'Number');
}
}
return obj;
}
} |
JavaScript | class Terminal {
constructor(selector, words) {
this.wordbank = words;
this.terminal = document.querySelector(selector);
this.prompt = new Prompt('#answers');
this.MAX_TOTAL_CHARS = 12 * 32;
this.MAX_HALF_CHARS = 12 * 16;
}
/**
* Displays the terminal or displays the end game messages, dependin on the value
* of displayTerminal
*
* @param {boolean} displayTerminal if true, displays the terminal
* @memberof Terminal
*/
toggleGrid(displayTerminal) {
const terminal = document.querySelector('.terminal-body');
const message = document.querySelector('.terminal-message');
if(displayTerminal) {
terminal.style.display = 'grid';
message.style.display = 'none';
} else {
terminal.style.display = 'none';
message.style.display = 'grid';
}
}
/**
* Starts the game. Destroys old terminals and values and builds a new one.
*
* @param {string} level novice advance expert master
* @memberof Terminal
*/
play(level) {
// set the difficulty
const difficulty = {
novice: { min: 4, max: 5},
advanced: { min: 6, max: 8 },
expert: { min: 9, max: 10 },
master: { min: 11, max: 12 }
}
this.wordLength = random(difficulty[level].max + 1, difficulty[level].min);
// get the words
const words = this.wordbank.filter(word => word.length === this.wordLength).map(word => word.toUpperCase());
// use a set to avoid duplicates
this.words = new Set();
while(this.words.size !== 10) {
this.words.add(words[random(words.length)]);
}
// turn it into an array to allow for array methods
this.words = Array.from(this.words);
// set the properties
this.password = this.words[random(this.words.length)];
this.cursor = 0;
this.chars = [];
this.attempts = 5;
// build the coolumns;
document.querySelectorAll('.terminal-col-narrow, .terminal-col-wide')
.forEach(col => col.innerHTML = '');
this.prompt.wipeLog();
this.prompt.createLog();
this.setAttempts(this.attempts);
this.toggleGrid(true);
this.populateSideColumns();
this.populateGrid();
// first item is always selected
this.prompt.setPrompt(this.chars[0].char);
}
deselectAll() {
this.chars.forEach(char=> char.deselect());
}
/**
* Moves the cursor from grid to grid
*
* @param {Event} event
* @memberof Terminal
*/
moveCursor(event) {
event.preventDefault();
const arrows = [
"ArrowUp",
"ArrowDown",
"ArrowLeft",
"ArrowRight"
];
if(arrows.includes(event.key)) {
/**
* Calculates the new position or doesn't move if new position is invalid.
*
* @param {number} position starting position
* @param {number} direction should be 1 (down and right) or -1 (up or left)
* @param {number} amt should be 1 (left or right) or 12 (up or down) or distance to other grid
*/
const calcPosition = (position, direction, amt) => {
const newPosition = position + (amt * direction);
if(newPosition < 0 || newPosition >= (32 * 12)) {
return position;
}
return newPosition;
}
// holds movement functions
// key values match event.key for arrow presses
// ArrowLeft and ArrowRight also have ability to jump across to other side
const move = {
ArrowUp: (position)=> {
return calcPosition(position, -1, 12);
},
ArrowDown: (position)=> {
return calcPosition(position, 1, 12);
},
ArrowLeft: (position)=> {
const edges = [];
for(let i = 16; i < 32; i++) {
edges.push(i * 12);
}
const distance = edges.includes(position) ? (12 * 15) + 1 : 1;
return calcPosition(position, -1, distance);
},
ArrowRight: (position)=> {
const edges = [];
for(let i = 0; i < 16; i++) {
edges.push((i * 12) + 11);
}
const distance = edges.includes(position) ? (12 * 15) + 1 : 1;
return calcPosition(position, 1, distance);
},
}
// helper function for the .forEach calls later on
const selectAll = (char)=> char.select();
this.cursor = move[event.key](this.cursor);
this.deselectAll();
const selectedChar = this.chars[this.cursor];
// if there's a wordData object, select the word
if(selectedChar.wordData) {
selectedChar.select();
const word = selectedChar.wordData.word;
this.chars.filter(char => char.wordData && char.wordData.word === word)
.forEach(selectAll);
this.prompt.setPrompt(word);
// if there's a bracketData object, select the bracket pair
} else if(selectedChar.bracketData) {
const id = selectedChar.bracketData.id;
const bracket = this.chars.filter(char => char.bracketData && char.bracketData.id === id);
bracket.forEach(selectAll);
this.prompt.setPrompt(bracket.map(char=> char.char).join(''));
// otherwise just select the character
} else {
selectedChar.select();
this.prompt.setPrompt(selectedChar.char);
}
} else if(event.key === "Enter") {
this.submitPrompt(this.chars[this.cursor]);
}
}
/**
* Ends the game, displays a message and sets up for the next game
*
* @param {String} msg message to be displayed
* @memberof Terminal
*/
endGame(msg) {
setTimeout(()=> {
this.prompt.wipeLog();
this.toggleGrid(false);
document.getElementById('display').innerHTML = msg;
}, 1000)
}
/**
* Sends the selected character to the prompter
* Performs the appropriate action if it recieves a char, bracket or word
*
* @param {Char} char
* @memberof Terminal
*/
submitPrompt(char) {
if(char.wordData) {
const matches = compare(char.wordData.word, this.password);
// if the selected word is the password, win the game
if(matches === 'match') {
this.prompt.setPrompt(char.wordData.word, true);
this.prompt.setPrompt('Entry granted!', true);
this.endGame('User Authenticated')
// or, reduce the attempts and lose if attempts is at zero
} else {
this.prompt.setPrompt(char.wordData.word, true);
this.prompt.setPrompt('Entry denied.', true);
this.prompt.setPrompt(`Likeness=${matches}`, true);
this.attempts -= 1;
this.setAttempts(this.attempts);
if(this.attempts === 0) {
this.prompt.setPrompt('Initializing Lockout', true);
this.endGame('System locked out')
}
}
} else if(char.bracketData) {
if(char.bracketData.func === 'reset') {
this.setAttempts(5);
this.prompt.setPrompt('Tries reset.', true);
} else {
let dud = this.words.filter(word => word !== this.password)[random(this.words.length - 1)];
let chars = this.chars.filter(char => char.wordData && char.wordData.word === dud);
chars.forEach(char => {
char.wordData = null;
char.setChar('.');
});
this.words = this.words.filter(word => word !== dud);
this.prompt.setPrompt('Dud removed.', true);
}
let bracketId = char.bracketData.id;
this.chars.filter(char => char.bracketData && char.bracketData.id === bracketId)
.forEach(char => char.bracketData = null);
} else {
this.prompt.setPrompt(char.char, true);
this.prompt.setPrompt('Error', true);
}
}
/**
* Sets the number of attempts remaining, starting at 5.
*
* @param {number} amt
* @memberof Terminal
*/
setAttempts(amt) {
if(amt < 0) {
amt = 0;
}
const attempts = document.getElementById('attempts');
attempts.innerHTML = '▉ '.repeat(amt);
this.attempts = amt;
}
/**
* Populates the side columns with hex values that start at a random number
* and increment by 12.
* I guess they're just to make them look like memory addresses
*
* @memberof Terminal
*/
populateSideColumns() {
const [ side1, side2 ] = document.querySelectorAll('.hex');
[side1, side2].forEach(side => side.innerHTML = '');
let MIN = 4096;
let MAX = 65535 - (32 * 12);
let start = random(MAX, MIN);
for(let i = 0; i < 32; i++) {
let side = i < 16 ? side1 : side2;
const line = document.createElement('div');
line.innerHTML = '0x' + (start.toString(16));
side.appendChild(line);
start += 12;
}
}
/**
* Populates the grid with special characters
* Once it does that, it adds words
* Once it does that, it adds matched brackets
* Once it does that, it adds unmatched brackets
* @memberof Terminal
*/
populateGrid() {
const SPECIAL = `!@#$%^&*_+-=\`\\|;':".,/?`.split('');
const BRACKETS = `{}[]<>()`.split('');
const [ side1, side2 ] = document.querySelectorAll('.code');
[side1, side2].forEach(side => side.innerHTML = '');
const usedPositions = new Set();
const usedRows = new Set();
// fetches an unused row from either half of the grid
const getUnusedRow = (i, half)=> {
let row;
do {
row = i < half ? ROWS[random(ROWS.length / 2)]
: ROWS[random(ROWS.length, (ROWS.length / 2) + 1)];
} while(usedRows.has(row));
usedRows.add(row);
return row;
}
// generates an array of rows (multiples of 12)
const ROWS = [];
for(let i = 0; i < 32; i++) {
ROWS.push(i * 12);
}
// fill out the grid with special characters
for(let i = 0; i < this.MAX_TOTAL_CHARS; i++) {
let side = i < this.MAX_HALF_CHARS ? side1 : side2;
const character = SPECIAL[random(SPECIAL.length)];
const char = new Char(character, i);
this.chars.push(char);
side.appendChild(char.div);
}
// add the words at random
this.words.forEach((word, i) => {
// find an unused row
let row = getUnusedRow(i, this.words.length / 2);
// calculate the starting position
let position;
do {
position = row + random(12);
} while(position + this.wordLength > this.MAX_TOTAL_CHARS || usedPositions.has(position));
// add the word to that position character by character
word.split('').forEach(character => {
this.chars[position].setWord(character, { word, position });
usedPositions.add(position);
//if a word spills into another row, add that row to used rows
const currentRow = Math.floor(position / 12) * 12;
if(!usedRows.has(currentRow)) {
usedRows.add(currentRow);
}
position += 1;
});
});
// add the bracket pairs
let functions = arrayshuffle(['reset', 'dud', 'dud', 'dud', 'dud']);
for(let i = 0; i < 5; i++) {
let func = functions[i];
let row = getUnusedRow(i, 3);
const start = row + random(11);
const end = start + random(12 - (start % 12));
const index = random(4) * 2;
const [ open, close ] = [ BRACKETS[index], BRACKETS[index + 1] ];
let id = i;
this.chars[start].setBracket(open, { start, end, id, func });
for(let i = start; i < end; i++) {
this.chars[i].setBracket(this.chars[i].char, { start, end, id, func});
}
this.chars[end].setBracket(close, { start, end, id, func });
}
// finally, sprinkle in some random unbalanced brackets
const numBrackets = random(20,15);
for(let i = 0; i < numBrackets;) {
let char = this.chars[random(this.chars.length)];
if(!char.wordData && !char.bracketData) {
char.setChar(BRACKETS[random(BRACKETS.length)]);
i++;
}
}
}
} |
JavaScript | class Chart
{
/**
* Constructor.
*
* @param {selection} parent The selected D3 parent element container
* @param {Configuration} configuration The application configuration
*/
constructor(parent, configuration)
{
this._configuration = configuration;
this._parent = parent;
this._hierarchy = new Hierarchy(this._configuration);
this._data = {};
}
/**
* Returns the SVG instance.
*
* @return {Svg}
*/
get svg()
{
return this._svg;
}
/**
* Update/Calculate the viewBox attribute of the SVG element.
*
* @private
*/
updateViewBox()
{
// Get bounding boxes
let svgBoundingBox = this._svg.visual.node().getBBox();
let clientBoundingBox = this._parent.node().getBoundingClientRect();
// View box should have at least the same width/height as the parent element
let viewBoxWidth = Math.max(clientBoundingBox.width, svgBoundingBox.width);
let viewBoxHeight = Math.max(clientBoundingBox.height, svgBoundingBox.height, MIN_HEIGHT);
// Calculate offset to center chart inside svg
let offsetX = (viewBoxWidth - svgBoundingBox.width) / 2;
let offsetY = (viewBoxHeight - svgBoundingBox.height) / 2;
// Adjust view box dimensions by padding and offset
let viewBoxLeft = Math.ceil(svgBoundingBox.x - offsetX - MIN_PADDING);
let viewBoxTop = Math.ceil(svgBoundingBox.y - offsetY - MIN_PADDING);
// Final width/height of view box
viewBoxWidth = Math.ceil(viewBoxWidth + (MIN_PADDING * 2));
viewBoxHeight = Math.ceil(viewBoxHeight + (MIN_PADDING * 2));
// Set view box attribute
this._svg.get()
.attr("viewBox", [
viewBoxLeft,
viewBoxTop,
viewBoxWidth,
viewBoxHeight
]);
// Add rectangle element
// this._svg
// .insert("rect", ":first-child")
// .attr("class", "background")
// .attr("width", "100%")
// .attr("height", "100%")
// .style("fill", "none")
// .style("pointer-events", "all");
//
// // Adjust rectangle position
// this._svg
// .select("rect")
// .attr("x", viewBoxLeft)
// .attr("y", viewBoxTop);
}
/**
* Returns the chart data.
*
* @return {Object}
*/
get data()
{
return this._data;
}
/**
* Sets the chart data.
*
* @param {Object} value The chart data
*/
set data(value)
{
this._data = value;
// Create the hierarchical data structure
this._hierarchy.init(this._data);
}
/**
* This method draws the chart.
*/
draw()
{
// Remove previously created content
this._parent.html("");
// Create the <svg> element
this._svg = new Svg(this._parent, this._configuration);
// Overlay must be placed after the <svg> element
this._overlay = new Overlay(this._parent);
// Init the <svg> events
this._svg.initEvents(this._overlay);
let personGroup = this._svg.get().select("g.personGroup");
let gradient = new Gradient(this._svg, this._configuration);
let that = this;
personGroup
.selectAll("g.person")
.data(this._hierarchy.nodes, (d) => d.data.id)
.enter()
.append("g")
.attr("class", "person")
.attr("id", (d) => "person-" + d.data.id);
// Create a new selection in order to leave the previous enter() selection
personGroup
.selectAll("g.person")
.each(function (d) {
let person = d3.select(this);
if (that._configuration.showColorGradients) {
gradient.init(d);
}
new Person(that._svg, that._configuration, person, d);
});
this.bindClickEventListener();
this.updateViewBox();
}
/**
* This method bind the "click" event listeners to a "person" element.
*/
bindClickEventListener()
{
let persons = this._svg.get()
.select("g.personGroup")
.selectAll("g.person")
.filter((d) => d.data.xref !== "")
.classed("available", true);
// Trigger method on click
persons.on("click", this.personClick.bind(this));
}
/**
* Method triggers either the "update" or "individual" method on the click on an person.
*
* @param {Event} event The current event
* @param {Object} data The D3 data object
*
* @private
*/
personClick(event, data)
{
// Trigger either "update" or "redirectToIndividual" method on click depending on person in chart
(data.depth === 0) ? this.redirectToIndividual(data.data.url) : this.update(data.data.updateUrl);
}
/**
* Redirects to the individual page.
*
* @param {String} url The individual URL
*
* @private
*/
redirectToIndividual(url)
{
window.location = url;
}
/**
* Updates the chart with the data of the selected individual.
*
* @param {String} url The update URL
*/
update(url)
{
let update = new Update(this._svg, this._configuration, this._hierarchy);
update.update(url, () => this.bindClickEventListener());
}
} |
JavaScript | class Bridge {
constructor (socket, app) {
this.didAuth = false
this.sessionId = ''
this.checkSession = app.get('checkSession')
this.changeSessionState = app.get('changeSessionState')
this.socket = socket
this.udp = null
socket.on('message', this.clientToGrid.bind(this))
socket.on('close', this.onSocketClose.bind(this))
}
authenticate (sessionId) {
try {
const state = this.checkSession(sessionId)
if (state === 'inactive') {
// Session has no active socket -> open
this.didAuth = true
this.changeSessionState(sessionId, 'active')
this.sessionId = sessionId
const udp = dgram.createSocket('udp4')
this.udp = udp
udp.bind()
udp.on('message', this.gridToClient.bind(this))
udp.on('close', this.onUDPClose.bind(this))
this.socket.send('ok')
} else {
// session did close or has an active socket -> close this socket
this.socket.close(1008, 'already active socket open')
}
} catch (err) {
// handle error
if (err.status === pouchdbErrors.INVALID_REQUEST.status) {
this.socket.close(1011, err.message)
} else {
this.socket.close(1008, 'wrong session id')
}
}
}
clientToGrid (message) {
if (message instanceof Buffer && this.didAuth) {
const ip = message.readUInt8(0) + '.' +
message.readUInt8(1) + '.' +
message.readUInt8(2) + '.' +
message.readUInt8(3)
const port = message.readUInt16LE(4)
const buffy = message.slice(6)
this.udp.send(buffy, 0, buffy.length, port, ip)
} else if (!this.didAuth && typeof message === 'string') {
this.authenticate(message)
}
}
gridToClient (message, rinfo) {
const buffy = Buffer.concat([
Buffer.alloc(6),
message
])
// add IP address
const ipParts = rinfo.address.split('.')
for (let i = 0; i < 4; i++) {
buffy.writeUInt8(Number(ipParts[i]), i)
}
// add port
buffy.writeUInt16LE(rinfo.port, 4)
this.socket.send(buffy, { binary: true })
}
onSocketClose (code, reason) {
if (this.socket && this.sessionId !== '') {
const nextState = code === 1000 ? 'end' : 'inactive'
try {
this.changeSessionState(this.sessionId, nextState)
} catch (err) {
console.error(err)
}
}
if (this.socket) {
this.socket = undefined
}
if (this.udp) {
this.udp.close()
this.udp = undefined
}
}
onUDPClose () {
if (this.udp) {
this.udp = undefined
}
if (this.socket) {
this.socket.close(1012, 'udp did close')
this.socket = undefined
}
}
} |
JavaScript | class BusinessDashboardParent extends React.Component{
/* -----------------------------------------------------------------------------
Constructor is used for state design, modularized to pass as props
----------------------------------------------------------------------------- */
constructor(props){
super(props);
this.state = {
// Values for the parent
currentLocation: '',
session: '',
currentStore: '',
currentMessage: 'Success!',
currentStatus: 'good',
load: () => {
//BE Call: On page load
let base = 'https://fuo-backend.herokuapp.com/business/printalllocation/';
let id = this.state.session;
let url = base + id;
fetch(url)
.then(res => {
if( res.status === 200){
return res.json();
}
else{
throw new Error("bad loading");
}
})
.then(data => {
this.setState({locations: data, locationBg: ''});
})
.catch(error => {
console.log('caught load');
console.log(error);
this.setState({currentMessage: 'Something went wrong...', currentStatus:'bad'});
});
base = 'https://fuo-backend.herokuapp.com/business/numoflocations/';
url = base + this.state.session;
fetch(url)
.then(res => {
if( res.status === 200){
return res.json();
}
else{
throw new Error("bad loading");
}
})
.then(data => this.setState({totalLocations: data}))
.catch(error => {
console.log('caught numLocations');
console.log(error);
this.setState({currentMessage: 'Something went wrong...', currentStatus:'bad'});
});
base = 'https://fuo-backend.herokuapp.com/business/getbusinessname/';
url = base + this.state.session;
fetch(url)
.then(res => {
if( res.status === 200){
return res.json();
}
else{
throw new Error("bad loading");
}
})
.then(data => this.setState({companyName: data.name}))
.catch(error => {
console.log('caught numLocations');
console.log(error);
this.setState({currentMessage: 'Something went wrong...', currentStatus:'bad'});
});
},
// Props for LeftSideBar -------------------------------------------------
logout: () => {
localStorage.clear();
window.location.assign('https://corona-food.herokuapp.com/landing.html');
},
companyName: '',
totalLocations: '',
addLocation: () => {
this.setState({formClass: this.state.formClass==="off"?"on":"off"});
},
// Props for LocationSearchBar -------------------------------------------
search: (e) => {
if(e === ''){
let base = 'https://fuo-backend.herokuapp.com/business/printalllocation/';
let id = this.state.session;
let url = base + id;
fetch(url)
.then(res => {
if( res.status === 200){
return res.json();
}
else{
throw new Error("bad loading");
}
})
.then(data => {this.setState({locations: data, locationBg: ''})})
.catch(error => {
console.log('caught load');
console.log(error);
});
}
else{
let base = 'https://fuo-backend.herokuapp.com/business/searchlocation/';
let id = this.state.session + '/';
let arg = e;
let url = base + id + arg;
console.log(url);
fetch(url)
.then(res => {
if(res.status === 200){
return res.json()
}
else{
throw new Error("bad search");
}
})
.then(data => {
this.setState({locations: data, locationBg: (data.length===0?'empty':'')});
})
.catch(error => {
console.log("caught search");
console.log(error);
this.setState({locations: [], locationBg: 'empty'});
});
}
},
// Props for Location ----------------------------------------------------
locations: [],
locationBg: 'empty',
selectLocation: (sel) => {
//Error when selection not found
if(sel === null){
alert("Select Location failed");
return
}
//BE Call: On store get
let base = 'https://fuo-backend.herokuapp.com/product/printallproduct/';
let id = sel.store_id;
let url = base + id;
fetch(url)
.then(res => {
if( res.status === 200){
return res.json();
}
else{
throw new Error("Unable to get store");
}
})
.then(data => {
let currentList = [];
for(let i = 0; i < data.length; i++){
currentList.push({
image: data[i].product_img,
category: data[i].category,
name: data[i].product_name,
amount: data[i].stock_amount,
price: data[i].price,
rate: data[i].coupon,
product_id: data[i].product_id,
expiration: data[i].expire_date
});
}
let list = [];
for(let i = 0; i < currentList.length; i++){
list.push(this.state.fillListing(currentList[i], 7));
}
this.setState({
right: {
address: sel.address,
totalProducts: data.length,
productsList: data
},
updateListings: currentList,
list: list,
currentLocation: sel.address,
currentStore: sel.store_id
});
})
.catch(error => {
console.log('caught store get');
console.log(error);
this.setState({currentMessage: 'Something went wrong...', currentStatus:'bad'});
});
},
//Props for LocationInfo -------------------------------------------------
right: {
address: 'No Selection',
totalProducts: 0,
productsList: []
},
rightControls: {
updateProducts: () => {
if(this.state.currentStore !== ''){
this.setState({updateClass: this.state.updateClass==="off"?"on":"off"});
}
else{
alert("No location selected");
}
},
deleteLocation: (e) => {
//BE Call: On location Delete
const method = {method: 'DELETE'};
let base = 'https://fuo-backend.herokuapp.com/business/deletelocation/';
let id = this.state.session + '/';
this.setState({currentStatus:''});
let arg = this.state.currentStore;
let url = base + id + arg;
if( this.state.currentStore!==''){
fetch(url, method)
.then(res => {
if( res.status === 200){
return res.json();
}
else{
throw new Error("Delete failed");
}
})
.then(data =>
{
base = 'https://fuo-backend.herokuapp.com/business/printalllocation/';
id = this.state.session;
url = base + id;
this.state.load();
this.setState({
currentStore: '',
right: {
address: "No Selection",
totalProducts: 0,
productsList: []
},
updateListings: [],
list: [],
currentStatus: 'good',
currentMessage: 'Success!'
});
}
)
.catch(error => {
console.log('caught delete');
console.log(error);
this.setState({currentMessage: 'Something went wrong...', currentStatus:'bad'});
});
}
else{
alert("No location selected");
}
},
},
// Props for AddLocation--------------------------------------------------
formClass: "off",
form: {
submitNewLocation: (location) => {
//BE Call: On location add
this.setState({currentStatus:''});
const method = {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
address: location.street + '.' + location.city + ',' + location.state + ' ' + location.zip,
name: location.name
})
};
let base = 'https://fuo-backend.herokuapp.com/business/addlocation/';
let id = this.state.session;
let url = base + id;
fetch(url, method)
.then(res => {
if(res.status === 200){
return res.json();
}
else{
throw new Error('Add location failed');
}
})
.then(data => {
base = 'https://fuo-backend.herokuapp.com/business/printalllocation/';
id = this.state.session;
url = base + id;
this.state.load();
this.setState({currentMessage: 'Success!', currentStatus:'good'})
}
)
.catch(error => {
console.log('caught add');
console.log(error);
this.setState({currentMessage: 'Something went wrong...', currentStatus:'bad'});
});
},
closeForm: (e) => {
this.setState({formClass: this.state.formClass==="off"?"on":"off"});
},
},
//Props for UpdateListings------------------------------------------------
updateListings: [],
removeListings: [],
list: [],
idx: -1,
key: 0,
updateClass: "off",
formControl: {
remove: (idx) => {
//find and remove by idx
let listings = this.state.updateListings;
let list = this.state.list;
let remove = this.state.removeListings;
let rem = null;
for(let i = 0; i < list.length; i++){
if(list[i].props.data.idx === idx){
rem = i;
break;
}
}
//Not found error
if(rem === null){
alert("Remove failed: could not find item");
return;
}
//Remove
remove.push(listings[rem]);
listings.splice(rem, 1);
list.splice(rem, 1);
//reset state
this.setState({updateListings: listings, list: list, removeListings: remove});
},
onChange: (idx, obj, focus) => {
//find and change by index
let listings = this.state.updateListings;
let list = this.state.list;
let mod = null;
for(let i = 0; i < listings.length; i++){
if(list[i].props.data.idx === idx){
mod = i;
break;
}
}
//Not found error
if(mod === null){
alert("Change failed: could not find item");
return;
}
//Modify
listings[mod] = obj;
list[mod] = this.state.fillListing(listings[mod], focus);
this.setState({updateListings: listings, list: list});
}
},
update: {
submitUpdate: () => {
//Repackage listings for HTTP request
let list = JSON.parse(JSON.stringify(this.state.updateListings));
if(!this.validate(list)){return false;}
let body = [];
let ids = [];
for(let i = 0; i < list.length; i++){
body.push({
product_name: list[i].name,
product_img: list[i].image,
category: list[i].category,
price: list[i].price,
expire_date: list[i].expiration,
stock_amount: list[i].amount,
coupon: list[i].rate
});
ids.push(list[i].product_id);
}
//BE Call: On products upsert
let method = {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: {}
};
let base = 'https://fuo-backend.herokuapp.com/product/upsert/';
let id = this.state.currentStore + '/';
this.setState({currentStatus:''});
for(let i = 0 ; i < body.length; i++){
let arg = ids[i];
let url = base + id + arg;
method.body = JSON.stringify(body[i]);
fetch(url, method)
.then(res => {
if( res.status === 200){
return res.json();
}
else{
throw new Error("bad upload");
}
})
.then(data => {
this.state.refreshCurrent();
this.setState({currentMessage: 'Success!', currentStatus:'good'});
})
.catch(error => {
console.log('caught upload');
console.log(error);
this.setState({currentMessage: 'Something went wrong...', currentStatus:'bad'});
});
}
//BE Call: On products delete
list = JSON.parse(JSON.stringify(this.state.removeListings));
this.setState({removeListings: []});
method = {
method: 'DELETE',
headers: {
'Content-Type': 'application/json'
},
}
base = 'https://fuo-backend.herokuapp.com/product/delete/';
id = this.state.currentStore + '/';
let url = '';
for(let i = 0; i < list.length; i++){
if(list[i].product_id !== '0'){
url = base + id + list[i].product_id;
fetch(url, method)
.then(res => {
if( res.status === 200){
return res.json();
}
else{
throw new Error("Delete item failed");
}
})
.then(data => {
this.state.refreshCurrent();
this.setState({currentMessage: 'Success!', currentStatus:'good'});
})
.catch(error => {
console.log('caught delete');
console.log(error);
this.setState({currentMessage: 'Something went wrong...', currentStatus:'bad'});
});
}
}
this.state.update.closeForm();
},
addListing: (e) => {
let listings = this.state.updateListings;
let list = this.state.list;
let newListing = {
image:'',
category:'None',
name: '',
amount: '',
price: '',
rate: '',
product_id: '0',
expiration: '',
idx: this.state.idx,
remove: this.state.formControl.remove,
onChange: this.state.formControl.onChange,
linkError: '',
nameError: '',
amountError: '',
priceError: '',
discountError: '',
expirationError: '',
}
let newList = (<ListingForm data={newListing} key={this.state.key} action={this.state.formControl} focus={7}/>)
listings.push(newListing);
list.push(newList);
this.setState({updateListings: listings, list: list, key: this.state.key+1, idx: this.state.idx-1});
},
closeForm: (e) => {
try{
e.preventDefault();
} catch(e){ console.log("saved!");}
this.setState({updateClass: this.state.updateClass==="off"?"on":"off"});
},
},
fillListing: (list, focus) => {
let newListing = {
image: list.image===null?'':list.image,
category: list.category,
name: list.name,
amount: list.amount,
price: list.price,
rate: list.rate,
product_id: list.product_id,
expiration: list.expiration,
product_id: list.product_id,
idx: this.state.idx,
remove: this.state.formControl.remove,
onChange: this.state.formControl.onChange
}
let fill = <ListingForm data={newListing} key={this.state.key} action={this.state.formControl} focus={focus}/>;
this.setState({key: this.state.key+1, idx: this.state.idx-1});
return fill;
},
refreshCurrent:()=>{
let base = 'https://fuo-backend.herokuapp.com/product/printallproduct/';
let id = this.state.currentStore;
let url = base + id;
fetch(url)
.then(res => {
if( res.status === 200){
return res.json();
}
else{
throw new Error("Failed to get new listings");
}
})
.then(data => {
let currentList = [];
for(let i = 0; i < data.length; i++){
currentList.push({
image: data[i].product_img,
category: data[i].category,
name: data[i].product_name,
amount: data[i].stock_amount,
price: data[i].price,
rate: data[i].coupon,
product_id: data[i].product_id,
expiration: data[i].expire_date
});
}
let list = [];
for(let i = 0; i < currentList.length; i++){
list.push(this.state.fillListing(currentList[i], 7));
}
this.setState({
right: {
address: this.state.currentLocation,
totalProducts: data.length,
productsList: data
},
updateListings: currentList,
list: list,
});
})
.catch(error => {
console.log('caught');
console.log(error);
});
}
};
//binding
this.validate = this.validate.bind(this);
}
/** validation for all listings are filled in */
validate = (list) => {
for (let i = 0; i < list.length; i++) {
if ( (list[i].image && !list[i].image.includes('.')) ||
(!list[i].name ) ||
(!list[i].amount || !Number(list[i].amount) ) ||
(!list[i].price || !Number(list[i].price) || Number(list[i].price) > 1000) ||
(!list[i].rate || !Number(list[i].rate)) ||
(!list[i].expiration || new Date(list[i].expiration) < new Date().setDate(new Date().getDate() - 1))
) {
alert('Please provide all required details.')
return false;
}
}
return true;
};
/* -----------------------------------------------------------------------------
Assemble page, pass state values into props
Action | Child functionality implemented in parent, then passed down
Data | Read only propss
Initial | Starter data that may get changed
----------------------------------------------------------------------------- */
render(){
return(
<div>
<LeftSideBar action={this.state.addLocation} data={this.state.logout} name={this.state.companyName} num={this.state.totalLocations}/>
<LocationSearchBar action={this.state.search} />
<Locations action={this.state.selectLocation} data={this.state.locations} initial={this.state.locationBg} />
<LocationInfo action={this.state.rightControls} data={this.state.right} />
<AddLocation action={this.state.form} data={this.state.formClass} />
<UpdateListings action={this.state.update} data={this.state.updateClass} initial={this.state.list}/>
<Status message={this.state.currentMessage} status={this.state.currentStatus}/>
</div>
);
}
/* -----------------------------------------------------------------------------
After Render
----------------------------------------------------------------------------- */
componentDidMount(){
//Alert logins on small bad screen sizes
if(window.innerWidth / window.innerHeight < 1.3 || window.innerHeight < 720){
alert("Layout has not been optimized for small screens. Please log in with a larger device.");
}
let body = {
token: localStorage.getItem("fuo-b")
};
fetch('https://fuo-backend.herokuapp.com/users/me/from/token/business', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(body)
})
.then(res => {
if(res.status === 200){
return res.json()
}
else{
window.location.assign('https://corona-food.herokuapp.com/');
throw new Error('There is no session');
}
})
.then(data => {
this.setState({session: data.user.business_id});
this.state.load();
})
.catch(err => {
console.log("caught b login");
console.log(err);
window.location.assign('https://corona-food.herokuapp.com/');
this.setState({currentMessage: 'Something went wrong...', currentStatus:'bad'});
});
}
} |
JavaScript | class CoreBadge extends HTMLElement {
/**
* Initialize private fields, shadowRoot and the view
*/
constructor() {
super();
// Initialize all private fields
this._value = this.getAttribute('value') || undefined;
this._max = this.getAttribute('max') || undefined;
this._isDot = this.hasAttribute('is-dot') || false;
this._hidden = this.hasAttribute('hidden') || false;
this._type = this.getAttribute('type') || undefined;
// Initialize the shadowRoot
this.attachShadow({mode: 'open'});
this.shadowRoot.appendChild(template.content.cloneNode(true));
this.shadowRoot.appendChild(style.cloneNode(true));
// Add 'change' event listener to this element so that
// every time a 'change' event is observed, update the view
const config = {attributes: false, childList: true, subtree: true};
const observer = new MutationObserver(this._updateTemplate.bind(this));
observer.observe(this, config);
this.addEventListener('change', this._updateTemplate.bind(this));
// Initialize the view
this._updateTemplate();
}
get max() {
return this._max;
}
/**
* The maximum number that can be put in the badge
* <br>If the value field is a number larger than max field,
* `${max}+` will be displayed in the badge
* @param {number} val
*/
set max(val) {
if (typeof val === 'number') {
this._max = val;
this.setAttribute('max', val);
} else {
this._max = undefined;
this.removeAttribute('max');
}
this._updateTemplate();
}
get isDot() {
return this._isDot;
}
/**
* If a little dot is displayed instead of the value
* @param {boolean} val
*/
set isDot(val) {
if (val === true) {
this._isDot = true;
this.setAttribute('is-dot', '');
} else {
this._isDot = false;
this.removeAttribute('is-dot');
}
this._updateTemplate();
}
get hidden() {
return this._hidden;
}
/**
* If the badge is displayed or not.
* @param {boolean} val
*/
set hidden(val) {
if (val === true) {
this._hidden = true;
this.setAttribute('hidden', '');
} else {
this._hidden = false;
this.removeAttribute('hidden');
}
this._updateTemplate();
}
get value() {
return this._value;
}
/**
* The content that the badge tries to display but may not be the same as the acutal displayed content
* when the value is a number larger than max field.
* @param {number|string} val
*/
set value(val) {
if (typeof val === 'string' || typeof val === 'number') {
this._value = val;
this.setAttribute('value', val);
} else {
this._value = undefined;
this.removeAttribute('value');
}
this._updateTemplate();
}
get type() {
return this._type;
}
/**
* The type of the badge chosen from [primary, success, warning, info, danger]
* @param {string} val
*/
set type(val) {
if (['primary', 'success', 'warning', 'info', 'danger'].indexOf(val) > -1) {
this._type = val;
this.setAttribute('type', val);
} else {
this._type = undefined;
this.removeAttribute('type');
}
this._updateTemplate();
}
/**
* The actual content to be displayed. It may be different from the given value because of max field.
*/
get content() {
if (this.isDot) return '';
const value = this.value;
const max = this.max;
const valueNum = parseInt(value);
const maxNum = parseInt(max);
if (!isNaN(valueNum) && !isNaN(maxNum)) {
return maxNum < valueNum ? `${maxNum}+` : valueNum;
}
return value;
}
/**
* Update the content of the transition element inside our template
*/
_updateTemplate() {
const update = !this.hidden && (this.content || this.content === 0 || this.isDot) ? `
<sup class="el-badge__content ${'el-badge__content--' + (this.type === null ? undefined : this.type)} ${this.innerHTML ? 'is-fixed' : ''} ${this.isDot ? 'is-dot' : ''}">
${this.content}
</sup>
` : '';
this.shadowRoot.querySelector('transition').innerHTML = update;
}
} |
JavaScript | class StatusMessage
{
/**
*
* @param {Integer} pProgress
* @param {String} pMessage
* @constructor
*/
constructor( pProgress, pMessage=""){
this.progress = pProgress;
this.msg = pMessage;
this.extra = null;
Logger.debug('<status message> : NEW : ',pMessage);
}
/**
* To create a messsage with "error" flag
* @param {Integer} pProgress
* @param {String} pMessage
* @returns {StatusMessage}
* @static
*/
static newError( pProgress, pMessage){
let m = new StatusMessage(pProgress, pMessage);
m.extra = "error";
Logger.debug('<status message> : ERROR : ',pMessage);
return m;
}
/**
* To create a message with "success" flag
*
* @param {String} pMessage
* @returns {StatusMessage}
* @static
*/
static newSuccess( pMessage){
let m = new StatusMessage(100, pMessage);
m.extra = "success";
Logger.debug('<status message> : SUCCESS : ',pMessage);
return m;
}
/**
*
* @param {*} pMsg
* @method
*/
append( pMsg){
return this.msg+"\n"+pMsg;
}
/**
* @method
*/
getProgress(){
return this.progress;
}
/**
* @method
*/
getMessage(){
return this.msg;
}
/**
* @method
*/
getExtra(){
return this.extra;
}
/**
* To export to a poor object, ready to be serialized into JSON format
*
* @method
*/
toJsonObject(){
let o = new Object();
o.progress = this.progress;
o.msg = this.msg;
o.extra = this.extra;
return o;
}
} |
JavaScript | class ToStringBuilder {
constructor(object, style, buffer) {
if (((object != null) || object === null) && ((style != null && style instanceof org.openprovenance.apache.commons.lang.builder.ToStringStyle) || style === null) && ((buffer != null && (buffer instanceof Object)) || buffer === null)) {
let __args = arguments;
if (this.buffer === undefined) {
this.buffer = null;
}
if (this.object === undefined) {
this.object = null;
}
if (this.style === undefined) {
this.style = null;
}
if (style == null) {
style = ToStringBuilder.getDefaultStyle();
}
if (buffer == null) {
buffer = { str: "", toString: function () { return this.str; } };
}
this.buffer = buffer;
this.style = style;
this.object = object;
style.appendStart(buffer, object);
}
else if (((object != null) || object === null) && ((style != null && style instanceof org.openprovenance.apache.commons.lang.builder.ToStringStyle) || style === null) && buffer === undefined) {
let __args = arguments;
{
let __args = arguments;
let buffer = null;
if (this.buffer === undefined) {
this.buffer = null;
}
if (this.object === undefined) {
this.object = null;
}
if (this.style === undefined) {
this.style = null;
}
if (style == null) {
style = ToStringBuilder.getDefaultStyle();
}
if (buffer == null) {
buffer = { str: "", toString: function () { return this.str; } };
}
this.buffer = buffer;
this.style = style;
this.object = object;
style.appendStart(buffer, object);
}
if (this.buffer === undefined) {
this.buffer = null;
}
if (this.object === undefined) {
this.object = null;
}
if (this.style === undefined) {
this.style = null;
}
}
else if (((object != null) || object === null) && style === undefined && buffer === undefined) {
let __args = arguments;
{
let __args = arguments;
let style = null;
let buffer = null;
if (this.buffer === undefined) {
this.buffer = null;
}
if (this.object === undefined) {
this.object = null;
}
if (this.style === undefined) {
this.style = null;
}
if (style == null) {
style = ToStringBuilder.getDefaultStyle();
}
if (buffer == null) {
buffer = { str: "", toString: function () { return this.str; } };
}
this.buffer = buffer;
this.style = style;
this.object = object;
style.appendStart(buffer, object);
}
if (this.buffer === undefined) {
this.buffer = null;
}
if (this.object === undefined) {
this.object = null;
}
if (this.style === undefined) {
this.style = null;
}
}
else
throw new Error('invalid overload');
}
static defaultStyle_$LI$() { if (ToStringBuilder.defaultStyle == null) {
ToStringBuilder.defaultStyle = org.openprovenance.apache.commons.lang.builder.ToStringStyle.DEFAULT_STYLE_$LI$();
} return ToStringBuilder.defaultStyle; }
/**
* <p>Gets the default <code>ToStringStyle</code> to use.</p>
*
* <p>This method gets a singleton default value, typically for the whole JVM.
* Changing this default should generally only be done during application startup.
* It is recommended to pass a <code>ToStringStyle</code> to the constructor instead
* of using this global default.</p>
*
* <p>This method can be used from multiple threads.
* Internally, a <code>volatile</code> variable is used to provide the guarantee
* that the latest value set using {@link #setDefaultStyle} is the value returned.
* It is strongly recommended that the default style is only changed during application startup.</p>
*
* <p>One reason for changing the default could be to have a verbose style during
* development and a compact style in production.</p>
*
* @return {org.openprovenance.apache.commons.lang.builder.ToStringStyle} the default <code>ToStringStyle</code>, never null
*/
static getDefaultStyle() {
return ToStringBuilder.defaultStyle_$LI$();
}
/**
* <p>Sets the default <code>ToStringStyle</code> to use.</p>
*
* <p>This method sets a singleton default value, typically for the whole JVM.
* Changing this default should generally only be done during application startup.
* It is recommended to pass a <code>ToStringStyle</code> to the constructor instead
* of changing this global default.</p>
*
* <p>This method is not intended for use from multiple threads.
* Internally, a <code>volatile</code> variable is used to provide the guarantee
* that the latest value set is the value returned from {@link #getDefaultStyle}.</p>
*
* @param {org.openprovenance.apache.commons.lang.builder.ToStringStyle} style the default <code>ToStringStyle</code>
* @throws IllegalArgumentException if the style is <code>null</code>
*/
static setDefaultStyle(style) {
if (style == null) {
throw Object.defineProperty(new Error("The style must not be null"), '__classes', { configurable: true, value: ['java.lang.Throwable', 'java.lang.Object', 'java.lang.RuntimeException', 'java.lang.IllegalArgumentException', 'java.lang.Exception'] });
}
ToStringBuilder.defaultStyle = style;
}
static reflectionToString$java_lang_Object(object) {
return org.openprovenance.apache.commons.lang.builder.ReflectionToStringBuilder.toString$java_lang_Object(object);
}
static reflectionToString$java_lang_Object$org_openprovenance_apache_commons_lang_builder_ToStringStyle(object, style) {
return org.openprovenance.apache.commons.lang.builder.ReflectionToStringBuilder.toString$java_lang_Object$org_openprovenance_apache_commons_lang_builder_ToStringStyle(object, style);
}
static reflectionToString$java_lang_Object$org_openprovenance_apache_commons_lang_builder_ToStringStyle$boolean(object, style, outputTransients) {
return org.openprovenance.apache.commons.lang.builder.ReflectionToStringBuilder.toString$java_lang_Object$org_openprovenance_apache_commons_lang_builder_ToStringStyle$boolean$boolean$java_lang_Class(object, style, outputTransients, false, null);
}
static reflectionToString$java_lang_Object$org_openprovenance_apache_commons_lang_builder_ToStringStyle$boolean$java_lang_Class(object, style, outputTransients, reflectUpToClass) {
return org.openprovenance.apache.commons.lang.builder.ReflectionToStringBuilder.toString$java_lang_Object$org_openprovenance_apache_commons_lang_builder_ToStringStyle$boolean$boolean$java_lang_Class(object, style, outputTransients, false, reflectUpToClass);
}
/**
* <p>Uses <code>ReflectionToStringBuilder</code> to generate a
* <code>toString</code> for the specified object.</p>
*
* @param {*} object the Object to be output
* @param {org.openprovenance.apache.commons.lang.builder.ToStringStyle} style the style of the <code>toString</code> to create, may be <code>null</code>
* @param {boolean} outputTransients whether to include transient fields
* @param {*} reflectUpToClass the superclass to reflect up to (inclusive), may be <code>null</code>
* @return {string} the String result
* @see ReflectionToStringBuilder#toString(Object,ToStringStyle,boolean,boolean,Class)
* @since 2.0
*/
static reflectionToString(object, style, outputTransients, reflectUpToClass) {
if (((object != null) || object === null) && ((style != null && style instanceof org.openprovenance.apache.commons.lang.builder.ToStringStyle) || style === null) && ((typeof outputTransients === 'boolean') || outputTransients === null) && ((reflectUpToClass != null && (reflectUpToClass["__class"] != null || ((t) => { try {
new t;
return true;
}
catch (_a) {
return false;
} })(reflectUpToClass))) || reflectUpToClass === null)) {
return org.openprovenance.apache.commons.lang.builder.ToStringBuilder.reflectionToString$java_lang_Object$org_openprovenance_apache_commons_lang_builder_ToStringStyle$boolean$java_lang_Class(object, style, outputTransients, reflectUpToClass);
}
else if (((object != null) || object === null) && ((style != null && style instanceof org.openprovenance.apache.commons.lang.builder.ToStringStyle) || style === null) && ((typeof outputTransients === 'boolean') || outputTransients === null) && reflectUpToClass === undefined) {
return org.openprovenance.apache.commons.lang.builder.ToStringBuilder.reflectionToString$java_lang_Object$org_openprovenance_apache_commons_lang_builder_ToStringStyle$boolean(object, style, outputTransients);
}
else if (((object != null) || object === null) && ((style != null && style instanceof org.openprovenance.apache.commons.lang.builder.ToStringStyle) || style === null) && outputTransients === undefined && reflectUpToClass === undefined) {
return org.openprovenance.apache.commons.lang.builder.ToStringBuilder.reflectionToString$java_lang_Object$org_openprovenance_apache_commons_lang_builder_ToStringStyle(object, style);
}
else if (((object != null) || object === null) && style === undefined && outputTransients === undefined && reflectUpToClass === undefined) {
return org.openprovenance.apache.commons.lang.builder.ToStringBuilder.reflectionToString$java_lang_Object(object);
}
else
throw new Error('invalid overload');
}
append$boolean(value) {
this.style.append$java_lang_StringBuffer$java_lang_String$boolean(this.buffer, null, value);
return this;
}
append$boolean_A(array) {
this.style.append$java_lang_StringBuffer$java_lang_String$boolean_A$java_lang_Boolean(this.buffer, null, array, null);
return this;
}
append$byte(value) {
this.style.append$java_lang_StringBuffer$java_lang_String$byte(this.buffer, null, value);
return this;
}
append$byte_A(array) {
this.style.append$java_lang_StringBuffer$java_lang_String$byte_A$java_lang_Boolean(this.buffer, null, array, null);
return this;
}
append$char(value) {
this.style.append$java_lang_StringBuffer$java_lang_String$char(this.buffer, null, value);
return this;
}
append$char_A(array) {
this.style.append$java_lang_StringBuffer$java_lang_String$char_A$java_lang_Boolean(this.buffer, null, array, null);
return this;
}
append$double(value) {
this.style.append$java_lang_StringBuffer$java_lang_String$double(this.buffer, null, value);
return this;
}
append$double_A(array) {
this.style.append$java_lang_StringBuffer$java_lang_String$double_A$java_lang_Boolean(this.buffer, null, array, null);
return this;
}
append$float(value) {
this.style.append$java_lang_StringBuffer$java_lang_String$float(this.buffer, null, value);
return this;
}
append$float_A(array) {
this.style.append$java_lang_StringBuffer$java_lang_String$float_A$java_lang_Boolean(this.buffer, null, array, null);
return this;
}
append$int(value) {
this.style.append$java_lang_StringBuffer$java_lang_String$int(this.buffer, null, value);
return this;
}
append$int_A(array) {
this.style.append$java_lang_StringBuffer$java_lang_String$int_A$java_lang_Boolean(this.buffer, null, array, null);
return this;
}
append$long(value) {
this.style.append$java_lang_StringBuffer$java_lang_String$long(this.buffer, null, value);
return this;
}
append$long_A(array) {
this.style.append$java_lang_StringBuffer$java_lang_String$long_A$java_lang_Boolean(this.buffer, null, array, null);
return this;
}
append$java_lang_Object(obj) {
this.style.append$java_lang_StringBuffer$java_lang_String$java_lang_Object$java_lang_Boolean(this.buffer, null, obj, null);
return this;
}
append$java_lang_Object_A(array) {
this.style.append$java_lang_StringBuffer$java_lang_String$java_lang_Object_A$java_lang_Boolean(this.buffer, null, array, null);
return this;
}
append$short(value) {
this.style.append$java_lang_StringBuffer$java_lang_String$short(this.buffer, null, value);
return this;
}
append$short_A(array) {
this.style.append$java_lang_StringBuffer$java_lang_String$short_A$java_lang_Boolean(this.buffer, null, array, null);
return this;
}
append$java_lang_String$boolean(fieldName, value) {
this.style.append$java_lang_StringBuffer$java_lang_String$boolean(this.buffer, fieldName, value);
return this;
}
append$java_lang_String$boolean_A(fieldName, array) {
this.style.append$java_lang_StringBuffer$java_lang_String$boolean_A$java_lang_Boolean(this.buffer, fieldName, array, null);
return this;
}
append$java_lang_String$boolean_A$boolean(fieldName, array, fullDetail) {
this.style.append$java_lang_StringBuffer$java_lang_String$boolean_A$java_lang_Boolean(this.buffer, fieldName, array, org.openprovenance.apache.commons.lang.BooleanUtils.toBooleanObject$boolean(fullDetail));
return this;
}
/**
* <p>Append to the <code>toString</code> a <code>boolean</code>
* array.</p>
*
* <p>A boolean parameter controls the level of detail to show.
* Setting <code>true</code> will output the array in full. Setting
* <code>false</code> will output a summary, typically the size of
* the array.</p>
*
* @param {string} fieldName the field name
* @param {boolean[]} array the array to add to the <code>toString</code>
* @param {boolean} fullDetail <code>true</code> for detail, <code>false</code>
* for summary info
* @return {org.openprovenance.apache.commons.lang.builder.ToStringBuilder} this
*/
append(fieldName, array, fullDetail) {
if (((typeof fieldName === 'string') || fieldName === null) && ((array != null && array instanceof Array && (array.length == 0 || array[0] == null || (typeof array[0] === 'boolean'))) || array === null) && ((typeof fullDetail === 'boolean') || fullDetail === null)) {
return this.append$java_lang_String$boolean_A$boolean(fieldName, array, fullDetail);
}
else if (((typeof fieldName === 'string') || fieldName === null) && ((array != null && array instanceof Array && (array.length == 0 || array[0] == null || (typeof array[0] === 'number'))) || array === null) && ((typeof fullDetail === 'boolean') || fullDetail === null)) {
return this.append$java_lang_String$byte_A$boolean(fieldName, array, fullDetail);
}
else if (((typeof fieldName === 'string') || fieldName === null) && ((array != null && array instanceof Array && (array.length == 0 || array[0] == null || (typeof array[0] === 'string'))) || array === null) && ((typeof fullDetail === 'boolean') || fullDetail === null)) {
return this.append$java_lang_String$char_A$boolean(fieldName, array, fullDetail);
}
else if (((typeof fieldName === 'string') || fieldName === null) && ((array != null && array instanceof Array && (array.length == 0 || array[0] == null || (typeof array[0] === 'number'))) || array === null) && ((typeof fullDetail === 'boolean') || fullDetail === null)) {
return this.append$java_lang_String$double_A$boolean(fieldName, array, fullDetail);
}
else if (((typeof fieldName === 'string') || fieldName === null) && ((array != null && array instanceof Array && (array.length == 0 || array[0] == null || (typeof array[0] === 'number'))) || array === null) && ((typeof fullDetail === 'boolean') || fullDetail === null)) {
return this.append$java_lang_String$float_A$boolean(fieldName, array, fullDetail);
}
else if (((typeof fieldName === 'string') || fieldName === null) && ((array != null && array instanceof Array && (array.length == 0 || array[0] == null || (typeof array[0] === 'number'))) || array === null) && ((typeof fullDetail === 'boolean') || fullDetail === null)) {
return this.append$java_lang_String$int_A$boolean(fieldName, array, fullDetail);
}
else if (((typeof fieldName === 'string') || fieldName === null) && ((array != null && array instanceof Array && (array.length == 0 || array[0] == null || (typeof array[0] === 'number'))) || array === null) && ((typeof fullDetail === 'boolean') || fullDetail === null)) {
return this.append$java_lang_String$long_A$boolean(fieldName, array, fullDetail);
}
else if (((typeof fieldName === 'string') || fieldName === null) && ((array != null && array instanceof Array && (array.length == 0 || array[0] == null || (array[0] != null))) || array === null) && ((typeof fullDetail === 'boolean') || fullDetail === null)) {
return this.append$java_lang_String$java_lang_Object_A$boolean(fieldName, array, fullDetail);
}
else if (((typeof fieldName === 'string') || fieldName === null) && ((array != null && array instanceof Array && (array.length == 0 || array[0] == null || (typeof array[0] === 'number'))) || array === null) && ((typeof fullDetail === 'boolean') || fullDetail === null)) {
return this.append$java_lang_String$short_A$boolean(fieldName, array, fullDetail);
}
else if (((typeof fieldName === 'string') || fieldName === null) && ((array != null) || array === null) && ((typeof fullDetail === 'boolean') || fullDetail === null)) {
return this.append$java_lang_String$java_lang_Object$boolean(fieldName, array, fullDetail);
}
else if (((typeof fieldName === 'string') || fieldName === null) && ((array != null && array instanceof Array && (array.length == 0 || array[0] == null || (typeof array[0] === 'boolean'))) || array === null) && fullDetail === undefined) {
return this.append$java_lang_String$boolean_A(fieldName, array);
}
else if (((typeof fieldName === 'string') || fieldName === null) && ((array != null && array instanceof Array && (array.length == 0 || array[0] == null || (typeof array[0] === 'number'))) || array === null) && fullDetail === undefined) {
return this.append$java_lang_String$byte_A(fieldName, array);
}
else if (((typeof fieldName === 'string') || fieldName === null) && ((array != null && array instanceof Array && (array.length == 0 || array[0] == null || (typeof array[0] === 'string'))) || array === null) && fullDetail === undefined) {
return this.append$java_lang_String$char_A(fieldName, array);
}
else if (((typeof fieldName === 'string') || fieldName === null) && ((array != null && array instanceof Array && (array.length == 0 || array[0] == null || (typeof array[0] === 'number'))) || array === null) && fullDetail === undefined) {
return this.append$java_lang_String$double_A(fieldName, array);
}
else if (((typeof fieldName === 'string') || fieldName === null) && ((array != null && array instanceof Array && (array.length == 0 || array[0] == null || (typeof array[0] === 'number'))) || array === null) && fullDetail === undefined) {
return this.append$java_lang_String$float_A(fieldName, array);
}
else if (((typeof fieldName === 'string') || fieldName === null) && ((array != null && array instanceof Array && (array.length == 0 || array[0] == null || (typeof array[0] === 'number'))) || array === null) && fullDetail === undefined) {
return this.append$java_lang_String$int_A(fieldName, array);
}
else if (((typeof fieldName === 'string') || fieldName === null) && ((array != null && array instanceof Array && (array.length == 0 || array[0] == null || (typeof array[0] === 'number'))) || array === null) && fullDetail === undefined) {
return this.append$java_lang_String$long_A(fieldName, array);
}
else if (((typeof fieldName === 'string') || fieldName === null) && ((array != null && array instanceof Array && (array.length == 0 || array[0] == null || (array[0] != null))) || array === null) && fullDetail === undefined) {
return this.append$java_lang_String$java_lang_Object_A(fieldName, array);
}
else if (((typeof fieldName === 'string') || fieldName === null) && ((array != null && array instanceof Array && (array.length == 0 || array[0] == null || (typeof array[0] === 'number'))) || array === null) && fullDetail === undefined) {
return this.append$java_lang_String$short_A(fieldName, array);
}
else if (((typeof fieldName === 'string') || fieldName === null) && ((typeof array === 'boolean') || array === null) && fullDetail === undefined) {
return this.append$java_lang_String$boolean(fieldName, array);
}
else if (((typeof fieldName === 'string') || fieldName === null) && ((typeof array === 'number') || array === null) && fullDetail === undefined) {
return this.append$java_lang_String$byte(fieldName, array);
}
else if (((typeof fieldName === 'string') || fieldName === null) && ((typeof array === 'string') || array === null) && fullDetail === undefined) {
return this.append$java_lang_String$char(fieldName, array);
}
else if (((typeof fieldName === 'string') || fieldName === null) && ((typeof array === 'number') || array === null) && fullDetail === undefined) {
return this.append$java_lang_String$short(fieldName, array);
}
else if (((typeof fieldName === 'string') || fieldName === null) && ((typeof array === 'number') || array === null) && fullDetail === undefined) {
return this.append$java_lang_String$int(fieldName, array);
}
else if (((typeof fieldName === 'string') || fieldName === null) && ((typeof array === 'number') || array === null) && fullDetail === undefined) {
return this.append$java_lang_String$long(fieldName, array);
}
else if (((typeof fieldName === 'string') || fieldName === null) && ((typeof array === 'number') || array === null) && fullDetail === undefined) {
return this.append$java_lang_String$float(fieldName, array);
}
else if (((typeof fieldName === 'string') || fieldName === null) && ((typeof array === 'number') || array === null) && fullDetail === undefined) {
return this.append$java_lang_String$double(fieldName, array);
}
else if (((typeof fieldName === 'string') || fieldName === null) && ((array != null) || array === null) && fullDetail === undefined) {
return this.append$java_lang_String$java_lang_Object(fieldName, array);
}
else if (((fieldName != null && fieldName instanceof Array && (fieldName.length == 0 || fieldName[0] == null || (typeof fieldName[0] === 'boolean'))) || fieldName === null) && array === undefined && fullDetail === undefined) {
return this.append$boolean_A(fieldName);
}
else if (((fieldName != null && fieldName instanceof Array && (fieldName.length == 0 || fieldName[0] == null || (typeof fieldName[0] === 'number'))) || fieldName === null) && array === undefined && fullDetail === undefined) {
return this.append$byte_A(fieldName);
}
else if (((fieldName != null && fieldName instanceof Array && (fieldName.length == 0 || fieldName[0] == null || (typeof fieldName[0] === 'string'))) || fieldName === null) && array === undefined && fullDetail === undefined) {
return this.append$char_A(fieldName);
}
else if (((fieldName != null && fieldName instanceof Array && (fieldName.length == 0 || fieldName[0] == null || (typeof fieldName[0] === 'number'))) || fieldName === null) && array === undefined && fullDetail === undefined) {
return this.append$double_A(fieldName);
}
else if (((fieldName != null && fieldName instanceof Array && (fieldName.length == 0 || fieldName[0] == null || (typeof fieldName[0] === 'number'))) || fieldName === null) && array === undefined && fullDetail === undefined) {
return this.append$float_A(fieldName);
}
else if (((fieldName != null && fieldName instanceof Array && (fieldName.length == 0 || fieldName[0] == null || (typeof fieldName[0] === 'number'))) || fieldName === null) && array === undefined && fullDetail === undefined) {
return this.append$int_A(fieldName);
}
else if (((fieldName != null && fieldName instanceof Array && (fieldName.length == 0 || fieldName[0] == null || (typeof fieldName[0] === 'number'))) || fieldName === null) && array === undefined && fullDetail === undefined) {
return this.append$long_A(fieldName);
}
else if (((fieldName != null && fieldName instanceof Array && (fieldName.length == 0 || fieldName[0] == null || (fieldName[0] != null))) || fieldName === null) && array === undefined && fullDetail === undefined) {
return this.append$java_lang_Object_A(fieldName);
}
else if (((fieldName != null && fieldName instanceof Array && (fieldName.length == 0 || fieldName[0] == null || (typeof fieldName[0] === 'number'))) || fieldName === null) && array === undefined && fullDetail === undefined) {
return this.append$short_A(fieldName);
}
else if (((typeof fieldName === 'boolean') || fieldName === null) && array === undefined && fullDetail === undefined) {
return this.append$boolean(fieldName);
}
else if (((typeof fieldName === 'number') || fieldName === null) && array === undefined && fullDetail === undefined) {
return this.append$byte(fieldName);
}
else if (((typeof fieldName === 'string') || fieldName === null) && array === undefined && fullDetail === undefined) {
return this.append$char(fieldName);
}
else if (((typeof fieldName === 'number') || fieldName === null) && array === undefined && fullDetail === undefined) {
return this.append$short(fieldName);
}
else if (((typeof fieldName === 'number') || fieldName === null) && array === undefined && fullDetail === undefined) {
return this.append$int(fieldName);
}
else if (((typeof fieldName === 'number') || fieldName === null) && array === undefined && fullDetail === undefined) {
return this.append$long(fieldName);
}
else if (((typeof fieldName === 'number') || fieldName === null) && array === undefined && fullDetail === undefined) {
return this.append$float(fieldName);
}
else if (((typeof fieldName === 'number') || fieldName === null) && array === undefined && fullDetail === undefined) {
return this.append$double(fieldName);
}
else if (((fieldName != null) || fieldName === null) && array === undefined && fullDetail === undefined) {
return this.append$java_lang_Object(fieldName);
}
else
throw new Error('invalid overload');
}
append$java_lang_String$byte(fieldName, value) {
this.style.append$java_lang_StringBuffer$java_lang_String$byte(this.buffer, fieldName, value);
return this;
}
append$java_lang_String$byte_A(fieldName, array) {
this.style.append$java_lang_StringBuffer$java_lang_String$byte_A$java_lang_Boolean(this.buffer, fieldName, array, null);
return this;
}
append$java_lang_String$byte_A$boolean(fieldName, array, fullDetail) {
this.style.append$java_lang_StringBuffer$java_lang_String$byte_A$java_lang_Boolean(this.buffer, fieldName, array, org.openprovenance.apache.commons.lang.BooleanUtils.toBooleanObject$boolean(fullDetail));
return this;
}
append$java_lang_String$char(fieldName, value) {
this.style.append$java_lang_StringBuffer$java_lang_String$char(this.buffer, fieldName, value);
return this;
}
append$java_lang_String$char_A(fieldName, array) {
this.style.append$java_lang_StringBuffer$java_lang_String$char_A$java_lang_Boolean(this.buffer, fieldName, array, null);
return this;
}
append$java_lang_String$char_A$boolean(fieldName, array, fullDetail) {
this.style.append$java_lang_StringBuffer$java_lang_String$char_A$java_lang_Boolean(this.buffer, fieldName, array, org.openprovenance.apache.commons.lang.BooleanUtils.toBooleanObject$boolean(fullDetail));
return this;
}
append$java_lang_String$double(fieldName, value) {
this.style.append$java_lang_StringBuffer$java_lang_String$double(this.buffer, fieldName, value);
return this;
}
append$java_lang_String$double_A(fieldName, array) {
this.style.append$java_lang_StringBuffer$java_lang_String$double_A$java_lang_Boolean(this.buffer, fieldName, array, null);
return this;
}
append$java_lang_String$double_A$boolean(fieldName, array, fullDetail) {
this.style.append$java_lang_StringBuffer$java_lang_String$double_A$java_lang_Boolean(this.buffer, fieldName, array, org.openprovenance.apache.commons.lang.BooleanUtils.toBooleanObject$boolean(fullDetail));
return this;
}
append$java_lang_String$float(fieldName, value) {
this.style.append$java_lang_StringBuffer$java_lang_String$float(this.buffer, fieldName, value);
return this;
}
append$java_lang_String$float_A(fieldName, array) {
this.style.append$java_lang_StringBuffer$java_lang_String$float_A$java_lang_Boolean(this.buffer, fieldName, array, null);
return this;
}
append$java_lang_String$float_A$boolean(fieldName, array, fullDetail) {
this.style.append$java_lang_StringBuffer$java_lang_String$float_A$java_lang_Boolean(this.buffer, fieldName, array, org.openprovenance.apache.commons.lang.BooleanUtils.toBooleanObject$boolean(fullDetail));
return this;
}
append$java_lang_String$int(fieldName, value) {
this.style.append$java_lang_StringBuffer$java_lang_String$int(this.buffer, fieldName, value);
return this;
}
append$java_lang_String$int_A(fieldName, array) {
this.style.append$java_lang_StringBuffer$java_lang_String$int_A$java_lang_Boolean(this.buffer, fieldName, array, null);
return this;
}
append$java_lang_String$int_A$boolean(fieldName, array, fullDetail) {
this.style.append$java_lang_StringBuffer$java_lang_String$int_A$java_lang_Boolean(this.buffer, fieldName, array, org.openprovenance.apache.commons.lang.BooleanUtils.toBooleanObject$boolean(fullDetail));
return this;
}
append$java_lang_String$long(fieldName, value) {
this.style.append$java_lang_StringBuffer$java_lang_String$long(this.buffer, fieldName, value);
return this;
}
append$java_lang_String$long_A(fieldName, array) {
this.style.append$java_lang_StringBuffer$java_lang_String$long_A$java_lang_Boolean(this.buffer, fieldName, array, null);
return this;
}
append$java_lang_String$long_A$boolean(fieldName, array, fullDetail) {
this.style.append$java_lang_StringBuffer$java_lang_String$long_A$java_lang_Boolean(this.buffer, fieldName, array, org.openprovenance.apache.commons.lang.BooleanUtils.toBooleanObject$boolean(fullDetail));
return this;
}
append$java_lang_String$java_lang_Object(fieldName, obj) {
this.style.append$java_lang_StringBuffer$java_lang_String$java_lang_Object$java_lang_Boolean(this.buffer, fieldName, obj, null);
return this;
}
append$java_lang_String$java_lang_Object$boolean(fieldName, obj, fullDetail) {
this.style.append$java_lang_StringBuffer$java_lang_String$java_lang_Object$java_lang_Boolean(this.buffer, fieldName, obj, org.openprovenance.apache.commons.lang.BooleanUtils.toBooleanObject$boolean(fullDetail));
return this;
}
append$java_lang_String$java_lang_Object_A(fieldName, array) {
this.style.append$java_lang_StringBuffer$java_lang_String$java_lang_Object_A$java_lang_Boolean(this.buffer, fieldName, array, null);
return this;
}
append$java_lang_String$java_lang_Object_A$boolean(fieldName, array, fullDetail) {
this.style.append$java_lang_StringBuffer$java_lang_String$java_lang_Object_A$java_lang_Boolean(this.buffer, fieldName, array, org.openprovenance.apache.commons.lang.BooleanUtils.toBooleanObject$boolean(fullDetail));
return this;
}
append$java_lang_String$short(fieldName, value) {
this.style.append$java_lang_StringBuffer$java_lang_String$short(this.buffer, fieldName, value);
return this;
}
append$java_lang_String$short_A(fieldName, array) {
this.style.append$java_lang_StringBuffer$java_lang_String$short_A$java_lang_Boolean(this.buffer, fieldName, array, null);
return this;
}
append$java_lang_String$short_A$boolean(fieldName, array, fullDetail) {
this.style.append$java_lang_StringBuffer$java_lang_String$short_A$java_lang_Boolean(this.buffer, fieldName, array, org.openprovenance.apache.commons.lang.BooleanUtils.toBooleanObject$boolean(fullDetail));
return this;
}
/**
* <p>Appends with the same format as the default <code>Object toString()
* </code> method. Appends the class name followed by
* {@link System#identityHashCode(Object)}.</p>
*
* @param {*} object the <code>Object</code> whose class name and id to output
* @return {org.openprovenance.apache.commons.lang.builder.ToStringBuilder} this
* @since 2.0
*/
appendAsObjectToString(object) {
org.openprovenance.apache.commons.lang.ObjectUtils.identityToString$java_lang_StringBuffer$java_lang_Object(this.getStringBuffer(), object);
return this;
}
/**
* <p>Append the <code>toString</code> from the superclass.</p>
*
* <p>This method assumes that the superclass uses the same <code>ToStringStyle</code>
* as this one.</p>
*
* <p>If <code>superToString</code> is <code>null</code>, no change is made.</p>
*
* @param {string} superToString the result of <code>super.toString()</code>
* @return {org.openprovenance.apache.commons.lang.builder.ToStringBuilder} this
* @since 2.0
*/
appendSuper(superToString) {
if (superToString != null) {
this.style.appendSuper(this.buffer, superToString);
}
return this;
}
/**
* <p>Append the <code>toString</code> from another object.</p>
*
* <p>This method is useful where a class delegates most of the implementation of
* its properties to another class. You can then call <code>toString()</code> on
* the other class and pass the result into this method.</p>
*
* <pre>
* private AnotherObject delegate;
* private String fieldInThisClass;
*
* public String toString() {
* return new ToStringBuilder(this).
* appendToString(delegate.toString()).
* append(fieldInThisClass).
* toString();
* }</pre>
*
* <p>This method assumes that the other object uses the same <code>ToStringStyle</code>
* as this one.</p>
*
* <p>If the <code>toString</code> is <code>null</code>, no change is made.</p>
*
* @param {string} toString the result of <code>toString()</code> on another object
* @return {org.openprovenance.apache.commons.lang.builder.ToStringBuilder} this
* @since 2.0
*/
appendToString(toString) {
if (toString != null) {
this.style.appendToString(this.buffer, toString);
}
return this;
}
/**
* <p>Returns the <code>Object</code> being output.</p>
*
* @return {*} The object being output.
* @since 2.0
*/
getObject() {
return this.object;
}
/**
* <p>Gets the <code>StringBuffer</code> being populated.</p>
*
* @return {{ str: string, toString: Function }} the <code>StringBuffer</code> being populated
*/
getStringBuffer() {
return this.buffer;
}
/**
* <p>Gets the <code>ToStringStyle</code> being used.</p>
*
* @return {org.openprovenance.apache.commons.lang.builder.ToStringStyle} the <code>ToStringStyle</code> being used
* @since 2.0
*/
getStyle() {
return this.style;
}
/**
* <p>Returns the built <code>toString</code>.</p>
*
* <p>This method appends the end of data indicator, and can only be called once.
* Use {@link #getStringBuffer} to get the current string state.</p>
*
* <p>If the object is <code>null</code>, return the style's <code>nullText</code></p>
*
* @return {string} the String <code>toString</code>
*/
toString() {
if (this.getObject() == null) {
/* append */ (sb => { sb.str += this.getStyle().getNullText(); return sb; })(this.getStringBuffer());
}
else {
this.style.appendEnd(this.getStringBuffer(), this.getObject());
}
return /* toString */ this.getStringBuffer().str;
}
} |
JavaScript | class RestMetaCollection {
/**
* Constructs a new <code>RestMetaCollection</code>.
* @alias module:model/RestMetaCollection
* @class
*/
constructor() {
}
/**
* Constructs a <code>RestMetaCollection</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/RestMetaCollection} obj Optional instance to populate.
* @return {module:model/RestMetaCollection} The populated <code>RestMetaCollection</code> instance.
*/
static constructFromObject(data, obj) {
if (data) {
obj = obj || new RestMetaCollection();
if (data.hasOwnProperty('NodePath')) {
obj['NodePath'] = ApiClient.convertToType(data['NodePath'], 'String');
}
if (data.hasOwnProperty('Metadatas')) {
obj['Metadatas'] = ApiClient.convertToType(data['Metadatas'], [RestMetadata]);
}
}
return obj;
}
/**
* @member {String} NodePath
*/
NodePath = undefined;
/**
* @member {Array.<module:model/RestMetadata>} Metadatas
*/
Metadatas = undefined;
} |
JavaScript | class RootReference {
constructor(env) {
this.env = env;
this.children = dict();
this.tag = CONSTANT_TAG;
}
get(key) {
// References should in general be identical to one another, so we can usually
// deduplicate them in production. However, in DEBUG we need unique references
// so we can properly key off them for the logging context.
if (DEBUG) {
// We register the template debug context now since the reference is
// created before the component itself. It shouldn't be possible to cause
// errors when accessing the root, only subproperties of the root, so this
// should be fine for the time being. The exception is helpers, but they
// set their context earlier.
//
// TODO: This points to a need for more first class support for arguments in
// the debugRenderTree. The fact that we can't accurately relate an argument
// reference to its component is problematic for debug tooling.
if (!this.didSetupDebugContext) {
this.didSetupDebugContext = true;
this.env.setTemplatePathDebugContext(this, this.debugLogName || 'this', null);
}
return new PropertyReference(this, key, this.env);
} else {
let ref = this.children[key];
if (ref === undefined) {
ref = this.children[key] = new PropertyReference(this, key, this.env);
}
return ref;
}
}
} |
JavaScript | class PropertyReference {
constructor(parentReference, propertyKey, env) {
this.parentReference = parentReference;
this.propertyKey = propertyKey;
this.env = env;
this.children = dict();
this.lastRevision = null;
if (DEBUG) {
env.setTemplatePathDebugContext(this, propertyKey, parentReference);
}
let valueTag = this.valueTag = createUpdatableTag();
let parentReferenceTag = parentReference.tag;
this.tag = combine([parentReferenceTag, valueTag]);
}
value() {
let {
tag,
lastRevision,
lastValue,
parentReference,
valueTag,
propertyKey
} = this;
if (lastRevision === null || !validateTag(tag, lastRevision)) {
let parentValue = parentReference.value();
if (isDict(parentValue)) {
let combined = track(() => {
lastValue = this.env.getPath(parentValue, propertyKey);
}, DEBUG && this.env.getTemplatePathDebugContext(this));
updateTag(valueTag, combined);
} else {
lastValue = undefined;
}
this.lastValue = lastValue;
this.lastRevision = valueForTag(tag);
}
return lastValue;
}
get(key) {
// References should in general be identical to one another, so we can usually
// deduplicate them in production. However, in DEBUG we need unique references
// so we can properly key off them for the logging context.
if (DEBUG) {
return new PropertyReference(this, key, this.env);
} else {
let ref = this.children[key];
if (ref === undefined) {
ref = this.children[key] = new PropertyReference(this, key, this.env);
}
return ref;
}
}
[UPDATE_REFERENCED_VALUE](value) {
let {
parentReference,
propertyKey
} = this;
let parentValue = parentReference.value();
this.env.setPath(parentValue, propertyKey, value);
}
} ////////// |
JavaScript | class IterationItemReference {
constructor(parentReference, itemValue, itemKey, env) {
this.parentReference = parentReference;
this.itemValue = itemValue;
this.env = env;
this.tag = createUpdatableTag();
this.children = dict();
if (DEBUG) {
env.setTemplatePathDebugContext(this, debugToString(itemKey), parentReference);
}
}
value() {
return this.itemValue;
}
update(value) {
dirtyTag(this.tag);
this.itemValue = value;
}
get(key) {
// References should in general be identical to one another, so we can usually
// deduplicate them in production. However, in DEBUG we need unique references
// so we can properly key off them for the logging context.
if (DEBUG) {
return new PropertyReference(this, key, this.env);
} else {
let ref = this.children[key];
if (ref === undefined) {
ref = this.children[key] = new PropertyReference(this, key, this.env);
}
return ref;
}
}
} |
JavaScript | class Recurring {
/**
* Init
* @param {UnzerSimple} unzer Unzer main class
*/
constructor(unzer) {
this._urlpath = '/types';
this._unzer = unzer;
}
/**
* GET recurring state
*
* @link https://docs.unzer.com/reference/api/#get-/v1/types/{methodid}/recurring
* @param {string} methodId Id of Payment method
* @return {Promise<Object>} Unzer response
*/
async get(methodId) {
let url = this._urlpath + '/' + methodId + '/recurring';
return this._unzer.get(url);
}
/**
* Set reccuring state for given UUID
* @link https://docs.unzer.com/reference/api/#post-/v1/types/recurring
* @param {string} uuid UUID of payment method
* @return {Promise<Object>}
*/
async postUuid(uuid) {
let url = this._urlpath + '/recurring';
return this._unzer.post(url, {uuid: uuid});
}
/**
* Set recurring state for given method id
* @link https://docs.unzer.com/reference/api/#post-/v1/types/{methodid}/recurring
* @param {string} methodId payment method id
* @param {object} payload post body payload
* @return {Promise<Object>}
*/
async postMethodId(methodId, payload) {
let url = this._urlpath + '/' + methodId + '/recurring';
return this._unzer.post(url, payload, {}, true);
}
} |
JavaScript | class Grid3D extends Grid {
/** Constructor of the Grid3D object.
* @param {GridSize} extents - the size of the grid in each dimension
* @param {boolean[]} [torus = [true,true,true]] - should the borders of
* the grid be linked, so that a cell moving out on the left reappears on
* the right? */
constructor( extents, torus = [true,true,true] ){
super( extents, torus )
// Check that the grid size is not too big to store pixel ID in 32-bit number,
// and allow fast conversion of coordinates to unique ID numbers.
/** @ignore */
this.Z_BITS = 1+Math.floor( Math.log2( this.extents[2] - 1 ) )
if( this.X_BITS + this.Y_BITS + this.Z_BITS > 32 ){
throw("Field size too large -- field cannot be represented as 32-bit number")
}
/** @ignore */
this.Z_MASK = (1 << this.Z_BITS)-1
/** @ignore */
this.Z_STEP = 1
/** @ignore */
this.Y_STEP = 1 << (this.Z_BITS)
/** @ignore */
this.X_STEP = 1 << (this.Z_BITS +this.Y_BITS)
/** Array with values for each pixel stored at the position of its
* {@link IndexCoordinate}. E.g. the value of pixel with coordinate i
* is stored as this._pixelArray[i].
* Note that this array is accessed indirectly via the
* {@link _pixels} set- and get methods.
* @private
* @type {Uint16Array} */
this._pixelArray = new Uint16Array(this.p2i(extents))
this.datatype = "Uint16"
}
/** Method for conversion from an {@link ArrayCoordinate} to an
* {@link IndexCoordinate}.
*
* See also {@link Grid3D#i2p} for the backward conversion.
*
* @param {ArrayCoordinate} p - the coordinate of the pixel to convert
* @return {IndexCoordinate} the converted coordinate.
*
* @example
* let grid = new CPM.Grid3D( [100,100,100], [true,true,true] )
* let p = grid.i2p( 5 )
* console.log( p )
* console.log( grid.p2i( p ))
*/
p2i( p ){
return ( p[0] << ( this.Z_BITS + this.Y_BITS ) ) +
( p[1] << this.Z_BITS ) +
p[2]
}
/** Method for conversion from an {@link IndexCoordinate} to an
* {@link ArrayCoordinate}.
*
* See also {@link Grid3D#p2i} for the backward conversion.
*
* @param {IndexCoordinate} i - the coordinate of the pixel to convert
* @return {ArrayCoordinate} the converted coordinate.
*
* @example
* let grid = new CPM.Grid3D( [100,100,100], [true,true,true] )
* let p = grid.i2p( 5 )
* console.log( p )
* console.log( grid.p2i( p ))
*/
i2p( i ){
return [i >> (this.Y_BITS + this.Z_BITS),
( i >> this.Z_BITS ) & this.Y_MASK, i & this.Z_MASK ]
}
/** This iterator returns locations and values of all non-zero pixels.
* Whereas the {@link pixels} generator yields only non-background pixels
* and specifies both their {@link ArrayCoordinate} and value, this
* generator yields all pixels by {@link IndexCoordinate} and does not
* report value.
*
* @return {IndexCoordinate} for each pixel, return its
* {@link IndexCoordinate}.
*
*
* @example
* let CPM = require( "path/to/build" )
* // make a grid and set some values
* let grid = new CPM.Grid3D( [100,100,100], [true,true,true] )
* grid.setpixi( 0, 1 )
* grid.setpixi( 1, 5 )
*
* // iterator
* for( let i of grid.pixelsi() ){
* console.log( i )
* }
*/
* pixelsi() {
let ii = 0, c = 0
for( let i = 0 ; i < this.extents[0] ; i ++ ){
let d = 0
for( let j = 0 ; j < this.extents[1] ; j ++ ){
for( let k = 0 ; k < this.extents[2] ; k ++ ){
yield ii
ii++
}
d += this.Y_STEP
ii = c + d
}
c += this.X_STEP
ii = c
}
}
/** This iterator returns locations and values of all non-zero pixels.
* @return {Pixel} for each pixel, return an array [p,v] where p are
* the pixel's array coordinates on the grid, and v its value.
*
* @example
* let CPM = require( "path/to/build" )
* // make a grid and set some values
* let grid = new CPM.Grid3D( [100,100,100], [true,true,true] )
* grid.setpix( [0,0,0], 1 )
* grid.setpix( [0,0,1], 5 )
*
* // iterator
* for( let p of grid.pixels() ){
* console.log( p )
* }
*/
* pixels() {
let ii = 0, c = 0
for( let i = 0 ; i < this.extents[0] ; i ++ ){
let d = 0
for( let j = 0 ; j < this.extents[1] ; j ++ ){
for( let k = 0 ; k < this.extents[2] ; k ++ ){
//noinspection JSUnresolvedVariable
let pixels = this._pixels
if( pixels[ii] > 0 ){
yield [[i,j,k], pixels[ii]]
}
ii++
}
d += this.Y_STEP
ii = c + d
}
c += this.X_STEP
ii = c
}
}
/** Return array of {@link IndexCoordinate} of the Moore neighbor pixels
* of the pixel at coordinate i. This function takes the 3D equivalent of
* the 2D Moore-8 neighborhood, excluding the pixel itself.
* @see https://en.wikipedia.org/wiki/Moore_neighborhood
* @param {IndexCoordinate} i - location of the pixel to get neighbors of.
* @param {boolean[]} [torus=[true,true,true]] - does the grid have linked
* borders? Defaults to the setting on this grid, see {@link torus}
* @return {IndexCoordinate[]} - an array of coordinates for all the
* neighbors of i.
*/
neighi( i, torus = this.torus ){
let p = this.i2p(i)
let xx = []
for( let d = 0 ; d <= 2 ; d ++ ){
if( p[d] === 0 ){
if( torus[d] ){
xx[d] = [p[d],this.extents[d]-1,p[d]+1]
} else {
xx[d] = [p[d],p[d]+1]
}
} else if( p[d] === this.extents[d]-1 ){
if( torus[d] ){
xx[d] = [p[d],p[d]-1,0]
} else {
xx[d] = [p[d],p[d]-1]
}
} else {
xx[d] = [p[d],p[d]-1,p[d]+1]
}
}
let r = [], first=true
for( let x of xx[0] ){
for( let y of xx[1] ){
for( let z of xx[2] ){
if( first ){
first = false
} else {
r.push( this.p2i( [x,y,z] ) )
}
}
}
}
return r
}
} |
JavaScript | class Event {
/**
* Initializes a new Event
*
* @param {Object} config Event configuration object
* @param {String} config.name Event name
* @param {String} [config.discordEventName = ''] Name of discord.js event that triggers this Event
* @param {Function} config.handler Event function
* @param {String} [config.type = 'discord'] Event type
* @param {String} [config.description = ''] Event description
* @param {String} [config.context = 'global'] Event context
* @param {String} [config.interval = '1d'] Event interval
* @param {Function} [config.enable = () => {}] function that runs before enabling the Event for a context
* @param {Function} [config.disable = () => {}] function that runs before disabling the Event for a context
* @param {String} sourcePath full path of Event source file
* @constructor
*/
constructor ({ name, discordEventName = '', handler, type = 'discord', description = '', context = 'global', interval = '1d', enable = () => {}, disable = () => {} }, sourcePath) {
this.name = name
this.discordEventName = (discordEventName.length > 0 ? discordEventName : name)
this.handler = handler
this.type = type
this.description = description
this.context = context
this.interval = interval
this.enable = enable
this.disable = disable
this.sourcePath = sourcePath
}
} |
JavaScript | class CreatePodForm extends Component {
initialState = {
name: "",
description: "",
};
constructor(props) {
super(props);
this.state = this.initialState;
// any method using this keyword must bind
// example: this.method = this.method.bind(this)
}
componentDidMount() {
// Things to do when the component is first rendered into the dom
}
componentWillUnmount() {
// Things to do when the component is removed
}
handleChange = (event) => {
const { name, value } = event.target;
this.setState({
[name]: value,
});
};
submitForm = () => {
this.props.handleSubmit(this.state);
this.setState(this.initialState);
};
render() {
return (
<div className="CreatePodForm">
<h3>Name: {this.state.name}</h3>
<h3>Description: {this.state.description}</h3>
<form className="form my-4">
<div class="form-group">
<label for="name">Project Name:</label>
<input
type="text"
class="form-control"
placeholder="Enter Project Name"
name="name"
value={this.state.name}
onChange={this.handleChange}
required
/>
<div class="valid-feedback">Valid.</div>
<div class="invalid-feedback">Please fill out this field.</div>
</div>
<div class="form-group">
<label for="description">Project Description:</label>
<input
type="text"
class="form-control"
placeholder="Enter Project Description"
name="description"
value={this.state.description}
onChange={this.handleChange}
required
/>
<div class="valid-feedback">Valid.</div>
<div class="invalid-feedback">Please fill out this field.</div>
</div>
<input
type="button"
value="submit"
class="btn btn-primary"
onClick={this.submitForm}
/>
</form>
</div>
);
}
} |
JavaScript | class Tab extends Node {
/**
* @param {string} label - text label for the tab
* @param {EnumerationProperty.<PreferencesDialog.<PreferencesTab>} property
* @param {PreferencesDialog.PreferencesTab} value - PreferencesTab shown when this tab is selected
*/
constructor( label, property, value ) {
const textNode = new Text( label, PreferencesDialog.TAB_OPTIONS );
// background Node behind the Text for layout spacing, and to increase the clickable area of the tab
const backgroundNode = new Rectangle( textNode.bounds.dilatedXY( 15, 10 ), {
children: [ textNode ]
} );
const underlineNode = new Line( 0, 0, textNode.width, 0, {
stroke: FocusHighlightPath.INNER_FOCUS_COLOR,
lineWidth: 5,
centerTop: textNode.centerBottom.plusXY( 0, 5 )
} );
super( {
children: [ backgroundNode, underlineNode ],
cursor: 'pointer',
// pdom
tagName: 'button',
innerContent: label,
ariaRole: 'tab',
focusable: true,
containerTagName: 'li'
} );
// @public {PreferenceTab}
this.value = value;
// voicing
this.initializeVoicing();
this.voicingNameResponse = StringUtils.fillIn( preferencesTabResponsePatternString, {
title: label
} );
const buttonListener = new PressListener( {
press: () => {
property.set( value );
// speak the object response on activation
this.voicingSpeakNameResponse();
},
// phet-io - opting out for now to get CT working
tandem: Tandem.OPT_OUT
} );
this.addInputListener( buttonListener );
Property.multilink( [ property, buttonListener.isOverProperty ], ( selectedTab, isOver ) => {
textNode.opacity = selectedTab === value ? 1 :
isOver ? 0.8 :
0.6;
this.focusable = selectedTab === value;
underlineNode.visible = selectedTab === value;
} );
}
} |
JavaScript | class BaseModel {
constructor() {
/** @const the underlying mongoose model used for queries */
this.mongooseModel_ = this.createMongooseModel_()
}
/**
* Returns the model schema. The child class must implement the static schema
* property.
* @return {string} the models schema
*/
getSchema() {
if (!this.constructor.schema) {
throw new Error("Schema not defined")
}
return this.constructor.schema
}
/**
* Returns the model name. The child class must implement the static modelName
* property.
* @return {string} the name of the model
*/
getModelName() {
if (!this.constructor.modelName) {
throw new Error("Every model must have a static modelName property")
}
return this.constructor.modelName
}
/**
* Returns the schema options defined in child class.
* @return {object} the schema options
*/
getSchemaOptions() {
if (!this.constructor.schemaOptions) {
return {}
}
return this.constructor.schemaOptions
}
/**
* @private
* Creates a mongoose model based on schema, schema options and model name.
* @return {Mongooose.Model} the mongoose model
*/
createMongooseModel_() {
const schema = this.getSchema()
const options = this.getSchemaOptions()
const mongooseSchema = new mongoose.Schema(schema, options)
return mongoose.model(this.getModelName(), mongooseSchema)
}
/**
*/
startSession() {
return this.mongooseModel_.startSession()
}
/**
* Queries the mongoose model via the mongoose's findOne.
* @param query {object} a mongoose selector query
* @param options {?object=} mongoose options
* @return {?mongoose.Document} the retreived mongoose document or null.
*/
findOne(query, options = {}) {
return this.mongooseModel_.findOne(query, options).lean()
}
/**
* Queries the mongoose model via the mongoose's find.
* @param query {object} a mongoose selector query
* @param options {?object=} mongoose options
* @return {Array<mongoose.Document>} the retreived mongoose documents or
* an empty array
*/
find(query, options, offset, limit) {
return this.mongooseModel_
.find(query, options)
.skip(offset)
.limit(limit)
.lean()
}
count() {
return this.mongooseModel_.count({})
}
/**
* Update a model via the mongoose model's updateOne.
* @param query {object} a mongoose selector query
* @param update {object} mongoose update object
* @param options {?object=} mongoose options
* @return {object} mongoose result
*/
updateOne(query, update, options = {}) {
options.new = true
return this.mongooseModel_.findOneAndUpdate(query, update, options).lean()
}
/**
* Update a model via the mongoose model's update.
* @param query {object} a mongoose selector query
* @param update {object} mongoose update object
* @param options {?object=} mongoose options
* @return {object} mongoose result
*/
update(query, update, options) {
return this.mongooseModel_.update(query, update, options)
}
/**
* Creates a document in the mongoose model's collection via create.
* @param object {object} the value of the document to be created
* @param options {?object=} mongoose options
* @return {object} mongoose result
*/
create(object, options) {
return this.mongooseModel_.create(object, options)
}
/**
* Deletes a document in the mongoose model's collection
* @param query {object} the value of the document to be created
* @param options {?object=} mongoose options
* @return {object} mongoose result
*/
deleteOne(query, options) {
return this.mongooseModel_.deleteOne(query, options)
}
/**
* Deletes many document in the mongoose model's collection
* @param query {object} the value of the document to be created
* @param options {?object=} mongoose options
* @return {object} mongoose result
*/
delete(query, options) {
return this.mongooseModel_.deleteMany(query, options)
}
} |
JavaScript | class State {
/**
* Set page map
* @param {PageMap} pageMap - page map
* @example State.setPageMap(new PageMap());
*/
static setPageMap(pageMap) {
this.pageMap = pageMap;
}
/**
* Set current page by Name
* @param {string} pageName - name of page ot set
* @example State.setPage("YourPage");
*/
static setPage(pageName) {
this.page = this.pageMap.getPage(pageName).pageObject;
}
/**
* Get current page
* @return {AbstractPage} - current page
* @throws {Error}
* @example State.getPage();
*/
static getPage() {
if (this.page) {
return this.page;
} else {
throw new Error("Current page is not defined")
}
}
} |
JavaScript | class PieceState {
// creates a new piece with a given color and id
constructor(color, id) {
this._color = color
this._id = id
this._state = State.HOME
this._location = null
this._capturer = null
this.selected = false
}
get color() {
return this._color
}
get id() {
return this._id
}
isHome() {
return this._state === State.HOME
}
isOut() {
return this._state === State.OUT
}
moveOut() {
const new_piece = new PieceState(this._color, this._id)
new_piece._state = State.OUT
new_piece._location = {
track: this._color,
position: KEY_POSITION.START,
}
return new_piece
}
isCaptured() {
return this._state === State.CAPTURED
}
makeCaptured(capturerColor) {
if (!this.isOut()) {
throw new Error("a piece can only be captured if out")
}
const new_piece = new PieceState(this._color, this._id)
new_piece._state = State.CAPTURED
new_piece._capturer = capturerColor
return new_piece
}
capturerColor() {
if (!this.isCaptured()) {
throw new Error("this piece is not captured")
}
return this._capturer
}
makeReleased() {
if (!this.isCaptured()) {
throw new Error("a piece can only be released if captured")
}
return new PieceState(this._color, this._id)
}
isGraduating() {
if (!this.isOut()) {
return false
}
return this._location.track === 'graduation_lane'
}
isGraduated() {
return this._state === State.GRADUATED
}
makeGraduated() {
if (!this.isGraduating()) {
throw new Error("a piece can only graduate if it's graduating")
}
const new_piece = new PieceState(this._color, this._id)
new_piece._state = State.GRADUATED
return new_piece
}
/**
* Return an object with fields "track" which is either
* 'graduation_lane' or <color>. If 'graduation_lane'
* 'position' is one of 1 through 5 or 6 (depending on the
* rules) and it will be located on its color's track. if
* <color> (which is one of our four colors), position
* represents the cell they are in. cell 0 represents the
* most counterclockwise position of that color. (e.g.,
* for RED that positon is the color that is connected to
* the BLUE HOME and the RED graduation triangle).
*/
location() {
if (!this.isOut()) {
throw new Error("This piece is not out, so it doesn't have a location")
}
return {
track: this._location.track,
position: this._location.position,
}
}
isAboutToEnterGraduationLane() {
if (!this.isOut()) {
return false
}
if (this._location.track !== this._color) {
return false
}
return this._location.position === KEY_POSITION.GRADUATE
}
forward(count, stop_at_graduation_entrance=false) {
if (!this.isOut()) {
throw new Error("This piece can't move forward because it's not out")
}
const new_piece = new PieceState(this._color, this._id)
new_piece._state = State.OUT
const new_position = this._location.position + count
if (this.isGraduating()) {
if (new_position > KEY_POSITION.LAST_GRAD) {
throw new Error("Cannot exceed graduation")
}
new_piece._location = {
track: GRAD_TRACK,
position: new_position
}
return new_piece
}
// TODO: fix comment below... lol. is code even good?
// this is bad design... but the case where isAboutToGraduate
// is handled in positioning. I should move it here because it
// doesn't really make sense that in this code it's assuming that
// that case is handled (when it could not by another implementer)
if (this.isAboutToEnterGraduationLane() && stop_at_graduation_entrance) {
if (count !== 1) {
throw new Error("Must roll a 1 to enter graduation")
}
new_piece._location = {
track: GRAD_TRACK,
position: 1,
}
return new_piece
}
const was_before_graduate = this._location.position <= KEY_POSITION.GRADUATE
if (this._location.track === this._color && was_before_graduate) {
let maybe_grad_track = this._location.track
let maybe_grad_position = new_position
if (maybe_grad_position > KEY_POSITION.GRADUATE) {
if (stop_at_graduation_entrance) {
throw new Error(
"The new position would exceed the graduation lane entry"
)
}
maybe_grad_track = GRAD_TRACK
maybe_grad_position = new_position - KEY_POSITION.GRADUATE
}
if (maybe_grad_track === GRAD_TRACK && maybe_grad_position > KEY_POSITION.LAST_GRAD) {
throw new Error("Cannot exceed graduation")
}
new_piece._location = {
track: maybe_grad_track,
position: maybe_grad_position,
}
return new_piece
}
new_piece._location = PieceState._nextLocation(
this._location.track, new_position
)
return new_piece
}
static _nextLocation(color, position) {
let new_color = color
let new_position = position
let was_old_color = false
while (new_position > KEY_POSITION.LAST) {
new_color = PieceState._nextTrackColor(new_color)
new_position = new_position - (KEY_POSITION.LAST + 1)
if (new_color === color) {
was_old_color = true
continue
}
if (was_old_color) {
throw new Error("We looped back, this is impossible")
}
}
return {track: new_color, position: new_position}
}
static _nextTrackColor(color) {
switch (color) {
case C.color.RED:
return C.color.GREEN
case C.color.GREEN:
return C.color.YELLOW
case C.color.YELLOW:
return C.color.BLUE
case C.color.BLUE:
return C.color.RED
default:
throw new Error(`invalid color ${color}`)
}
}
equal(other) {
return this.color === other.color
&& this.id === other.id
&& this._state === other._state
&& this._location === other._location
&& this._capturer === other._capturer
}
sameColor(other) {
return this.color === other.color
}
} |
JavaScript | class Choice {
constructor (value, index, label, selected, image) {
this.CHOICE_INDEX = index
this.CHOICE_VALUE = String(value)
this.CHOICE_LABEL = label
if (selected) {
this.CHOICE_SELECTED = true
} else {
this.CHOICE_SELECTED = false
}
this.CHOICE_IMAGE = image
}
} |
JavaScript | class PhobosClient extends Client {
/**
* Create a PhobosClient
* @param {object} options Discord.js Client options
*/
constructor (options) {
super(options)
/**
* Configs defined in src/config.js
* @type {object}
*/
this.config = config
/**
* Contains categories that contain the actual commands
* @type {Collection}
*/
this.commands = new Collection()
/**
* All aliases to commands (kinda like a index)
* @type {Collection}
*/
this.aliases = new Collection()
/**
* Command cooldowns
* @type {Collection}
*/
this.cooldowns = new Collection()
/**
* Custom logger
* @type {object}
*/
this.log = log
/**
* Databases
* @type {object}
*/
this.db = {
user: db.User,
guild: db.Guild
}
}
/**
* Get a command from name or alias
* @param {string} name Command name or alias
* @returns {object} Command
*/
getCmd (name) {
// Loop through all categories and find commands in them
for (const category of this.commands.values()) {
const cmd = category.get(name)
if (cmd) {
return cmd
}
}
// If not found, find in aliases
return this.aliases.get(name)
}
} |
JavaScript | class FilterSelectionInput extends React.Component {
constructor( props ) {
super( props );
this.state = Object.assign( {}, props, {
isModalOpen: false,
'labelText': 'Filter'
} );
this.onClearButtonClick = this.onClearButtonClick.bind( this );
this.setFilterSelection = this.setFilterSelection.bind( this );
this.onAction = this.onAction.bind( this );
}
componentDidMount() {
this.filterSelector.addEventListener( "action", this.onAction );
}
componentWillUnmount() {
this.filterSelector.removeEventListener( "action", this.onAction );
}
componentWillReceiveProps( nextProps ) {
this.setState( Object.assign( this.state, nextProps, {
isModalOpen: false,
'searching': false
} ) );
}
onAction( evt ) {
if ( evt.detail.type === "named_text_selection" ) {
console.log( "FilterSelectionInput.onAction %o", evt.detail );
if ( evt.detail.lookup == null && evt.detail.id == null ) {
//unset
this.onClearButtonClick( {} );
return;
}
if ( evt.detail.lookup && evt.detail.lookup.length > 1 ) {
this.setState( {
searching: false,
value: evt.detail.lookup,
type : 'RELATIONSHIP_QUERY_LOOKUP'
})
if( this.props.onChange ) {
this.props.onChange( {
'value': evt.detail.lookup,
'type': 'RELATIONSHIP_QUERY_LOOKUP',
'parameter' : 'RELATIONSHIP_QUERY_LOOKUP'
} );
}
} else {
this.setState( {
searching: false,
value: evt.detail.id,
type : 'RELATIONSHIP_QUERY_ID'
})
if( this.props.onChange ) {
this.props.onChange( {
'value': evt.detail.id,
'type': 'RELATIONSHIP_QUERY_ID',
'parameter' : 'RELATIONSHIP_QUERY_ID'
} );
}
}
}
}
onClearButtonClick( event ) {
this.setState( {
value: 'Default',
'searching': false
} );
if( this.props.onReset ) {
this.props.onReset();
} else if( this.props.onChange ) {
this.props.onChange( {
'parameter': 'RELATIONSHIP_QUERY_ID',
'value': ''
} );
this.props.onChange( {
'parameter': 'RELATIONSHIP_QUERY_LOOKUP',
'value': ''
} );
}
}
setFilterSelection( obj ) {
if( obj.lookup ) {
this.setState( {
'searching': !this.state.searching,
'value': obj.lookup,
'type' : 'RELATIONSHIP_QUERY_LOOKUP'
} );
} else {
this.setState( {
'searching': !this.state.searching,
'value': obj.id,
'type' : 'RELATIONSHIP_QUERY_ID'
} );
}
if( this.props.valueChange ) {
this.props.valueChange( {
'value': this.state.value,
'type' : obj.lookup ? 'RELATIONSHIP_QUERY_LOOKUP' : 'RELATIONSHIP_QUERY_ID'
} );
}
}
render() {
return (
<div className = "form-group" >
<label className=" control-label" htmlFor={this.props.parameter}>
{this.state.labelText}:
</label>
<div>
<iq-named-text-selector data-type="filter"
data-initial-value={this.state.value}
ref={( filterSelector ) => { this.filterSelector = filterSelector; }} />
<em className="help-block" > { this.state.help } </em>
</div>
</div>
);
}
stopIt( evt ) {
evt.stopPropagation();
}
openModal() {
this.setState( {
isModalOpen: true
} );
}
closeModal() {
this.setState( {
isModalOpen: false
} );
}
} |
JavaScript | class EtiquetasController {
/**
* @param $uibModal
* @param toastr
* @param {EtiquetasService} EtiquetasService
* @param {ProcesosService} ProcesosService
* @param {ActividadesService} ActividadesService
* @param AppConfig
*
**/
constructor($uibModal, toastr, EtiquetasService, ProcesosService, ActividadesService, AppConfig) {
/** @private */
this.ITEMS_SELECT = AppConfig.elementosBusquedaSelect;
/** @private */
this.$uibModal = $uibModal;
/** @private */
this.toastr = toastr;
/** @private */
this.etiquetasService = EtiquetasService;
/** @private */
this.actividadesService = ActividadesService;
/** @type {boolean} */
this.busquedaVisible = true;
/** @private */
this.totalProcesos = 0;
/** @type {Proceso[]} */
this.procesos = [];
ProcesosService.obtenerTodos(false)
.then(procesos => {
/** @type {Proceso[]} */
this.procesos = [].concat(...procesos);
this.procesos.push({codigo: undefined, evento: ''});
});
ActividadesService.obtenerTodos(1, ['orden', 'asc'], null, 0)
.then(actividades => {
this.actividades = actividades;
});
this.estados = [ETIQUETA_PENDIENTE, ETIQUETA_OK_DESC, ETIQUETA_NOK_DESC];
this.etiquetasService.obtenerTodos()
.then(etiquetas => {
let etiquetasOrdenadasPorCodigo = sortBy(etiquetas, ['codigo']);
/** @type {Etiqueta[]} */
this.etiquetas = etiquetasOrdenadasPorCodigo;
/** @type {Etiqueta[]} */
this.datos = etiquetasOrdenadasPorCodigo;
});
this.presentacion = {
entidad: 'Etiqueta',
atributoPrincipal: 'descripcion',
ordenInicial: ['codigo', 'asc'],
columnas: [
{nombre: 'codigo', display: 'ID', ordenable: true},
{nombre: 'proceso.display', display: 'Proceso', ordenable: true},
{nombre: 'actividad.display', display: 'Actividad', ordenable: true},
{nombre: 'descripcionEstado.ordenActividad', display: 'Orden', ordenable: true},
{nombre: 'descripcionEstado.nombre', display: 'Estado', ordenable: true},
{nombre: 'descripcion', display: 'Descripción', ordenable: true},
]
};
this.columnasExcel = {
titulos: ['ID', 'Proceso', 'Actividad', 'Orden', 'Estado', 'Descripción'],
campos: ['codigo', 'proceso.display', 'actividad.display', 'descripcionEstado.ordenActividad', 'descripcionEstado.nombre', 'descripcion']
};
}
/**
* Propiedad que devuelve true si no se está mostrando la lista completa de procesos en un momento determinado.
* @return {boolean}
*/
get mostrandoResultadosParcialesProcesos() {
return this.totalProcesos > this.ITEMS_SELECT + 1;
}
/**
* Filtra la lista de procesos según el string que haya escrito el usuario. Es case insensitive.
* @param {string} busqueda
* @return {Proceso[]}
*/
filtrarProcesos(busqueda) {
const busquedaLower = busqueda.toLowerCase();
const resultado = filter(this.procesos, (elemento) => {
return (busqueda && elemento.evento) ? includes(elemento.evento.toLowerCase(), busquedaLower) : true;
});
this.totalProcesos = resultado.length;
if (resultado.length > this.ITEMS_SELECT + 1) {
return resultado.slice(0, this.ITEMS_SELECT + 1);
} else {
return resultado;
}
}
/**
* Abre el modal que se utiliza para crear/editar una etiqueta. Cuando se termina de trabajar con la etiqueta,
* actualiza o crea una fila correspondiente en la tabla.
*
* @param {Etiqueta} [etiqueta] Si no se pasa una etiqueta, el modal se abre en modo de creación.
*/
mostrarModalEtiqueta(etiqueta) {
const contenedor = angular.element(document.getElementById('modalEdicionEtiqueta'));
const modal = this.$uibModal.open({
template,
appendTo: contenedor,
size: 'dialog-centered', // hack para que el modal salga centrado verticalmente
controller: 'ModalEdicionEtiquetasController',
controllerAs: '$modal',
resolve: {
// Los elementos que se inyectan al controlador del modal se deben pasar de esta forma:
entidad: () => { return etiqueta; },
actividades: () => { return this.actividades; }
}
});
modal.result.then((resultado) => {
this.etiquetas = this.etiquetasService.etiquetas;
if (this.busquedaActiva) {
this.buscar();
} else {
this.datos = clone(this.etiquetas);
}
if (!isNil(resultado) && !isNil(resultado.codigo) && !this.filaEsVisible(resultado)) {
this.toastr.warning('Aunque se guardaron los cambios, la etiqueta no está visible en la tabla en estos momentos.');
}
if (this.actividadesService.actividades.length === 0) {
// Es necesario volver a pedir las actividades
this.actividadesService.obtenerTodos(1, ['orden', 'asc'], null, 0)
.then(actividades => {
this.actividades = actividades;
});
}
});
modal.result.catch(() => { });
}
/**
* Edita los datos de una etiqueta.
* @param {Etiqueta} etiqueta
*/
editarEtiqueta(etiqueta) {
let clon = cloneDeep(etiqueta);
clon.proceso = etiqueta.proceso.valor;
clon.actividad = etiqueta.actividad.valor;
this.mostrarModalEtiqueta(clon);
}
/**
* Elimina una etiqueta
* @param {Etiqueta} etiqueta
*/
eliminarEtiqueta(etiqueta) {
const fnActualizarEtiquetas = () => {
this.etiquetas = this.etiquetasService.etiquetas;
if (this.busquedaActiva) {
this.buscar();
} else {
this.datos = clone(this.etiquetas);
}
};
return this.etiquetasService.eliminar(etiqueta)
.then(() => {
fnActualizarEtiquetas();
})
.catch(response => {
if (response && response.status === 404) {
fnActualizarEtiquetas();
}
throw response;
});
}
buscar() {
if (Object.getOwnPropertyNames(this.paramsBusqueda).length === 0) {
this.mostrarTodos();
} else {
this.busquedaActiva = true;
this.datos = reduce(this.etiquetas, (resultado, item) => {
let coincidencia = isMatchWith(item, this.paramsBusqueda, (objValue, srcValue, key, object) => {
if (key === 'descripcion') {
return objValue && includes(objValue.toLowerCase(), srcValue.toLowerCase());
} else if (key === 'proceso') {
return isNil(srcValue) || objValue.valor.id === srcValue.id;
} else if (key === 'estado') {
return isNil(srcValue) || object.descripcionEstado.nombre === srcValue;
}
});
if (coincidencia) {
resultado.push(item);
}
return resultado;
}, []);
}
}
mostrarTodos() {
this.paramsBusqueda = {};
this.busquedaActiva = false;
this.datos = clone(this.etiquetas);
}
/**
* Devuelve verdadero si la etiqueta está visible en la tabla en ese momento.
* @param {Etiqueta} etiqueta
* @return {boolean}
*/
filaEsVisible(etiqueta) {
if (isNil(etiqueta)) {
return false;
}
return !!find(this.datos, (item) => {
return item.codigo === etiqueta.codigo;
});
}
} |
JavaScript | class SeparatorHeader extends Component {
view() {
return <li className="Dropdown-separator TagInject--Utility-Header">{app.translator.trans('flagrow-utility-tag-inject.forum.tags.utility-header')}</li>;
}
} |
JavaScript | class Group{
/**
* Builds a new group.
* @param {string} name - Required parameter. The name of the group.
* @param {string} startDate - Optional parameter. The date when the group was founded. Defaults to "".
* @param {string} endDate - Optional parameter. The date when the group broke apart. Defaults to "".
* @constructor
*/
constructor(name, startDate="", endDate=""){
this._name = name;
this._startDate = startDate;
this._endDate = endDate;
}
set name(name){
this._name = name;
}
get name(){
return this._name;
}
set startDate(startDate){
this._startDate = startDate;
}
get startDate(){
return this._startDate;
}
set endDate(endDate){
this._endDate = endDate;
}
get endDate(){
return this._endDate;
}
} |
JavaScript | class SelectResourcePlugin extends BasePlugin {
constructor(opts) {
super(opts || {});
// frequency for crawling resources
if (this.opts.crawlFrequency) {
this.opts.crawlFrequency = parseInt(this.opts.crawlFrequency, 10);
}
}
// eslint-disable-next-line class-methods-use-this
getPhase() {
return BasePlugin.PHASE.SELECT;
}
// eslint-disable-next-line class-methods-use-this
test() {
return true;
}
// eslint-disable-next-line class-methods-use-this
apply(site) {
return site.getResourceToCrawl(this.opts.crawlFrequency);
}
} |
JavaScript | class ChatService{
constructor(API, UserService){
'ngInject';
this.API = API;
this.UserService = UserService;
}
/**
* getConversations gets conversations involving this user and other users
* @return {promise} promise of data
*/
getConversations(){
return this.API.one('chat/get_conversations').get()
}
/**
* getConversation get conversation between this user and other user
* @param {object} data request data
* @return {promise} promise of data
*/
getConversation(data){
return this.API.all('chat/get_conversation').post(data)
}
/**
* send message
* @param {object} data request data
*/
sendMessage(data){
return this.API.all('chat/sendmessage').post(data)
}
/**
* getOtherUser get other user involved in conversation
* @param {object} convo conversation object
* @return {object} user info
*/
getOtherUser(convo){
if(convo.sender_id === this.UserService.user.id){
return {
id: convo.recipient_id,
firstname: convo.recipient.firstname,
lastname: convo.recipient.lastname,
avatar: convo.recipient.avatar
}
}else{
return {
id: convo.sender_id,
firstname: convo.sender.firstname,
lastname: convo.sender.lastname,
avatar: convo.sender.avatar
}
}
}
/**
* getConvoAvatar get avatar of other user
* @param {object} convo conversation object
* @return {string} avatar url
*/
getConvoAvatar(convo){
if(convo && this.UserService.user){
//if sender is current user return recipient info else return sender info
if(convo.sender_id === this.UserService.user.id){
return "/uploads/avatars/"+convo.recipient.avatar;
}else{
return "/uploads/avatars/"+convo.sender.avatar;
}
}else{
return "/uploads/avatars/avatar-5.png";
}
}
} |
JavaScript | class BaseFormField extends React.Component {
constructor(props) {
super(props);
this.htmlId = `form-field-${this.props.name}`;
this.state = {
value: props.initial
};
}
validateField() {
let value = this.state.value || "";
if (this.props.required && value.length <= 0) {
throw `${this.props.name} is required to complete this form.`;
}
}
getValue() {
if (this.state.value !== null && this.state.value !== undefined) {
return this.state.value;
} else {
return this.props.initial;
}
}
render() {
let label = null;
if (this.props.label) {
label = <label htmlFor={this.htmlId}>
{this.props.label}
</label>
}
return <div className="form-group">
{label}
{this.renderField()}
</div>
}
} |
End of preview. Expand
in Dataset Viewer.
README.md exists but content is empty.
Use the Edit dataset card button to edit it.
- Downloads last month
- 66