language
stringclasses 5
values | text
stringlengths 15
988k
|
---|---|
JavaScript | class ActiveRequests {
constructor (feed) {
this.feed = feed
this.requests = new Set()
}
add (req) {
this.requests.add(req)
}
remove (req) {
this.requests.delete(req)
}
cancel () {
for (const req of this.requests) this.feed.cancel(req)
}
} |
JavaScript | class HomeContainer extends React.Component {
render() {
return (
<Panel>
<Row>
<Col xs={12} md={6}>
<h2>Start Here</h2>
<p>This is a good place to start building your React app.</p>
</Col>
<Col xs={12} md={6}>
<Image src="https://cdn-images-1.medium.com/max/1200/1*m_q0YKyWw7Qqbh-qklinTw.png" responsive />
</Col>
</Row>
</Panel>
);
}
} |
JavaScript | class Toast extends React.Component {
constructor(props) {
super(props);
//Ininitialize the toast state
this.state = {
"visible": false,
"color": "error",
"message": ""
};
this.timer = null;
//Bind some methods
this.close = this.close.bind(this);
this.display = this.display.bind(this);
this.displayError = this.displayError.bind(this);
this.displayWarning = this.displayWarning.bind(this);
this.displaySuccess = this.displaySuccess.bind(this);
}
//Hide the toast
close() {
clearTimeout(this.timer);
return this.setState({"visible": false});
}
//Display a toast message
display(color, message, time) {
let self = this;
//Check the provided time
if (typeof time !== "number" || time <= 0) {
time = this.props.timeout;
}
//Display this toast message
return this.setState({"visible": true, "color": color, "message": message}, function () {
//Check if there are an active timer
if (self.timer) {
clearTimeout(self.timer);
}
//Register the new timer
self.timer = delay(time, function () {
return self.setState({"visible": false});
});
});
}
//Display an error message
displayError(message, time) {
return this.display("error", message, time);
}
//Display a warning message
displayWarning(message, time) {
return this.display("warning", message, time);
}
//Display a success message
displaySuccess(message, time) {
return this.display("success", message, time);
}
//Build the alert element
renderAlert() {
let self = this;
//Build the alert close component
let alertClose = React.createElement(AlertClose, {
"onClick": function () {
return self.close();
}
});
//Return the alert component
return React.createElement(Alert, {"color": this.state.color}, alertClose, this.state.message);
}
render() {
let self = this;
let toastClass = ["neutrine-toast", "neutrine-toast--" + this.props.position];
//Check if the toast is visible
if (this.state.visible === true) {
toastClass.push("neutrine-toast--visible");
}
//Return the toast component
return React.createElement("div", {"className": toastClass.join(" ")}, this.renderAlert());
}
} |
JavaScript | class AuthCustomPlugin {
constructor(config, options) {
return this;
}
/**
* Authenticate an user.
* @param user user to log
* @param password provided password
* @param cb callback function
*/
authenticate(user, password, cb) {
// here your code
}
/**
* check grants for such user.
*/
allow_access() {
// in case of restrict the access
}
/**
* check grants to publish
*/
allow_publish() {
// in cass to check if has permission to publish
}
} |
JavaScript | @withStyles(styles, { name: "SkMediaGalleryItem" })
class MediaGalleryItem extends Component {
static propTypes = {
/**
* CSS class names
*/
classes: PropTypes.object,
/**
* The 0-based integer position of this item within a group of MediaGalleryItems
*/
index: PropTypes.number,
/**
* Product media
*/
media: PropTypes.object,
/**
* Click callback
* @example (event, media) => {}
*/
onClick: PropTypes.func
};
static defaultProps = {
onClick: () => {}
};
/**
* Click handler for ButtonBase
* @param {SyntheticEvent} event Event
* @returns {undefined}
*/
handleClick = (event) => {
this.props.onClick(event, this.props.media, this.props.index);
};
render() {
const { classes, media } = this.props;
// If all props are undefined then skip rendering component
if (!media) return null;
return (
<ButtonBase className={classes.root} onClick={this.handleClick}>
<ProgressiveImage presrc={media.URLs.medium} src={media.URLs.medium} />
</ButtonBase>
);
}
} |
JavaScript | class Base {
/**
* @hideconstructor
* @param {*} children
* @param {*} inlineMaker
* @param {*} preface
*/
constructor(children) {
this.childrenNames = Object.keys(children);
Object.keys(children).map(name => this[name] = implicitCast(children[name]));
this._getChildren().map(child => child.parent = this);
this.preface = '';
this._shaderBindings = new Map();
}
loadSprites() {
return Promise.all(this._getChildren().map(child => child.loadSprites()));
}
_bind(metadata) {
this._compile(metadata);
return this;
}
_setUID(idGenerator) {
this._uid = idGenerator.getID(this);
this._getChildren().map(child => child._setUID(idGenerator));
}
_dataReady(){
this._getChildren().map(child => child._dataReady());
}
isFeatureDependent() {
return this._getChildren().some(child => child.isFeatureDependent());
}
_prefaceCode(glslCode) {
return glslCode
? `\n${this._buildGLSLCode(glslCode)}\n`
: '';
}
_buildGLSLCode(glslCode) {
return `
#ifndef DEF_${this._uid}
#define DEF_${this._uid}
${glslCode}
#endif`;
}
_getDependencies() {
return this._getChildren().map(child => child._getDependencies()).reduce((x, y) => x.concat(y), []);
}
_resolveAliases(aliases) {
this._getChildren().map(child => child._resolveAliases(aliases));
}
_compile(metadata) {
this._getChildren().map(child => child._compile(metadata));
}
_setGenericGLSL(inlineMaker, preface) {
this.inlineMaker = inlineMaker;
this.preface = (preface ? preface : '');
}
/**
* Generate GLSL code
* @param {*} getGLSLforProperty fn to get property IDs and inform of used properties
*/
_applyToShaderSource(getGLSLforProperty) {
const childSources = this.childrenNames.map(name => this[name]._applyToShaderSource(getGLSLforProperty));
let childInlines = {};
childSources.map((source, index) => childInlines[this.childrenNames[index]] = source.inline);
return {
preface: this._prefaceCode(childSources.map(s => s.preface).reduce((a, b) => a + b, '') + this.preface),
inline: this.inlineMaker(childInlines, getGLSLforProperty)
};
}
/**
* Inform about a successful shader compilation. One-time post-compilation WebGL calls should be done here.
* @param {*} program
*/
_postShaderCompile(program, gl) {
this.childrenNames.forEach(name => this[name]._postShaderCompile(program, gl));
}
_getBinding(shader) {
if (!this._shaderBindings.has(shader)) {
this._shaderBindings.set(shader, {});
}
return this._shaderBindings.get(shader);
}
_resetViewportAgg() {
this._getChildren().forEach(child => child._resetViewportAgg());
}
accumViewportAgg(feature) {
this._getChildren().forEach(child => child.accumViewportAgg(feature));
}
/**
* Pre-rendering routine. Should establish the current timestamp in seconds since an arbitrary point in time as needed.
* @param {number} timestamp
*/
_setTimestamp(timestamp) {
this.childrenNames.forEach(name => this[name]._setTimestamp(timestamp));
}
/**
* Pre-rendering routine. Should establish related WebGL state as needed.
* @param {*} l
*/
_preDraw(...args) {
this.childrenNames.forEach(name => this[name]._preDraw(...args));
}
/**
* @jsapi
* @returns true if the evaluation of the function at styling time won't be the same every time.
*/
isAnimated() {
return this._getChildren().some(child => child.isAnimated());
}
/**
* Replace child *toReplace* by *replacer*
* @param {*} toReplace
* @param {*} replacer
*/
replaceChild(toReplace, replacer) {
const name = this.childrenNames.find(name => this[name] == toReplace);
this[name] = replacer;
replacer.parent = this;
replacer.notify = toReplace.notify;
}
notify() {
this.parent.notify();
}
/**
* Linear interpolation between this and finalValue with the specified duration
* @api
* @param {Expression} final
* @param {Expression} duration
* @param {Expression} blendFunc
* @memberof carto.expressions.Base
* @instance
* @name blendTo
*/
blendTo(final, duration = 500) {
//TODO blendFunc = 'linear'
final = implicitCast(final);
const parent = this.parent;
const blender = blend(this, final, transition(duration));
parent.replaceChild(this, blender);
blender.notify();
return final;
}
_blendFrom(final, duration = 500, interpolator = null) {
if (this.default && final.default) {
return;
}
final = implicitCast(final);
const parent = this.parent;
const blender = blend(final, this, transition(duration), interpolator);
parent.replaceChild(this, blender);
blender.notify();
}
/**
* @returns a list with the expression children
*/
_getChildren() {
return this.childrenNames.map(name => this[name]);
}
_getMinimumNeededSchema() {
// Depth First Search => reduce using union
return this._getChildren().map(child => child._getMinimumNeededSchema()).reduce(schema.union, schema.IDENTITY);
}
// eslint-disable-next-line no-unused-vars
eval(feature) {
throw new Error('Unimplemented');
}
isA(expressionClass) {
return this instanceof expressionClass;
}
} |
JavaScript | class Typeahead extends Component {
static propTypes = {
customClasses: propTypes.object,
maxVisible: propTypes.number,
options: propTypes.oneOfType([propTypes.array, propTypes.object]),
header: propTypes.string,
isAllowSearchDropDownHeader: propTypes.bool,
fuzzySearchEmptyMessage: propTypes.string,
fuzzySearchKeyAttribute: propTypes.string,
fuzzySearchIdAttribute: propTypes.string,
datatype: propTypes.string,
dynamicOptions: propTypes.bool,
disabled: propTypes.bool,
defaultValue: propTypes.string,
placeholder: propTypes.string,
onOptionSelected: propTypes.func,
onKeyDown: propTypes.func,
fetchData: propTypes.func
};
static defaultProps = {
options: [],
header: "Category",
datatype: "text",
dynamicOptions:false,
customClasses: {},
defaultValue: "",
placeholder: "",
isAllowSearchDropDownHeader: true,
fuzzySearchEmptyMessage: "No result found",
fuzzySearchKeyAttribute: "name",
fuzzySearchIdAttribute: "id",
onKeyDown: function(event) {
return;
},
onOptionSelected: function(option) {}
};
constructor(props) {
super(props);
this.datepickerRef = null;
this.entryRef = null;
this.selRef = null;
this.inputRef = null;
debugger
this.state = {
// The set of all options... Does this need to be state? I guess for lazy load...
options: this.props.options,
header: this.props.header,
datatype: this.props.datatype,
dynamicOptions:this.props.dynamicOptions,
// The currently visible set of options
visible: this.getOptionsForValue(null, this.props.options),
// This should be called something else, "entryValue"
entryValue: this.props.defaultValue,
// A valid typeahead value
selection: null,
focused: false
};
this.fuzzySearchKeyAttribute = this.props.fuzzySearchKeyAttribute;
}
componentWillReceiveProps(nextProps) {
this.fuzzySearchKeyAttribute = nextProps.fuzzySearchKeyAttribute || this.props.fuzzySearchKeyAttribute;
debugger
this.setState({
options: nextProps.options,
header: nextProps.header,
datatype: nextProps.datatype,
dynamicOptions:nextProps.dynamicOptions,
visible: nextProps.options
});
}
getOptionsForValue(value = this.props.defaultValue, options) {
if (value == null) {
value = this.props.defaultValue;
}
let extract = null;
if (options && options.length && typeof options[0] == "object") {
extract = {
pre: "<",
post: ">",
extract: obj => {
let val = obj[this.fuzzySearchKeyAttribute];
if (!val) {
throw "fuzzySearchKeyAttribute is missing inside options(values) list";
}
return val;
}
};
}
var result = fuzzy.filter(value, options, extract).map(function(res) {
return res.original;
});
if (this.props.maxVisible) {
result = result.slice(0, this.props.maxVisible);
}
if (this.props.datatype == "textoptions" && !this.props.isAllowCustomValue) {
return result.length == 0 ? [this.props.fuzzySearchEmptyMessage] : result;
} else {
return result;
}
}
setEntryText(value) {
if (this.entryRef != null) {
this.entryRef.value = value;
}
this._onTextEntryUpdated();
}
_renderIncrementalSearchResults() {
if (this.props.isElemenFocused == undefined) {
if (!this.state.focused) {
return "";
}
} else {
if (!this.props.isElemenFocused) {
return "";
}
}
// Something was just selected
if (this.state.selection) {
return "";
}
// There are no typeahead / autocomplete suggestions
if (!this.state.visible.length) {
return "";
}
return (
<TypeaheadSelector
ref={ref => (this.selRef = ref)}
fromTokenizer={this.props.fromTokenizer}
options={this.state.visible}
header={this.state.header}
isAllowSearchDropDownHeader={this.props.isAllowSearchDropDownHeader}
fuzzySearchKeyAttribute={this.fuzzySearchKeyAttribute}
fuzzySearchIdAttribute={this.props.fuzzySearchIdAttribute}
fuzzySearchEmptyMessage={this.props.fuzzySearchEmptyMessage}
renderSearchItem={this.props.renderSearchItem}
onOptionSelected={this._onOptionSelected.bind(this)}
customClasses={this.props.customClasses}
/>
);
}
_onOptionSelected(option) {
var nEntry = this.entryRef;
nEntry.focus();
nEntry.value = option;
this.setState({
visible: this.getOptionsForValue(option, this.state.options),
selection: option,
entryValue: option
});
this.props.onOptionSelected(option);
}
_onTextEntryUpdated = () => {
var value = "";
if (this.entryRef != null) {
value = this.entryRef.value;
}
this.setState({
visible: this.getOptionsForValue(value, this.state.options),
selection: null,
entryValue: value
},()=>{
if(this.props.dynamicOptions && this.state.datatype ==='textoptions'){
this.props.fetchData(value)
}
});
};
_onEnter = event => {
if (this.selRef && this.selRef) {
if (!this.selRef.state.selection) {
return this.props.onKeyDown(event);
}
this._onOptionSelected(this.selRef.state.selection);
}
};
_onEscape = () => {
this.selRef.setSelectionIndex(null);
};
_onTab = event => {
var option = this.selRef.state.selection ? this.selRef.state.selection : this.state.visible[0];
this._onOptionSelected(option);
};
eventMap(event) {
var events = {};
if (this.selRef && this.selRef) {
events[KeyEvent.DOM_VK_UP] = this.selRef.navUp;
events[KeyEvent.DOM_VK_DOWN] = this.selRef.navDown;
}
events[KeyEvent.DOM_VK_RETURN] = events[KeyEvent.DOM_VK_ENTER] = this._onEnter;
events[KeyEvent.DOM_VK_ESCAPE] = this._onEscape;
events[KeyEvent.DOM_VK_TAB] = this._onTab;
return events;
}
_onKeyDown = event => {
// If Enter pressed
if (event.keyCode === KeyEvent.DOM_VK_RETURN || event.keyCode === KeyEvent.DOM_VK_ENTER) {
// If no options were provided so we can match on anything
if (this.props.options.length === 0) {
this._onOptionSelected(this.state.entryValue);
} else if (this.props.options.indexOf(this.state.entryValue) > -1 || (this.state.entryValue.trim() != "" && this.props.isAllowCustomValue)) {
// If what has been typed in is an exact match of one of the options
this._onOptionSelected(this.state.entryValue);
}
}
// If there are no visible elements, don't perform selector navigation.
// Just pass this up to the upstream onKeydown handler
if (!this.selRef) {
return this.props.onKeyDown(event);
}
var handler = this.eventMap()[event.keyCode];
if (handler) {
handler(event);
} else {
return this.props.onKeyDown(event);
}
// Don't propagate the keystroke back to the DOM/browser
event.preventDefault();
};
_onFocus = event => {
if (this.props.onElementFocused) {
this.props.onElementFocused({ focused: true });
} else {
this.setState({ focused: true });
}
};
isDescendant(parent, child) {
var node = child.parentNode;
while (node != null) {
if (node == parent) {
return true;
}
node = node.parentNode;
}
return false;
}
_handleDateChange = date => {
this.props.onOptionSelected(date.format("YYYY-MM-DD HH:mm:ss"));
};
_showDatePicker() {
if (this.state.datatype == "date") {
return true;
}
return false;
}
getInputRef() {
if (this._showDatePicker()) {
return this.datepickerRef.dateinputRef.entryRef;
} else {
return this.entryRef;
}
}
_getTypeaheadInput({ classList, inputClassList }) {
return (
<span ref={ref => (this.inputRef = ref)} className={classList} onFocus={this._onFocus}>
<input
ref={ref => (this.entryRef = ref)}
type="text"
placeholder={this.props.placeholder}
className={inputClassList}
defaultValue={this.state.entryValue}
onChange={this._onTextEntryUpdated}
onKeyDown={this._onKeyDown}
/>
{this._renderIncrementalSearchResults()}
</span>
);
}
render() {
var inputClasses = {};
inputClasses[this.props.customClasses.input] = !!this.props.customClasses.input;
var inputClassList = classNames(inputClasses);
var classes = {
typeahead: true
};
classes[this.props.className] = !!this.props.className;
var classList = classNames(classes);
if (this._showDatePicker()) {
return (
<span ref={ref => (this.inputRef = ref)} className={classList} onFocus={this._onFocus}>
<DatePicker
isAllowOperator={this.props.isAllowOperator}
ref={ref => (this.datepickerRef = ref)}
dateFormat={"YYYY-MM-DD HH:mm:ss"}
onChange={this._handleDateChange}
onKeyDown={this._onKeyDown}
/>
</span>
);
}
return this._getTypeaheadInput({ classList, inputClassList });
}
} |
JavaScript | class PositionData {
/**
* Constructs a new <code>PositionData</code>.
* The Position object.
* @alias module:model/PositionData
*/
constructor() {
PositionData.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>PositionData</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/PositionData} obj Optional instance to populate.
* @return {module:model/PositionData} The populated <code>PositionData</code> instance.
*/
static constructFromObject(data, obj) {
if (data) {
obj = obj || new PositionData();
if (data.hasOwnProperty('symbol_id_exchange')) {
obj['symbol_id_exchange'] = ApiClient.convertToType(data['symbol_id_exchange'], 'String');
}
if (data.hasOwnProperty('symbol_id_coinapi')) {
obj['symbol_id_coinapi'] = ApiClient.convertToType(data['symbol_id_coinapi'], 'String');
}
if (data.hasOwnProperty('avg_entry_price')) {
obj['avg_entry_price'] = ApiClient.convertToType(data['avg_entry_price'], 'Number');
}
if (data.hasOwnProperty('quantity')) {
obj['quantity'] = ApiClient.convertToType(data['quantity'], 'Number');
}
if (data.hasOwnProperty('side')) {
obj['side'] = OrdSide.constructFromObject(data['side']);
}
if (data.hasOwnProperty('unrealized_pnl')) {
obj['unrealized_pnl'] = ApiClient.convertToType(data['unrealized_pnl'], 'Number');
}
if (data.hasOwnProperty('leverage')) {
obj['leverage'] = ApiClient.convertToType(data['leverage'], 'Number');
}
if (data.hasOwnProperty('cross_margin')) {
obj['cross_margin'] = ApiClient.convertToType(data['cross_margin'], 'Boolean');
}
if (data.hasOwnProperty('liquidation_price')) {
obj['liquidation_price'] = ApiClient.convertToType(data['liquidation_price'], 'Number');
}
if (data.hasOwnProperty('raw_data')) {
obj['raw_data'] = ApiClient.convertToType(data['raw_data'], Object);
}
}
return obj;
}
} |
JavaScript | class AuthService {
static getPwdHash(password) {
return crypto.createHash('sha256').update(password).digest('hex');
}
static getUserToken(username, validityTime) {
const date = new Date();
const expires = date.setDate(date.getDate() + validityTime);
return {
token: jwt.encode({
username: username,
expireDate: expires
}, JwtSecret),
expires: expires
};
}
// Finds a user by the specified token and returns the user
static findUserByToken(token, isActive = true) {
return new Promise((resolve, reject) => {
try {
const decoded = jwt.decode(token, JwtSecret);
if (decoded.expireDate > Date.now()) {
return User.findOne({ username: decoded.username, active: isActive }).exec().then((user) => {
if (user) {
return resolve(user);
}
return reject();
});
}
return reject();
}
catch (err) {
return reject();
}
});
}
// Finds a user by the specified user name and password
static findUserByCredentials(username, password) {
return User.findOne({ username: username, password: AuthService.getPwdHash(password), active: true }).exec();
}
// Finds a user by the specified user name
// Can be used for example for checking if a user exists
static findUserByUsername(username) {
return User.findOne({ username: username }).exec();
}
// Generates the auth token for the specified user
static generateAuthToken(user) {
return AuthService.getUserToken(user.username, AuthTokenValidityTime);
}
// Generates a random token containing hex characters
// length: length of the token. Must be even number, otherwise the result length is length - 1.
static generateRandomToken(length) {
return crypto.randomBytes(Math.floor(length / 2)).toString('hex');
}
// Parses auth token from the request
static parseTokenFromReq(req) {
return (req.body && req.body.access_token) || (req.query && req.query.access_token) ||
req.headers['x-access-token'];
}
// Registers the user
// Note: doesn't validate the input parameters so it must be validated before calling the method
static register(username, password, email, activate = false) {
// The email address must be unique
// If an active account exists with the same email, user is notified by email
return User.find({ email: email, active: true }).then((users) => {
if (users && users.length > 0) {
EmailService.sendEmailAddressReservedEmail(users[0].email);
return Promise.resolve();
}
const user = new User({
username: username,
password: AuthService.getPwdHash(password),
email: email,
active: activate
});
const userStatistics = new UserStatistics({
username: username
});
return userStatistics.save()
.then(() => user.save())
.then(() => {
if (!activate) {
const token = AuthService.generateAccountActivationToken(user.username).token;
EmailService.sendAccountActivationEmail(user.email, user.username, token);
}
return Promise.resolve();
});
});
}
// Activates the account of a user specified by the token
static activate(token) {
return AuthService.findUserByToken(token, false)
.then((user) => { // eslint-disable-line arrow-body-style
// Make sure that there isn't already an active account with the email
return User.find({ email: user.email, active: true }).then((users) => {
if (users && users.length > 0) {
return Promise.reject();
}
user.active = true;
return user.save();
});
});
}
// Removes the account of a user specified by the token
static remove(token) {
return AuthService.findUserByToken(token)
.then((user) => { // eslint-disable-line arrow-body-style
return UserStatistics.remove({ username: user.username })
.then(() => user.remove());
});
}
// Generates the account activation token for the specified username
static generateAccountActivationToken(username) {
return AuthService.getUserToken(username, AccountActivationTokenValidityTime);
}
// Generates the forgot password token for the specified username
static generateForgotPasswordToken(username) {
return AuthService.getUserToken(username, ForgotTokenValidityTime);
}
// Orders password renewal email for accounts registered with the specified email address
static orderPasswordRenewal(email) {
return new Promise((resolve, reject) => {
User.find({ email: email, active: true }).then((users) => {
if (users && users.length > 0) {
users.forEach((user) => {
const token = AuthService.generateForgotPasswordToken(user.username).token;
EmailService.sendPasswordRenewEmail(user.email, user.username, token);
});
return resolve();
}
return reject();
});
});
}
// Changes the password of a user specified by the token
// Note: doesn't validate the password so it must be validated before calling the method
static changePassword(token, password) {
return AuthService.findUserByToken(token)
.then((user) => {
user.password = AuthService.getPwdHash(password);
return user.save();
});
}
// Changes the username of a user specified by the token
// Note: doesn't validate the username so it must be validated before calling the method
static changeUsername(token, username) {
return AuthService.findUserByToken(token)
.then((user) => { // eslint-disable-line arrow-body-style
return UserStatistics.update({ username: user.username }, { $set: { username: username } }).then(() => {
user.username = username;
return user.save();
});
});
}
static validateUsername(username) {
return !(!(typeof (username) === 'string') || username.length < GameValidation.minUsernameLength ||
username.length > GameValidation.maxUsernameLength);
}
static validatePassword(password) {
return !(!(typeof (password) === 'string') || password.length < GameValidation.minPasswordLength ||
password.length > GameValidation.maxPasswordLength);
}
} |
JavaScript | class WrapupRepairCompletePage extends PolymerElement {
static get is() {
return 'wrapup-repair-complete-page';
}
static get template() {
return html`{__html_template__}`;
}
/** @override */
ready() {
super.ready();
}
/** @protected */
onDiagnosticsButtonClick_() {}
/** @protected */
onShutdownClick_() {}
/** @protected */
onRmaLogButtonClick_() {
const dialog = /** @type {!CrDialogElement} */ (
this.shadowRoot.querySelector('#logsDialog'));
if (!dialog.open) {
dialog.showModal();
}
}
/** @protected */
onBatteryCutButtonClick_() {
const dialog = /** @type {!CrDialogElement} */ (
this.shadowRoot.querySelector('#batteryCutDialog'));
if (!dialog.open) {
dialog.showModal();
}
}
/** @protected */
onCancelClick_() {
const dialogs = /** @type {!NodeList<!CrDialogElement>} */ (
this.shadowRoot.querySelectorAll('cr-dialog'));
Array.from(dialogs).map((dialog) => {
dialog.close();
});
}
} |
JavaScript | class Logger {
static info (str = '') {
console.log(str)
}
// static error (str = '') {
// console.error(str)
// }
} |
JavaScript | class Gist extends Requestable {
/**
* Create a Gist.
* @param {string} id - the id of the gist (not required when creating a gist)
* @param {Requestable.auth} [auth] - information required to authenticate to Github
* @param {string} [apiBase=https://api.github.com] - the base Github API URL
*/
constructor(id, auth, apiBase) {
super(auth, apiBase);
this.__id = id;
}
/**
* Fetch a gist.
* @see https://developer.github.com/v3/gists/#get-a-single-gist
* @param {Requestable.callback} [cb] - will receive the gist
* @return {Promise} - the Promise for the http request
*/
read(cb) {
return this._request('GET', `/gists/${this.__id}`, null, cb);
}
/**
* Create a new gist.
* @see https://developer.github.com/v3/gists/#create-a-gist
* @param {Object} gist - the data for the new gist
* @param {Requestable.callback} [cb] - will receive the new gist upon creation
* @return {Promise} - the Promise for the http request
*/
create(gist, cb) {
return this._request('POST', '/gists', gist, cb)
.then((response) => {
this.__id = response.data.id;
return response;
});
}
/**
* Delete a gist.
* @see https://developer.github.com/v3/gists/#delete-a-gist
* @param {Requestable.callback} [cb] - will receive true if the request succeeds
* @return {Promise} - the Promise for the http request
*/
delete(cb) {
return this._request('DELETE', `/gists/${this.__id}`, null, cb);
}
/**
* Fork a gist.
* @see https://developer.github.com/v3/gists/#fork-a-gist
* @param {Requestable.callback} [cb] - the function that will receive the gist
* @return {Promise} - the Promise for the http request
*/
fork(cb) {
return this._request('POST', `/gists/${this.__id}/forks`, null, cb);
}
/**
* Update a gist.
* @see https://developer.github.com/v3/gists/#edit-a-gist
* @param {Object} gist - the new data for the gist
* @param {Requestable.callback} [cb] - the function that receives the API result
* @return {Promise} - the Promise for the http request
*/
update(gist, cb) {
return this._request('PATCH', `/gists/${this.__id}`, gist, cb);
}
/**
* Star a gist.
* @see https://developer.github.com/v3/gists/#star-a-gist
* @param {Requestable.callback} [cb] - will receive true if the request is successful
* @return {Promise} - the Promise for the http request
*/
star(cb) {
return this._request('PUT', `/gists/${this.__id}/star`, null, cb);
}
/**
* Unstar a gist.
* @see https://developer.github.com/v3/gists/#unstar-a-gist
* @param {Requestable.callback} [cb] - will receive true if the request is successful
* @return {Promise} - the Promise for the http request
*/
unstar(cb) {
return this._request('DELETE', `/gists/${this.__id}/star`, null, cb);
}
/**
* Check if a gist is starred by the user.
* @see https://developer.github.com/v3/gists/#check-if-a-gist-is-starred
* @param {Requestable.callback} [cb] - will receive true if the gist is starred and false if the gist is not starred
* @return {Promise} - the Promise for the http request
*/
isStarred(cb) {
return this._request204or404(`/gists/${this.__id}/star`, null, cb);
}
/**
* List the gist's commits
* @see https://developer.github.com/v3/gists/#list-gist-commits
* @param {Requestable.callback} [cb] - will receive the array of commits
* @return {Promise} - the Promise for the http request
*/
listCommits(cb) {
return this._requestAllPages(`/gists/${this.__id}/commits`, null, cb);
}
/**
* Fetch one of the gist's revision.
* @see https://developer.github.com/v3/gists/#get-a-specific-revision-of-a-gist
* @param {string} revision - the id of the revision
* @param {Requestable.callback} [cb] - will receive the revision
* @return {Promise} - the Promise for the http request
*/
getRevision(revision, cb) {
return this._request('GET', `/gists/${this.__id}/${revision}`, null, cb);
}
/**
* List the gist's comments
* @see https://developer.github.com/v3/gists/comments/#list-comments-on-a-gist
* @param {Requestable.callback} [cb] - will receive the array of comments
* @return {Promise} - the promise for the http request
*/
listComments(cb) {
return this._requestAllPages(`/gists/${this.__id}/comments`, null, cb);
}
/**
* Fetch one of the gist's comments
* @see https://developer.github.com/v3/gists/comments/#get-a-single-comment
* @param {number} comment - the id of the comment
* @param {Requestable.callback} [cb] - will receive the comment
* @return {Promise} - the Promise for the http request
*/
getComment(comment, cb) {
return this._request('GET', `/gists/${this.__id}/comments/${comment}`, null, cb);
}
/**
* Comment on a gist
* @see https://developer.github.com/v3/gists/comments/#create-a-comment
* @param {string} comment - the comment to add
* @param {Requestable.callback} [cb] - the function that receives the API result
* @return {Promise} - the Promise for the http request
*/
createComment(comment, cb) {
return this._request('POST', `/gists/${this.__id}/comments`, {body: comment}, cb);
}
/**
* Edit a comment on the gist
* @see https://developer.github.com/v3/gists/comments/#edit-a-comment
* @param {number} comment - the id of the comment
* @param {string} body - the new comment
* @param {Requestable.callback} [cb] - will receive the modified comment
* @return {Promise} - the promise for the http request
*/
editComment(comment, body, cb) {
return this._request('PATCH', `/gists/${this.__id}/comments/${comment}`, {body: body}, cb);
}
/**
* Delete a comment on the gist.
* @see https://developer.github.com/v3/gists/comments/#delete-a-comment
* @param {number} comment - the id of the comment
* @param {Requestable.callback} [cb] - will receive true if the request succeeds
* @return {Promise} - the Promise for the http request
*/
deleteComment(comment, cb) {
return this._request('DELETE', `/gists/${this.__id}/comments/${comment}`, null, cb);
}
} |
JavaScript | class Context extends Component {
static propTypes = {
children: element.isRequired,
};
static childContextTypes = {
insertCss: func.isRequired,
};
getChildContext = () => ({
insertCss: (...insertedStyles) => {
// eslint-disable-next-line no-underscore-dangle
const removeCss = insertedStyles.map(x => x._insertCss());
return () => { removeCss.forEach(f => f()); };
},
});
render = () => this.props.children;
} |
JavaScript | class Fetcher {
constructor (exchangeSettings) {
this.exchangeSettings = exchangeSettings
// Twelve Data API
this.api = axios.create({
baseURL: 'https://api.twelvedata.com',
timeout: 10000
})
}
/**
* Get historical information from Alpha Vantage API
*
* @param {Object} exchangeParams Params dictionary object containing: 'symbol', 'interval' and 'outputsize'
*/
async getData (exchangeParams) {
let cacheFile = 'cachedData.json'
if (exchangeParams.interval === '1week') {
cacheFile = 'cachedDataWeekly.json'
}
if (fs.existsSync('./' + cacheFile) &&
this.exchangeSettings.use_cache) {
const data = fs.readFileSync('./' + cacheFile, 'utf8')
if (data) {
return Promise.resolve(JSON.parse(data))
} else {
return Promise.reject(new Error('Empty data in history file.'))
}
} else {
const params = {
symbol: exchangeParams.symbol,
interval: exchangeParams.interval,
outputsize: exchangeParams.outputsize,
order: 'ASC',
apikey: this.exchangeSettings.api_key
}
// Both data arrays should contain data bout OHLC and datetime
try {
const response = await this.api.get('/time_series', { params: params })
if (!Object.prototype.hasOwnProperty.call(response.data, 'values')) {
return Promise.reject(new Error('Missing values key in response. HTTP status code: ' + response.status + ' with text : ' + response.statusText + '. Reponse:\n' + JSON.stringify(response.data)))
}
return this.postProcessingTimeseries(response.data.values, cacheFile)
} catch (error) {
console.log(error)
throw new Error(error)
}
}
}
/**
* Helper function for processing index time-series
* @param {Array} timeseries Time-series candle data
* @param {String} cacheFile Filename store data to (if cache enabled)
*/
postProcessingTimeseries (timeseries, cacheFile) {
if (typeof (timeseries) === 'undefined' || timeseries === null || timeseries.length <= 0) {
return Promise.reject(new Error('Still invalid or empty data received from API'))
}
const series = timeseries.map(value =>
Candle.createIndex(
parseFloat(value.open), // Open
parseFloat(value.high), // High
parseFloat(value.low), // Low
parseFloat(value.close), // Close
new Date(value.datetime).getTime()) // Timestamp in ms since Epoch
)
if (series && this.exchangeSettings.use_cache) {
fs.writeFile('./' + cacheFile, JSON.stringify(series, null, 2), 'utf-8', (err) => {
if (err) throw err
})
}
return series
}
} |
JavaScript | class NamespaceId {
/**
* Create NamespaceId from namespace string name (ex: nem or domain.subdom.subdome)
* or id in form of array number (ex: [929036875, 2226345261])
*
* @param id
*/
constructor(id) {
if (id instanceof Array) {
this.id = new Id_1.Id(id);
}
else if (typeof id === 'string') {
this.fullName = id;
this.id = new Id_1.Id(NamespaceMosaicIdGenerator_1.NamespaceMosaicIdGenerator.namespaceId(id));
}
}
/**
* Create a NamespaceId object from its encoded hexadecimal notation.
* @param encoded
* @returns {NamespaceId}
*/
static createFromEncoded(encoded) {
const uint = format_1.Convert.hexToUint8(encoded).reverse();
const hex = format_1.Convert.uint8ToHex(uint);
const namespace = new NamespaceId(Id_1.Id.fromHex(hex).toDTO());
return namespace;
}
/**
* Get string value of id
* @returns {string}
*/
toHex() {
return this.id.toHex();
}
/**
* Compares namespaceIds for equality.
*
* @return boolean
*/
equals(id) {
if (id instanceof NamespaceId) {
return this.id.equals(id.id);
}
return false;
}
/**
* Create DTO object
*/
toDTO() {
return {
id: this.id.toDTO(),
fullName: this.fullName ? this.fullName : '',
};
}
} |
JavaScript | class Tracing {
constructor(channel) {
this._context = void 0;
this._sources = new Set();
this._instrumentationListener = void 0;
this._context = channel;
this._instrumentationListener = {
onApiCallBegin: (apiCall, stackTrace) => {
for (const frame of (stackTrace === null || stackTrace === void 0 ? void 0 : stackTrace.frames) || []) this._sources.add(frame.file);
}
};
}
async start(options = {}) {
if (options.sources) this._context._instrumentation.addListener(this._instrumentationListener);
await this._context._wrapApiCall(async channel => {
await channel.tracingStart(options);
await channel.tracingStartChunk({
title: options.title
});
});
}
async startChunk(options = {}) {
this._sources = new Set();
await this._context._wrapApiCall(async channel => {
await channel.tracingStartChunk(options);
});
}
async stopChunk(options = {}) {
await this._context._wrapApiCall(async channel => {
await this._doStopChunk(channel, options.path);
});
}
async stop(options = {}) {
await this._context._wrapApiCall(async channel => {
await this._doStopChunk(channel, options.path);
await channel.tracingStop();
});
}
async _doStopChunk(channel, filePath) {
const sources = this._sources;
this._sources = new Set();
this._context._instrumentation.removeListener(this._instrumentationListener);
const skipCompress = !this._context._connection.isRemote();
const result = await channel.tracingStopChunk({
save: !!filePath,
skipCompress
});
if (!filePath) {
// Not interested in artifacts.
return;
} // If we don't have anything locally and we run against remote Playwright, compress on remote side.
if (!skipCompress && !sources) {
const artifact = _artifact.Artifact.from(result.artifact);
await artifact.saveAs(filePath);
await artifact.delete();
return;
} // We either have sources to append or we were running locally, compress on client side
const promise = new _async.ManualPromise();
const zipFile = new _yazl.default.ZipFile();
zipFile.on('error', error => promise.reject(error)); // Add sources.
if (sources) {
for (const source of sources) {
try {
if (_fs.default.statSync(source).isFile()) zipFile.addFile(source, 'resources/src@' + (0, _utils.calculateSha1)(source) + '.txt');
} catch (e) {}
}
}
await _fs.default.promises.mkdir(_path.default.dirname(filePath), {
recursive: true
});
if (skipCompress) {
// Local scenario, compress the entries.
for (const entry of result.entries) zipFile.addFile(entry.value, entry.name);
zipFile.end(undefined, () => {
zipFile.outputStream.pipe(_fs.default.createWriteStream(filePath)).on('close', () => promise.resolve());
});
return promise;
} // Remote scenario, repack.
const artifact = _artifact.Artifact.from(result.artifact);
const tmpPath = filePath + '.tmp';
await artifact.saveAs(tmpPath);
await artifact.delete();
_yauzl.default.open(tmpPath, (err, inZipFile) => {
if (err) {
promise.reject(err);
return;
}
(0, _utils.assert)(inZipFile);
let pendingEntries = inZipFile.entryCount;
inZipFile.on('entry', entry => {
inZipFile.openReadStream(entry, (err, readStream) => {
if (err) {
promise.reject(err);
return;
}
zipFile.addReadStream(readStream, entry.fileName);
if (--pendingEntries === 0) {
zipFile.end(undefined, () => {
zipFile.outputStream.pipe(_fs.default.createWriteStream(filePath)).on('close', () => {
_fs.default.promises.unlink(tmpPath).then(() => {
promise.resolve();
});
});
});
}
});
});
});
return promise;
}
} |
JavaScript | class Gulp extends Undertaker {
constructor( registry ) {
super( registry );
// Bind the functions for destructuring
this.task = this.task.bind( this );
this.series = this.series.bind( this );
this.parallel = this.parallel.bind( this );
this.registry = this.registry.bind( this );
this.tree = this.tree.bind( this );
this.lastRun = this.lastRun.bind( this );
// Let people use these from our instance
this.Gulp = Gulp;
this.dest = vfs.dest;
this.src = vfs.src;
this.symlink = vfs.symlink;
this.pipeline = pump.pipeline;
this.pump = pump.pump;
}
// Modified to handle tasks that return arrays
task( taskName, fn ) {
if ( typeof taskName === "function" ) {
fn = taskName;
taskName = fn.displayName || fn.name;
}
if ( ! fn ) return this._getTask( taskName );
this._setTask( taskName, done => {
const job = fn( done );
return Array.isArray( job ) ? pump( job ) : job;
} );
}
// Wrapper for `vfs.src( globs, { read: false } )`
path( globs, opt ) {
if ( opt === null ) opt = {};
opt.read = false;
return vfs.src( globs, opt );
}
} |
JavaScript | class App extends Component {
constructor(props) {
super(props); //
this.state = {
videos: [], //array of videos
selectedVideo: null
}; //imidiately kicks off search
this.videoSearch('surfboards')
}
//pass callback method to earchbar and make new YTSearch, to set new state of videos
//refactored youtube search into own method, takes single string, based down to search bar,
//search bar will call
videoSearch(term) {
YTSearch({ key: API_KEY, term: term}, (videos) => {
this.setState({
videos: videos,
selectedVideo: videos [0]
}); //moved search within constructor
}); //if key and value is same string then can condense videos same as videos: videos
}
render() { //props in class component are available in any method we define as this.props
const videoSearch = _.debounce((term) => {this.videoSearch(term) }, 300);
//func now renders every 300 milisecs throttles the search.
return ( //components are child fo App, //passing videos as prop, props arrive to VideoList func as arguement
//props videos is passed to VideoList func as argument
<div>
<SearchBar onSearchTermChange={videoSearch} />
<VideoDetail video={this.state.selectedVideo} />
<VideoList
onVideoSelect={selectedVideo => this.setState({selectedVideo})}
videos={this.state.videos} />
</div>
);
}
} |
JavaScript | class About extends Component {
render() {
return (
<div className="container full-height-grow">
<header className="main-header">
<a href="" className="brand-logo">
<img className="logo-secondary" src={logo} alt="" />
</a>
<nav className="main-nav">
<ul>
<li className="nav-items secondary-nav">
<Link to={"/about"}>About</Link>
</li>
<li className="nav-items secondary-nav">
<Link to={"/login"}>Log In</Link>
</li>
</ul>
</nav>
</header>
<Footer/>
</div>
);
}
} |
JavaScript | class QuickSort{
/**
* @constructor constructor function of QuickSort class
* @param {array} inputArray [ input array ]
* @param {string} option [ "ASC/asc" or "DESC/desc" ]
*/
constructor(inputArray, option){
this.option = option.toLowerCase();
this.result = this.quickSort(inputArray, 0, inputArray.length - 1, option);
}
/**
* @method QuickSort.swapArrayByIndex
* @param {array} inputArray [ input array ]
* @param {number} from [ Swap from index value]
* @param {number} to [ Swap to index value]
* @return {array} Swaped array
*/
swapArrayByIndex(inputArray, from, to){
var swapTemp = inputArray[to];
inputArray[to] = inputArray[from];
inputArray[from] = swapTemp;
return inputArray;
}
/**
* @method QuickSort.partition
* @param {array} inputArray [ input array ]
* @param {number} lowestIndex [ Initial index value of the input array ]
* @param {number} highestIndex [ Lase index value of the input array ]
* @return {array} Sort array & index value
*/
partition(inputArray, lowestIndex, highestIndex){
//Taking array last value from the
var pivotValue = inputArray[highestIndex];
var i = lowestIndex - 1;
var result = {};
for (var j = 0; j <= highestIndex - 1; j++){
// If current element is smaller than or equal to pivot
if((inputArray[j] <= pivotValue && this.option === "asc") || (inputArray[j] >= pivotValue && this.option === "desc") ){
i++;
//Swap the array
inputArray = this.swapArrayByIndex(inputArray, i, j);
}
}
result.inputArray = this.swapArrayByIndex(inputArray, i+1, highestIndex);
result.index = i+1;
return result;
}
/**
* @method QuickSort.partition
* @description Main method holds all the logics
* @param {array} inputArray [ input array ]
* @param {number} lowestIndex [ Initial index value of the input array ]
* @param {number} highestIndex [ Lase index value of the input array ]
* @return {array} sorted array
*/
quickSort(inputArray, lowestIndex, highestIndex){
if(lowestIndex < highestIndex){
var partitionResult = this.partition(inputArray, 0, highestIndex);
this.quickSort(partitionResult.inputArray, lowestIndex, partitionResult.index - 1);//QuickSort Right
this.quickSort(partitionResult.inputArray, partitionResult.index + 1, highestIndex);//QuickSort Left
}
return partitionResult;
}
} |
JavaScript | class RegionMap extends React.Component {
mapRef = React.createRef();
state = {
// The map instance to use during cleanup
map: null,
};
getMap = () => {
const H = window.H;
const addCircleToMap = (map) => {
let circle = new H.map.Circle(
// The central point of the circle
// {lat:19.152240522253486, lng:72.95038723899198},
{
lat: 19.092172567483823,
lng: 72.9119350918738
},
// The radius of the circle in meters
25000, {
style: {
strokeColor: 'rgba(255,207,21,1)', // Color of the perimeter
lineWidth: 2,
fillColor: 'rgba(255,207,21,0.3)' // Color of the circle
}
}
);
circle.addEventListener('tap', (evt) => {
// get instance of circle via evt.target
let target = evt.target;
// set the map dimensions to bounding box of circle
map.getViewModel().setLookAtData({
bounds: target.getBoundingBox()
});
// this.setState({map: this.state.map, bbox: target.getBoundingBox()})
});
map.addObject(circle);
}
/*
* Boilerplate map initialization code starts below:
*/
//Step 1: initialize communication with the platform
// In your own code, replace variable window.apikey with your own apikey
var platform = new H.service.Platform({
apikey: process.env.REACT_APP_HERE_API
});
var defaultLayers = platform.createDefaultLayers();
//Step 2: initialize a map - this map is centered over Europe
var map = new H.Map(
this.mapRef.current,
defaultLayers.vector.normal.map, {
center: {
lat: 19.092172567483823,
lng: 72.9119350918738
},
zoom: 10.5,
pixelRatio: window.devicePixelRatio || 1
});
// add a resize listener to make sure that the map occupies the whole container
window.addEventListener('resize', () => {
map.getViewPort().resize();
// console.log("map resize")
});
// onResize(this.mapRef.current, () => map.getViewPort().resize());
//Step 3: make the map interactive
// MapEvents enables the event system
// Behavior implements default interactions for pan/zoom (also on mobile touch environments)
var behavior = new H.mapevents.Behavior(new H.mapevents.MapEvents(map), {
enabled: H.mapevents.Behavior.DRAGGING | H.mapevents.Behavior.DBLTAPZOOM
});
// Create the default UI components
var ui = H.ui.UI.createDefault(map, defaultLayers);
addCircleToMap(map);
this.setState({
map: map,
})
}
componentDidMount() {
try {
this.getMap()
} catch (error) {
console.log(error)
this.getMap()
}
}
componentWillUnmount() {
// Cleanup after the map to avoid memory leaks when this component exits the page
if (this.state.map) this.state.map.dispose();
}
render() {
return (
// Set a height on the map so it will display
<div id='region-map' ref={this.mapRef} />
);
}
} |
JavaScript | class ASTDataContainer {
/**
*
* @param {Object} ast
*/
constructor(ast) {
this.value = ast;
}
cloneValue() {
return espurify(this.value);
}
transform(transformFn) {
const result = transformFn(this.value);
if (result == null) {
throw new Error("transform function should not return null");
}
this.value = result;
}
/**
* @param transformFn
* @param {ASTSourceOptions} options
*/
transformStrict(transformFn, options) {
var AST = healingAST(this.value, options);
var result = transformFn(AST);
assert(result != null && typeof result === "object", "transform function should not return null");
this.value = result;
}
} |
JavaScript | class MapRenderer extends CanvasRenderer {
/**
* Constructor.
*/
constructor() {
super();
this.selector = getMapCanvas;
this.title = 'Map';
}
/**
* @inheritDoc
*/
beforeOverlay() {
var mapContainer = MapContainer.getInstance();
if (mapContainer.is3DEnabled()) {
var webGL = mapContainer.getWebGLRenderer();
if (webGL) {
webGL.renderSync();
}
} else {
var olMap = mapContainer.getMap();
if (olMap) {
olMap.renderSync();
}
}
}
/**
* @inheritDoc
*/
getHeight() {
var mapCanvas = this.getRenderElement();
return mapCanvas ? mapCanvas.height : 0;
}
/**
* @inheritDoc
*/
getWidth() {
var mapCanvas = this.getRenderElement();
return mapCanvas ? mapCanvas.width : 0;
}
/**
* @inheritDoc
*/
getFill() {
return /** @type {string} */ (Settings.getInstance().get(['bgColor'], '#000'));
}
} |
JavaScript | class Texture {
constructor(settings) {
const {
texture,
size,
dimensions,
output,
context,
type = 'NumberTexture',
kernel,
internalFormat,
textureFormat
} = settings;
if (!output) throw new Error('settings property "output" required.');
if (!context) throw new Error('settings property "context" required.');
this.texture = texture;
this.size = size;
this.dimensions = dimensions;
this.output = output;
this.context = context;
/**
* @type {Kernel}
*/
this.kernel = kernel;
this.type = type;
this._deleted = false;
this.internalFormat = internalFormat;
this.textureFormat = textureFormat;
}
/**
* @desc Converts the Texture into a JavaScript Array
* @returns {TextureArrayOutput}
*/
toArray() {
throw new Error(`Not implemented on ${this.constructor.name}`);
}
/**
* @desc Clones the Texture
* @returns {Texture}
*/
clone() {
throw new Error(`Not implemented on ${this.constructor.name}`);
}
/**
* @desc Deletes the Texture
*/
delete() {
this._deleted = true;
return this.context.deleteTexture(this.texture);
}
} |
JavaScript | class CollectionResponse extends AbstractResponse {
/**
* @param {function} modelClass
* @param {RawResponse} rawResponse
* @abstract
*/
constructor(modelClass, rawResponse)
{
super(modelClass, rawResponse);
this._assertNotInstanceOfAbstract(CollectionResponse);
/**
* Array of results, instantiated with their model class
*/
this._results = rawResponse.results.map(function(result){
return new modelClass(result);
});
/**
* The pagination data for the response
* @member {PagerData} _pager
* @private
*/
this._pager = raw.body && raw.body.pager ? new PagerData(raw.body.pager) : null;
}
/**
* The results from the API
* @returns {Object[]}
*/
get results(){
throw new Error('Accessor "results" not implemented by '+this.className);
}
/**
* The pagination data for the response
* @returns {PagerData}
*/
get pager(){
return this._pager;
}
} |
JavaScript | class StorjModule {
getStorjLibNativeModule(){
return storjLib;
}
/**
* Generate mnemonic
* @returns {Promise<boolean>}
*/
async generateMnemonic() {
try {
let response = await storjLib.generateMnemonic();
if(!response.isSuccess){
console.log('generateMnemonic ', response.error.message);
}
return response;
} catch(e) {
console.log(e);
}
}
/**
* Check if mnemonic provided has valid format
* @param {string} mnemonic
* @returns {Promise<boolean>}
*/
async checkMnemonic(mnemonic) {
let response = await storjLib.checkMnemonic(mnemonic);
if(!response.isSuccess){
console.log('checkMnemonic ', response.error.message);
}
return response.isSuccess;
};
/**
* Send new registration request
* @param {string} email
* @param {string} password
* @param {function} sucessCallback Callback that is called on Success, returns email address from the request
* @param {function} errorCallback Callback for error handeling, returns error message
*/
async register(email, password, errorCallback) {
let response = await storjLib.register(email, password);
if(!response.isSuccess){
console.log('register ', response.error.message);
}
return response;
};
/**
* Verify if user exist in storj network
* @param {string} email
* @param {string} password
* @returns {Promise<boolean>}
*/
async verifyKeys(email, password) {
let response = await storjLib.verifyKeys(email, password);
if(!response.isSuccess){
console.log('verifyKeys ', response.error.message);
}
return response;
};
/**
* Check if auth file allready exist on the device
* @returns {Promise<boolean>}
*/
async keysExists() {
let response = await storjLib.keysExists();
if(!response.isSuccess){
console.log('keysExists ', response.error.message);
}
return response.isSuccess;
};
/**
* Creates new auth file for given credentials and stores it on the device
* and saves them in the current context
* @param {string} email
* @param {string} password
* @param {string} mnemonic
* @param {string} passcode optional, pass if you want to protect auth file with additional password
* @returns {Promise<boolean>}
*/
async importKeys(email, password, mnemonic, passcode) {
let response = await storjLib.importKeys(email, password, mnemonic, passcode);
if(!response.isSuccess){
console.log('importKeys ', response.error.message);
}
return response.isSuccess;
};
/**
* Delete auth file
* @returns {Promise<boolean>}
*/
async deleteKeys() {
let response = await storjLib.deleteKeys();
if(!response.isSuccess){
console.log('deleteKeys', response.error.message);
}
return response.isSuccess;
};
/**
*
* @param {string} passcode needed if user has protected your auth file with additional password
*/
async getKeys(passcode) {
let response = await storjLib.getKeys(passcode);
if(!response.isSuccess) {
console.log('getKeys ', response.error.message);
}
return response;
};
/**
* List buckets for logged in user
* @returns {Promise<BucketModel[]>}
*/
async getBuckets() {
let result = [];
let response = await storjLib.getBuckets();
if(!response.isSuccess) {
console.log('getBuckets ', response.error.message);
return result;
}
result = JSON.parse(response.result).map((bucket) => {
return new BucketModel(bucket);
});
return result;
}
/**
* Deletes bucket by Id
* @param {string} bucketId
*/
async deleteBucket(bucketId) {
return await storjLib.deleteBucket(bucketId);
}
/**
* download file to storj network
* @returns {Promise<any>}
*/
async downloadFile(bucketId, fileId, localPath) {
let response = await storjLib.downloadFile(bucketId, fileId, localPath);
if(!response.isSuccess) {
console.log('downloadFile ', response);
}
return response;
}
/**
* cancel file downloading
* @returns {Promise<any>}
*/
async cancelDownload(fileRef) {
let response = await storjLib.cancelDownload(fileRef);
if(!response.isSuccess) {
console.log('cancelDownload ', response.error.message);
}
return response;
}
/**
* cancel file uploading
* @returns {Promise<any>}
*/
async cancelUpload(fileRef) {
let response = await storjLib.cancelUpload(fileRef);
if(!response.isSuccess) {
console.log('cancelUpload ', response.error.message);
}
return response;
}
/**
* download file to storj network
* @returns {Promise<any>}
*/
async uploadFile(bucketId, localPath) {
let response = await storjLib.uploadFile(bucketId, localPath);
if(response.isSuccess) {
response.result = new FileModel(JSON.parse(response.result));
} else {
console.log('uploadFile ', response.error.message);
}
return response;
};
/**
* List buckets for logged in user
* @returns {Promise<FileModel[]>}
*/
async listFiles(bucketId) {
let response = await storjLib.listFiles(bucketId);
if(response.isSuccess) {
response.result = JSON.parse(response.result).map(file => {
return new FileModel(file);
});
} else {
console.log('listFiles ', response.error.message);
}
return response;
};
/**
* Create bucket
* @returns {Promise<BucketModel>}
*/
async createBucket(bucketName) {
let response = await storjLib.createBucket(bucketName);
if(response.isSuccess) {
response.result = new BucketModel(JSON.parse(response.result));
} else {
console.log('createBucket ', response.error.message);
}
return response;
};
async getDownloadFolderPath(){
let response = await storjLib.getDownloadFolderPath();
if(!response.isSuccess){
console.log("getDownloadFolderPath ", response.error.message);
}
return response.result;
}
/**
*
* @param {string} bucketId
* @param {string} fileId
*/
async deleteFile(bucketId, fileId) {
let response = await storjLib.deleteFile(bucketId, fileId);
if(!response.isSuccess) {
console.log('deleteFile ', response.error.message);
}
return response;
}
} |
JavaScript | class Schema {
/**
* Creates an instance of Schema.
*
* @param {Object<Field>} _fields Object containing Field definitions.
* @memberof Schema
*/
constructor(_fields) {
this._fields = _fields
}
/**
* Validates Document Data agains Fields.
*
* @param {Object} [data={}]
* @param {Object<Field>} [fields=this._fields]
* @returns Validated Document Data.
* @memberof Schema
*/
async validate(data = {}, fields = this._fields) {
const filteredData = {}
await asyncForEach(
Object.entries(fields),
async ([key, field]) => {
const filteredFieldData = await field.validate(data[key])
if (filteredFieldData !== field._OptionalSymbol)
filteredData[key] = filteredFieldData
}
)
return filteredData
}
/**
* Validates Document Data against selected Fields.
*
* @param {Object} [data={}] Document Data
* @param {Set} [changedKeys=new Set()] Set with Paths of changed Fields.
* @returns Valdiated Document Data.
* @memberof Schema
*/
async validateSelected(data = {}, changedKeys = new Set()) {
const selectedFields = {}
for (let key of changedKeys.keys()) {
key = key.split('.')[0]
selectedFields[key] = this._fields[key]
}
return {
...data,
...await this.validate(data, selectedFields)
}
}
} |
JavaScript | class NoFilter extends stream.Transform {
/**
* Create an instance of NoFilter.
*
* @param {string|Buffer|BufferEncoding|NoFilterOptions} [input] Source data.
* @param {BufferEncoding|NoFilterOptions} [inputEncoding] Encoding
* name for input, ignored if input is not a String.
* @param {NoFilterOptions} [options] Other options.
*/
constructor(input, inputEncoding, options = {}) {
let inp = null
let inpE = /** @type {BufferEncoding?} */ (null)
switch (typeof input) {
case 'object':
if (Buffer.isBuffer(input)) {
inp = input
} else if (input) {
options = input
}
break
case 'string':
inp = input
break
case 'undefined':
break
default:
throw new TypeError('Invalid input')
}
switch (typeof inputEncoding) {
case 'object':
if (inputEncoding) {
options = inputEncoding
}
break
case 'string':
inpE = /** @type {BufferEncoding} */ (inputEncoding)
break
case 'undefined':
break
default:
throw new TypeError('Invalid inputEncoding')
}
if (!options || typeof options !== 'object') {
throw new TypeError('Invalid options')
}
if (inp == null) {
inp = options.input
}
if (inpE == null) {
inpE = options.inputEncoding
}
delete options.input
delete options.inputEncoding
const watchPipe = options.watchPipe == null ? true : options.watchPipe
delete options.watchPipe
const readError = Boolean(options.readError)
delete options.readError
super(options)
this.readError = readError
if (watchPipe) {
this.on('pipe', readable => {
// @ts-ignore: TS2339 (using internal interface)
const om = readable._readableState.objectMode
// @ts-ignore: TS2339 (using internal interface)
if ((this.length > 0) && (om !== this._readableState.objectMode)) {
throw new Error(
'Do not switch objectMode in the middle of the stream'
)
}
// @ts-ignore: TS2339 (using internal interface)
this._readableState.objectMode = om
// @ts-ignore: TS2339 (using internal interface)
this._writableState.objectMode = om
})
}
if (inp != null) {
this.end(inp, inpE)
}
}
/**
* Is the given object a {NoFilter}?
*
* @param {object} obj The object to test.
* @returns {boolean} True if obj is a NoFilter.
*/
static isNoFilter(obj) {
return obj instanceof this
}
/**
* The same as nf1.compare(nf2). Useful for sorting an Array of NoFilters.
*
* @param {NoFilter} nf1 The first object to compare.
* @param {NoFilter} nf2 The second object to compare.
* @returns {number} -1, 0, 1 for less, equal, greater.
* @throws {TypeError} Arguments not NoFilter instances.
* @example
* const arr = [new NoFilter('1234'), new NoFilter('0123')]
* arr.sort(NoFilter.compare)
*/
static compare(nf1, nf2) {
if (!(nf1 instanceof this)) {
throw new TypeError('Arguments must be NoFilters')
}
if (nf1 === nf2) {
return 0
}
return nf1.compare(nf2)
}
/**
* Returns a buffer which is the result of concatenating all the
* NoFilters in the list together. If the list has no items, or if
* the totalLength is 0, then it returns a zero-length buffer.
*
* If length is not provided, it is read from the buffers in the
* list. However, this adds an additional loop to the function, so
* it is faster to provide the length explicitly if you already know it.
*
* @param {Array<NoFilter>} list Inputs. Must not be all either in object
* mode, or all not in object mode.
* @param {number} [length=null] Number of bytes or objects to read.
* @returns {Buffer|Array} The concatenated values as an array if in object
* mode, otherwise a Buffer.
* @throws {TypeError} List not array of NoFilters.
*/
static concat(list, length) {
if (!Array.isArray(list)) {
throw new TypeError('list argument must be an Array of NoFilters')
}
if ((list.length === 0) || (length === 0)) {
return Buffer.alloc(0)
}
if ((length == null)) {
length = list.reduce((tot, nf) => {
if (!(nf instanceof NoFilter)) {
throw new TypeError('list argument must be an Array of NoFilters')
}
return tot + nf.length
}, 0)
}
let allBufs = true
let allObjs = true
const bufs = list.map(nf => {
if (!(nf instanceof NoFilter)) {
throw new TypeError('list argument must be an Array of NoFilters')
}
const buf = nf.slice()
if (Buffer.isBuffer(buf)) {
allObjs = false
} else {
allBufs = false
}
return buf
})
if (allBufs) {
// @ts-ignore: TS2322, tsc can't see the type checking above
return Buffer.concat(bufs, length)
}
if (allObjs) {
return [].concat(...bufs).slice(0, length)
}
// TODO: maybe coalesce buffers, counting bytes, and flatten in arrays
// counting objects? I can't imagine why that would be useful.
throw new Error('Concatenating mixed object and byte streams not supported')
}
/**
* @ignore
*/
_transform(chunk, encoding, callback) {
// @ts-ignore: TS2339 (using internal interface)
if (!this._readableState.objectMode && !Buffer.isBuffer(chunk)) {
chunk = Buffer.from(chunk, encoding)
}
this.push(chunk)
callback()
}
/**
* @returns {Buffer[]} The current internal buffers. They are layed out
* end to end.
* @ignore
*/
_bufArray() {
// @ts-ignore: TS2339 (using internal interface)
let bufs = this._readableState.buffer
// HACK: replace with something else one day. This is what I get for
// relying on internals.
if (!Array.isArray(bufs)) {
let b = bufs.head
bufs = []
while (b != null) {
bufs.push(b.data)
b = b.next
}
}
return bufs
}
/**
* Pulls some data out of the internal buffer and returns it.
* If there is no data available, then it will return null.
*
* If you pass in a size argument, then it will return that many bytes. If
* size bytes are not available, then it will return null, unless we've
* ended, in which case it will return the data remaining in the buffer.
*
* If you do not specify a size argument, then it will return all the data in
* the internal buffer.
*
* @param {number} [size=null] Number of bytes to read.
* @returns {string|Buffer|null} If no data or not enough data, null. If
* decoding output a string, otherwise a Buffer.
* @throws Error If readError is true and there was underflow.
* @fires NoFilter#read When read from.
*/
read(size) {
const buf = super.read(size)
if (buf != null) {
/**
* Read event. Fired whenever anything is read from the stream.
*
* @event NoFilter#read
* @param {Buffer|string|object} buf What was read.
*/
this.emit('read', buf)
if (this.readError && (buf.length < size)) {
throw new Error(`Read ${buf.length}, wanted ${size}`)
}
} else if (this.readError) {
throw new Error(`No data available, wanted ${size}`)
}
return buf
}
/**
* Return a promise fulfilled with the full contents, after the 'finish'
* event fires. Errors on the stream cause the promise to be rejected.
*
* @param {Function} [cb=null] Finished/error callback used in *addition*
* to the promise.
* @returns {Promise<Buffer|string>} Fulfilled when complete.
*/
promise(cb) {
let done = false
return new Promise((resolve, reject) => {
this.on('finish', () => {
const data = this.read()
if ((cb != null) && !done) {
done = true
cb(null, data)
}
resolve(data)
})
this.on('error', er => {
if ((cb != null) && !done) {
done = true
cb(er)
}
reject(er)
})
})
}
/**
* Returns a number indicating whether this comes before or after or is the
* same as the other NoFilter in sort order.
*
* @param {NoFilter} other The other object to compare.
* @returns {number} -1, 0, 1 for less, equal, greater.
* @throws {TypeError} Arguments must be NoFilters.
*/
compare(other) {
if (!(other instanceof NoFilter)) {
throw new TypeError('Arguments must be NoFilters')
}
if (this === other) {
return 0
}
const buf1 = this.slice()
const buf2 = other.slice()
// These will both be buffers because of the check above.
if (Buffer.isBuffer(buf1) && Buffer.isBuffer(buf2)) {
return buf1.compare(buf2)
}
throw new Error('Cannot compare streams in object mode')
}
/**
* Do these NoFilter's contain the same bytes? Doesn't work if either is
* in object mode.
*
* @param {NoFilter} other Other NoFilter to compare against.
* @returns {boolean} Equal?
*/
equals(other) {
return this.compare(other) === 0
}
/**
* Read bytes or objects without consuming them. Useful for diagnostics.
* Note: as a side-effect, concatenates multiple writes together into what
* looks like a single write, so that this concat doesn't have to happen
* multiple times when you're futzing with the same NoFilter.
*
* @param {number} [start=0] Beginning offset.
* @param {number} [end=length] Ending offset.
* @returns {Buffer|Array} If in object mode, an array of objects. Otherwise,
* concatenated array of contents.
*/
slice(start, end) {
// @ts-ignore: TS2339 (using internal interface)
if (this._readableState.objectMode) {
return this._bufArray().slice(start, end)
}
const bufs = this._bufArray()
switch (bufs.length) {
case 0: return Buffer.alloc(0)
case 1: return bufs[0].slice(start, end)
default: {
const b = Buffer.concat(bufs)
// TODO: store the concatented bufs back
// @_readableState.buffer = [b]
return b.slice(start, end)
}
}
}
/**
* Get a byte by offset. I didn't want to get into metaprogramming
* to give you the `NoFilter[0]` syntax.
*
* @param {number} index The byte to retrieve.
* @returns {number} 0-255.
*/
get(index) {
return this.slice()[index]
}
/**
* Return an object compatible with Buffer's toJSON implementation, so that
* round-tripping will produce a Buffer.
*
* @returns {string|Array|{type: 'Buffer',data: number[]}} If in object mode,
* the objects. Otherwise, JSON text.
* @example <caption>output for 'foo', not in object mode</caption>
* ({
* type: 'Buffer',
* data: [102, 111, 111],
* })
*/
toJSON() {
const b = this.slice()
if (Buffer.isBuffer(b)) {
return b.toJSON()
}
return b
}
/**
* Decodes and returns a string from buffer data encoded using the specified
* character set encoding. If encoding is undefined or null, then encoding
* defaults to 'utf8'. The start and end parameters default to 0 and
* NoFilter.length when undefined.
*
* @param {BufferEncoding} [encoding='utf8'] Which to use for decoding?
* @param {number} [start=0] Start offset.
* @param {number} [end=length] End offset.
* @returns {string} String version of the contents.
*/
toString(encoding, start, end) {
const buf = this.slice(start, end)
if (!Buffer.isBuffer(buf)) {
return JSON.stringify(buf)
}
if (!encoding || (encoding === 'utf8')) {
return td.decode(buf)
}
return buf.toString(encoding)
}
/**
* @ignore
*/
[Symbol.for('nodejs.util.inspect.custom')](depth, options) {
const bufs = this._bufArray()
const hex = bufs.map(b => {
if (Buffer.isBuffer(b)) {
return options.stylize(b.toString('hex'), 'string')
}
return JSON.stringify(b)
}).join(', ')
return `${this.constructor.name} [${hex}]`
}
/**
* Current readable length, in bytes.
*
* @returns {number} Length of the contents.
*/
get length() {
// @ts-ignore: TS2339 (using internal interface)
return this._readableState.length
}
/**
* Write a JavaScript BigInt to the stream. Negative numbers will be
* written as their 2's complement version.
*
* @param {bigint} val The value to write.
* @returns {boolean} True on success.
*/
writeBigInt(val) {
let str = val.toString(16)
if (val < 0) {
// Two's complement
// Note: str always starts with '-' here.
const sz = BigInt(Math.floor(str.length / 2))
const mask = BigInt(1) << (sz * BigInt(8))
val = mask + val
str = val.toString(16)
}
if (str.length % 2) {
str = `0${str}`
}
return this.push(Buffer.from(str, 'hex'))
}
/**
* Read a variable-sized JavaScript unsigned BigInt from the stream.
*
* @param {number} [len=null] Number of bytes to read or all remaining
* if null.
* @returns {bigint} A BigInt.
*/
readUBigInt(len) {
const b = this.read(len)
if (!Buffer.isBuffer(b)) {
return null
}
return BigInt(`0x${b.toString('hex')}`)
}
/**
* Read a variable-sized JavaScript signed BigInt from the stream in 2's
* complement format.
*
* @param {number} [len=null] Number of bytes to read or all remaining
* if null.
* @returns {bigint} A BigInt.
*/
readBigInt(len) {
const b = this.read(len)
if (!Buffer.isBuffer(b)) {
return null
}
let ret = BigInt(`0x${b.toString('hex')}`)
// Negative?
if (b[0] & 0x80) {
// Two's complement
const mask = BigInt(1) << (BigInt(b.length) * BigInt(8))
ret -= mask
}
return ret
}
/**
* Write an 8-bit unsigned integer to the stream. Adds 1 byte.
*
* @param {number} value 0..255.
* @returns {boolean} True on success.
*/
writeUInt8(value) {
const b = Buffer.from([value])
return this.push(b)
}
/**
* Write a little-endian 16-bit unsigned integer to the stream. Adds
* 2 bytes.
*
* @param {number} value 0..65535.
* @returns {boolean} True on success.
*/
writeUInt16LE(value) {
const b = Buffer.alloc(2)
b.writeUInt16LE(value)
return this.push(b)
}
/**
* Write a big-endian 16-bit unsigned integer to the stream. Adds
* 2 bytes.
*
* @param {number} value 0..65535.
* @returns {boolean} True on success.
*/
writeUInt16BE(value) {
const b = Buffer.alloc(2)
b.writeUInt16BE(value)
return this.push(b)
}
/**
* Write a little-endian 32-bit unsigned integer to the stream. Adds
* 4 bytes.
*
* @param {number} value 0..2**32-1.
* @returns {boolean} True on success.
*/
writeUInt32LE(value) {
const b = Buffer.alloc(4)
b.writeUInt32LE(value)
return this.push(b)
}
/**
* Write a big-endian 32-bit unsigned integer to the stream. Adds
* 4 bytes.
*
* @param {number} value 0..2**32-1.
* @returns {boolean} True on success.
*/
writeUInt32BE(value) {
const b = Buffer.alloc(4)
b.writeUInt32BE(value)
return this.push(b)
}
/**
* Write a signed 8-bit integer to the stream. Adds 1 byte.
*
* @param {number} value (-128)..127.
* @returns {boolean} True on success.
*/
writeInt8(value) {
const b = Buffer.from([value])
return this.push(b)
}
/**
* Write a signed little-endian 16-bit integer to the stream. Adds 2 bytes.
*
* @param {number} value (-32768)..32767.
* @returns {boolean} True on success.
*/
writeInt16LE(value) {
const b = Buffer.alloc(2)
b.writeUInt16LE(value)
return this.push(b)
}
/**
* Write a signed big-endian 16-bit integer to the stream. Adds 2 bytes.
*
* @param {number} value (-32768)..32767.
* @returns {boolean} True on success.
*/
writeInt16BE(value) {
const b = Buffer.alloc(2)
b.writeUInt16BE(value)
return this.push(b)
}
/**
* Write a signed little-endian 32-bit integer to the stream. Adds 4 bytes.
*
* @param {number} value (-2**31)..(2**31-1).
* @returns {boolean} True on success.
*/
writeInt32LE(value) {
const b = Buffer.alloc(4)
b.writeUInt32LE(value)
return this.push(b)
}
/**
* Write a signed big-endian 32-bit integer to the stream. Adds 4 bytes.
*
* @param {number} value (-2**31)..(2**31-1).
* @returns {boolean} True on success.
*/
writeInt32BE(value) {
const b = Buffer.alloc(4)
b.writeUInt32BE(value)
return this.push(b)
}
/**
* Write a little-endian 32-bit float to the stream. Adds 4 bytes.
*
* @param {number} value 32-bit float.
* @returns {boolean} True on success.
*/
writeFloatLE(value) {
const b = Buffer.alloc(4)
b.writeFloatLE(value)
return this.push(b)
}
/**
* Write a big-endian 32-bit float to the stream. Adds 4 bytes.
*
* @param {number} value 32-bit float.
* @returns {boolean} True on success.
*/
writeFloatBE(value) {
const b = Buffer.alloc(4)
b.writeFloatBE(value)
return this.push(b)
}
/**
* Write a little-endian 64-bit double to the stream. Adds 8 bytes.
*
* @param {number} value 64-bit float.
* @returns {boolean} True on success.
*/
writeDoubleLE(value) {
const b = Buffer.alloc(8)
b.writeDoubleLE(value)
return this.push(b)
}
/**
* Write a big-endian 64-bit float to the stream. Adds 8 bytes.
*
* @param {number} value 64-bit float.
* @returns {boolean} True on success.
*/
writeDoubleBE(value) {
const b = Buffer.alloc(8)
b.writeDoubleBE(value)
return this.push(b)
}
/**
* Write a signed little-endian 64-bit BigInt to the stream. Adds 8 bytes.
*
* @param {bigint} value BigInt.
* @returns {boolean} True on success.
*/
writeBigInt64LE(value) {
const b = Buffer.alloc(8)
b.writeBigInt64LE(value)
return this.push(b)
}
/**
* Write a signed big-endian 64-bit BigInt to the stream. Adds 8 bytes.
*
* @param {bigint} value BigInt.
* @returns {boolean} True on success.
*/
writeBigInt64BE(value) {
const b = Buffer.alloc(8)
b.writeBigInt64BE(value)
return this.push(b)
}
/**
* Write an unsigned little-endian 64-bit BigInt to the stream. Adds 8 bytes.
*
* @param {bigint} value Non-negative BigInt.
* @returns {boolean} True on success.
*/
writeBigUInt64LE(value) {
const b = Buffer.alloc(8)
b.writeBigUInt64LE(value)
return this.push(b)
}
/**
* Write an unsigned big-endian 64-bit BigInt to the stream. Adds 8 bytes.
*
* @param {bigint} value Non-negative BigInt.
* @returns {boolean} True on success.
*/
writeBigUInt64BE(value) {
const b = Buffer.alloc(8)
b.writeBigUInt64BE(value)
return this.push(b)
}
/**
* Read an unsigned 8-bit integer from the stream. Consumes 1 byte.
*
* @returns {number} Value read.
*/
readUInt8() {
const b = this.read(1)
if (!Buffer.isBuffer(b)) {
return null
}
return b.readUInt8()
}
/**
* Read a little-endian unsigned 16-bit integer from the stream.
* Consumes 2 bytes.
*
* @returns {number} Value read.
*/
readUInt16LE() {
const b = this.read(2)
if (!Buffer.isBuffer(b)) {
return null
}
return b.readUInt16LE()
}
/**
* Read a little-endian unsigned 16-bit integer from the stream.
* Consumes 2 bytes.
*
* @returns {number} Value read.
*/
readUInt16BE() {
const b = this.read(2)
if (!Buffer.isBuffer(b)) {
return null
}
return b.readUInt16BE()
}
/**
* Read a little-endian unsigned 32-bit integer from the stream.
* Consumes 4 bytes.
*
* @returns {number} Value read.
*/
readUInt32LE() {
const b = this.read(4)
if (!Buffer.isBuffer(b)) {
return null
}
return b.readUInt32LE()
}
/**
* Read a little-endian unsigned 16-bit integer from the stream.
* Consumes 4 bytes.
*
* @returns {number} Value read.
*/
readUInt32BE() {
const b = this.read(4)
if (!Buffer.isBuffer(b)) {
return null
}
return b.readUInt32BE()
}
/**
* Read a signed 8-bit integer from the stream. Consumes 1 byte.
*
* @returns {number} Value read.
*/
readInt8() {
const b = this.read(1)
if (!Buffer.isBuffer(b)) {
return null
}
return b.readInt8()
}
/**
* Read a little-endian signed 16-bit integer from the stream.
* Consumes 2 bytes.
*
* @returns {number} Value read.
*/
readInt16LE() {
const b = this.read(2)
if (!Buffer.isBuffer(b)) {
return null
}
return b.readInt16LE()
}
/**
* Read a little-endian signed 16-bit integer from the stream.
* Consumes 2 bytes.
*
* @returns {number} Value read.
*/
readInt16BE() {
const b = this.read(2)
if (!Buffer.isBuffer(b)) {
return null
}
return b.readInt16BE()
}
/**
* Read a little-endian signed 32-bit integer from the stream.
* Consumes 4 bytes.
*
* @returns {number} Value read.
*/
readInt32LE() {
const b = this.read(4)
if (!Buffer.isBuffer(b)) {
return null
}
return b.readInt32LE()
}
/**
* Read a little-endian signed 16-bit integer from the stream.
* Consumes 4 bytes.
*
* @returns {number} Value read.
*/
readInt32BE() {
const b = this.read(4)
if (!Buffer.isBuffer(b)) {
return null
}
return b.readInt32BE()
}
/**
* Read a 32-bit little-endian float from the stream.
* Consumes 4 bytes.
*
* @returns {number} Value read.
*/
readFloatLE() {
const b = this.read(4)
if (!Buffer.isBuffer(b)) {
return null
}
return b.readFloatLE()
}
/**
* Read a 32-bit big-endian float from the stream.
* Consumes 4 bytes.
*
* @returns {number} Value read.
*/
readFloatBE() {
const b = this.read(4)
if (!Buffer.isBuffer(b)) {
return null
}
return b.readFloatBE()
}
/**
* Read a 64-bit little-endian float from the stream.
* Consumes 8 bytes.
*
* @returns {number} Value read.
*/
readDoubleLE() {
const b = this.read(8)
if (!Buffer.isBuffer(b)) {
return null
}
return b.readDoubleLE()
}
/**
* Read a 64-bit big-endian float from the stream.
* Consumes 8 bytes.
*
* @returns {number} Value read.
*/
readDoubleBE() {
const b = this.read(8)
if (!Buffer.isBuffer(b)) {
return null
}
return b.readDoubleBE()
}
/**
* Read a signed 64-bit little-endian BigInt from the stream.
* Consumes 8 bytes.
*
* @returns {bigint} Value read.
*/
readBigInt64LE() {
const b = this.read(8)
if (!Buffer.isBuffer(b)) {
return null
}
return b.readBigInt64LE()
}
/**
* Read a signed 64-bit big-endian BigInt from the stream.
* Consumes 8 bytes.
*
* @returns {bigint} Value read.
*/
readBigInt64BE() {
const b = this.read(8)
if (!Buffer.isBuffer(b)) {
return null
}
return b.readBigInt64BE()
}
/**
* Read an unsigned 64-bit little-endian BigInt from the stream.
* Consumes 8 bytes.
*
* @returns {bigint} Value read.
*/
readBigUInt64LE() {
const b = this.read(8)
if (!Buffer.isBuffer(b)) {
return null
}
return b.readBigUInt64LE()
}
/**
* Read an unsigned 64-bit big-endian BigInt from the stream.
* Consumes 8 bytes.
*
* @returns {bigint} Value read.
*/
readBigUInt64BE() {
const b = this.read(8)
if (!Buffer.isBuffer(b)) {
return null
}
return b.readBigUInt64BE()
}
} |
JavaScript | class Reference {
/**
* @constructor
* @param {String} type - the Reference type constant (e.g., REFERENCE_CHILD_OF or REFERENCE_FOLLOWS_FROM
* @param {SpanContext|Span} referencedContext - the SpanContext being referred to.
* As a convenience, a Span instance may be passed in instead (in which case its .context() is used here)
* @returns {Reference}
*/
constructor (type, referencedContext) {
assert([REFERENCE_CHILD_OF, REFERENCE_FOLLOWS_FROM].includes(type), 'Invalid type')
assert(
referencedContext instanceof Span || referencedContext instanceof SpanContext,
'referencedContext must have a type Span or SpanContext'
)
this._type = type
this._referencedContext = referencedContext instanceof Span ?
referencedContext.context() :
referencedContext
}
/**
* @method referencedContext
* @return {SpanContext} referencedContext
*/
referencedContext () {
return this._referencedContext
}
/**
* @method type
* @return {String} type
*/
type () {
return this._type
}
} |
JavaScript | class Tracker {
/**
* @private
*/
constructor(options) {
const opts = {
interpolate: true,
...options,
};
/**
* Pixel ratio to use to draw the canvas. Default to window.devicePixelRatio
* @type {Array<trajectory>}
*/
this.pixelRatio = options.pixelRatio || window.devicePixelRatio || 1;
/**
* Array of trajectories.
* @type {Array<trajectory>}
*/
this.trajectories = [];
/**
* Array of trajectories that are currently drawn.
* @type {Array<key>}
*/
this.renderedTrajectories = [];
/**
* Active interpolation calculation or not. If false, the train will not move until we receive the next message for the websocket.
* @type {boolean}
*/
this.interpolate = !!opts.interpolate;
/**
* Function to Convert coordinate to canvas pixel.
* @type {function}
*/
this.getPixelFromCoordinate = opts.getPixelFromCoordinate;
/**
* Id of the trajectory which is hovered.
* @type {string}
*/
this.hoverVehicleId = opts.hoverVehicleId;
/**
* Id of the trajectory which is selected.
* @type {string}
*/
this.selectedVehicleId = opts.selectedVehicleId;
/**
* Function use to filter the features displayed.
* @type {function}
*/
this.filter = opts.filter;
/**
* Function use to sort the features displayed.
* @type {function}
*/
this.sort = opts.sort;
/**
* Function use to style the features displayed.
* @type {function}
*/
this.style = opts.style;
// we draw directly on the canvas since openlayers is too slow.
/**
* HTML <canvas> element.
* @type {Canvas}
*/
this.canvas = opts.canvas || document.createElement('canvas');
this.canvas.width = opts.width * this.pixelRatio;
this.canvas.height = opts.height * this.pixelRatio;
this.canvas.setAttribute(
'style',
[
'position: absolute',
'top: 0',
'bottom: 0',
`width: ${opts.width}px`,
`height: ${opts.height}px`,
'pointer-events: none',
'visibility: visible',
'margin-top: inherit', // for scrolling behavior.
].join(';'),
);
/**
* 2d drawing context on the canvas.
* @type {CanvasRenderingContext2D}
*/
this.canvasContext = this.canvas.getContext('2d');
}
/**
* Set visibility of the canvas.
* @param {boolean} visible The visibility of the layer
*/
setVisible(visible) {
if (this.canvas) {
this.canvas.style.visibility = visible ? 'visible' : 'hidden';
}
}
/**
* Define the trajectories.
* @param {array<ol/Feature~Feature>} trajectories
*/
setTrajectories(trajectories = []) {
if (this.sort) {
trajectories.sort(this.sort);
}
this.trajectories = trajectories;
}
/**
* Return the trajectories.
* @returns {array<trajectory>} trajectories
*/
getTrajectories() {
return this.trajectories || [];
}
/**
* Clear the canvas.
* @private
*/
clear() {
if (this.canvasContext) {
this.canvasContext.clearRect(0, 0, this.canvas.width, this.canvas.height);
}
}
/**
* Draw all the trajectories available to the canvas.
* @param {Date} currTime The date to render.
* @param {number[2]} size Size ([width, height]) of the canvas to render.
* @param {number} resolution Which resolution of the map to render.
* @param {boolean} noInterpolate If true trajectories are not interpolated but
* drawn at the last known coordinate. Use this for performance optimization
* during map navigation.
* @private
*/
renderTrajectories(
currTime = Date.now(),
size = [],
resolution,
noInterpolate = false,
) {
this.clear();
const [width, height] = size;
if (
width &&
height &&
(this.canvas.width !== width || this.canvas.height !== height)
) {
[this.canvas.width, this.canvas.height] = [
width * this.pixelRatio,
height * this.pixelRatio,
];
}
this.canvas.style.left = '0px';
this.canvas.style.top = '0px';
this.canvas.style.transform = ``;
this.canvas.style.width = `${this.canvas.width / this.pixelRatio}px`;
this.canvas.style.height = `${this.canvas.height / this.pixelRatio}px`;
/**
* Current resolution.
* @type {number}
*/
this.currResolution = resolution || this.currResolution;
let hoverVehicleImg;
let hoverVehiclePx;
let hoverVehicleWidth;
let hoverVehicleHeight;
let selectedVehicleImg;
let selectedVehiclePx;
let selectedVehicleWidth;
let selectedVehicleHeight;
this.renderedTrajectories = [];
for (let i = (this.trajectories || []).length - 1; i >= 0; i -= 1) {
const traj = this.trajectories[i];
// We simplify the traj object
const { geometry, timeIntervals, timeOffset } = traj;
if (this.filter && !this.filter(traj, i, this.trajectories)) {
// eslint-disable-next-line no-continue
continue;
}
let coord = null;
let rotation;
if (traj.coordinate && (noInterpolate || !this.interpolate)) {
coord = traj.coordinate;
} else if (timeIntervals && timeIntervals.length > 1) {
const now = currTime - (timeOffset || 0);
let start;
let end;
let startFrac;
let endFrac;
let timeFrac;
// Search th time interval.
for (let j = 0; j < timeIntervals.length - 1; j += 1) {
// Rotation only available in tralis layer.
[start, startFrac, rotation] = timeIntervals[j];
[end, endFrac] = timeIntervals[j + 1];
if (start <= now && now <= end) {
break;
} else {
start = null;
end = null;
}
}
// The geometry can also be a Point
if (geometry.getType() === GeomType.POINT) {
coord = geometry.getCoordinates();
} else if (geometry.getType() === GeomType.LINE_STRING) {
if (start && end) {
// interpolate position inside the time interval.
timeFrac = this.interpolate
? Math.min((now - start) / (end - start), 1)
: 0;
const geomFrac = this.interpolate
? timeFrac * (endFrac - startFrac) + startFrac
: 0;
coord = geometry.getCoordinateAt(geomFrac);
// We set the rotation and the timeFraction of the trajectory (used by tralis).
this.trajectories[i].rotation = rotation;
this.trajectories[i].endFraction = timeFrac;
// It happens that the now date was some ms before the first timeIntervals we have.
} else if (now < timeIntervals[0][0]) {
[[, , rotation]] = timeIntervals;
timeFrac = 0;
coord = geometry.getFirstCoordinate();
} else if (now > timeIntervals[timeIntervals.length - 1][0]) {
[, , rotation] = timeIntervals[timeIntervals.length - 1];
timeFrac = 1;
coord = geometry.getLastCoordinate();
}
} else {
// eslint-disable-next-line no-console
console.error(
'This geometry type is not supported. Only Point or LineString are. Current geometry: ',
geometry,
);
}
// We set the rotation and the timeFraction of the trajectory (used by tralis).
// if rotation === null that seems there is no rotation available.
this.trajectories[i].rotation = rotation;
this.trajectories[i].endFraction = timeFrac || 0;
}
if (coord) {
// We set the rotation of the trajectory (used by tralis).
this.trajectories[i].coordinate = coord;
let px = this.getPixelFromCoordinate(coord);
if (!px) {
// eslint-disable-next-line no-continue
continue;
}
px = px.map((p) => {
return p * this.pixelRatio;
});
// Trajectory with pixel (i.e. within map extent) will be in renderedTrajectories.
this.trajectories[i].rendered = true;
this.renderedTrajectories.push(this.trajectories[i]);
const vehicleImg = this.style(
traj,
this.currResolution,
this.pixelRatio,
);
if (!vehicleImg) {
// eslint-disable-next-line no-continue
continue;
}
const imgWidth = vehicleImg.width;
const imgHeight = vehicleImg.height;
if (
this.hoverVehicleId !== traj.id &&
this.selectedVehicleId !== traj.id
) {
this.canvasContext.drawImage(
vehicleImg,
px[0] - imgWidth / 2,
px[1] - imgHeight / 2,
imgWidth,
imgHeight,
);
}
if (this.hoverVehicleId === traj.id) {
// Store the canvas to draw it at the end
hoverVehicleImg = vehicleImg;
hoverVehiclePx = px;
hoverVehicleWidth = imgWidth;
hoverVehicleHeight = imgHeight;
}
if (this.selectedVehicleId === traj.id) {
// Store the canvas to draw it at the end
selectedVehicleImg = vehicleImg;
selectedVehiclePx = px;
selectedVehicleWidth = imgWidth;
selectedVehicleHeight = imgHeight;
}
}
}
if (selectedVehicleImg) {
this.canvasContext.drawImage(
selectedVehicleImg,
selectedVehiclePx[0] - selectedVehicleWidth / 2,
selectedVehiclePx[1] - selectedVehicleHeight / 2,
selectedVehicleWidth,
selectedVehicleHeight,
);
}
if (hoverVehicleImg) {
this.canvasContext.drawImage(
hoverVehicleImg,
hoverVehiclePx[0] - hoverVehicleWidth / 2,
hoverVehiclePx[1] - hoverVehicleHeight / 2,
hoverVehicleWidth,
hoverVehicleHeight,
);
}
}
/**
* Clean the canvas and the events the tracker.
* @private
*/
destroy() {
unByKey(this.olEventsKeys);
this.renderedTrajectories = [];
this.clear();
}
} |
JavaScript | class Wallet extends PureComponent {
static navigationOptions = ({ navigation }) => getWalletNavbarOptions('wallet.title', navigation);
static propTypes = {
/**
* Map of accounts to information objects including balances
*/
accounts: PropTypes.object,
/**
* ETH to current currency conversion rate
*/
conversionRate: PropTypes.number,
/**
* Currency code of the currently-active currency
*/
currentCurrency: PropTypes.string,
/**
/* navigation object required to push new views
*/
navigation: PropTypes.object,
/**
* An object containing each identity in the format address => account
*/
identities: PropTypes.object,
/**
* A string that represents the selected address
*/
selectedAddress: PropTypes.string,
/**
* An array that represents the user tokens
*/
tokens: PropTypes.array,
/**
* An array that represents the user collectibles
*/
collectibles: PropTypes.array,
/**
* Current provider ticker
*/
ticker: PropTypes.string,
/**
* Current onboarding wizard step
*/
wizardStep: PropTypes.number
};
state = {
refreshing: false
};
accountOverviewRef = React.createRef();
mounted = false;
componentDidMount = () => {
requestAnimationFrame(async () => {
const { AssetsDetectionController, AccountTrackerController } = Engine.context;
AssetsDetectionController.detectAssets();
AccountTrackerController.refresh();
this.mounted = true;
});
};
onRefresh = async () => {
requestAnimationFrame(async () => {
this.setState({ refreshing: true });
const {
AssetsDetectionController,
AccountTrackerController,
CurrencyRateController,
TokenRatesController
} = Engine.context;
const actions = [
AssetsDetectionController.detectAssets(),
AccountTrackerController.refresh(),
CurrencyRateController.start(),
TokenRatesController.poll()
];
await Promise.all(actions);
this.setState({ refreshing: false });
});
};
componentWillUnmount() {
this.mounted = false;
}
renderTabBar() {
return (
<DefaultTabBar
underlineStyle={styles.tabUnderlineStyle}
activeTextColor={colors.blue}
inactiveTextColor={colors.fontTertiary}
backgroundColor={colors.white}
tabStyle={styles.tabStyle}
textStyle={styles.textStyle}
/>
);
}
onChangeTab = obj => {
InteractionManager.runAfterInteractions(() => {
if (obj.ref.props.tabLabel === strings('wallet.tokens')) {
Analytics.trackEvent(ANALYTICS_EVENT_OPTS.WALLET_TOKENS);
} else {
Analytics.trackEvent(ANALYTICS_EVENT_OPTS.WALLET_COLLECTIBLES);
}
});
};
onRef = ref => {
this.accountOverviewRef = ref;
};
renderContent() {
const {
accounts,
conversionRate,
currentCurrency,
identities,
selectedAddress,
tokens,
collectibles,
navigation,
ticker
} = this.props;
let balance = 0;
let assets = tokens;
if (accounts[selectedAddress]) {
balance = renderFromWei(accounts[selectedAddress].balance);
assets = [
{
name: 'Ether', // FIXME: use 'Ether' for mainnet only, what should it be for custom networks?
symbol: getTicker(ticker),
isETH: true,
balance,
balanceFiat: weiToFiat(hexToBN(accounts[selectedAddress].balance), conversionRate, currentCurrency),
logo: '../images/eth-logo.png'
},
...tokens
];
} else {
assets = tokens;
}
const account = { address: selectedAddress, ...identities[selectedAddress], ...accounts[selectedAddress] };
return (
<View style={styles.wrapper}>
<AccountOverview account={account} navigation={navigation} onRef={this.onRef} />
<ScrollableTabView
renderTabBar={this.renderTabBar}
// eslint-disable-next-line react/jsx-no-bind
onChangeTab={obj => this.onChangeTab(obj)}
>
<Tokens navigation={navigation} tabLabel={strings('wallet.tokens')} tokens={assets} />
<CollectibleContracts
navigation={navigation}
tabLabel={strings('wallet.collectibles')}
collectibles={collectibles}
/>
</ScrollableTabView>
</View>
);
}
renderLoader() {
return (
<View style={styles.loader}>
<ActivityIndicator size="small" />
</View>
);
}
/**
* Return current step of onboarding wizard if not step 5 nor 0
*/
renderOnboardingWizard = () => {
const { wizardStep } = this.props;
return (
[1, 2, 3, 4].includes(wizardStep) && (
<OnboardingWizard navigation={this.props.navigation} coachmarkRef={this.accountOverviewRef} />
)
);
};
render = () => (
<ErrorBoundary view="Wallet">
<View style={baseStyles.flexGrow} testID={'wallet-screen'}>
<ScrollView
style={styles.wrapper}
refreshControl={<RefreshControl refreshing={this.state.refreshing} onRefresh={this.onRefresh} />}
>
{this.props.selectedAddress ? this.renderContent() : this.renderLoader()}
</ScrollView>
{this.renderOnboardingWizard()}
</View>
</ErrorBoundary>
);
} |
JavaScript | class VigenereCipheringMachine {
constructor(direct = true) {
this.direct = direct;
}
encrypt(message, key) {
if (message === undefined || key === undefined) {
throw Error("Incorrect arguments!")
}
let k = 0;
message = message.toUpperCase();
key = key.toUpperCase();
let result = '';
for (let char of message) {
if (/[A-Z]/.test(char)) {
result += this.encryptOneLetter(char, key[k]);
k++;
if (k > key.length - 1) {
k = 0;
}
} else {
result += char;
}
}
if (!this.direct) {
return this.reverse(result);
} else {
return result;
}
}
encryptOneLetter(x, y) {
let alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
let newPosition = alphabet.indexOf(x) + alphabet.indexOf(y);
if (newPosition > 25) {
newPosition = newPosition % 26;
}
return alphabet[newPosition];
}
decryptOneLetter(x, y) {
let alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
let decryptPosition = alphabet.indexOf(x) - alphabet.indexOf(y);
if (decryptPosition < 0) {
decryptPosition = 26 + decryptPosition;
}
return alphabet[decryptPosition];
}
decrypt(message, key) {
if (message === undefined || key === undefined) {
throw Error("Incorrect arguments!")
}
let k = 0;
message = message.toUpperCase();
key = key.toUpperCase();
let result = '';
for (let char of message) {
if (/[A-Z]/.test(char)) {
result += this.decryptOneLetter(char, key[k]);
k++;
if (k > key.length - 1) {
k = 0;
}
} else {
result += char;
}
}
if (!this.direct) {
return this.reverse(result);
} else {
return result;
}
}
reverse(str) {
return str.split('').reverse().join('');
}
} |
JavaScript | class RankGlobalGD extends Number {
/**
* @description Whether the rank is a valid number
* @type {boolean}
*/
get hasRank() { return Number.isInteger(this.valueOf()) && this.valueOf() > 0; }
/**
* @description Whether the rank is within the Top 10
* @type {boolean}
*/
get isTop10() { return this.hasRank && this.valueOf() <= 10; }
/**
* @description Whether the rank is within the Top 50
* @type {boolean}
*/
get isTop50() { return this.hasRank && this.valueOf() <= 50; }
/**
* @description Whether the rank is within the Top 100
* @type {boolean}
*/
get isTop100() { return this.hasRank && this.valueOf() <= 100; }
/**
* @description Whether the rank is within the Top 200
* @type {boolean}
*/
get isTop200() { return this.hasRank && this.valueOf() <= 200; }
/**
* @description Whether the rank is within the Top 500
* @type {boolean}
*/
get isTop500() { return this.hasRank && this.valueOf() <= 500; }
/**
* @description Whether the rank is within the Top 1000
* @type {boolean}
*/
get isTop1000() { return this.hasRank && this.valueOf() <= 1000; }
/**
* @description Whether the highest trophy is top 1
* @type {boolean}
*/
get isTrophyTop1() { return this.valueOf() == 1; }
/**
* @description Whether the highest trophy is gold
* @type {boolean}
*/
get isTrophyGold() { return this.hasRank && this.valueOf() > 1 && this.valueOf() <= RankGlobalGD.TROPHY_GOLD_THRESHOLD; }
/**
* @description Whether the highest trophy is silver
* @type {boolean}
*/
get isTrophySilver() { return this.hasRank && this.valueOf() > RankGlobalGD.TROPHY_GOLD_THRESHOLD && this.valueOf() <= RankGlobalGD.TROPHY_SILVER_THRESHOLD; }
/**
* @description Whether the highest trophy is bronze
* @type {boolean}
*/
get isTrophyBronze() { return this.hasRank && this.valueOf() > RankGlobalGD.TROPHY_SILVER_THRESHOLD && this.valueOf() <= RankGlobalGD.TROPHY_BRONZE_THRESHOLD; }
/**
* @description Whether the highest trophy is green
* @type {boolean}
*/
get isTrophyGreen() { return this.hasRank && this.valueOf() > RankGlobalGD.TROPHY_BRONZE_THRESHOLD && this.valueOf() <= RankGlobalGD.TROPHY_GREEN_THRESHOLD; }
/**
* @description Whether the highest trophy is blue
* @type {boolean}
*/
get isTrophyBlue() { return this.hasRank && this.valueOf() > RankGlobalGD.TROPHY_GREEN_THRESHOLD && this.valueOf() <= RankGlobalGD.TROPHY_BLUE_THRESHOLD; }
/**
* @description Whether the highest trophy is purple
* @type {boolean}
*/
get isTrophyPurple() { return this.hasRank && this.valueOf() > RankGlobalGD.TROPHY_BLUE_THRESHOLD && this.valueOf() <= RankGlobalGD.TROPHY_PURPLE_THRESHOLD; }
/**
* @description Whether the highest trophy is the default trophy
* @type {boolean}
*/
get isTrophyDefault() { return this.hasRank && this.valueOf() > RankGlobalGD.TROPHY_PURPLE_THRESHOLD; }
/**
* @description Returns the name of the highest rank trophy or "DEFAULT"
* @type {TROPHY_NAMES}
*/
get trophyType() {
return this.hasRank
? this.isTrophyTop1
? "TOP_1"
: this.isTrophyGold
? "GOLD"
: this.isTrophySilver
? "SILVER"
: this.isTrophyBronze
? "BRONZE"
: this.isTrophyGreen
? "GREEN"
: this.isTrophyBlue
? "BLUE"
: this.isTrophyPurple
? "PURPLE"
: "DEFAULT"
: "DEFAULT";
}
/**
* @type {?Emote}
*/
get trophyEmote() {
switch (this.trophyType) {
default: { return null; }
case "TOP_1": { return EMOTE_TROPHY_1; }
case "GOLD": { return EMOTE_TROPHY_GOLD; }
case "SILVER": { return EMOTE_TROPHY_SILVER; }
case "BRONZE": { return EMOTE_TROPHY_BRONZE; }
case "GREEN": { return EMOTE_TROPHY_GREEN; }
case "BLUE": { return EMOTE_TROPHY_BLUE; }
case "PURPLE": { return EMOTE_TROPHY_PURPLE; }
case "DEFAULT": { return EMOTE_TROPHY_DEFAULT; }
}
}
} |
JavaScript | class ContractEventListener extends BaseEventListener {
/**
* Constructor.
* @param {Contract} contract The contract instance
* @param {string} eventName The name of the contract event being listened for
* @param {function} eventCallback The event callback called when an event is received.
* It has signature (err, BlockEvent, blockNumber, transactionId)
* @param {module:fabric-network.Network~EventListenerOptions} options
*/
constructor(contract, eventName, eventCallback, options) {
super(contract.network, eventCallback, options);
this.contract = contract;
this.eventName = eventName;
}
_registerListener() {
this.registration = this.eventService.registerChaincodeListener(
this.contract.chaincodeId,
this.eventName,
this.onEvent.bind(this),
this.eventServiceOptions
);
}
/*
* This is the called by the base.onEvent() class event processing.
* This will be the sending of the unique data for this event Listener type
* to the user's callback.
*/
async _onEvent(event) {
const method = '_onEvent';
logger.debug('%s - start', method);
try {
const {blockNumber, chaincodeEvents} = event;
logger.debug('%s - calling user callback', method);
await this.eventCallback(null, blockNumber.toString(), chaincodeEvents);
logger.debug('%s - completed calling user callback', method);
} catch (err) {
logger.error('%s - Error executing callback: %s', method, err);
}
}
} |
JavaScript | class GameCanvas extends Canvas {
/**
* The Game Canvas constructor
*/
constructor() {
super();
this.init("game");
}
/**
* Draws the Ghosts Targets for testing
* @param {Array.<Ghost>} ghosts
*/
drawTargets(ghosts) {
this.ctx.save();
ghosts.forEach((ghost) => {
this.ctx.fillStyle = ghost.getBodyColor();
this.ctx.strokeStyle = ghost.getBodyColor();
let tile = Board.getTileXYCenter(ghost.getTargetTile());
this.ctx.beginPath();
this.ctx.moveTo(ghost.getX(), ghost.getY());
this.ctx.lineTo(tile.x, tile.y);
this.ctx.fillRect(tile.x - 4, tile.y - 4, 8, 8);
this.ctx.stroke();
});
this.ctx.restore();
}
} |
JavaScript | class SurrogateSideEffect extends GenericSideEffect {
/**
* Applies or removes interaction styles from plot elements. An array of row ids needs to be passed
* which identifies the plot elements and applies styles to them.
*
* To apply the interaction style,
* ```
* const entryRowIds = entrySet[0].uids;
* const interactionStyle = [{
* type: 'fill',
* intensity: [0, 0, 15, 0] // hsla configuration
* }];
*
* this.applyInteractionStyle(entryRowIds, interactionStyle, 'brighten', true);
* ```
* @public
* @param {Array} set Array of row ids.
* @param {Array} config Style configuration.
* @param {Object} config[0] fill or stroke configuration.
* @param {string} config[0].type Type of style - fill or stroke.
* @param {Array} config[0].intensity hsla configuration.
* @param {string} interactionType Type of interaction. This is needed for storing the styles for
* each type of interaction in the plot elements.
* @param {boolean} apply Whether to apply or remove the interaction style.
*
* @return {SurrogateSideEffect} Instance of surrogate side effect.
*/
applyInteractionStyle (set, config = {}, layers) {
const { interactionType, apply, reset = false } = config;
const allLayers = layers || this.firebolt.context.layers();
allLayers.forEach((layer) => {
const { interactive } = layer.config();
if (interactive !== false) {
const layerFields = layer.data().getFieldsConfig();
const filteredUids = set.uids.filter(([, measures = []]) => measures.every(m => m in layerFields))
.map(d => d[0]);
const options = { apply, reset, styles: null };
layer.applyInteractionStyle(interactionType, filteredUids, options);
}
});
return this;
}
} |
JavaScript | class TwingLoaderRelativeFilesystem {
constructor() {
this.cache = new Map();
this.errorCache = new Map();
}
getSourceContext(name, from) {
return this.findTemplate(name, true, from).then((path) => {
return new Promise((resolve) => {
readFile(path, 'UTF-8', (err, data) => {
resolve(new TwingSource(data, name, path));
});
});
});
}
getCacheKey(name, from) {
return this.findTemplate(name, true, from);
}
exists(name, from) {
name = this.normalizeName(this.resolvePath(name, from));
if (this.cache.has(name)) {
return Promise.resolve(true);
}
return this.findTemplate(name, false, from).then((name) => {
return name !== null;
});
}
isFresh(name, time, from) {
return this.findTemplate(name, true, from).then((name) => {
return new Promise((resolve) => {
fsStat(name, (err, stat) => {
resolve(stat.mtime.getTime() < time);
});
});
});
}
/**
* Checks if the template can be found.
*
* @param {string} name The template name
* @param {boolean} throw_ Whether to throw an exception when an error occurs
* @param {TwingSource} from The source that initiated the template loading
*
* @returns {Promise<string>} The template name or null
*/
findTemplate(name, throw_ = true, from = null) {
let _do = () => {
name = this.normalizeName(this.resolvePath(name, from));
if (this.cache.has(name)) {
return this.cache.get(name);
}
if (this.errorCache.has(name)) {
if (!throw_) {
return null;
}
throw new TwingErrorLoader(this.errorCache.get(name), -1, from);
}
try {
this.validateName(name, from);
}
catch (e) {
if (!throw_) {
return null;
}
throw e;
}
try {
let stat = statSync(name);
if (stat.isFile()) {
this.cache.set(name, resolvePath(name));
return this.cache.get(name);
}
}
catch (e) {
// noop, we'll throw later if needed
}
this.errorCache.set(name, `Unable to find template "${name}".`);
if (!throw_) {
return null;
}
throw new TwingErrorLoader(this.errorCache.get(name), -1, from);
};
return new Promise((resolve, reject) => {
try {
resolve(_do());
}
catch (e) {
reject(e);
}
});
}
normalizeName(name) {
if (name === null) {
return '';
}
return name.replace(/\\/g, '/').replace(/\/{2,}/g, '/');
}
validateName(name, from) {
if (name.indexOf(`\0`) > -1) {
throw new TwingErrorLoader('A template name cannot contain NUL bytes.', -1, from);
}
}
resolve(name, from, shouldThrow = false) {
return this.findTemplate(name, shouldThrow, from);
}
resolvePath(name, from) {
if (name && from && !isAbsolutePath(name)) {
name = joinPath(dirname(from.getResolvedName()), name);
}
return name;
}
} |
JavaScript | class Items extends React.Component {
static manifest = Object.freeze({
items: {
type: 'okapi',
records: 'items',
path: 'inventory/items',
params: {
query: 'holdingsRecordId==!{holdingsRecord.id}',
limit: '5000',
},
resourceShouldRefresh: true,
},
});
constructor(props) {
super(props);
this.editItemModeThisLayer = false;
}
render() {
const {
resources: { items },
instance,
holdingsRecord,
getSearchParams,
} = this.props;
if (!items || !items.hasLoaded) return null;
const itemRecords = items.records;
const itemsFormatter = {
'Item: barcode': (item) => {
return (
<React.Fragment>
<Link
to={`/inventory/view/${instance.id}/${holdingsRecord.id}/${item.id}?${getSearchParams()}`}
data-test-item-link
>
<span data-test-items-app-icon>
<AppIcon app="inventory" iconKey="item" size="small">
{get(item, 'barcode', '')}
</AppIcon>
</span>
</Link>
{item.barcode &&
<CopyToClipboard text={item.barcode}>
<IconButton icon="clipboard" />
</CopyToClipboard>
}
</React.Fragment>
);
},
'status': x => get(x, ['status', 'name']) || '--',
'Material Type': x => get(x, ['materialType', 'name']),
};
return (
<div data-test-items>
<IntlConsumer>
{intl => (
<FormattedMessage id="ui-inventory.items">
{ariaLabel => (
<MultiColumnList
id="list-items"
contentData={itemRecords}
rowMetadata={['id', 'holdingsRecordId']}
formatter={itemsFormatter}
visibleColumns={['Item: barcode', 'status', 'Material Type']}
columnMapping={{
'Item: barcode': intl.formatMessage({ id: 'ui-inventory.item.barcode' }),
'status': intl.formatMessage({ id: 'ui-inventory.status' }),
'Material Type': intl.formatMessage({ id: 'ui-inventory.materialType' }),
}}
ariaLabel={ariaLabel}
containerRef={(ref) => { this.resultsList = ref; }}
interactive={false}
/>
)}
</FormattedMessage>
)}
</IntlConsumer>
</div>);
}
} |
JavaScript | class Util {
/**
* Extend an array just like JQuery's extend.
* @param {object} arguments Objects to be merged.
* @return {object} Merged objects.
*/
static extend() {
for (let i = 1; i < arguments.length; i++) {
for (let key in arguments[i]) {
if (Object.prototype.hasOwnProperty.call(arguments[i], key)) {
if (typeof arguments[0][key] === 'object' && typeof arguments[i][key] === 'object') {
this.extend(arguments[0][key], arguments[i][key]);
}
else {
arguments[0][key] = arguments[i][key];
}
}
}
}
return arguments[0];
}
/**
* Retrieve true string from HTML encoded string.
* @param {string} input Input string.
* @return {string} Output string.
*/
static htmlDecode(input) {
var dparser = new DOMParser().parseFromString(input, 'text/html');
return dparser.documentElement.textContent;
}
/**
* Revert order of right-to-left chunks.
*
* Words can be mixed as right-to-left and left-to-right, and the
* parsed input from the text field will have a different order than the
* displayed words. The right-to-left chunks are reversed here.
*
* @param {object[]} words Words object.
* @param {string} word.solution Word to test.
* @return {object[]} RTL words reordered.
*/
static revertRTL(words) {
let reversedWords = [];
let currentRTL = [];
// Reverse RTL blocks, keep LTR
words.forEach(word => {
const isRTL = Util.containsRTLCharacters(word.solution);
if (isRTL) {
currentRTL.push(word);
}
else {
reversedWords = reversedWords.concat(currentRTL.reverse());
currentRTL = [];
reversedWords.push(word);
}
});
if (currentRTL.length !== 0) {
reversedWords = reversedWords.concat(currentRTL.reverse());
}
return reversedWords;
}
/**
* Split word into alternatives using | but not \| as delimiter.
*
* Can be replaced by word.split(/(?<!\\)\|/) as soon as lookbehinds in
* regular expressions are commonly available in browsers (mind IE11 though)
*
* @param {string} word Word to be split.
* @param {string[]} Word alternatives.
*/
static splitWordAlternatives(word) {
const wordReversed = word.split('').reverse().join('');
const alternatives = wordReversed.split(/\|(?!\\)/);
return alternatives
.map(alternative => alternative.split('').reverse().join('').replace('\\|', '|'))
.reverse();
}
/**
* Check for right-to-left characters.
*
* @param {string} input Input to check for right-to-left characters.
* @return {boolean} True, if input contains right-to-left characters.
*/
static containsRTLCharacters(input) {
return new RegExp('^[^' + Util.RTL + ']*?[' + Util.RTL + ']').test(input);
}
/**
* Combine all possible combinations of strings from two sets.
*
* ['a', 'b', 'c'] and ['d', 'e'] become ['a d', 'a e', 'b d', 'b e', 'c d', 'c e']
*
* @param {object[]} words1 First set of strings.
* @param {object[]} words2 Second set of strings.
* @param {string} [delimiter=' '] Delimiter between each string.
*/
static buildCombinations(words1, words2, delimiter = ' ') {
const result = [];
words1.forEach(word1 => {
result.push(
...words2.map(word2 => (word2 === '') ? word1 : `${word2}${delimiter}${word1}`)
);
});
return result;
}
/**
* Format language tag (RFC 5646). Assuming "language-coutry". No validation.
* Cmp. https://tools.ietf.org/html/rfc5646
* @param {string} languageTag Language tag.
* @return {string} Formatted language tag.
*/
static formatLanguageCode(languageCode) {
if (typeof languageCode !== 'string') {
return languageCode;
}
/*
* RFC 5646 states that language tags are case insensitive, but
* recommendations may be followed to improve human interpretation
*/
const segments = languageCode.split('-');
segments[0] = segments[0].toLowerCase(); // ISO 639 recommendation
if (segments.length > 1) {
segments[1] = segments[1].toUpperCase(); // ISO 3166-1 recommendation
}
languageCode = segments.join('-');
return languageCode;
}
/**
* Shuffle array.
* @param {object[]} array Array.
* @return {object[]} Shuffled array.
*/
static shuffleArray(array) {
let j, x, i;
for (i = array.length - 1; i > 0; i--) {
j = Math.floor(Math.random() * (i + 1));
x = array[i];
array[i] = array[j];
array[j] = x;
}
return array;
}
} |
JavaScript | class GoogleAnalyticsTracker {
/**
* Save all tracker related data that is needed to call native methods with proper data.
* @param {string} trackerId Your tracker id, something like: UA-12345-1
* @param {{fieldName: fieldIndex}} customDimensionsFieldsIndexMap Custom dimensions field/index pairs
*/
constructor(trackerId, customDimensionsFieldsIndexMap) {
this.id = trackerId;
this.customDimensionsFieldsIndexMap = customDimensionsFieldsIndexMap;
}
/**
* If Tracker has customDimensionsFieldsIndexMap, it will transform
* customDimensions map pairs {field: value} to {fieldIndex: value}.
* Otherwise customDimensions are passed trough untouched.
* Underlay native methods will transform provided customDimensions map to expected format.
* Google analytics expect dimensions to be tracker with 'dimension{index}' keys,
* not dimension field names.
* @ignore
* @param {{fieldName: value}} customDimensions
* @returns {{fieldIndex: value}}
*/
transformCustomDimensionsFieldsToIndexes(customDimensions) {
if (this.customDimensionsFieldsIndexMap) {
return Object.keys(this.customDimensionsFieldsIndexMap)
.filter(key => isValidCustomDimension(customDimensions[key]))
.reduce((mappedCustomDimensions, key) => {
const dimensionIndex = this.customDimensionsFieldsIndexMap[key];
mappedCustomDimensions[dimensionIndex] = customDimensions[key];
return mappedCustomDimensions;
}, {});
}
return customDimensions;
}
transformPayload(payload) {
if (payload && payload.customDimensions) {
let customDimensions = payload.customDimensions;
let transformed = this.transformCustomDimensionsFieldsToIndexes(customDimensions);
payload.customDimensions = transformed;
}
}
/**
* Track the current screen/view. Calling this will also set the "current view" for other calls.
* So events tracked will be tagged as having occured on the current view, `Home` in this example.
* This means it is important to track navigation, especially if events can fire on different views.
* @example
* tracker.trackScreenView('Home');
* @example
* // With payload:
* const payload = { impressionList: "Sale", impressionProducts: [ { id: "PW928", name: "Premium bundle" } ] };
* tracker.trackScreenView("SplashModal", payload);
* @param {string} screenName (Required) The name of the current screen
* @param {HitPayload} payload (Optional) An object containing the hit payload
*/
trackScreenView(screenName, payload = null) {
this.transformPayload(payload);
NativeBridges_1.AnalyticsBridge.trackScreenView(this.id, screenName, payload);
}
/**
* Track an event that has occured
* @example
* tracker.trackEvent("DetailsButton", "Click");
* @example
* // Track event with label and value
* tracker.trackEvent("AppVersionButton", "Click", { label: "v1.0.3", value: 22 });
* @example
* // Track with a payload (ecommerce in this case):
* const product = {
* id: "P12345",
* name: "Android Warhol T-Shirt",
* category: "Apparel/T-Shirts",
* brand: "Google",
* variant: "Black",
* price: 29.2,
* quantity: 1,
* couponCode: "APPARELSALE"
* };
* const transaction = {
* id: "T12345",
* affiliation: "Google Store - Online",
* revenue: 37.39,
* tax: 2.85,
* shipping: 5.34,
* couponCode: "SUMMER2013"
* };
* const productAction = {
* transaction,
* action: 7 // Purchase action, see ProductActionEnum
* }
* const payload = { products: [ product ], productAction: productAction }
* tracker.trackEvent("FinalizeOrderButton", "Click", null, payload);
* @param {string} category (Required) The event category
* @param {string} action (Required) The event action
* @param {EventMetadata} eventMetadata (Optional) An object containing event metadata
* @param {HitPayload} payload (Optional) An object containing the hit payload
*/
trackEvent(category, action, eventMetadata, payload = null) {
this.transformPayload(payload);
NativeBridges_1.AnalyticsBridge.trackEvent(this.id, category, action, (eventMetadata && eventMetadata.label ? eventMetadata.label : null), (eventMetadata && eventMetadata.value != null ? eventMetadata.value.toString() : null), payload);
}
/**
* Track a timing measurement
* @example
* tracker.trackTiming("testcategory", 2000, { name: "LoadList" }); // name metadata is required
* @example
* // With optional label:
* tracker.trackTiming("testcategory", 2000, { name: "LoadList", label: "v1.0.3" });
* @example
* @param {string} category (Required) The event category
* @param {number} interval (Required) The timing measurement in milliseconds
* @param {TimingMetadata} timingMetadata (Required) An object containing timing metadata
* @param {HitPayload} payload (Optional) An object containing the hit payload
*/
trackTiming(category, interval, timingMetadata, payload = null) {
this.transformPayload(payload);
NativeBridges_1.AnalyticsBridge.trackTiming(this.id, category, interval, timingMetadata.name, timingMetadata.label, payload);
}
/**
* Track an exception
* @example
* try {
* ...
* } catch(error) {
* tracker.trackException(error.message, false);
* }
* @param {string} error (Required) The description of the error
* @param {boolean} fatal (Optional) A value indiciating if the error was fatal, defaults to false
* @param {HitPayload} payload (Optional) An object containing the hit payload
*/
trackException(error, fatal = false, payload = null) {
this.transformPayload(payload);
NativeBridges_1.AnalyticsBridge.trackException(this.id, error, fatal, payload);
}
/**
* Track a social interaction, Facebook, Twitter, etc.
* @example tracker.trackSocialInteraction("Twitter", "Post");
* @param {string} network
* @param {string} action
* @param {string} targetUrl
* @param {HitPayload} payload (Optional) An object containing the hit payload
*/
trackSocialInteraction(network, action, targetUrl, payload) {
this.transformPayload(payload);
NativeBridges_1.AnalyticsBridge.trackSocialInteraction(this.id, network, action, targetUrl, payload);
}
/**
* Sets the current userId for tracking.
* @example tracker.setUser("12345678");
* @param {string} userId An anonymous identifier that complies with Google Analytic's user ID policy
*/
setUser(userId) {
NativeBridges_1.AnalyticsBridge.setUser(this.id, userId);
}
/**
* Sets the current clientId for tracking.
* @example tracker.setClient("35009a79-1a05-49d7-b876-2b884d0f825b");
* @param {string} clientId A anonymous identifier that complies with Google Analytic's client ID policy
*/
setClient(clientId) {
NativeBridges_1.AnalyticsBridge.setClient(this.id, clientId);
}
/**
* Get the client id to be used for purpose of logging etc.
* @example tracker.getClientId().then(clientId => console.log("Client id is: ", clientId));
* @returns {Promise<string>}
*/
getClientId() {
return NativeBridges_1.AnalyticsBridge.getClientId(this.id);
}
/**
* Also called advertising identifier collection, and is used for advertising features.
*
* **Important**: For iOS you can only use this method if you have done the optional step 6 from the installation guide. Only enable this (and link the appropriate libraries) if you plan to use advertising features in your app, or else your app may get rejected from the AppStore.
* @example tracker.allowIDFA(true);
* @param {boolean} enabled (Optional) Defaults to true
*/
allowIDFA(enabled = true) {
NativeBridges_1.AnalyticsBridge.allowIDFA(this.id, enabled);
}
/**
* Overrides the app name logged in Google Analytics. The Bundle name is used by default. Note: This has to be set each time the App starts.
* @example tracker.setAppName("YourAwesomeApp");
* @param {string} appName (Required)
*/
setAppName(appName) {
NativeBridges_1.AnalyticsBridge.setAppName(this.id, appName);
}
/**
* Sets the trackers appVersion
* @example tracker.setAppVersion("1.3.2");
* @param {string} appVersion (Required)
*/
setAppVersion(appVersion) {
NativeBridges_1.AnalyticsBridge.setAppVersion(this.id, appVersion);
}
/**
* Sets if AnonymizeIp is enabled
* If enabled the last octet of the IP address will be removed
* @example tracker.setAnonymizeIp(true);
* @param {boolean} enabled (Required)
*/
setAnonymizeIp(enabled) {
NativeBridges_1.AnalyticsBridge.setAnonymizeIp(this.id, enabled);
}
/**
* Sets tracker sampling rate.
* @example tracker.setSamplingRate(50);
* @param {number} sampleRatio (Required) Percentage 0 - 100
*/
setSamplingRate(sampleRatio) {
NativeBridges_1.AnalyticsBridge.setSamplingRate(this.id, sampleRatio);
}
/**
* Sets the currency for tracking.
* @example tracker.setCurrency("EUR");
* @param {string} currencyCode (Required) The currency ISO 4217 code
*/
setCurrency(currencyCode) {
NativeBridges_1.AnalyticsBridge.setCurrency(this.id, currencyCode);
}
/**
* Sets if uncaught exceptions should be tracked
* Important to note: On iOS this option is set on all trackers. On Android it is set per tracker.
* If you are using multiple trackers on iOS, this will enable & disable on all trackers.
* @param {boolean} enabled
*/
setTrackUncaughtExceptions(enabled) {
NativeBridges_1.AnalyticsBridge.setTrackUncaughtExceptions(this.id, enabled);
}
/**
* This function lets you manually dispatch all hits which are queued.
* Use this function sparingly, as it will normally happen automatically
* as a batch. This function will also dispatch for all trackers.
* @example tracker.dispatch().then(done => console.log("Dispatch is done: ", done));
* @returns {Promise<boolean>} Returns when done
*/
dispatch() {
return NativeBridges_1.AnalyticsBridge.dispatch();
}
/**
* The same as `dispatch`, but also gives you the ability to time out
* the Promise in case dispatch takes too long.
* @example
* tracker
* .dispatchWithTimeout(10000)
* .then(done => console.log("Dispatch is done: ", done));
* @param {number} timeout The timeout. Default value is 15 sec.
* @returns {Promise<boolean>} Returns when done or timed out
*/
dispatchWithTimeout(timeout = -1) {
if (timeout < 0) {
return NativeBridges_1.AnalyticsBridge.dispatch();
}
let timer = null;
const withTimeout = (timeout) => new Promise(resolve => {
timer = setTimeout(() => {
timer = null;
resolve(false);
}, Math.min(timeout, DEFAULT_DISPATCH_TIMEOUT));
});
return Promise.race([
NativeBridges_1.AnalyticsBridge.dispatch(),
withTimeout(timeout)
]).then(result => {
if (timer) {
clearTimeout(timer);
}
return result;
});
}
} |
JavaScript | class CategoryTree {
/**
* @param {Object} parameters
* @param {String} parameters.categoryId The category id.
* @param {Object} [parameters.graphqlContext] The optional GraphQL execution context passed to the resolver.
* @param {Object} [parameters.actionParameters] Some optional parameters of the I/O Runtime action, like for example authentication info.
* @param {CategoryTreeLoader} [parameters.categoryTreeLoader] An optional CategoryTreeLoader, to optimise caching.
* @param {ProductsLoader} [parameters.productsLoader] An optional ProductsLoader, to optimise caching.
*/
constructor(parameters) {
this.categoryId = parameters.categoryId;
this.graphqlContext = parameters.graphqlContext;
this.actionParameters = parameters.actionParameters;
this.categoryTreeLoader = parameters.categoryTreeLoader || new CategoryTreeLoader(parameters.actionParameters);
this.productsLoader = parameters.productsLoader || new ProductsLoader(parameters.actionParameters);
/**
* This class returns a Proxy to avoid having to implement a getter for all properties.
*/
return new LoaderProxy(this);
}
__load() {
console.debug(`Loading category for ${this.categoryId}`);
return this.categoryTreeLoader.load(this.categoryId);
}
/**
* Converts some category data from the 3rd-party commerce system into the Magento GraphQL format.
* Properties that require some extra data fetching with the 3rd-party system must have dedicated getters
* in this class.
*
* @param {Object} data
* @returns {Object} The backend category data converted into a GraphQL "CategoryTree" data.
*/
__convertData(data) {
return {
id: data.id,
position: data.id,
url_key: data.id,
url_path: data.slug,
name: data.title,
description: data.description,
product_count: 2
};
}
get __typename() {
return 'CategoryTree';
}
get children() {
return this.__load().then(() => {
if (!this.data.subcategories || this.data.subcategories.length == 0) {
return [];
}
return this.data.subcategories.map(
(categoryId) =>
new CategoryTree({
categoryId: categoryId,
graphqlContext: this.graphqlContext,
actionParameters: this.actionParameters,
categoryTreeLoader: this.categoryTreeLoader,
productsLoader: this.productsLoader
})
);
});
}
// children_count is a String in the Magento schema
get children_count() {
return this.__load().then(() => {
if (!this.data.subcategories || this.data.subcategories.length == 0) {
return '0';
}
return this.data.subcategories.length.toString();
});
}
// Getters cannot have arguments, so we define a function
products(params) {
// We don't need to call this.__load() here because only fetching the products
// of a category does not require fetching the category itself
return new Products({
search: {
categoryId: this.categoryId,
pageSize: params.pageSize,
currentPage: params.currentPage
},
graphqlContext: this.graphqlContext,
actionParameters: this.actionParameters,
productsLoader: this.productsLoader,
categoryTreeLoader: this.categoryTreeLoader
});
}
} |
JavaScript | class RichTextEditorSelection extends RichTextEditorStyles(LitElement) {
/**
* Store tag name to make it easier to obtain directly.
*/
static get tag() {
return "rich-text-editor-selection";
}
static get styles() {
return [
...super.styles,
css`
:host {
background-color: var(--rich-text-editor-selection-bg);
margin: 0;
padding: 0;
display: inline;
}
:host([hidden]) {
display: none;
}
:host([collapsed]):after {
content: '|';
color: var(--rich-text-editor-selection-bg);
background-color: transparent;
}
`,
];
}
render() {
return html` <slot></slot> `;
}
static get properties() {
return {
editor: {
type: Object,
},
collapsed: {
type: Boolean,
reflect: true,
attribute: "collapsed",
},
hidden: {
type: Boolean,
reflect: true,
attribute: "hidden",
},
id: {
type: String,
reflect: true,
attribute: "id",
},
observer: {
type: Object,
},
range: {
type: Object,
},
toolbar: {
type: Object,
},
__toolbars: {
type: Array,
},
};
}
constructor() {
super();
let sel = this;
this.hidden = true;
this.__toolbars = [];
this.__clipboard = document.createElement("textarea");
this.__clipboard.setAttribute("aria-hidden", true);
this.__clipboard.style.position = "absolute";
this.__clipboard.style.left = "-9999px";
this.__clipboard.style.top = "0px";
this.__clipboard.style.width = "0px";
this.__clipboard.style.height = "0px";
this.id = this._generateUUID();
document.body.appendChild(this.__clipboard);
window.addEventListener("paste", (e) => console.log("paste", e));
window.addEventListener("register", this._handleRegistration.bind(sel));
/*
extendForward.addEventListener('click', () => {
window.getSelection().modify('extend', 'forward', 'character');
});
extendBackward.addEventListener('click', () => {
window.getSelection().modify('extend', 'backward', 'character');
});*/
}
updated(changedProperties) {
super.updated(changedProperties);
changedProperties.forEach((oldValue, propName) => {});
}
/**
* life cycle, element is disconnected
*/
disconnectedCallback() {
super.disconnectedCallback();
}
/**
* undo for canceled edits
*
* @param {object} editor
* @memberof RichTextEditorSelection
*/
cancelEdits(editor) {
editor.revert();
this.edit(editor, false);
}
/**
* disables contenteditable
*
* @param {object} editor
* @memberof RichTextEditorSelection
*/
disableEditing(editor) {
if (!!editor) {
this.getRoot(editor).onselectionchange = undefined;
//editor.observeChanges(false);
editor.contenteditable = false;
editor.makeSticky(false);
}
}
/**
* executes button command on current range
*
*/
execCommand(command, val, range, toolbar) {
console.log(
">>>>>>>> execCommand",
command,
val,
range,
toolbar,
!range || range.cloneContents()
);
let editor = toolbar.editor;
if (range) {
this.range = editor.range;
this.updateRange(editor, range);
this.selectRange(range, editor);
if (command === "replaceHTML") {
let node = this.getRangeNode();
node.innerHTML = val;
} else if (command !== "paste") {
console.log("command", range, this.getRangeNode());
document.execCommand(command, false, val);
} else if (navigator.clipboard) {
this.pasteFromClipboard(editor);
}
this.highlight(toolbar, false);
}
}
/**
* Updates selected range based on toolbar and editor
* @param {event} e editor change event
* @param {deselect} if editor is being deselected
* @returns {void}
*/
edit(editor, editable = true) {
let toolbar = !editor ? undefined : this.getConnectedToolbar(editor),
oldEditor = editable ? toolbar.editor : undefined;
this.highlight(editor, false);
if (toolbar && oldEditor !== editor) {
this.disableEditing(oldEditor);
toolbar.editor = editor;
this.enableEditing(editor, toolbar);
}
}
/**
* enables content editable
*
* @param {*} editor
* @param {*} [toolbar=this.getConnectedToolbar(editor)]
* @memberof RichTextEditorSelection
*/
enableEditing(editor, toolbar = this.getConnectedToolbar(editor)) {
if (!!editor) {
editor.makeSticky(toolbar.sticky);
editor.parentNode.insertBefore(toolbar, editor);
editor.contenteditable = true;
this.updateRange(editor);
//editor.observeChanges(this.getRoot(editor));
this.getRoot(editor).onselectionchange = (e) => this.updateRange(editor);
}
}
/**
* expands selection to a specific ancestor
* @param {string} selectors comma-separated list of selectors
* @param {object} range
* @returns {object} updated range
*/
expandRangeTo(selectors = "", range) {
let node = range ? this.getRangeNode(range) : undefined,
tagName = node && node.tagName ? node.tagName.toLowerCase() : undefined,
selectorsList = selectors.toLowerCase().replace(/\s*/g, "").split(",");
if (selectorsList.includes(tagName)) {
return node;
} else if (node.closest(selectors)) {
range.selectNode(node.closest(selectors));
return range;
}
}
/**
* node selected or its parent node
*
* @param {object} range
* @returns object
* @memberof RichTextEditorSelection
*/
getRangeNode(range) {
let common = !range ? undefined : range.commonAncestorContainer,
startContainer = !range ? undefined : range.startContainer,
startOffset = !range ? undefined : range.startOffset,
endContainer = !range ? undefined : range.endContainer,
endOffset = !range ? undefined : range.endOffset,
startNode =
!startContainer || !startContainer.children
? undefined
: startContainer.children[startOffset - 1],
rootNode =
startContainer === endContainer && endOffset - startOffset === 1
? startNode
: common;
return rootNode;
}
/**
* gets closest shadowRoot or document from node
*
* @param {object} node
* @returns object
* @memberof RichTextEditorSelection
*/
getRoot(node) {
return !node || node === document
? document
: node.parentNode
? this.getRoot(node.parentNode)
: node;
}
/**
* paste content into a range;
* override this function to make your own filters
*
* @param {string} pasteContent html to be pasted
* @returns {string} filtered html as string
*/
getSanitizeClipboard(pasteContent) {
let regex = "<body(.*\n)*>(.*\n)*</body>";
if (pasteContent.match(regex) && pasteContent.match(regex).length > 0)
pasteContent = pasteContent.match(regex)[0].replace(/<\?body(.*\n)*\>/i);
return pasteContent;
}
/**
* gets toolbar currently assocatied with given editor
*
* @param {*} editor
* @returns
* @memberof RichTextEditorSelection
*/
getConnectedToolbar(editor) {
if (!editor.id) editor.id = this._generateUUID();
if (!editor.__connectedToolbar) {
//get toolbar by id
let toolbar,
filter = !editor.toolbar
? []
: (this.__toolbars || []).filter(
(toolbar) => toolbar.id === editor.toolbar
);
//get toolbar by type
if (filter.length === 0) {
filter = !editor.type
? []
: (this.__toolbars || []).filter(
(toolbar) => toolbar.type === editor.type
);
}
if (filter[0]) {
toolbar = filter[0];
} else if (filter.length === 0) {
//make toolbar
toolbar = document.createElement(
editor.type || "rich-text-editor-toolbar"
);
editor.parentNode.insertBefore(toolbar, editor);
}
toolbar.id = editor.toolbar || this._generateUUID();
editor.toolbar = toolbar.id;
editor.__connectedToolbar = toolbar;
}
return editor.__connectedToolbar;
}
/**
* selects and highlights a node
*
* @param {object} node
* @param {object} toolbar
* @returns {void}
* @memberof RichTextEditorSelection
*/
highlightNode(node, toolbar) {
this.selectNode(node, toolbar.range);
this.highlight(toolbar);
}
/**
* adds or removes hightlight
* @param {object} contents contents to be highlighted
* @param {boolean} [add=true] add highlight?
* @returns {void}
*/
highlight(toolbar, add = true) {
this.toolbar = toolbar;
let editor = toolbar.editor;
if (add !== false) {
if (toolbar.range) {
this.hidden = false;
toolbar.range.insertNode(this);
toolbar.range.setStartAfter(this);
this.range = toolbar.range;
}
} else {
this.updateRange(toolbar.editor, toolbar.range);
this.hidden = true;
this.toolbar = undefined;
this.range = undefined;
document.body.appendChild(this);
}
}
/**
* gets clipboard data and pastes into an editor's range
*
* @param {obj} editor
* @memberof RichTextEditorSelection
*/
pasteFromClipboard(editor) {
console.log("pasteFromClipboard", editor);
setTimeout(async () => {
let sel = window.getSelection(),
range = editor.range,
text = await navigator.clipboard.readText();
this.__clipboard.value = text;
this.__clipboard.focus();
this.__clipboard.select();
document.execCommand("paste");
sel.removeAllRanges();
sel.addRange(range);
this.pasteIntoEditor(editor, this.__clipboard.value);
}, 2000);
}
/**
* pastes content into editor's selected range
*
* @param {obj} editor editor
* @param {obj} pasteContent content to paste
* @param {boolean} [sanitize=true]
* @memberof RichTextEditorSelection
*/
pasteIntoEditor(editor, pasteContent, sanitize = true) {
console.log("pasteIntoEditor", editor);
if (editor)
this.pasteIntoRange(
editor,
editor.range,
sanitize ? this.getSanitizeClipboard(pasteContent) : pasteContent
);
}
/**
* paste content into a range
*
* @param {object} range where content will be pasted
* @param {string} pasteContent html to be pasted
* @returns {void}
*/
pasteIntoRange(editor, range, pasteContent) {
console.log("pasteIntoRange", editor);
let div = document.createElement("div"),
parent = range.commonAncestorContainer.parentNode,
closest = parent.closest(
"[contenteditable=true]:not([disabled]),input:not([disabled]),textarea:not([disabled])"
);
if ((editor = closest)) {
div.innerHTML = pasteContent;
if (range && range.extractContents) {
range.extractContents();
}
range.insertNode(div);
while (div.firstChild) {
div.parentNode.insertBefore(div.firstChild, div);
}
div.parentNode.removeChild(div);
}
}
/**
* sets up editor's event listeners
*
* @param {object} editor
* @param {boolean} [add=true]
* @returns {object} toolbar
* @memberof RichTextEditorSelection
*/
registerEditor(editor, remove = false) {
let toolbar = !editor ? undefined : this.getConnectedToolbar(editor),
handlers = {
focus: (e) => this.edit(editor),
blur: (e) => this._handleBlur(editor, e),
keydown: (e) => this._handleShortcutKeys(editor, e),
click: (e) => this._handleEditorClick(editor, e),
getrange: (e) => {
this.toolbar = toolbar;
this.updateRange(editor, editor.range);
},
pastefromclipboard: (e) => this.pasteFromClipboard(e.detail),
pastecontent: (e) => this._handlePaste(e),
};
if (!remove) {
//add event listeners
editor.addEventListener("mousedown", handlers.focus);
editor.addEventListener("focus", handlers.focus);
editor.addEventListener("keydown", handlers.keydown);
editor.addEventListener("blur", handlers.blur);
editor.addEventListener("getrange", handlers.getrange);
editor.addEventListener(
"pastefromclipboard",
handlers.pastefromclipboard
);
editor.addEventListener("pastecontent", handlers.pastecontent);
//editor.addEventListener("click", handlers.click);
} else {
editor.removeEventListener("mousedown", handlers.focus);
editor.removeEventListener("focus", handlers.focus);
editor.removeEventListener("keydown", handlers.keydown);
editor.removeEventListener("blur", handlers.blur);
editor.removeEventListener("getrange", handlers.getrange);
editor.removeEventListener(
"pastefromclipboard",
handlers.pastefromclipboard
);
editor.removeEventListener("pastecontent", handlers.pastecontent);
}
return editor.__connectedToolbar;
}
/**
* updates toolbar list
*
* @param {*} toolbar
* @param {boolean} [remove=false]
* @memberof RichTextEditorSelection
*/
registerToolbar(toolbar, remove = false) {
let handlers = {
exec: (e) => {
e.stopImmediatePropagation();
this.execCommand(
e.detail.command,
e.detail.commandVal,
e.detail.range,
toolbar
);
},
highlight: (e) => {
e.stopImmediatePropagation();
this.highlight(toolbar.editor, e.detail);
},
highlightnode: (e) => {
e.stopImmediatePropagation();
this.highlightNode(e.detail, toolbar);
},
selectnode: (e) => {
e.stopImmediatePropagation();
this.selectNode(e.detail, toolbar.range);
},
selectnodecontents: (e) => {
e.stopImmediatePropagation();
this.selectNode(e.detail, toolbar.range);
},
selectrange: (e) => {
e.stopImmediatePropagation();
this.selectRange(e.detail, toolbar.editor);
},
pastefromclipboard: (e) => {
e.stopImmediatePropagation();
this.pasteFromClipboard(e.detail);
},
wrapselection: (e) => {
e.stopImmediatePropagation();
this.surroundRange(e.detail, toolbar.range);
},
};
if (!remove && !toolbar.registered) {
this.__toolbars.push(toolbar);
toolbar.addEventListener("command", handlers.exec);
toolbar.addEventListener("highlight", handlers.highlight);
toolbar.addEventListener("highlightnode", handlers.highlightnode);
toolbar.addEventListener("selectnode", handlers.selectnode);
toolbar.addEventListener(
"selectnodecontents",
handlers.selectnodecontents
);
toolbar.addEventListener("selectrange", handlers.selectrange);
toolbar.addEventListener(
"pastefromclipboard ",
handlers.pastefromclipboard
);
toolbar.addEventListener("wrapselection ", handlers.wrapselection);
toolbar.registered = true;
} else {
toolbar.registered = false;
toolbar.removeEventListener("command", handlers.exec);
toolbar.removeEventListener("highlight", handlers.highlight);
toolbar.removeEventListener("highlightnode", handlers.highlightnode);
toolbar.removeEventListener("selectnode", handlers.selectnode);
toolbar.removeEventListener(
"selectnodecontents",
handlers.selectnodecontents
);
toolbar.removeEventListener("selectrange", handlers.selectrange);
toolbar.removeEventListener(
"pastefromclipboard ",
handlers.pastefromclipboard
);
this.__toolbars = this.__toolbars.filter((bar) => bar !== toolbar);
}
}
/**
* sets selection range to specified node
* @param {object} node node to select
* @returns {void}
*/
selectNode(node, range, editor = this.toolbar.editor) {
if (range) {
range.selectNode(node);
if (editor) this.updateRange(editor, range);
}
}
/**
* sets selection range to specified node's contents
* @param {object} node node to select
* @returns {void}
*/
selectNodeContents(node, range, editor = this.toolbar.editor) {
if (node) {
if (!range) {
let sel = window.getSelection();
range = document.createRange();
sel.removeAllRanges();
sel.addRange(range);
}
if (editor) this.updateRange(editor);
}
}
/**
* selects or deselects(collapses) a range
*
* @param {object} range
* @param {boolean} [select=true] select range?
* @memberof RichTextEditorSelection
*/
selectRange(range, select = true, editor) {
if (range) {
if (select) {
let sel = window.getSelection();
sel.removeAllRanges();
sel.addRange(range);
} else {
if (!range.isCollapsed) range.collapse();
}
if (editor) this.updateRange(editor);
}
return range;
}
surroundRange(node, range) {
if (range) {
range.surroundContents(node);
if (editor) this.updateRange(editor);
}
return range;
}
updateRange(editor, range) {
if (editor) {
let toolbar = this.getConnectedToolbar(editor);
this.toolbar = toolbar;
if (!range) range = editor.range;
editor.range = range;
if (toolbar) {
toolbar.selectedNode = editor.selectedNode;
toolbar.selectionAncestors = editor.selectionAncestors;
toolbar.range = range;
}
}
}
/**
* Generate a UUID
* @returns {string} unique id
*/
_generateUUID() {
let hex = Math.floor((1 + Math.random()) * 0x10000)
.toString(16)
.substring(1);
return "rte-" + "ss-s-s-s-sss".replace(/s/g, hex);
}
/**
* preserves highlight on editor selection when editor is not focus
*
* @param {*} editor
* @param {*} e
* @memberof RichTextEditorSelection
*/
_handleBlur(editor, e) {
if (
e.relatedTarget === null ||
!e.relatedTarget.startsWith === "rich-text-editor"
) {
this.edit(editor, true);
} else if (editor) {
this.highlight(editor);
}
}
_handleEditorClick(editor, e) {
let toolbar = !editor ? undefined : this.getConnectedToolbar(editor),
target = normalizeEventPath(e)[0];
/*if (editor.contenteditable && normalizeEventPath(e)[0] !== editor) {
editor.range = editor.range;
let button = toolbar.buttons.filter(
button => button.tag === normalizeEventPath(e)[0].tagName.toLowerCase()
),
range =
editor.range
? editor.range
: false,
start =
range && range.startContainer
? range.startContainer.childNodes[range.startOffset]
: false,
end =
range && range.endContainer
? range.endContainer.childNodes[range.endOffset - 1]
: false;
if (button && button[0] && start === end && start === normalizeEventPath(e)[0]) {
button[0]._buttonTap(e);
} else if (button && button[0]) {
this.selectNode(normalizeEventPath(e)[0],range);
}
} else if (editor.contenteditable){
//this.selectNodeContents(editor);
}*/
}
/**
* registers parts of the editor so that selection can manage them
*
* @param {event} e
* @memberof RichTextEditorSelection
*/
_handleRegistration(e) {
if (e.detail) {
if (e.detail.toolbar)
this.registerToolbar(e.detail.toolbar, e.detail.remove);
if (e.detail.editor)
this.registerEditor(e.detail.editor, e.detail.remove);
}
}
/**
* when a shortcut key is pressed, fire keypressed event on button associated with it
* @param {object} editor editor that detects a shortcut key
* @param {event} e key event
*/
_handleShortcutKeys(editor, e) {
let toolbar = !editor ? undefined : this.getConnectedToolbar(editor);
if (editor.contenteditable) {
let key = e.key;
if (e.shiftKey) key = "shift+" + key;
if (e.altKey) key = "alt+" + key;
if (
(window.navigator.platform === "MacIntel" && e.metaKey) ||
e.ctrlKey
) {
key = "ctrl+" + key;
}
if (toolbar.shortcutKeys[key]) toolbar.shortcutKeys[key]._keysPressed(e);
}
}
} |
JavaScript | class Taxonomies extends Container {
constructor(node, path) {
super(node, path);
}
get taxonomiesButton() {
return this.getByRole('button', { name: /Taxonomies/ });
}
get categories() {
return this.getAllByRole('checkbox');
}
get addNewCategoryButton() {
return this.getByRole('button', { name: /Add New Category/ });
}
get newCategoryNameInput() {
return this.getByRole('textbox', {
name: /New Category Name/,
});
}
get parentDropdownButton() {
return this.getByRole('button', { name: /Parent Category/ });
}
get tagTokenRemoveButtons() {
return this.getAllByRole('button', { name: /Remove Tag/ });
}
get tagsInput() {
return this.getByRole('combobox', { name: /Add New Tag/ });
}
} |
JavaScript | class Component {
constructor(gameObject) {
/**
* The name of the Component.
* @type {string}
* @name TDLib.Components.Component#name
* @since 1.0.0
*/
this.name = this.constructor.name;
/**
* The Sprite using the Component.
* @type {TDLib.Sprites.Sprite}
* @name TDLib.Components.Component#gameObject
* @since 1.0.0
*/
this.gameObject = gameObject;
}
} |
JavaScript | class Player {
constructor(symbol, isTurn = false) {
this.symbol = symbol;
this.isTurn = isTurn;
this.clicksArr = [];
this.combsArr = [];
}
play() {
this.isTurn = !this.isTurn;
}
getClickCnt() {
return this.clicksArr.length;
}
getSymbol() {
return this.symbol;
}
isWinner() {
if (this.clicksArr.length >= 3) {
this.combsArr = subset(this.clicksArr, 3);
if (isInWinArray(this.combsArr)) {
return true;
}
}
return false;
}
reset() {
let len = this.clicksArr.length;
this.clicksArr.splice(0, len);
}
} |
JavaScript | class GameBoard {
constructor(SYMBOLS) {
this.playerX = new Player(SYMBOLS[0], true);
this.playerO = new Player(SYMBOLS[1], false);
this.gameStatus = true;
this.index = 0;
}
isBoardFull() {
if (this.getGameClicks() > 8)
return true;
else
return false;
}
isGameOver() {
if (this.gameStatus && this.isBoardFull())
return true;
else
return false;
}
getGameClicks() {
let sum = this.playerX.getClickCnt()
+ this.playerO.getClickCnt();
return sum;
}
getPlayer(index) {
return ((index === 0) ? this.playerX : this.playerO);
}
resetGame() {
this.playerX.reset();
this.playerO.reset();
}
} |
JavaScript | class Storage {
constructor(key) {
try {
localStorage.setItem(key, 'LS')
localStorage.removeItem(key)
this.available = true
} catch (e) {
this.available = false
}
}
setItem(key, val) {
if (this.available) localStorage.setItem(key, val)
return Promise.resolve()
}
getItem(key) {
let val = null
if (this.available) val = localStorage.getItem(key)
return Promise.resolve(val)
}
getAllKeys() {
return Promise.resolve(this.available ?
Object.keys(localStorage) : [])
}
} |
JavaScript | class LimitsRepository {
constructor(repositoryLocator, redisClient) {
this.client = redisClient;
}
tableName(realm) {
return `limits_${realm}`;
}
/**
* This method finds limit records by realm
* @param {*} realm - realm-name
* @return list of limits
*/
async findByRealm(realm) {
assert(realm, 'realm-name not specified for limits');
let table = this.tableName(realm);
return new Promise((resolve, reject) => {
this.client.hgetall(table, (err, limits) => {
if (err) {
reject(new PersistenceError(`Could not find limit with realm ${realm} due to ${err}`));
} else {
resolve(Object.entries(limits || []).map(([k,v]) => {
let obj = JSON.parse(v);
return new Limits(obj.type, obj.resource, obj.maxAllowed, 0, null);
}));
}
});
});
}
/**
* This method saves object and returns updated object
* @param {*} realm - realm-name
* @param {*} limit - to save
*/
async save(realm, limit) {
assert(realm, 'realm-name not specified for limits');
assert(limit, 'limit not specified');
let table = this.tableName(realm);
let key = limit.uniqueKey();
let toSave = extend({}, limit);
toSave.value = 0;
toSave.expirationDate = null;
//
return new Promise((resolve, reject) => {
this.client.hmset(table, key, JSON.stringify(toSave), (err) => {
if (err) {
reject(err);
} else {
resolve(limit);
}
});
});
}
/**
* This method removes object by principal-name
* @param {*} realm - realm-name
* @param {*} limit - to remove
*/
async remove(realm, limit) {
assert(realm, 'realm-name not specified for limits');
let table = this.tableName(realm);
let key = limit.uniqueKey();
return new Promise((resolve, reject) => {
this.client.hdel(table, key, (err) => {
if (err) {
reject(new PersistenceError(`Could not remove limit with realm-name ${realm} and key ${key} due to ${err}`));
} else {
resolve(true);
}
});
});
}
} |
JavaScript | class WidgetToolbarRepository extends Plugin {
/**
* @inheritDoc
*/
static get requires() {
return [ ContextualBalloon ];
}
/**
* @inheritDoc
*/
static get pluginName() {
return 'WidgetToolbarRepository';
}
/**
* @inheritDoc
*/
init() {
const editor = this.editor;
const balloonToolbar = editor.plugins.get( 'BalloonToolbar' );
// Disables the default balloon toolbar for all widgets.
if ( balloonToolbar ) {
this.listenTo( balloonToolbar, 'show', evt => {
if ( isWidgetSelected( editor.editing.view.document.selection ) ) {
evt.stop();
}
}, { priority: 'high' } );
}
/**
* A map of toolbars.
*
* @protected
* @member {Map.<string,Object>} #_toolbars
*/
this._toolbars = new Map();
/**
* @private
*/
this._balloon = this.editor.plugins.get( 'ContextualBalloon' );
this.listenTo( editor.ui, 'update', () => {
this._updateToolbarsVisibility();
} );
// UI#update is not fired after focus is back in editor, we need to check if balloon panel should be visible.
this.listenTo( editor.ui.focusTracker, 'change:isFocused', () => {
this._updateToolbarsVisibility();
}, { priority: 'low' } );
}
/**
* Registers toolbar in the WidgetToolbarRepository. It renders it in the `ContextualBalloon` based on the value of the invoked
* `visibleWhen` function. Toolbar items are gathered from `items` array.
* The balloon's CSS class is by default `ck-toolbar-container` and may be override with the `balloonClassName` option.
*
* Note: This method should be called in the {@link module:core/plugin~PluginInterface#afterInit `Plugin#afterInit()`}
* callback (or later) to make sure that the given toolbar items were already registered by other plugins.
*
* @param {String} toolbarId An id for the toolbar. Used to
* @param {Object} options
* @param {Array.<String>} options.items Array of toolbar items.
* @param {Function} options.visibleWhen Callback which specifies when the toolbar should be visible for the widget.
* @param {String} [options.balloonClassName='ck-toolbar-container'] CSS class for the widget balloon.
*/
register( toolbarId, { items, visibleWhen, balloonClassName = 'ck-toolbar-container' } ) {
const editor = this.editor;
const toolbarView = new ToolbarView();
if ( this._toolbars.has( toolbarId ) ) {
/**
* Toolbar with the given id was already added.
*
* @error widget-toolbar-duplicated
* @param toolbarId Toolbar id.
*/
throw new CKEditorError( 'widget-toolbar-duplicated: Toolbar with the given id was already added.', { toolbarId } );
}
toolbarView.fillFromConfig( items, editor.ui.componentFactory );
this._toolbars.set( toolbarId, {
view: toolbarView,
visibleWhen,
balloonClassName,
} );
}
/**
* Iterates over stored toolbars and makes them visible or hidden.
*
* @private
*/
_updateToolbarsVisibility() {
for ( const toolbar of this._toolbars.values() ) {
if ( !this.editor.ui.focusTracker.isFocused || !toolbar.visibleWhen( this.editor.editing.view.document.selection ) ) {
this._hideToolbar( toolbar );
} else {
this._showToolbar( toolbar );
}
}
}
/**
* Hides the given toolbar.
*
* @private
* @param {Object} toolbar
*/
_hideToolbar( toolbar ) {
if ( !this._isToolbarVisible( toolbar ) ) {
return;
}
this._balloon.remove( toolbar.view );
}
/**
* Shows up the toolbar if the toolbar is not visible and repositions the toolbar's balloon when toolbar's
* view is the most top view in balloon stack.
*
* It might happen here that the toolbar's view is under another view. Then do nothing as the other toolbar view
* should be still visible after the {@link module:core/editor/editorui~EditorUI#event:update}.
*
* @private
* @param {Object} toolbar
*/
_showToolbar( toolbar ) {
if ( this._isToolbarVisible( toolbar ) ) {
repositionContextualBalloon( this.editor );
} else if ( !this._balloon.hasView( toolbar.view ) ) {
this._balloon.add( {
view: toolbar.view,
position: getBalloonPositionData( this.editor ),
balloonClassName: toolbar.balloonClassName,
} );
}
}
/**
* @private
* @param {Object} toolbar
*/
_isToolbarVisible( toolbar ) {
return this._balloon.visibleView == toolbar.view;
}
} |
JavaScript | class MembersSegmentStringTransform extends Transform {
deserialize(serialized) {
if (serialized === 'all') {
return 'status:free,status:-free';
}
if (serialized === 'none') {
return null;
}
return serialized;
}
serialize(deserialized) {
if (deserialized === 'status:free,status:-free') {
return 'all';
}
if (!deserialized) {
return 'none';
}
return deserialized;
}
} |
JavaScript | class Demo extends React.PureComponent {
static defaultProps = {
title: 'This is a demo',
value: 0
}
constructor(props) {
super(props)
const { title, value } = props
this.state = {
title,
value
}
}
add = () => {
this.setState({
value: this.state.value + 1
})
}
change = ev => {
this.setState({
value: ev.target.value
})
}
static getDerivedStateFromProps(nextProps, prevState) {
const { title } = nextProps
// 当传入的type发生变化的时候,更新state
if (title !== prevState.title) {
return {
title
}
}
// 否则,对于state不进行任何操作
return null
}
render() {
return (
<div className="container">
<h1>{this.state.title}</h1>
<div className="counter">{this.state.value}</div>
<input value={this.state.value} onChange={this.change} />
<button onClick={this.add}>Value ++</button>
</div>
)
}
} |
JavaScript | class EudlRecognizerResult extends RecognizerResult {
constructor(nativeResult) {
super(nativeResult.resultState);
/**
* The address of the EU Driver License owner.
*/
this.address = nativeResult.address;
/**
* The birth Data of the EU Driver License owner.
*/
this.birthData = nativeResult.birthData;
/**
* The country of the EU Driver License owner.
*/
this.country = nativeResult.country;
/**
* The driver Number of the EU Driver License owner.
*/
this.driverNumber = nativeResult.driverNumber;
/**
* The expiry Date of the EU Driver License owner.
*/
this.expiryDate = nativeResult.expiryDate != null ? new Date(nativeResult.expiryDate) : null;
/**
* face image from the document if enabled with returnFaceImage property.
*/
this.faceImage = nativeResult.faceImage;
/**
* The first Name of the EU Driver License owner.
*/
this.firstName = nativeResult.firstName;
/**
* full document image if enabled with returnFullDocumentImage property.
*/
this.fullDocumentImage = nativeResult.fullDocumentImage;
/**
* The issue Date of the EU Driver License owner.
*/
this.issueDate = nativeResult.issueDate != null ? new Date(nativeResult.issueDate) : null;
/**
* The issuing Authority of the EU Driver License owner.
*/
this.issuingAuthority = nativeResult.issuingAuthority;
/**
* The last Name of the EU Driver License owner.
*/
this.lastName = nativeResult.lastName;
/**
* The personal Number of the EU Driver License owner.
*/
this.personalNumber = nativeResult.personalNumber;
}
} |
JavaScript | class EudlRecognizer extends Recognizer {
constructor() {
super('EudlRecognizer');
/**
* Country of scanning Eudl. The default value of EudlCountryAny will scan all supported driver's licenses.
*
*
*/
this.country = EudlCountry.Automatic;
/**
* Defines if owner's address should be extracted from EU Driver License
*
*
*/
this.extractAddress = true;
/**
* Defines if owner's date of expiry should be extracted from EU Driver License
*
*
*/
this.extractDateOfExpiry = true;
/**
* Defines if owner's date of issue should be extracted from EU Driver License
*
*
*/
this.extractDateOfIssue = true;
/**
* Defines if owner's issuing authority should be extracted from EU Driver License
*
*
*/
this.extractIssuingAuthority = true;
/**
* Defines if owner's personal number should be extracted from EU Driver License
*
*
*/
this.extractPersonalNumber = true;
/**
* Property for setting DPI for face images
* Valid ranges are [100,400]. Setting DPI out of valid ranges throws an exception
*
*
*/
this.faceImageDpi = 250;
/**
* Property for setting DPI for full document images
* Valid ranges are [100,400]. Setting DPI out of valid ranges throws an exception
*
*
*/
this.fullDocumentImageDpi = 250;
/**
* Sets whether face image from ID card should be extracted
*
*
*/
this.returnFaceImage = false;
/**
* Sets whether full document image of ID card should be extracted.
*
*
*/
this.returnFullDocumentImage = false;
this.createResultFromNative = function (nativeResult) { return new EudlRecognizerResult(nativeResult); }
}
} |
JavaScript | class NumberFormatterRegistry extends _models.RegistryWithDefaultKey {
constructor() {
super({
name: 'NumberFormatter',
overwritePolicy: _types.OverwritePolicy.WARN
});
this.registerValue(_NumberFormats.default.SMART_NUMBER, (0, _createSmartNumberFormatter.default)());
this.registerValue(_NumberFormats.default.SMART_NUMBER_SIGNED, (0, _createSmartNumberFormatter.default)({
signed: true
}));
this.setDefaultKey(_NumberFormats.default.SMART_NUMBER);
}
get(formatterId) {
const targetFormat = `${formatterId === null || typeof formatterId === 'undefined' || formatterId === '' ? this.defaultKey : formatterId}`.trim();
if (this.has(targetFormat)) {
return super.get(targetFormat);
} // Create new formatter if does not exist
const formatter = (0, _createD3NumberFormatter.default)({
formatString: targetFormat
});
this.registerValue(targetFormat, formatter);
return formatter;
}
format(formatterId, value) {
return this.get(formatterId)(value);
}
} |
JavaScript | class Form extends Component {
/**
* @constructor
* @param {Object} props
* @return {Void}
*/
constructor (props) {
super(props)
/**
* validations
* @description Holds functions which correspond to form elements and will be used for validation
* @type {Array}
*/
this.validations = []
// Bind private functions
this.registerValidation = this.registerValidation.bind(this)
this.removeValidation = this.removeValidation.bind(this)
this.isFormValid = this.isFormValid.bind(this)
this.submit = this.submit.bind(this)
}
/**
* registerValidation
* @param {Boolean} isValidFunc
* @description Will push a new validation function to the current stack
* Returning a function to remove the validation function if a component
* unmounts
* @return {Function}
*/
registerValidation (isValidFunc) {
this.validations = [...this.validations, isValidFunc]
return () => { this.removeValidation(isValidFunc) }
}
/**
* removeValidation
* @param {Function} ref
* @description Removes a specific validation function from the current stack
* @return {Void}
*/
removeValidation (ref) {
this.validations = this.validations.filter(filter => filter !== ref)
}
/**
* isFormValid
* @param {Boolean} showErrors
* @description Checks all validations and returns a boolean if form is valid or not
* @return {Boolean}
*/
isFormValid (showErrors) {
return this.validations.reduce((memo, isValidFunc) => {
return isValidFunc(showErrors) && memo
}, true)
}
/**
* @param evt
*/
submit (evt) {
const { handleSubmit } = this.props
if (evt && evt.preventDefault) {
evt.preventDefault()
}
if (this.isFormValid(true)) {
handleSubmit ? handleSubmit({...this.props.values}) : null
}
}
/**
* getChildContext
* @return {Object}
*/
getChildContext () {
return {
update: this.props.update,
submit: this.submit,
values: this.props.values,
initialValues: this.props.initialValues,
validators: this.props.validators,
registerValidation: this.registerValidation,
isFormValid: this.isFormValid,
updateErrors: this.props.updateErrors,
errors: this.props.errors
}
}
render () {
/**
* @const
* @type {String}
*/
const modifiedClassNames = classNames('form', this.props.className)
return (
<form className={modifiedClassNames} onSubmit={this.submit} autoComplete={this.props.autocomplete ? 'on' : 'off'}>
{this.props.children}
</form>
)
}
} |
JavaScript | class EventStore extends HTMLElement {
constructor() {
super();
this.onStateChanged = this.onStateChanged.bind(this);
this._update = this._update.bind(this);
this._timer = 0;
this._timeOffset = 0;
this._days = [];
}
/**
* Interval function to determine which day is currently active and whether
* or not chat should be enabled.
*/
_update() {
const now = +new Date() + this._timeOffset;
let daysPropertiesChange = false;
let activeDay = null;
// If there was a previously active day (because the user has their tab open for a long time),
// then prefer it over showing the upcoming day (we store that in nextPendingDay).
let nextPendingDay = null;
for (const day of this._days || []) {
const timeOffsetBy = (minutes) => {
const d = new Date(day.when);
d.setMinutes(d.getMinutes() + minutes);
return +d;
};
const activeStart = timeOffsetBy(-bufferMinutes);
const activeEnd = timeOffsetBy(day.duration + bufferMinutes);
const chatStart = timeOffsetBy(-bufferChatMinutes);
const chatEnd = timeOffsetBy(day.duration + bufferChatMinutes);
// DEBUG
// Suggest leaving this checked-in because it's very useful for debugging.
// console.log(
// 'day.when',
// `${new Date(day.when)}\n`,
// 'activeStart:',
// `${new Date(activeStart)}\n`,
// 'chatStart:',
// `${new Date(chatStart)}\n`,
// 'activeEnd:',
// `${new Date(activeEnd)}\n`,
// 'chatEnd:',
// `${new Date(chatEnd)}\n`,
// );
// Are we past the completion of this day? This allows the YT link to show up.
const isComplete = now >= activeEnd;
if (day.isComplete !== isComplete) {
day.isComplete = isComplete;
daysPropertiesChange = true;
}
if (!isComplete && nextPendingDay === null) {
// The first time we find an incomplete day (e.g., tomorrow's event day), mark it as the
// next pending day we use as the active fallback.
nextPendingDay = day;
}
// Is this day active (within the buffer time range)?
const isActive = now >= activeStart && now < activeEnd;
if (isActive) {
activeDay = day;
}
// Is this the active day for chat (within the actual time range)?
const isChatActive = now >= chatStart && now < chatEnd;
if (day.isChatActive !== isChatActive) {
day.isChatActive = isChatActive;
daysPropertiesChange = true;
}
}
// If there was no previously active day, then choose the upcoming day.
// If we've reached the end of the event then revert to the first day.
if (activeDay === null) {
activeDay = nextPendingDay ? nextPendingDay : this._days[0];
}
// If there was a property change on any particular day, change the Array
// reference so listeners can use simple comparisons to force a refresh.
if (daysPropertiesChange) {
this._days = this._days.slice();
}
store.setState({
eventDays: this._days,
activeEventDay: activeDay,
});
}
connectedCallback() {
const raw = JSON.parse(this.textContent.trim());
for (let i = 0; i < raw.days.length; ++i) {
const day = raw.days[i];
day.index = i;
day.isComplete = false;
day.isChatActive = false;
}
this._days = raw.days || [];
store.setState({communityEvents: raw.communityEvents});
this._update();
this._timer = window.setInterval(this._update, timerEveryMillisecond);
store.subscribe(this.onStateChanged);
this.onStateChanged(store.getState());
}
disconnectedCallback() {
store.unsubscribe(this.onStateChanged);
this._days = [];
this._update();
window.clearInterval(this._timer);
}
onStateChanged({timeOffset}) {
if (this._timeOffset !== timeOffset) {
this._timeOffset = timeOffset;
this._update();
}
}
} |
JavaScript | class Slide extends Component {
static defaultProps = {
defaultStyle: {
flexShrink: 0,
},
};
constructor(props) {
super(props);
this.state = {
style: props.style || {},
};
this.slide = React.createRef();
}
componentDidMount() {
const element = this.slide.current;
this.setState({ element });
}
render() {
let { style } = this.state;
const {
active,
children,
className,
index,
defaultStyle,
next,
} = this.props;
const cname = cn({
slide: true,
[`slide-${index}`]: true,
[className]: !!className,
});
const display = active === index || next === index;
const newStyle = {
...defaultStyle,
...style,
display: display ? '' : 'none',
};
return (
<div className={cname} style={newStyle} ref={this.slide}>
{children}
</div>
);
}
} |
JavaScript | class ModalTemplate extends Template {
_instance = null;
/**
* Creates a modal given a reference element. Use `Modal.shared` with a
* subclass to get a canolical reference
*
* @param {string} title - title of modal
* @param {HTMLElement} root - Root view of the template
* @param {TemplateType} type - Type of the template to reference.
*/
constructor(title, root, type) {
super(root, type);
this._title = title;
this._subtitle = null;
}
/**
* Obtains subtitle or nil
* @type {?string}
*/
get subtitle() { return this._subtitle; }
/**
* Sets the subtitle (note: may not update until re-created)
* @type {string}
*/
set subtitle(newSubtitle) { this._subtitle = newSubtitle; }
/**
* Returns shared instance, only applicable for subclasses
* @type {Modal}
*/
static get shared() {
return this._instance || (this._instance = new this());
}
/**
* Returns the modal title
* @type {string}
*/
get title() { return this._title; }
} |
JavaScript | class JsonData extends HTMLElement {
constructor() {
super();
const shadowRoot = this.attachShadow({mode: 'open'});
shadowRoot.appendChild(shadowTmpl.content.cloneNode(true));
this.state = {
isLoading: false,
hasError: false,
isLoaded: false,
errorMessage: null,
};
this.handleButtonClick = this.handleButtonClick.bind(this);
}
static get observedAttributes() {
return ['url', 'url-params'];
}
attributeChangedCallback(attr, oldVal, /* newVal */) {
switch (attr) {
case 'url':
case 'url-params':
if (oldVal !== null && !this.manualFetchMode) {
this.fetch();
}
break;
}
}
connectedCallback() {
this.elements = {
isLoading: this.querySelector('is-loading'),
hasError: this.querySelector('has-error'),
isLoaded: this.querySelector('is-loaded'),
clickButton: null,
};
// Handle the [click-selector] Attribute. If defined on the <json-data>
// Control then data is not fetched until the user clicks the element specified
// from the selector. This feature along with the form elements that use the
// attribute [data-bind] allows for search pages and forms to be developed through HTML.
if (this.clickSelector !== null) {
this.elements.clickButton = document.querySelector(this.clickSelector);
if (this.elements.clickButton === null) {
const error = 'Element not found for <json-data> Web Component using [click-selector]: ' + String(this.clickSelector);
showErrorAlert(error);
} else {
this.elements.clickButton.addEventListener('click', this.handleButtonClick);
}
return;
}
// Only fetch data automatically once when the element is attached to
// the DOM. If [removeChild] and [appendChild] are used to move the
// element on the page this prevents the web service from being called
// multiple times.
if (this.state !== undefined && !this.state.isLoading && !this.state.hasError && !this.state.isLoaded) {
if (!this.manualFetchMode) {
this.fetch();
}
}
}
disconnectedCallback() {
if (this.elements && this.elements.clickButton !== null) {
this.elements.clickButton.removeEventListener('click', this.handleButtonClick);
this.elements.clickButton = null;
}
}
/**
* Internal function used with [click-selector]
*/
handleButtonClick() {
// Disable button while data is being fetched
if (typeof this.elements.clickButton.disabled === 'boolean') {
this.elements.clickButton.disabled = true;
}
// Get all form elements that have the [data-bind="{name}"] attribute
const elements = document.querySelectorAll('input[data-bind],select[data-bind],textarea[data-bind]');
const params = {};
for (const el of elements) {
const name = el.getAttribute('data-bind');
if (el.nodeName === 'INPUT' && el.type === 'checkbox') {
params[name] = el.checked;
} else {
params[name] = el.value;
}
}
// Set URL Params, this triggers `fetch`. First it must be defined
// before having data populated otherwise it won't trigger the fetch.
this.setAttribute('url-params', '');
this.setAttribute('url-params', JSON.stringify(params));
}
get url() {
return this.getAttribute('url');
}
set url(newValue) {
this.setAttribute('url', newValue);
}
get urlParams() {
return this.getAttribute('url-params');
}
set urlParams(newValue) {
if (typeof newValue !== 'object') {
this.showError(`When setting [urlParams] of <json-data> the value must be an object but was instead a type of [${typeof newValue}].`);
return;
}
this.setAttribute('url-params', JSON.stringify(newValue));
}
get loadOnlyOnce() {
return (this.getAttribute('load-only-once') !== null);
}
get clickSelector() {
return this.getAttribute('click-selector');
}
get manualFetchMode() {
return (this.getAttribute('manual-fetch-mode') !== null);
}
get isLoading() {
return this.state.isLoading;
}
set isLoading(val) {
this.state.isLoading = (val === true ? true : false);
if (this.elements.isLoading) {
this.elements.isLoading.style.display = (this.state.isLoading ? '' : 'none');
}
}
get hasError() {
return this.state.hasError;
}
set hasError(val) {
this.state.hasError = (val === true ? true : false);
if (this.elements.hasError) {
this.elements.hasError.style.display = (this.state.hasError ? '' : 'none');
}
}
get isLoaded() {
return this.state.isLoaded;
}
set isLoaded(val) {
this.state.isLoaded = (val === true ? true : false);
if (this.elements.isLoaded) {
this.elements.isLoaded.style.display = (this.state.isLoaded ? '' : 'none');
}
}
dispatchContentReady() {
// Dispatch Standard DOM Event. Because it bubbles up it can be easily
// handled from the document root:
// document.addEventListener('app:contentReady', () => { ... });
this.dispatchEvent(new Event(appEvents.contentReady, { bubbles: true }));
// Execute JavaScript from [onready] attribute if one is defined
const js = this.getAttribute('onready');
if (js) {
try {
if (!this.isConnected) {
// Only call user code if the element is still connected to the DOM.
// For SPA if the user clicks of the page on a long running task then
// fetch will still be running but the element will not longer be connected.
// This would result in an error being shown to the user if an expected
// element or other item is missing from the page.
return;
}
const fn = new Function('return ' + js);
const result = fn();
if (typeof result === 'function') {
result();
}
} catch(e) {
showErrorAlert(`Error from function <json-data onready="${js}">: ${e.message}`);
console.error(e);
}
}
}
async fetch() {
const urlPath = this.url;
let url = urlPath;
if (url === null || url === '') {
await this.showError('Error, element <json-data> is missing attribute [url]');
this.dispatchContentReady();
return;
}
// If [url-params] is defined by empty then wait for
// it to be set before fetching data.
let urlParams = this.getAttribute('url-params');
if (urlParams === '' && url.includes(':')) {
return;
}
// Load from Cache if [load-only-once] is defined and the
// same content was previously viewed.
if (this.loadOnlyOnce) {
const data = getDataFromCache(urlPath, urlParams);
if (data !== null) {
await this._setLoadedState(data);
this.dispatchContentReady();
return;
}
}
if (urlParams) {
urlParams = JSON.parse(urlParams);
}
url = buildUrl(url, urlParams);
this.isLoading = true;
this.isLoaded = false;
this.hasError = false;
await this.bindData();
fetch(url, {
mode: 'cors',
cache: 'no-store',
credentials: 'same-origin',
})
.then(response => {
const status = response.status;
if ((status >= 200 && status < 300) || status === 304) {
return Promise.resolve(response);
} else {
const error = 'Error loading data. Server Response Code: ' + status + ', Response Text: ' + response.statusText;
return Promise.reject(error);
}
})
.then(response => {
return response.json();
})
.then(async (data) => {
if (this.loadOnlyOnce) {
saveDataToCache(urlPath, urlParams, data);
}
await this._setLoadedState(data);
})
.catch(async (error) => {
await this.showError(error);
})
.finally(() => {
if (this.elements.clickButton !== null && typeof this.elements.clickButton.disabled === 'boolean') {
this.elements.clickButton.disabled = false;
}
this.dispatchContentReady();
});
}
async showError(message) {
this.isLoading = false;
this.isLoaded = false;
this.hasError = true;
this.state.errorMessage = message;
this.dispatchEvent(new CustomEvent(appEvents.error, { bubbles: true, detail: message }));
await this.bindData();
console.error(message);
}
async _setLoadedState(data) {
this.isLoading = false;
this.isLoaded = true;
this.hasError = false;
this.state.errorMessage = null;
const transformData = this.getAttribute('transform-data');
if (transformData) {
try {
if (typeof window[transformData] === 'function') {
const data2 = window[transformData](data);
if (typeof data2 === 'object' && data2 !== null) {
Object.assign(this.state, data2);
} else {
await this.showError(`Function [${transformData}()] must return an object.`);
}
} else {
await this.showError(`Function [${transformData}()] was not found.`);
}
} catch (e) {
await this.showError(e);
}
} else {
Object.assign(this.state, data);
}
if (typeof data.hasError === 'boolean') {
this.hasError = data.hasError;
}
await this.bindData();
}
async bindData() {
// Wait until child web components are defined otherwise
// custom properties such as [value] will not be available.
await componentsAreDefined(this, '[data-bind]');
// Update all elements with the attribute [data-bind]
// - If only [data-bind] is defined then pass the entire state
// - Otherwise pass the field value from the key
let elements = this.querySelectorAll('[data-bind]');
for (const element of elements) {
const key = element.getAttribute('data-bind');
let value = (key === '' ? this.state : getBindValue(this.state, key));
const dataType = element.getAttribute('data-format');
if (dataType !== null) {
if (typeof format[dataType] === 'function') {
value = format[dataType](value);
} else if (typeof window[dataType] === 'function') {
try {
value = window[dataType](value);
} catch (e) {
console.error(e);
value = 'Error: ' + e.message;
}
} else {
value = 'Error: Unknown format [' + dataType + ']';
}
}
setElementText(element, value);
}
// Update all elements with the [data-bind-attr] attribute.
// This will typically be used to replace <a href> and other
// attributes with values from the downloaded data.
elements = this.querySelectorAll('[data-bind-attr]');
for (const element of elements) {
bindAttrTmpl(element, 'data-bind-attr', this.state);
}
// Show or hide elements based on [data-show="js-expression"].
// Elements here will have the toggled `style.display` for viewing
// or to hide based on the result of the expression. This is similar
// behavior to Vue [v-show].
elements = this.querySelectorAll('[data-show]');
for (const element of elements) {
if (this.state.isLoading) {
// [data-show] elements will be hidden during loading
element.style.display = 'none';
} else {
const expression = element.getAttribute('data-show');
try {
const tmpl = new Function('state', 'format', 'with(state){return ' + expression + '}');
const result = tmpl(this.state, format);
element.style.display = (result === true ? '' : 'none');
} catch (e) {
element.style.display = '';
console.error(`Error evaluating JavaScript expression from [data-show="${expression}"] attribute.`);
console.error(e);
}
}
}
// Call functions on elements that define the [data-bind-refresh] attribute.
// This allows for elements to be updated as needed from HTML. This will most
// commonly be used with [click-selector] and other Web Components. For example
// the places demo search screen does this with <input is="input-filter">.
elements = this.querySelectorAll('[data-bind-refresh]');
for (const element of elements) {
const fnName = element.getAttribute('data-bind-refresh');
try {
element[fnName]();
} catch (e) {
console.error(`Error calling function from element with [data-bind-refresh="${fnName}"].`);
console.error(e);
console.log(element);
}
}
// For Safari, Samsung Internet, and Edge
polyfillCustomElements();
}
} |
JavaScript | class SHA384Algo extends sha512_js_1.SHA512Algo {
_doReset() {
this._hash = new x64_core_js_1.X64WordArray([
new x64_core_js_1.X64Word(0xcbbb9d5d, 0xc1059ed8),
new x64_core_js_1.X64Word(0x629a292a, 0x367cd507),
new x64_core_js_1.X64Word(0x9159015a, 0x3070dd17),
new x64_core_js_1.X64Word(0x152fecd8, 0xf70e5939),
new x64_core_js_1.X64Word(0x67332667, 0xffc00b31),
new x64_core_js_1.X64Word(0x8eb44a87, 0x68581511),
new x64_core_js_1.X64Word(0xdb0c2e0d, 0x64f98fa7),
new x64_core_js_1.X64Word(0x47b5481d, 0xbefa4fa4),
]);
}
_doFinalize() {
const hash = super._doFinalize.call(this);
hash.sigBytes -= 16;
return hash;
}
} |
JavaScript | class TotalFilter {
static getAttributeTypeMap() {
return TotalFilter.attributeTypeMap;
}
} |
JavaScript | class N2UserInterface {
/**
* Initialize properties, set up the collapse-depth menu, and set up other
* elements of the toolbar.
* @param {N2Diagram} n2Diag A reference to the main diagram.
*/
constructor(n2Diag) {
this.n2Diag = n2Diag;
this.leftClickedNode = document.getElementById('ptN2ContentDivId');
this.rightClickedNode = null;
this.lastClickWasLeft = true;
this.leftClickIsForward = true;
this.findRootOfChangeFunction = null;
this.callSearchFromEnterKeyPressed = false;
this.backButtonHistory = [];
this.forwardButtonHistory = [];
this._setupCollapseDepthElement();
this.updateClickedIndices();
document.getElementById(
'searchButtonId'
).onclick = this.searchButtonClicked.bind(this);
this._setupToolbar();
this._setupSearch();
this.legend = new N2Legend(this.n2Diag.modelData);
this.toggleLegend();
}
/** Set up the menu for selecting an arbitrary depth to collapse to. */
_setupCollapseDepthElement() {
let self = this;
let collapseDepthElement = this.n2Diag.dom.parentDiv.querySelector(
'#depth-slider'
);
collapseDepthElement.max = this.n2Diag.model.maxDepth - 1;
collapseDepthElement.value = collapseDepthElement.max;
collapseDepthElement.onmouseup = function(e) {
const modelDepth = parseInt(e.target.value);
self.collapseToDepthSelectChange(modelDepth);
};
}
/**
* When a node is right-clicked or otherwise targeted for collapse, make sure it
* has children and isn't the root node. Set the node as minimized and update
* the diagram drawing.
*/
collapse() {
testThis(this, 'N2UserInterface', 'collapse');
let node = this.leftClickedNode;
if (!node.hasChildren()) return;
// Don't allow minimizing of root node
if (node.depth > this.n2Diag.zoomedElement.depth || node.type !== 'root') {
this.rightClickedNode = node;
if (this.collapsedRightClickNode !== undefined) {
this.rightClickedNode = this.collapsedRightClickNode;
this.collapsedRightClickNode = undefined;
}
this.findRootOfChangeFunction = this.findRootOfChangeForRightClick.bind(
this
);
N2TransitionDefaults.duration = N2TransitionDefaults.durationFast;
this.lastClickWasLeft = false;
node.toggleMinimize();
this.n2Diag.update();
}
}
/* When a node is right-clicked, collapse it. */
rightClick(node1, node2) {
testThis(this, 'N2UserInterface', 'rightClick');
this.leftClickedNode = node1;
this.rightClickedNode = node2;
let node = this.leftClickedNode;
node['collapsable'] = true;
this.backButtonHistory.push({
node: node,
});
d3.event.preventDefault();
d3.event.stopPropagation();
this.collapse();
}
/**
* Update states as if a left-click was performed, which may or may not have
* actually happened.
* @param {N2TreeNode} node The node that was targetted.
*/
_setupLeftClick(node) {
this.leftClickedNode = node;
this.lastClickWasLeft = true;
if (this.leftClickedNode.depth > this.n2Diag.zoomedElement.depth) {
this.leftClickIsForward = true; // forward
} else if (this.leftClickedNode.depth < this.n2Diag.zoomedElement.depth) {
this.leftClickIsForward = false; // backwards
}
this.n2Diag.updateZoomedElement(node);
N2TransitionDefaults.duration = N2TransitionDefaults.durationFast;
}
/**
* React to a left-clicked node by zooming in on it.
* @param {N2TreeNode} node The targetted node.
*/
leftClick(node) {
testThis(this, 'N2UserInterface', 'leftClick');
if (!node.hasChildren() || node.isParam()) return;
if (d3.event.button != 0) return;
this.backButtonHistory.push({
node: this.n2Diag.zoomedElement,
});
this.forwardButtonHistory = [];
this._setupLeftClick(node);
d3.event.preventDefault();
d3.event.stopPropagation();
this.n2Diag.update();
}
/**
* Set up for an animated transition by setting and remembering where things were.
*/
updateClickedIndices() {
enterIndex = exitIndex = 0;
if (this.lastClickWasLeft) {
if (this.leftClickIsForward) {
exitIndex =
this.leftClickedNode.rootIndex -
this.n2Diag.zoomedElementPrev.rootIndex;
} else {
enterIndex =
this.n2Diag.zoomedElementPrev.rootIndex -
this.leftClickedNode.rootIndex;
}
}
}
/**
* When the back history button is clicked, pop the top node from that
* history stack, and disable the button if the stack is empty. Find the
* neared un-minimized node (if not the node itself) and zoom to that.
* Add the previous zoomed node to the forward history stack.
*/
backButtonPressed() {
testThis(this, 'N2UserInterface', 'backButtonPressed');
if (this.backButtonHistory.length == 0) return;
let node = this.backButtonHistory[this.backButtonHistory.length - 1].node;
// Check to see if the node is a collapsed node or not
if (node.collapsable) {
this.leftClickedNode = node;
this.forwardButtonHistory.push({
node: this.leftClickedNode,
});
this.collapse();
} else {
// this.n2Diag.dom.parentDiv.querySelector ('#backButtonId').disabled = this
// .backButtonHistory.length == 0
// ? 'disabled'
// : false;
for (let obj = node; obj != null; obj = obj.parent) {
//make sure history item is not minimized
if (obj.isMinimized) return;
}
this.forwardButtonHistory.push({
node: this.n2Diag.zoomedElement,
});
this._setupLeftClick(node);
}
this.backButtonHistory.pop();
this.n2Diag.update();
}
/**
* When the forward history button is clicked, pop the top node from that
* history stack, and disable the button if the stack is empty. Find the
* neared un-minimized node (if not the node itself) and zoom to that.
* Add the previous zoomed node to the back history stack.
*/
forwardButtonPressed() {
testThis(this, 'N2UserInterface', 'forwardButtonPressed');
if (this.forwardButtonHistory.length == 0) return;
let node = this.forwardButtonHistory.pop().node;
this.n2Diag.dom.parentDiv.querySelector('#forwardButtonId').disabled = this
.forwardButtonHistory.length == 0 ?
'disabled' :
false;
for (let obj = node; obj != null; obj = obj.parent) {
// make sure history item is not minimized
if (obj.isMinimized) return;
}
this.backButtonHistory.push({
node: this.n2Diag.zoomedElement,
});
this._setupLeftClick(node);
this.n2Diag.update();
}
/**
* When the last event to change the zoom level was a right-click,
* return the targetted node. Called during drawing/transition.
* @returns The last right-clicked node.
*/
findRootOfChangeForRightClick() {
return this.rightClickedNode;
}
/**
* When the last event to change the zoom level was the selection
* from the collapse depth menu, return the node with the
* appropriate depth.
* @returns The node that has the selected depth if it exists.
*/
findRootOfChangeForCollapseDepth(node) {
for (let obj = node; obj != null; obj = obj.parent) {
//make sure history item is not minimized
if (obj.depth == this.n2Diag.chosenCollapseDepth) return obj;
}
return node;
}
/**
* When either of the collapse or uncollapse toolbar buttons are
* pressed, return the parent component of the targetted node if
* it has one, or the node itself if not.
* @returns Parent component of output node or node itself.
*/
findRootOfChangeForCollapseUncollapseOutputs(node) {
return node.hasOwnProperty('parentComponent') ?
node.parentComponent :
node;
}
/**
* When the home button (aka return-to-root) button is clicked, zoom
* to the root node.
*/
homeButtonClick() {
testThis(this, 'N2UserInterface', 'homeButtonClick');
this.backButtonHistory.push({
node: this.n2Diag.zoomedElement,
});
this.forwardButtonHistory = [];
this._setupLeftClick(this.n2Diag.model.root);
this.uncollapseButtonClick(this.n2Diag.model.root);
this.n2Diag.update();
}
/**
* When the up button is pushed, add the current zoomed element to the
* back button history, and zoom to its parent.
*/
upOneLevelButtonClick() {
testThis(this, 'N2UserInterface', 'upOneLevelButtonClick');
if (this.n2Diag.zoomedElement === this.n2Diag.model.root) return;
this.backButtonHistory.push({
node: this.n2Diag.zoomedElement,
});
this.forwardButtonHistory = [];
this._setupLeftClick(this.n2Diag.zoomedElement.parent);
this.n2Diag.update();
}
/**
* Minimize the specified node and recursively minimize its children.
* @param {N2TreeNode} node The current node to operate on.
*/
_collapseOutputs(node) {
if (node.subsystem_type && node.subsystem_type == 'component') {
node.isMinimized = true;
}
if (node.hasChildren()) {
for (let child of node.children) {
this._collapseOutputs(child);
}
}
}
/**
* React to a button click and collapse all outputs of the specified node.
* @param {N2TreeNode} node The initial node, usually the currently zoomed element.
*/
collapseOutputsButtonClick(startNode) {
testThis(this, 'N2UserInterface', 'collapseOutputsButtonClick');
this.findRootOfChangeFunction = this.findRootOfChangeForCollapseUncollapseOutputs;
N2TransitionDefaults.duration = N2TransitionDefaults.durationSlow;
this.lastClickWasLeft = false;
this._collapseOutputs(startNode);
this.n2Diag.update();
}
/**
* Mark this node and all of its children as unminimized
* @param {N2TreeNode} node The node to operate on.
*/
_uncollapse(node) {
if (!node.isParam()) {
node.isMinimized = false;
}
if (node.hasChildren()) {
for (let child of node.children) {
this._uncollapse(child);
}
}
}
/**
* React to a button click and uncollapse the specified node.
* @param {N2TreeNode} startNode The initial node.
*/
uncollapseButtonClick(startNode) {
testThis(this, 'N2UserInterface', 'uncollapseButtonClick');
this.findRootOfChangeFunction = this.findRootOfChangeForCollapseUncollapseOutputs;
N2TransitionDefaults.duration = N2TransitionDefaults.durationSlow;
this.lastClickWasLeft = false;
this._uncollapse(startNode);
this.n2Diag.update();
}
/**
* Recursively minimize non-parameter nodes to the specified depth.
* @param {N2TreeNode} node The node to work on.
* @param {Number} depth If the node's depth is the same or more, collapse it.
*/
_collapseToDepth(node, depth) {
if (node.isParamOrUnknown()) {
return;
}
node.isMinimized = node.depth < depth ? false : true;
if (node.hasChildren()) {
for (let child of node.children) {
this._collapseToDepth(child, depth);
}
}
}
/**
* React to a new selection in the collapse-to-depth drop-down.
* @param {Number} newChosenCollapseDepth Selected depth to collapse to.
*/
collapseToDepthSelectChange(newChosenCollapseDepth) {
testThis(this, 'N2UserInterface', 'collapseToDepthSelectChange');
this.n2Diag.chosenCollapseDepth = newChosenCollapseDepth;
if (this.n2Diag.chosenCollapseDepth > this.n2Diag.zoomedElement.depth) {
this._collapseToDepth(
this.n2Diag.model.root,
this.n2Diag.chosenCollapseDepth
);
}
this.findRootOfChangeFunction = this.findRootOfChangeForCollapseDepth.bind(
this
);
N2TransitionDefaults.duration = N2TransitionDefaults.durationSlow;
this.lastClickWasLeft = false;
this.n2Diag.update();
}
/**
* React to the toggle-solver-name button press and show non-linear if linear
* is currently shown, and vice-versa.
*/
toggleSolverNamesCheckboxChange() {
testThis(this, 'N2UserInterface', 'toggleSolverNamesCheckboxChange');
this.n2Diag.toggleSolverNameType();
this.n2Diag.dom.parentDiv.querySelector(
'#linear-solver-button'
).className = !this.n2Diag.showLinearSolverNames ?
'fas icon-nonlinear-solver solver-button' :
'fas icon-linear-solver solver-button';
this.legend.toggleSolvers(this.n2Diag.showLinearSolverNames);
if (this.legend.shown)
this.legend.show(
this.n2Diag.showLinearSolverNames,
this.n2Diag.style.solvers
);
this.n2Diag.update();
}
/**
* React to the show path button press and show paths if they're not already
* show, and vice-versa.
*/
// showPathCheckboxChange() {
// testThis(this, 'N2UserInterface', 'showPathCheckboxChange');
// this.n2Diag.showPath = !this.n2Diag.showPath;
// this.n2Diag.dom.parentDiv.querySelector(
// '#currentPathId'
// ).style.display = this.n2Diag.showPath ? 'block' : 'none';
// this.n2Diag.dom.parentDiv.querySelector(
// '#showCurrentPathButtonId'
// ).className = this.n2Diag.showPath ?
// 'myButton myButtonToggledOn' :
// 'myButton';
// }
/** React to the toggle legend button, and show or hide the legend below the N2. */
toggleLegend() {
testThis(this, 'N2UserInterface', 'toggleLegend');
this.legend.toggle(
this.n2Diag.showLinearSolverNames,
this.n2Diag.style.solvers
);
this.n2Diag.dom.parentDiv.querySelector('#legend-button').className = this
.legend.shown ?
'fas icon-key active-tab-icon' :
'fas icon-key';
}
toggleNodeData() {
testThis(this, 'N2UserInterface', 'toggleNodeData');
const infoButton = document.querySelector('#info-button');
const nodeData = document.querySelector('#node-data-container');
const nodeDataClassName = nodeData.className;
if (nodeDataClassName.includes('hide-node-data')) {
nodeData.className = 'node-info-container';
infoButton.className = 'fas icon-info-circle active-tab-icon';
} else {
nodeData.className = 'node-info-container hide-node-data';
infoButton.className = 'fas icon-info-circle';
}
}
/** Associate all of the buttons on the toolbar with a method in N2UserInterface. */
_setupToolbar() {
let self = this; // For callbacks that change "this". Alternative to using .bind().
// let toolbar = document.getElementById('toolbarDiv');
let toolbar = document.getElementById('true-toolbar');
toolbar.querySelector('#reset-graph').onclick = function() {
self.homeButtonClick();
};
toolbar.querySelector('#undo-graph').onclick = function() {
self.backButtonPressed();
};
toolbar.querySelector('#redo-graph').onclick = function() {
self.forwardButtonPressed();
};
// trueToolbar.querySelector("#upOneLevelButtonId").onclick =
// function() {
// self.upOneLevelButtonClick();
// };
toolbar.querySelector('#expand-element').onclick = function() {
self.uncollapseButtonClick(self.n2Diag.zoomedElement);
};
toolbar.querySelector('#expand-all').onclick = function() {
self.uncollapseButtonClick(self.n2Diag.model.root);
};
toolbar.querySelector('#collapse-element').onclick = function() {
self.collapseOutputsButtonClick(self.n2Diag.zoomedElement);
};
toolbar.querySelector('#collapse-element-2').onclick = function() {
self.collapseOutputsButtonClick(self.n2Diag.zoomedElement);
};
toolbar.querySelector('#collapse-all').onclick = function() {
self.collapseOutputsButtonClick(self.n2Diag.model.root);
};
toolbar.querySelector('#expand-element').onclick = function() {
self.uncollapseButtonClick(self.n2Diag.zoomedElement);
};
toolbar.querySelector('#expand-all').onclick = function() {
self.uncollapseButtonClick(self.n2Diag.model.root);
};
toolbar.querySelector('#collapse-element').onclick = function() {
self.collapseOutputsButtonClick(self.n2Diag.zoomedElement);
};
toolbar.querySelector('#collapse-all').onclick = function() {
self.collapseOutputsButtonClick(self.n2Diag.model.root);
};
toolbar.querySelector('#hide-connections').onclick = function() {
self.n2Diag.clearArrows();
};
toolbar.querySelector('#show-connections').onclick = function() {
self.n2Diag.showArrows();
};
toolbar.querySelector('#show-all-connections').onclick = function() {
self.n2Diag.showAllArrows();
};
// toolbar.querySelector('#showCurrentPathButtonId').onclick = function() {
// self.showPathCheckboxChange();
// };
toolbar.querySelector('#legend-button').onclick = function() {
self.toggleLegend();
};
toolbar.querySelector('#linear-solver-button').onclick = function() {
self.toggleSolverNamesCheckboxChange();
};
toolbar.querySelector('#text-slider').oninput = function(e) {
const fontSize = e.target.value;
self.n2Diag.fontSizeSelectChange(fontSize);
const fontSizeIndicator = trueToolbar.querySelector(
'#font-size-indicator'
);
fontSizeIndicator.innerHTML = fontSize + ' px';
};
toolbar.querySelector('#model-slider').onmouseup = function(e) {
const modelHeight = parseInt(e.target.value);
self.n2Diag.verticalResize(modelHeight);
};
toolbar.querySelector('#save-button').onclick = function() {
self.n2Diag.saveSvg();
};
toolbar.querySelector('#info-button').onclick = function() {
self.toggleNodeData();
};
document.getElementById('question-button').onclick = DisplayModal;
}
_setupSearch() {
let self = this; // For callbacks that change "this". Alternative to using .bind().
// Keyup so it will be after the input and awesomplete-selectcomplete event listeners
window.addEventListener(
'keyup',
self.searchEnterKeyUpEventListener.bind(self),
true
);
// Keydown so it will be before the input and awesomplete-selectcomplete event listeners
window.addEventListener(
'keydown',
self.searchEnterKeyDownEventListener.bind(self),
true
);
}
/** Make sure UI controls reflect history and current reality. */
update() {
testThis(this, 'N2UserInterface', 'update');
// this.n2Diag.dom.parentDiv.querySelector('#currentPathId').innerHTML =
// 'PATH: root' +
// (this.n2Diag.zoomedElement.parent ? '.' : '') +
// this.n2Diag.zoomedElement.absPathName;
this.n2Diag.dom.parentDiv.querySelector('#undo-graph').disabled = this
.backButtonHistory.length == 0 ?
'disabled' :
false;
this.n2Diag.dom.parentDiv.querySelector('#redo-graph').disabled = this
.forwardButtonHistory.length == 0 ?
'disabled' :
false;
// this.n2Diag.dom.parentDiv.querySelector('#upOneLevelButtonId').disabled =
// this.n2Diag.zoomedElement === this.n2Diag.model.root ? 'disabled' : false;
this.n2Diag.dom.parentDiv.querySelector('#reset-graph').disabled = this
.n2Diag.zoomedElement === this.n2Diag.model.root ?
'disabled' :
false;
// for (let i = 2; i <= this.n2Diag.model.maxDepth; ++i) {
// this.n2Diag.dom.parentDiv.querySelector(
// '#idCollapseDepthOption' + i
// ).style.display = i <= this.n2Diag.zoomedElement.depth ? 'none' : 'block';
// }
}
/** Called when the search button is actually or effectively clicked to start a search. */
searchButtonClicked() {
testThis(this, 'N2UserInterface', 'searchButtonClicked');
this.n2Diag.search.performSearch();
this.findRootOfChangeFunction = this.n2Diag.search.findRootOfChangeForSearch;
N2TransitionDefaults.duration = N2TransitionDefaults.durationSlow;
this.lastClickWasLeft = false;
this.n2Diag.search.updateRecomputesAutoComplete = false;
this.n2Diag.update();
}
/**
* Called when the enter key is pressed in the search input box.
* @param {Event} e Object with information about the event.
*/
searchEnterKeyDownEventListener(e) {
testThis(this, 'N2UserInterface', 'searchEnterKeyDownEventListener');
let target = e.target;
if (target.id == 'awesompleteId') {
let key = e.which || e.keyCode;
if (key === 13) {
// 13 is enter
this.callSearchFromEnterKeyPressed = true;
}
}
}
searchEnterKeyUpEventListener(e) {
testThis(this, 'N2UserInterface', 'searchEnterKeyUpEventListener');
let target = e.target;
if (target.id == 'awesompleteId') {
let key = e.which || e.keyCode;
if (key == 13) {
// 13 is enter
if (this.callSearchFromEnterKeyPressed) {
this.searchButtonClicked();
}
}
}
}
} |
JavaScript | class IdentityRegistry extends Registry {
/**
* Get an existing identity registry.
*
* @param {SecurityContext} securityContext The user's security context.
* @param {ModelManager} modelManager The ModelManager to use for this identity registry.
* @param {Factory} factory The factory to use for this identity registry.
* @param {Serializer} serializer The Serializer to use for this identity registry.
* @return {Promise} A promise that will be resolved with a {@link IdentityRegistry}
* instance representing the identity registry.
*/
static getIdentityRegistry(securityContext, modelManager, factory, serializer) {
Util.securityCheck(securityContext);
if (!modelManager) {
throw new Error('modelManager not specified');
} else if (!factory) {
throw new Error('factory not specified');
} else if (!serializer) {
throw new Error('serializer not specified');
}
return Registry.getRegistry(securityContext, REGISTRY_TYPE, 'org.hyperledger.composer.system.Identity')
.then((registry) => {
return new IdentityRegistry(registry.id, registry.name, securityContext, modelManager, factory, serializer);
});
}
/**
* Create an identity registry.
* <strong>Note: Only to be called by framework code. Applications should
* retrieve instances from {@link BusinessNetworkConnection}</strong>
* </p>
*
* @param {string} id The unique identifier of the identity registry.
* @param {string} name The display name for the identity registry.
* @param {SecurityContext} securityContext The security context to use for this asset registry.
* @param {ModelManager} modelManager The ModelManager to use for this identity registry.
* @param {Factory} factory The factory to use for this identity registry.
* @param {Serializer} serializer The Serializer to use for this identity registry.
* @private
*/
constructor(id, name, securityContext, modelManager, factory, serializer) {
super(REGISTRY_TYPE, id, name, securityContext, modelManager, factory, serializer);
}
/**
* Unsupported operation; you cannot add an identity to an identity
* registry.
*
* @param {Resource} resource The resource to be added to the registry.
* @param {string} data The data for the resource.
*
*/
add(resource) {
throw new Error('cannot add identity to an identity registry');
}
/**
* Unsupported operation; you cannot add an identity to an identity
* registry.
*
* @param {Resource[]} resources The resources to be added to the registry.
*
*/
addAll(resources) {
throw new Error('cannot add identities to a identity registry');
}
/**
* Unsupported operation; you cannot update an identity in an identity
* registry. This method will always throw an exception when called.
*
* @param {Resource} resource The resource to be updated in the registry.
*
*/
update(resource) {
throw new Error('cannot update identities in an identity registry');
}
/**
* Unsupported operation; you cannot update an identity in an identity
* registry.
*
* @param {Resource[]} resources The resources to be updated in the asset registry.
*
*/
updateAll(resources) {
throw new Error('cannot update identities in an identity registry');
}
/**
* Unsupported operation; you cannot remove an identity from an identity
* registry. This method will always throw an exception when called.
*
* @param {(Resource|string)} resource The resource, or the unique identifier of the resource.
*
*/
remove(resource) {
throw new Error('cannot remove identities from an identity registry');
}
/**
* Unsupported operation; you cannot remove an identity from an identity
* registry. This method will always throw an exception when called.
*
* @param {(Resource[]|string[])} resources The resources, or the unique identifiers of the resources.
*
*/
removeAll(resources) {
throw new Error('cannot remove identities from an identity registry');
}
} |
JavaScript | class PerennialChampionAchievementCompiler {
/**
* Compiles a perennial champion achievement object to a trigger object.
*/
static compile(pc_object) {
const rank = Utils.checkNonEmptyString(pc_object.rank);
const payout_accumulated = Utils.checkNumberGTE(pc_object.payoutAccumulated, 0);
const xp = Utils.checkNumberGTE(pc_object.xp, 0);
const name = 'pc_' + rank;
const trigger_object = {
'name': name,
'queue': 'pc',
'target': 'player',
'condition': {
'payoutAccumulated': { '$gte': payout_accumulated }
},
'action': {
'$push': {
'mails': {
'name': name,
'xp': xp
}
}
}
};
//TODO: trigger_object.__proto__ = Trigger.prototype;
return trigger_object;
}
} |
JavaScript | class PopoverViewController extends ViewController {
/**
* Creates a popover view with a given trigger + target.
* @param {?HTMLElement} root The root element to bind to.
* @param {HTMLElement} trigger binds `onclick` as a trigger to this node.
* @param {Template} template will display this view on trigger.
* @param {?HTMLElement} [untrigger=document] element to untrigger.
*/
constructor(root, trigger, template, untrigger = document) {
const instance = template.unique();
super(instance);
/**
* State is `true` when opening. `false` when closing
* @type {ActionControllerDelegate}
*/
this.delegate = new ActionControllerDelegate();
this._trigger = trigger;
this._template = template;
this._node = instance;
this._isActive = false;
this._untriggerTimeout = null;
this._animationTime = this._node.dataset.animationTime || 0; // in ms
this._parent = template.getParent(document.body);
this._node.classList.add("template");
if (this._node.parentNode === null) {
this._parent.appendChild(this._node);
}
this._keyBinding = null;
const untriggers = this._node.getElementsByClassName('popvc__untrigger');
for (const localUntrigger of untriggers) {
this.bindUntrigger(localUntrigger);
}
// Setup hide trigger
untrigger?.addEventListener("click", (event) => {
if (this._isActive) {
let target = event.target;
// Target is not in DOM
if (!(document.body.contains(event.target) || event.target === document.body)) { return }
// Target is outside of popover
if (!this._node.contains(untrigger) && (
this._node.contains(target) ||
this._trigger.contains(target)
)) { return }
this.untrigger();
}
});
this.bindTrigger(trigger);
}
/**
* Adds a new trigger node.
* @param {string|HTMLElement} trigger - A new trigger to add
*/
bindTrigger(trigger) {
if (typeof trigger === 'string') {
trigger = document.getElementById(trigger);
}
trigger.addEventListener("click", () => {
this.trigger();
}, false);
}
/**
* Binds an untrigger node.
* @param {string|HTMLElement} untrigger - A new untrigger to add
*/
bindUntrigger(untrigger) {
if (typeof untrigger === 'string') {
untrigger = document.getElementById(untrigger);
}
untrigger.addEventListener("click", () => {
this.untrigger();
}, false);
}
/**
* Sets into an active state
*/
trigger() {
this._template.willLoad();
this.delegate.didSetStateTo(this, true);
this._isActive = true;
if (this._untriggerTimeout) {
clearTimeout(this._untriggerTimeout);
}
this._node.classList.remove("template");
window.setTimeout(() => {
this._node.classList.add("template--active");
});
this._trigger.classList.add("state-active");
this._node.focus();
this._keyBinding = KeyManager.shared.register('Escape', () => {
this.untrigger();
});
this._template.didLoad();
}
/**
* Sets into inactive state.
*/
untrigger() {
this._template.willUnload();
this.delegate.didSetStateTo(this, false);
this._isActive = false;
this._trigger.classList.remove("state-active");
this._node.classList.remove("template--active");
this._untriggerTimeout = setTimeout(() => {
this._untriggerTimeout = null;
this._node.classList.add("template");
}, this._animationTime);
this._keyBinding?.();
this._keyBinding = null;
this._template.didUnload();
}
} |
JavaScript | class Timeout {
set(t, value) {
return new Promise((resolve, reject) => {
this.clear();
const callback = value ? () => reject(new Error(`${value}`)) : resolve;
this._timer = setTimeout(callback, t);
});
}
clear() {
if (this._timer) {
clearTimeout(this._timer);
}
}
wrap(promise, t, value) {
const wrappedPromise = this._promiseFinally(promise, () => this.clear());
const timer = this.set(t, value);
return Promise.race([wrappedPromise, timer]);
}
_promiseFinally(promise, fn) {
const success = (result) => {
fn();
return result;
};
const error = (e) => {
fn();
return Promise.reject(e);
};
return Promise.resolve(promise).then(success, error);
}
static set(t, value) {
return new Timeout().set(t, value);
}
static wrap(promise, t, value) {
return new Timeout().wrap(promise, t, value);
}
} |
JavaScript | class TransactionBuilder {
constructor() {
this.listOfUTXO = null;
this.outputAddresses = null;
this.totalAmount = null;
this.changeAddress = null;
this.feeAmount = 0;
this.secretKey = null;
this.type = "regular";
}
build() {
// Check required information
if (this.listOfUTXO === null)
throw new ArgumentError("It is necessary to inform a list of unspent output transactions.");
if (this.outputAddress === null)
throw new ArgumentError("It is necessary to inform the destination address.");
if (this.totalAmount === null)
throw new ArgumentError("It is necessary to inform the transaction value.");
// Calculates the change amount
const totalAmountOfUTXO = R.sum(R.pluck("amount", this.listOfUTXO));
const changeAmount = totalAmountOfUTXO - this.totalAmount - this.feeAmount;
// For each transaction input, calculates the hash of the input and sign the data.
const self = this;
const inputs = R.map(utxo => {
const txiHash = CryptoUtil.hash({
address: utxo.address,
index: utxo.index,
transaction: utxo.transaction
});
utxo.signature = CryptoEDDSAUtil.signHash(CryptoEDDSAUtil.generateKeyPairFromSecret(self.secretKey), txiHash);
return utxo;
}, this.listOfUTXO);
const outputs = [];
// Add target receiver
outputs.push({
address: this.outputAddress,
amount: this.totalAmount
});
// Add change amount
if (changeAmount > 0) {
outputs.push({
address: this.changeAddress,
amount: changeAmount
});
} else throw new ArgumentError("The sender does not have enough to pay for the transaction.");
// The remaining value is the fee to be collected by the block's creator.
return Transaction.fromJson({
data: {
inputs: inputs,
outputs: outputs
},
hash: null,
id: CryptoUtil.randomId(64),
type: this.type
});
}
change(changeAddress) {
this.changeAddress = changeAddress;
return this;
}
fee(amount) {
this.feeAmount = amount;
return this;
}
from(listOfUTXO) {
this.listOfUTXO = listOfUTXO;
return this;
}
sign(secretKey) {
this.secretKey = secretKey;
return this;
}
to(address, amount) {
this.outputAddress = address;
this.totalAmount = amount;
return this;
}
type(type) {
this.type = type;
}
} |
JavaScript | class TickParam extends Param {
constructor() {
super(optionsFromArguments(TickParam.getDefaults(), arguments, ["value"]));
this.name = "TickParam";
/**
* The timeline which tracks all of the automations.
*/
this._events = new Timeline(Infinity);
/**
* The internal holder for the multiplier value
*/
this._multiplier = 1;
const options = optionsFromArguments(TickParam.getDefaults(), arguments, ["value"]);
// set the multiplier
this._multiplier = options.multiplier;
// clear the ticks from the beginning
this._events.cancel(0);
// set an initial event
this._events.add({
ticks: 0,
time: 0,
type: "setValueAtTime",
value: this._fromType(options.value),
});
this.setValueAtTime(options.value, 0);
}
static getDefaults() {
return Object.assign(Param.getDefaults(), {
multiplier: 1,
units: "hertz",
value: 1,
});
}
setTargetAtTime(value, time, constant) {
// approximate it with multiple linear ramps
time = this.toSeconds(time);
this.setRampPoint(time);
const computedValue = this._fromType(value);
// start from previously scheduled value
const prevEvent = this._events.get(time);
const segments = Math.round(Math.max(1 / constant, 1));
for (let i = 0; i <= segments; i++) {
const segTime = constant * i + time;
const rampVal = this._exponentialApproach(prevEvent.time, prevEvent.value, computedValue, constant, segTime);
this.linearRampToValueAtTime(this._toType(rampVal), segTime);
}
return this;
}
setValueAtTime(value, time) {
const computedTime = this.toSeconds(time);
super.setValueAtTime(value, time);
const event = this._events.get(computedTime);
const previousEvent = this._events.previousEvent(event);
const ticksUntilTime = this._getTicksUntilEvent(previousEvent, computedTime);
event.ticks = Math.max(ticksUntilTime, 0);
return this;
}
linearRampToValueAtTime(value, time) {
const computedTime = this.toSeconds(time);
super.linearRampToValueAtTime(value, time);
const event = this._events.get(computedTime);
const previousEvent = this._events.previousEvent(event);
const ticksUntilTime = this._getTicksUntilEvent(previousEvent, computedTime);
event.ticks = Math.max(ticksUntilTime, 0);
return this;
}
exponentialRampToValueAtTime(value, time) {
// aproximate it with multiple linear ramps
time = this.toSeconds(time);
const computedVal = this._fromType(value);
// start from previously scheduled value
const prevEvent = this._events.get(time);
// approx 10 segments per second
const segments = Math.round(Math.max((time - prevEvent.time) * 10, 1));
const segmentDur = ((time - prevEvent.time) / segments);
for (let i = 0; i <= segments; i++) {
const segTime = segmentDur * i + prevEvent.time;
const rampVal = this._exponentialInterpolate(prevEvent.time, prevEvent.value, time, computedVal, segTime);
this.linearRampToValueAtTime(this._toType(rampVal), segTime);
}
return this;
}
/**
* Returns the tick value at the time. Takes into account
* any automation curves scheduled on the signal.
* @param event The time to get the tick count at
* @return The number of ticks which have elapsed at the time given any automations.
*/
_getTicksUntilEvent(event, time) {
if (event === null) {
event = {
ticks: 0,
time: 0,
type: "setValueAtTime",
value: 0,
};
}
else if (isUndef(event.ticks)) {
const previousEvent = this._events.previousEvent(event);
event.ticks = this._getTicksUntilEvent(previousEvent, event.time);
}
const val0 = this._fromType(this.getValueAtTime(event.time));
let val1 = this._fromType(this.getValueAtTime(time));
// if it's right on the line, take the previous value
const onTheLineEvent = this._events.get(time);
if (onTheLineEvent && onTheLineEvent.time === time && onTheLineEvent.type === "setValueAtTime") {
val1 = this._fromType(this.getValueAtTime(time - this.sampleTime));
}
return 0.5 * (time - event.time) * (val0 + val1) + event.ticks;
}
/**
* Returns the tick value at the time. Takes into account
* any automation curves scheduled on the signal.
* @param time The time to get the tick count at
* @return The number of ticks which have elapsed at the time given any automations.
*/
getTicksAtTime(time) {
const computedTime = this.toSeconds(time);
const event = this._events.get(computedTime);
return Math.max(this._getTicksUntilEvent(event, computedTime), 0);
}
/**
* Return the elapsed time of the number of ticks from the given time
* @param ticks The number of ticks to calculate
* @param time The time to get the next tick from
* @return The duration of the number of ticks from the given time in seconds
*/
getDurationOfTicks(ticks, time) {
const computedTime = this.toSeconds(time);
const currentTick = this.getTicksAtTime(time);
return this.getTimeOfTick(currentTick + ticks) - computedTime;
}
/**
* Given a tick, returns the time that tick occurs at.
* @return The time that the tick occurs.
*/
getTimeOfTick(tick) {
const before = this._events.get(tick, "ticks");
const after = this._events.getAfter(tick, "ticks");
if (before && before.ticks === tick) {
return before.time;
}
else if (before && after &&
after.type === "linearRampToValueAtTime" &&
before.value !== after.value) {
const val0 = this._fromType(this.getValueAtTime(before.time));
const val1 = this._fromType(this.getValueAtTime(after.time));
const delta = (val1 - val0) / (after.time - before.time);
const k = Math.sqrt(Math.pow(val0, 2) - 2 * delta * (before.ticks - tick));
const sol1 = (-val0 + k) / delta;
const sol2 = (-val0 - k) / delta;
return (sol1 > 0 ? sol1 : sol2) + before.time;
}
else if (before) {
if (before.value === 0) {
return Infinity;
}
else {
return before.time + (tick - before.ticks) / before.value;
}
}
else {
return tick / this._initialValue;
}
}
/**
* Convert some number of ticks their the duration in seconds accounting
* for any automation curves starting at the given time.
* @param ticks The number of ticks to convert to seconds.
* @param when When along the automation timeline to convert the ticks.
* @return The duration in seconds of the ticks.
*/
ticksToTime(ticks, when) {
return this.getDurationOfTicks(ticks, when);
}
/**
* The inverse of [[ticksToTime]]. Convert a duration in
* seconds to the corresponding number of ticks accounting for any
* automation curves starting at the given time.
* @param duration The time interval to convert to ticks.
* @param when When along the automation timeline to convert the ticks.
* @return The duration in ticks.
*/
timeToTicks(duration, when) {
const computedTime = this.toSeconds(when);
const computedDuration = this.toSeconds(duration);
const startTicks = this.getTicksAtTime(computedTime);
const endTicks = this.getTicksAtTime(computedTime + computedDuration);
return endTicks - startTicks;
}
/**
* Convert from the type when the unit value is BPM
*/
_fromType(val) {
if (this.units === "bpm" && this.multiplier) {
return 1 / (60 / val / this.multiplier);
}
else {
return super._fromType(val);
}
}
/**
* Special case of type conversion where the units === "bpm"
*/
_toType(val) {
if (this.units === "bpm" && this.multiplier) {
return (val / this.multiplier) * 60;
}
else {
return super._toType(val);
}
}
/**
* A multiplier on the bpm value. Useful for setting a PPQ relative to the base frequency value.
*/
get multiplier() {
return this._multiplier;
}
set multiplier(m) {
// get and reset the current value with the new multiplier
// might be necessary to clear all the previous values
const currentVal = this.value;
this._multiplier = m;
this.cancelScheduledValues(0);
this.setValueAtTime(currentVal, 0);
}
} |
JavaScript | class Plugin {
static plugins = {}
static register (name, plugin) {
this.plugins[name] = plugin
}
static execute (context, name, args) {
this.plugins[name].apply(context, args)
}
} |
JavaScript | class Preload extends Component {
constructor(props) {
super(props)
this.state = {
result: null,
error: null
}
}
componentDidMount() {
this.props.promise
.then(result => this.setState({ result }))
.catch(error => this.setState({ error }))
}
render() {
const { loader, children } = this.props
const { result, error } = this.state
if (result || error) {
return children(result, error)
}
return loader || null
}
} |
JavaScript | class SearchBar extends Component{
constructor(props) {
super(props);
this.state = { term : '' };
}
render() {
return (
<div className = "search-bar">
<input
value = {this.state.term}
onChange = { event => this.onInputChange(event.target.value) } />
</div>
);
}
/*on change in input text,change event is called. setState causes value to be re-rendered and set to current state input value*/
//pass the event handler to the element to be monitored
//when we attach a handler, we add an event to the function
onInputChange(term) {
this.setState({term});
this.props.onSearchTermChange(term);
//console.log(event.target.value);
}
} |
JavaScript | class PayoutsPostRequest {
constructor() {
this.path = '/v1/payments/payouts?';
this.verb = 'POST';
this.body = null;
this.headers = {
'Content-Type': 'application/json'
};
}
payPalPartnerAttributionId(payPalPartnerAttributionId) {
this.headers['PayPal-Partner-Attribution-Id'] = payPalPartnerAttributionId;
return this;
}
payPalRequestId(payPalRequestId) {
this.headers['PayPal-Request-Id'] = payPalRequestId;
return this;
}
requestBody(createPayoutRequest) {
this.body = createPayoutRequest;
return this;
}
} |
JavaScript | class Track extends GraphContent {
/**
* @class
* @param {object} input - Input JSON
*/
constructor(input) {
super();
this.config = loadInput(input);
this.trackGroupPath = null;
}
/**
* @inheritdoc
*/
load(graph) {
if (!isUniqueKey(graph.tracks, this.config.key)) {
throw new Error(errors.THROW_MSG_UNIQUE_KEY_NOT_PROVIDED);
}
this.trackGroupPath = createTrackContainer(
graph.config,
graph.svg,
this.config
);
/**
* To load the gantt track selector, we need to find the track-height, this gets updated only when updateTrackProps gets called.
*
* We Need to loadGanttTrackSelector prior to all other components, since trackSelector is part of trackGroup and should be layered bottom,
* to ensure the clickable functionality.
*/
updateTrackProps(graph.config, this.config, true);
loadGanttTrackSelector(graph, this.trackGroupPath, this.config);
if (utils.notEmpty(this.config.activities)) {
loadActivities(
graph,
this.trackGroupPath,
this.config.trackLabel,
this.config.activities
);
}
if (utils.notEmpty(this.config.tasks)) {
loadTasks(
graph,
this.trackGroupPath,
this.config.trackLabel,
this.config.tasks
);
}
if (utils.notEmpty(this.config.events)) {
loadEvents(
graph,
this.trackGroupPath,
this.config.trackLabel,
this.config.events
);
}
if (utils.notEmpty(this.config.actions)) {
loadActions(
graph,
this.trackGroupPath,
this.config.trackLabel,
this.config.actions
);
}
return this;
}
/**
* @inheritdoc
*/
unload(graph) {
updateTrackProps(graph.config, this.config);
unloadGanttTrackSelector(graph, this.trackGroupPath);
if (utils.notEmpty(this.config.activities)) {
unloadActivities(graph, this.trackGroupPath);
}
if (utils.notEmpty(this.config.tasks)) {
unloadTasks(graph, this.trackGroupPath);
}
if (utils.notEmpty(this.config.events)) {
unloadEvents(graph, this.trackGroupPath);
}
if (utils.notEmpty(this.config.actions)) {
unloadActions(graph, this.trackGroupPath);
}
removeTrackContainer(graph.svg, this.config.key);
this.config = {};
return this;
}
/**
* @inheritdoc
*/
resize(graph) {
if (utils.notEmpty(this.trackGroupPath)) {
translateTrackSelector(
graph.scale,
graph.config,
this.trackGroupPath,
this.config
);
}
if (utils.notEmpty(this.config.activities)) {
translateActivities(graph.scale, graph.config, this.trackGroupPath);
}
if (utils.notEmpty(this.config.tasks)) {
translateTasks(graph.scale, graph.config, this.trackGroupPath);
}
if (
utils.notEmpty(this.config.actions) ||
utils.notEmpty(this.config.events)
) {
translateDataPoints(graph.scale, graph.config, this.trackGroupPath);
}
return this;
}
/**
* @inheritdoc
*/
redraw(graph) {
addTrackLabelEventHandler(graph.svg, this.config.trackLabel);
return this;
}
} |
JavaScript | class ThatLowCarbLifeScraper extends BaseScraper {
constructor(url) {
super(url, "thatlowcarblife.com/");
}
scrape($) {
this.defaultSetImage($);
const { ingredients, instructions, time } = this.recipe;
this.recipe.name = $(".mv-create-title-primary")
.text()
.trim()
.replace(/\s\s+/g, "");
$(".mv-create-ingredients")
.children("ul")
.children("li")
.each((i, el) => {
// They added a '\n' character for some reason, gotta remove it!
ingredients.push($(el).text().trim().replace(/\s\s+/g, ""));
});
var inst = $(".mv-create-instructions");
inst
.children("ol")
.children("li")
.each((i, el) => {
instructions.push($(el).text().trim().replace(/\s\s+/g, ""));
});
time.prep = this.textTrim($(".mv-create-time-prep .mv-create-time-format"));
time.cook = this.textTrim(
$(".mv-create-time-active .mv-create-time-format")
);
time.total = this.textTrim(
$(".mv-create-time-total .mv-create-time-format")
);
this.recipe.servings = this.textTrim(
$(".mv-create-time-yield .mv-create-time-format")
);
}
} |
JavaScript | class AdminSocketController extends Controller {
/**
* Handle ADMIN_JOIN_TUTORIAL_QUIZ event.
* @param connection
* @returns {Function}
*/
requestJoinTutorialQuiz(connection) {
return async data => {
let tutorialQuiz = await TutorialQuiz.findOne({_id: data});
if(tutorialQuiz) {
connection.join(`admin:tutorialQuiz:${tutorialQuiz._id}`);
connection.getSocket()
.emit("ADMIN_JOIN_TUTORIAL_QUIZ_SUCCESS", `Joined tutorial quiz group ${tutorialQuiz._id}.`);
} else {
connection.getSocket().emit("ADMIN_ERROR", "Unable to join, quiz instance not found.");
}
};
}
/**
* Handle ADMIN_GET_JOINED_STUDENTS event.
* @param connection
* @returns {Function}
*/
getJoinedStudents(connection) {
return async data => {
let tutorialQuiz = await TutorialQuiz.findOne({_id: data});
if(tutorialQuiz) {
let connections = connectionPool.getConnectionsInRoom(`tutorialQuiz:${tutorialQuiz._id}`);
// Normalize connections to connection.user and send back.
connection.getSocket().emit(
"ADMIN_GET_JOINED_STUDENTS_SUCCESS",
connections.map(connection => connection.user));
} else {
connection.getSocket().emit("ADMIN_ERROR", "Unable to join, quiz instance not found.");
}
}
}
} |
JavaScript | class UiHelper {
static init() {
var _generatedModal = {};
this.storeModal = (params) => {
_generatedModal[params.key.toString().replaceAll('-', '_')] = {
modalid: params.modalid,
formid: params.formid ? params.formid : '',
modal: params.modal
};
}
this.getModal = (modalid = null) => {
if (modalid) {
var key = modalid.split('-');
var key = key.join('_');
var modal = this.generatedModal[key];
return { modal: modal.modal, callback: this.ajaxSubmit };
} else
return _generatedModal;
}
this.instance = {
validator: {}
};
}
static addNotifItem(wrapper, item) {
let notif = '';
let count = $('#notif-count').text();
item.forEach(i => {
notif += `
<div class="d-flex flex-row mb-3 pb-3 border-bottom ${!i.tanggal_baca ? 'belum-baca' : 'sudah-baca'}">
<div class="pl-3 pr-2">
<span id="${i.id}" class="n-item" style="cursor:pointer">
<p class="font-weight-medium mb-1">${!i.tanggal_baca ? '<b>' + i.judul + '</b>' : i.judul}</p>
<p class="text-muted mb-0 text-small">${i.tanggal}</p>
</span>
</div>
</div>
`;
});
$(wrapper).html(notif);
if (!count)
count = 0;
else
count = parseInt(count);
let activeItem = $('div.belum-baca').length;
if(item.length > 0)
$('#notif-count').text(activeItem).show();
}
static generateModal(modalId, wrapper, opt) {
let body = "";
let foot = "";
let stored = null;
let kembalian = null;
if (!opt.type)
opt.type = "nonForm";
if (!modalId) {
alert("Id Modal harus di isi!");
return;
}
if (!opt) {
alert("Opt harus di isi!");
return;
}
if (!opt.modalTitle)
opt.modalTitle = "";
if (!opt.modalSubtitle)
opt.modalSubtitle = "";
if (opt.modalBody)
body += this.tambahkanBody(opt.type, opt);
if (opt.modalFooter) {
opt.modalFooter.forEach(el => {
var id = !el.id ? "" : el.id;
var data = el.data ? el.data : "";
foot += `<button ${data} type = "${el.type}" id = "${id}" class = "${el.class}"> ${el.text} </button>`;
});
}
if (!opt.modalPos)
opt.modalPos = 'def';
var modalTemplate = opt.modalPos == 'def' ?
`<div class="modal fade" id="${modalId}" tabindex="-1" role="dialog">
<div class="modal-dialog ${opt.size}" role="document">
<div class="modal-content">
<div class="modal-header d-block">
<div class = 'd-flex'>
<h5 class="modal-title"> ${opt.modalTitle}</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<h6 id="modal-subtitle" class = "modal-title text-muted"> ${opt.modalSubtitle} </h6>
</div>
<div class="modal-body">${body}</div>
<div class="modal-footer">${foot}</div>
</div>
</div>
</div>`
:
opt.modalPos == 'left' ?
`<div class="modal fade modal-left" id="${modalId}" tabindex="-1" role="dialog">
<div class="modal-dialog ${opt.size}" role="document">
<div class="modal-content">
<div class="modal-header d-block">
<div class = 'd-flex'>
<h5 class="modal-title"> ${opt.modalTitle}</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<h6 class = "modal-title text-muted"> ${opt.modalSubtitle} </h6>
</div>
<div class="modal-body">${body}</div>
<div class="modal-footer">${foot}</div>
</div>
</div>
</div>`
:
`<div class="modal fade modal-right" id="${modalId}" tabindex="-1" role="dialog">
<div class="modal-dialog ${opt.size}" role="document">
<div class="modal-content">
<div class="modal-header d-block">
<div class = 'd-flex'>
<h5 class="modal-title"> ${opt.modalTitle}</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<h6 class = "modal-title text-muted"> ${opt.modalSubtitle} </h6>
</div>
<div class="modal-body">${body}</div>
<div class="modal-footer">${foot}</div>
</div>
</div>
</div>`
;
if (opt.open)
opt.tulis = true;
if (!wrapper)
opt.tulis = false;
if (!opt.ajax)
opt.ajax = false;
if (opt.tulis)
$(wrapper).append(modalTemplate);
if (opt.open)
$("#" + modalId).modal('show');
if (opt.destroy) {
$("#" + modalId).on('hidden.bs.modal', (e) => {
e.preventDefault();
$("#" + e.target.id).remove();
if (this.instance.validator[modalId.replaceAll('-', '_')]) {
this.instance.validator[modalId.replaceAll('-', '_')].destroy();
delete (this.instance.validator[modalId.replaceAll('-', '_')]);
}
});
}
if (opt.type == 'form') {
stored = { key: modalId, modal: modalTemplate, modalid: modalId, formid: opt.formOpt.formId },
kembalian = { 'modalId': modalId, 'formId': opt.formOpt.formId, 'modal': modalTemplate }
if (opt.ajax) {
var ajaxSubmit = (formId = null) => {
var formid = !formId ? opt.formOpt.formId : formId;
var succes = opt.submitSuccess ? opt.submitSuccess : () => { };
var fail = opt.submitFail ? opt.submitFail : () => { };
var sebelumSubmit = opt.sebelumSubmit ? opt.sebelumSubmit : () => {};
var rules = {};
var options = {
success: succes,
beforeSubmit: sebelumSubmit,
method: opt.ajaxMethod
};
if (opt.rules) {
opt.rules.forEach(rule => {
jQuery.validator.addMethod(rule.name, rule.method, rule.message);
rules[rule.field] = {};
rules[rule.field][rule.name] = true;
})
}
this.instance.validator[modalId.replaceAll('-', '_')] = $("#" + formid).validate({
rules: rules,
submitHandler: function (form) {
$('#' + formid + ' #alert_danger, #alert_success').html('').hide();
$(form).ajaxSubmit(options);
}
});
}
this.ajaxSubmit = ajaxSubmit;
ajaxSubmit();
} else {
this.instance.validator[modalId.replaceAll('-', '_')] = $("#" + opt.formOpt.formid).validate();
}
} else {
stored = { key: modalId, modal: modalTemplate, modalid: modalId };
kembalian = { 'modalId': modalId, 'modal': modalTemplate }
}
if (opt.eventListener) {
$("#" + modalId).on('shown.bs.modal', function () {
opt.eventListener.forEach(ev => {
$(ev.element).on(ev.type, ev.callback);
})
});
}
$("#" + modalId).on('hidden.bs.modal', opt.saatTutup);
$("#" + modalId).on('shown.bs.modal', opt.saatBuka);
this.storeModal(stored);
if (opt.kembali)
return kembalian;
}
static tambahkanBody(type, opt) {
let bodyEl = '';
let inputEl = "";
let buttonsEl = "";
const cardEl = opt.modalBody.card;
const input = opt.modalBody.input;
const buttons = opt.modalBody.buttons;
if (!opt.modalBody.extra)
opt.modalBody.extra = '';
if (type == 'form') {
var form = opt.formOpt;
if (!form.formId)
form.formId = 'noId'
if (!form.enctype)
form.enctype = '';
if (!form.formMethod)
form.formMethod = "POST";
if (!form.formAttr)
form.formAttr = '';
if (!form.formClass)
form.formClass = '';
input.forEach(element => {
if (element.type == 'select')
inputEl += this.generateSelect(element);
else if (element.type == 'custom')
inputEl += element.text;
else
inputEl += this.generateInput(element);
});
if (buttons) {
buttons.forEach(el => {
var id = !el.id ? "" : el.id;
var data = el.data ? el.data : "";
buttonsEl += `<button ${data} type = "${el.type}" id = "${id}" class = "${el.class}"> ${el.text} </button>`;
});
}
bodyEl += `
<form enctype = "${form.enctype}" ${form.formAttr} class="${form.formClass}" id ="${form.formId}" method = "${form.formMethod}" action = "${form.formAct}">
<div id="alert_danger" style="display: none" class="alert alert-danger" role="alert"> </div>
<div id="alert_success" style="display: none" class="alert alert-success" role="alert"> </div>
${inputEl}
${buttonsEl}
</form>
${opt.modalBody.extra}`;
return bodyEl;
}
else if (type == 'card group') {
let card = "";
if (opt.modalBody.cardDisplay == 'grid')
card += '<div class="row row-cols-1 row-cols-md-2">';
cardEl.forEach(element => {
card += '<div class="col mb-4">';
card += this.generateCard(element);
card += '</div>';
});
if (opt.modalBody.cardDisplay == 'grid')
card += '</div>';
bodyEl += card + '</div>';
} else if (type == 'inputNF') {
input.forEach(element => {
if (element.type == 'select')
inputEl += this.generateSelect(element);
else
inputEl += this.generateInput(element);
});
bodyEl += `
${inputEl}
${opt.modalBody.extra}`
} else if (type == 'custom')
bodyEl = opt.modalBody.customBody;
return bodyEl;
}
static generateCard(el) {
let card = "";
let cardHead = "";
let Topimage = '';
let Bottomimage = '';
let Leftimage = '';
let Rightimage = '';
let foots = '';
let links = "";
let buttons = "";
var params = ['title', 'footerClass', 'text', 'styles', 'tipe', 'value', 'imagewrapper', 'subtitle', 'class'];
let badges = '';
params.forEach(item => {
if (!el[item])
el[item] = ''
});
if (el.width == 'standart' || !el.width)
cardHead += `<div id="${el.id}" class="card ${el.class}" style="width: 18rem; ${el.styles}">`;
else
cardHead += `<div id="${el.id}" class="card ${el.class}" style="width: ${el.width}; ${el.styles}">`;
if (el.footer) {
foots += `<div class="card-footer ${el.footerClass}">`;
el.footer.forEach(foot => {
let options = ['pembungkus', 'button', 'btnType', 'tujuan', 'class', 'id', 'text', 'link', 'tag', 'extra']
options.forEach(item => {
if (!foot[item])
foot[item] = '';
});
if (foot.type == 'button') {
if (foot.button)
foots += foot.button;
else if (foot.text && foot.btnType != 'link')
foots += `<button id="${foot.id}" type="${foot.btnType}" ${foot.extra} class= "btn ${foot.class}">${foot.text}</button>`;
else if (foot.text && foot.btnType == 'link')
foots += `<a id="${foot.id}" href="${foot.tujuan}" ${foot.extra} class= "btn ${foot.class}"> ${foot.text} </a>`;
}
else if (foot.type == 'link') {
if (foot.link)
foots += foot.button;
else if (foot.text && !foot.link)
foots += `<a id="${foot.id}" href="${foot.tujuan}" ${foot.extra} class= "btn ${foot.class}"> ${foot.text} </a>`;
}
else if (foot.type == 'text') {
if (foot.text && !foot.tag)
foots += text;
else if (foot.tag) {
foots += `<${foot.tag} id="${foot.id}" ${foot.extra} class ="${foot.class}" > ${foot.text} </${foot.tag}>`;
}
}
})
foots += '</div>';
}
if (el.badge) {
badges += `<div class="position-relative">`;
el.badge.forEach(b => {
if (!b.id)
b.id = '';
if (!b.class)
b.class = '';
if (!b.extra)
b.extra = '';
badges += `<span ${b.id} class="badge badge-pill position-absolute badge-top-left ${b.class}" ${b.extra}>${b.text}</span>`;
});
badges += `</div>`;
}
if (el.images) {
el.images.forEach(image => {
if (!image.styles)
image.styles = '';
if (!image.class)
image.class = '';
if (!image.type)
image.type = '';
if (image.position == 'top' && image.type == 'carousel') {
Topimage += `
<div class="slick-item">
${badges}
<img class="card-img-top ${image.class}" style="${image.styles}" src="${image.src}" alt="${image.alt}">
</div>`;
}
if (image.position == 'top' && image.type != 'carousel')
Topimage += `<img class="card-img-top ${image.class}" style="${image.styles}" src="${image.src}" alt="${image.alt}">`;
if (image.position == 'left')
Leftimage += `<img class="card-img-top ${image.class}" style="${image.styles}" src="${image.src}" alt="${image.alt}">`;
if (image.position == 'bottom')
Bottomimage += `<img class="card-img-top ${image.class}" style="${image.styles}" src="${image.src}" alt="${image.alt}">`;
if (image.position == 'right')
Rightimage += `<img class="card-img-top ${image.class}" style="${image.styles}" src="${image.src}" alt="${image.alt}">`;
});
}
if (el.buttons && el.buttons.length > 0) {
el.buttons.forEach(button => {
if (!button.class)
button.class = '';
if (!button.type)
button.type = 'button';
if (!button.id)
button.id = '';
if (!button.extra)
button.extra = '';
else if (button.type == 'link')
buttons += `<a id="${button.id}" ${button.extra} href="${button.link}" class="btn ${button.class}">${button.text}</a>`;
else
buttons += `<button id="${button.id}" ${button.extra} type="${button.type} class="btn ${button.class}">${button.text}</button>`;
})
}
if (el.links && el.links.length > 0) {
el.links.forEach(link => {
if (!link.class)
link.class = '';
if (!link.id)
link.id = '';
if (!link.extra)
link.extra = '';
links += `<a href="${link.href}" ${link.extra} id="${link.id}" class="card-link ${link.class}">${link.text}</a>`;
})
}
if (el.type == 'image') {
card +=
`${cardHead}
${badges}
${Topimage}
</div>`;
} else {
if (!Leftimage && !Rightimage) {
if (el.type == 'carousel') {
card +=
`${cardHead}
<div class="carousel ${el.imagewrapper}">
${Topimage}
</div>
<div class="card-body">
<h5 class="card-title ${el.titleClass}">${el.title}</h5>
<h6 class="card-subtitle mb-2 ${el.subtitleClass}">${el.subtitle}</h6>
<p class="card-text ${el.textClass}">${el.text}</p>
<div style="margin: -6rem 0 0 0;" class="slick-navs-dots slider-nav text-center">
${links}
</div>
${buttons}
${Bottomimage}
</div>
${foots}
</div>`;
} else {
card +=
`${cardHead}
${badges}
${Topimage}
<div class="card-body">
<h5 class="card-title ${el.titleClass}">${el.title}</h5>
<h6 class="card-subtitle mb-2 ${el.subtitleClass}">${el.subtitle}</h6>
<p class="card-text ${el.textClass}">${el.text}</p>
${links}
${buttons}
${Bottomimage}
</div>
${foots}
</div>`;
}
} else {
card += `
${cardHead}
<div class="card-body">
<div style='display: flex'>
${Leftimage}
<div style="margin-left: 2%">
<h5 class="card-title">${el.title}</h5>
<h6 class="card-subtitle mb-2">${el.subtitle}</h6>
<p class="card-text">${el.text}</p>
</div>
${Rightimage}
</div>
${links}
${buttons}
</div>
${foots}
</div>`
}
}
return card;
}
static generateSelect(el) {
var options = el.options ? Object.keys(el.options) : '';
var id = !el.id ? el.name : el.id;
var def = el.default ? el.default : '';
var params = ['label', 'fgClass', 'attr', 'labelClass', 'class'];
var nullOpt = el.nullOpt ? `<option value = "" selected> ${el.nullOpt}</option>` : '';
var selectOpt = nullOpt;
params.forEach(item => {
if (!el[item])
el[item] = ''
});
if (options) {
options.forEach((opt, index) => {
let dataitem = '';
if (el.options[opt].data) {
Object.keys(el.options[opt].data).forEach(i => {
dataitem += `data-${i} ="${el.options[opt].data[i]}"`;
})
}
if (def && opt == def)
selectOpt += `<option ${dataitem} value = "${opt}" selected> ${el.options[opt].text}</option>`;
else
selectOpt += `<option ${dataitem} value = "${opt}"> ${el.options[opt].text}</option>`;
});
}
var select = `
<div class = "form-group ${el.fgClass}">
<label class = "control-label ${el.labelClass}" for = "${id}"> ${el.label}</label>
<select name = "${el.name}" id = "${id}" ${el.attr} class = "form-control ${el.class}" >
${selectOpt}
</select>
</div>`;
return select
}
static generateInput(el) {
var id = !el.id ? el.name : el.id;
var placeholder = el.placeholder ? el.placeholder : "";
var khusus = ['hidden', 'file', 'select'];
var params = ['label', 'fgClass', 'attr', 'value', 'labelClass', 'class'];
params.forEach(item => {
if (!el[item])
el[item] = ''
});
if (el.type == 'file') {
return `
<div class="input-group col-sm-7 ${el.fgClass}">
<span class="input-group-btn">
<span class="btn btn-default btn-file">
Browse… <input type="${el.type}" name="${el.name}" id="${id}">
</span>
</span>
<input type="text" value="${el.value}" class="form-control ${el.class}" readonly>
</div>`
}
if (el.type == 'hidden')
return `<input type='hidden' value="${el.value}" id="${id}" name = "${el.name}" />`
if (el.type == 'textarea')
return `<div class = "form-group"><label class= "control-label ${el.labelClass}" for = "${id}"> ${el.label} </label> <textarea name = "${el.name}" id = "${id}" class = "form-control ${el.class}" ${el.attr} placeholder = "${placeholder}">${el.value}</textarea></div>`;
if (!khusus.includes(el.type))
return `<div class = "form-group"> <label class= "control-label ${el.labelClass}" for = "${id}"> ${el.label} </label> <input name = "${el.name}" type = "${el.type}" id = "${id}" value = "${el.value}" class = "form-control ${el.class}" ${el.attr} placeholder = "${placeholder}"> </div>`;
}
static getInstance() {
return this.instance;
}
static makeToast(opt) {
let non_req = ['tempel', 'textColor', 'bg', 'delay', 'wrapper', 'toastTime', 'show', 'return', 'hancurkan', 'toastTitle', 'toastMessage', 'cara_tempel'];
non_req.forEach(nq => {
if (!opt[nq])
opt[nq] = '';
});
if (!opt.autohide)
opt.autohide = false
if (!opt.delay && opt.autohide)
opt.delay = 3000;
if (!opt.toastId) {
alert('toastId tidak boleh kosong');
return;
}
let toast = `
<div aria-live="assertive" aria-atomic="true" role="alert" id="${opt.toastId}" data-delay ="${opt.delay}" class="toast ${opt.bg} ${opt.textColor}" style="position: fixed;top: 20%;right: 0;" data-autohide="${opt.autohide}">
<div class="toast-header">
<strong class="mr-auto">${opt.toastTitle}</strong>
<small>${opt.toastTime}</small>
<button type="button" class="ml-2 mb-1 close" data-dismiss="toast" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="toast-body">
${opt.toastMessage}
</div>
</div>
`;
if ((opt.tempel && opt.wrapper) || opt.show) {
if (!opt.cara_tempel)
$(opt.wrapper).append(toast);
if (opt.cara_tempel == 'after')
$(opt.wrapper).after(toast);
if (opt.cara_tempel == 'prepend')
$(opt.wrapper).prepend(toast);
if (opt.cara_tempel == 'before')
$(opt.wrapper).before(toast);
}
if (opt.show)
$('#' + opt.toastId).toast('show');
if (opt.return)
return toast;
$("#" + opt.toastId).on('hidden.bs.toast', function () {
if (opt.hancurkan)
$('#' + opt.toastId).remove();
})
}
static makeNotify(opt) {
const params = [
'dismiss', 'timpa', 'atasbawah', 'kirikanan', 'append', 'saatmembuka',
'saatterbuka', 'saatmenutup', 'saattertutup', 'progressBar'
];
params.forEach(item => {
if (!opt.params)
opt[params] = '';
})
$.notify(
{
title: opt.title ? opt.title : "Bootstrap Notify",
message: opt.message ? opt.message : "Here is a notification!",
target: "_blank"
},
{
element: opt.append ? opt.append : 'body',
position: null,
type: opt.type ? opt.type : 'success',
allow_dismiss: opt.dismiss ? opt.dismiss : true,
newest_on_top: opt.timpa ? opt.timpa : true,
showProgressbar: opt.progressBar ? opt.progressBar : false,
placement: {
from: opt.atasbawah,
align: opt.kirikanan
},
offset: 20,
spacing: 10,
z_index: 1031,
delay: opt.delay ? opt.delay : 5000,
timer: 2000,
url_target: "_blank",
mouse_over: null,
animate: {
enter: "animated fadeInDown",
exit: "animated fadeOutUp"
},
onShow: opt.saatmembuka ? opt.saatmembuka : null,
onShown: opt.saatterbuka ? opt.saatterbuka : null,
onClose: opt.saatmenutup ? opt.saatmenutup : null,
onClosed: opt.saattertutup ? opt.saattertutup : null,
icon_type: "class",
template:
'<div data-notify="container" class="col-11 col-sm-3 alert alert-{0} " role="alert">' +
'<button type="button" aria-hidden="true" class="close" data-notify="dismiss">×</button>' +
'<span data-notify="icon"></span> ' +
'<span data-notify="title">{1}</span> ' +
'<span data-notify="message">{2}</span>' +
'<div class="progress" data-notify="progressbar">' +
'<div class="progress-bar progress-bar-{0}" role="progressbar" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100" style="width: 0%;"></div>' +
"</div>" +
'<a href="{3}" target="{4}" data-notify="url"></a>' +
"</div>"
}
);
}
static showLoading(autoend = false, opt) {
// Show loading
$('body').addClass('show-spinner');
$('body').addClass('modal-open');
$('.c-overlay').show();
if (autoend && opt.delay) {
setTimeout(function () {
this.endLoading(opt.endConf);
}, opt.delay);
}
}
static endLoading(shownotif = true, opt = null) {
// def option
if (!opt)
opt = { notif: {} }
if (!opt.notif) {
opt.notif.conf = {
type: 'notify',
conf: {
type: 'danger',
message: 'Terjadi kesalahan',
title: 'Error'
}
}
} else {
if (!opt.notif.type) {
opt.notif.type = 'notyfy'
} else if (!opt.notif.conf) {
if (opt.notif.type == 'notify') {
opt.notif.conf = {
type: 'danger',
message: 'Terjadi kesalahan',
title: 'Error'
}
} else {
opt.notif.conf = {
type: 'danger',
toastId: 'defToast',
toastTitle: 'Error',
toastMessage: 'Terjadi kesalahan',
autohide: true,
}
}
}
}
// End loading
setTimeout(function () {
$('body').removeClass('show-spinner');
$('.c-overlay').hide();
}, 3000);
if (shownotif) {
if (opt.notif.type == 'toast')
this.makeToast(opt.notif.conf);
if (opt.notif.type == 'notify')
this.makeNotify(opt.notif.conf);
}
}
} |
JavaScript | class Role {
/**
* Constructs a new role object.
*
* * `creep` - The creep that is fulfilling this role
* * `defaultBehavior` - Behavior the role should use if one is not set
* * `behaviorTransitions` - A `string, string` map of current behavior to next behavior
*/
constructor(creep, defaultBehavior, behaviorTransitions) {
if (!creep || !(creep instanceof Creep)) {
throw new Error(`No creep passed to Role constructor: ${JSON.stringify(creep)}`)
}
this.creep = creep
this.behaviorTransitions = behaviorTransitions
if (!this.creep.memory.behaviorId) {
this.creep.memory.behaviorId = defaultBehavior
}
}
/**
* Default handling of changing from one behavior to the next.
*
* Subclasses should override this function if they need to do something beyond simply
* transitioning to the next behavior, such as clearing the creep's target.
*/
setNextBehavior() {
this.creep.memory.behaviorId = this.behaviorTransitions[this.creep.memory.behaviorId]
}
toString() {
return `[Role ${this.constructor.id}]`
}
/**
* Draws the appropriate room visualizations for the creep's role.
*
* Subclasses should override this function if they need to do something beyond simply drawing
* a line to the creep's current target.
*/
visualize() {
if (this.creep.target) {
this.creep.room.visual.line(this.creep.pos, this.creep.target.pos, {
color: "#0f0",
lineStyle: "dashed"
})
}
}
} |
JavaScript | class OwtEvent {
// eslint-disable-next-line require-jsdoc
constructor(type) {
this.type = type;
}
} |
JavaScript | class MessageEvent extends OwtEvent {
// eslint-disable-next-line require-jsdoc
constructor(type, init) {
super(type);
/**
* @member {string} origin
* @instance
* @memberof Owt.Base.MessageEvent
* @desc ID of the remote endpoint who published this stream.
*/
this.origin = init.origin;
/**
* @member {string} message
* @instance
* @memberof Owt.Base.MessageEvent
*/
this.message = init.message;
/**
* @member {string} to
* @instance
* @memberof Owt.Base.MessageEvent
* @desc Values could be "all", "me" in conference mode, or undefined in
* P2P mode.
*/
this.to = init.to;
}
} |
JavaScript | class ErrorEvent extends OwtEvent {
// eslint-disable-next-line require-jsdoc
constructor(type, init) {
super(type);
/**
* @member {Error} error
* @instance
* @memberof Owt.Base.ErrorEvent
*/
this.error = init.error;
}
} |
JavaScript | class MuteEvent extends OwtEvent {
// eslint-disable-next-line require-jsdoc
constructor(type, init) {
super(type);
/**
* @member {Owt.Base.TrackKind} kind
* @instance
* @memberof Owt.Base.MuteEvent
*/
this.kind = init.kind;
}
} |
JavaScript | class ButtonField extends BaseField {
/**
* Redefinition of base guiField static property 'mixins'.
*/
static get mixins() {
return super.mixins.concat(ButtonFieldMixin);
}
} |
JavaScript | class App extends Component {
constructor(props) {
super(props);
this.state = {
isAuthenticated: false,
isAuthenticating: true,
CognitoID: "",
userID:""
};
}
/*
We use use currentAuthenticatedUser to enable a session. So that if a person
refreshes the website, all state can the reaquired. But if the try statement fails,
then we can most likely say that there is session created in Cognito.
*/
async componentDidMount() {
try {
const CurrentUser= await Auth.currentAuthenticatedUser({bypassCache: false});
const UserPlaylist= await API.graphql(graphqlOperation(listUserPlaylists, {CognitoID: CurrentUser.username }));
this.setState({
CognitoID: CurrentUser.username,
userID: UserPlaylist.data.listUserPlaylistss.items[0].id,
isAuthenticated:true,
isAuthenticating: false
});
}
catch(e) {
if (e !== 'No current user') {
console.log(e);
}
}
this.setState({ isAuthenticating: false });
}
/*
Here are a couple of function that help us with setting up the state
when a new user has been created or when a person decides to Loggin.
*/
userHasAuthenticated = authenticated => {
this.setState({ isAuthenticated: authenticated });
}
setUserID = async (id) =>{
this.setState({userID: id });
}
setCognitoID = async id => {
this.setState({CognitoID: id});
}
handleLogout = (event) => {
Auth.signOut().then(data => {
console.log(data);
this.setState({
isAuthenticated: false,
isAuthenticating: true,
CognitoID: "",
userID:""
});
}).catch(error =>{
console.log(error);
})
}
render() {
/*
These props are created since they are used by the container components
for example Sign In or Sign Up. They are also used when doing API calls to
the GraphQL API.
*/
const childProps = {
isAuthenticated: this.state.isAuthenticated,
userHasAuthenticated: this.userHasAuthenticated,
CognitoID:this.state.CognitoID,
setCognitoID: this.setCognitoID,
userID: this.state.userID,
setUserID: this.setUserID
};
/*
Depending on if the a user has signed in and Authenticated we want them
to have see different elements. We use React Route to Route to the
different directories of the website.
*/
return (
!this.state.isAuthenticating &&
<div className="App container">
<Navbar fluid collapseOnSelect>
<Navbar.Header>
<Navbar.Brand>
<Link to="/">Youtube Playlist</Link>
</Navbar.Brand>
<Navbar.Toggle />
</Navbar.Header>
<Nav>
<LinkContainer exact to="/">
<NavItem >
Home
</NavItem>
</LinkContainer>
<LinkContainer to="/playlists">
<NavItem >
Playlists
</NavItem>
</LinkContainer>
</Nav>
<Navbar.Collapse>
<Nav pullRight>
{this.state.isAuthenticated
?
<NavItem href="/login" onClick={this.handleLogout}>Logout</NavItem>
: <Fragment>
<LinkContainer to="/signup">
<NavItem>Signup</NavItem>
</LinkContainer>
<LinkContainer to="/login">
<NavItem>Login</NavItem>
</LinkContainer>
</Fragment>
}
</Nav>
</Navbar.Collapse>
</Navbar>
<Routes childProps={childProps} />
</div>
);
}
} |
JavaScript | class SubscriptionSet {
constructor() {
this.set = {
subscribe: {},
psubscribe: {}
};
}
add(set, channel) {
this.set[mapSet(set)][channel] = true;
}
del(set, channel) {
delete this.set[mapSet(set)][channel];
}
channels(set) {
return Object.keys(this.set[mapSet(set)]);
}
isEmpty() {
return (this.channels("subscribe").length === 0 &&
this.channels("psubscribe").length === 0);
}
} |
JavaScript | class StorageProfile {
/**
* Create a StorageProfile.
* @member {object} [imageReference] Specifies information about the image to
* use. You can specify information about platform images, marketplace
* images, or virtual machine images. This element is required when you want
* to use a platform image, marketplace image, or virtual machine image, but
* is not used in other creation operations.
* @member {string} [imageReference.publisher] The image publisher.
* @member {string} [imageReference.offer] Specifies the offer of the
* platform image or marketplace image used to create the virtual machine.
* @member {string} [imageReference.sku] The image SKU.
* @member {string} [imageReference.version] Specifies the version of the
* platform image or marketplace image used to create the virtual machine.
* The allowed formats are Major.Minor.Build or 'latest'. Major, Minor, and
* Build are decimal numbers. Specify 'latest' to use the latest version of
* an image available at deploy time. Even if you use 'latest', the VM image
* will not automatically update after deploy time even if a new version
* becomes available.
* @member {object} [osDisk] Specifies information about the operating system
* disk used by the virtual machine. <br><br> For more information about
* disks, see [About disks and VHDs for Azure virtual
* machines](https://docs.microsoft.com/azure/virtual-machines/virtual-machines-windows-about-disks-vhds?toc=%2fazure%2fvirtual-machines%2fwindows%2ftoc.json).
* @member {string} [osDisk.osType] This property allows you to specify the
* type of the OS that is included in the disk if creating a VM from
* user-image or a specialized VHD. <br><br> Possible values are: <br><br>
* **Windows** <br><br> **Linux**. Possible values include: 'Windows',
* 'Linux'
* @member {object} [osDisk.encryptionSettings] Specifies the encryption
* settings for the OS Disk. <br><br> Minimum api-version: 2015-06-15
* @member {object} [osDisk.encryptionSettings.diskEncryptionKey] Specifies
* the location of the disk encryption key, which is a Key Vault Secret.
* @member {string} [osDisk.encryptionSettings.diskEncryptionKey.secretUrl]
* The URL referencing a secret in a Key Vault.
* @member {object} [osDisk.encryptionSettings.diskEncryptionKey.sourceVault]
* The relative URL of the Key Vault containing the secret.
* @member {string}
* [osDisk.encryptionSettings.diskEncryptionKey.sourceVault.id] Resource Id
* @member {object} [osDisk.encryptionSettings.keyEncryptionKey] Specifies
* the location of the key encryption key in Key Vault.
* @member {string} [osDisk.encryptionSettings.keyEncryptionKey.keyUrl] The
* URL referencing a key encryption key in Key Vault.
* @member {object} [osDisk.encryptionSettings.keyEncryptionKey.sourceVault]
* The relative URL of the Key Vault containing the key.
* @member {string}
* [osDisk.encryptionSettings.keyEncryptionKey.sourceVault.id] Resource Id
* @member {boolean} [osDisk.encryptionSettings.enabled] Specifies whether
* disk encryption should be enabled on the virtual machine.
* @member {string} [osDisk.name] The disk name.
* @member {object} [osDisk.vhd] The virtual hard disk.
* @member {string} [osDisk.vhd.uri] Specifies the virtual hard disk's uri.
* @member {object} [osDisk.image] The source user image virtual hard disk.
* The virtual hard disk will be copied before being attached to the virtual
* machine. If SourceImage is provided, the destination virtual hard drive
* must not exist.
* @member {string} [osDisk.image.uri] Specifies the virtual hard disk's uri.
* @member {string} [osDisk.caching] Specifies the caching requirements.
* <br><br> Possible values are: <br><br> **None** <br><br> **ReadOnly**
* <br><br> **ReadWrite** <br><br> Default: **None for Standard storage.
* ReadOnly for Premium storage**. Possible values include: 'None',
* 'ReadOnly', 'ReadWrite'
* @member {string} [osDisk.createOption] Specifies how the virtual machine
* should be created.<br><br> Possible values are:<br><br> **Attach** \u2013
* This value is used when you are using a specialized disk to create the
* virtual machine.<br><br> **FromImage** \u2013 This value is used when you
* are using an image to create the virtual machine. If you are using a
* platform image, you also use the imageReference element described above.
* If you are using a marketplace image, you also use the plan element
* previously described. Possible values include: 'FromImage', 'Empty',
* 'Attach'
* @member {number} [osDisk.diskSizeGB] Specifies the size of an empty data
* disk in gigabytes. This element can be used to overwrite the name of the
* disk in a virtual machine image. <br><br> This value cannot be larger than
* 1023 GB
* @member {object} [osDisk.managedDisk] The managed disk parameters.
* @member {string} [osDisk.managedDisk.storageAccountType] Specifies the
* storage account type for the managed disk. Possible values are:
* Standard_LRS or Premium_LRS. Possible values include: 'Standard_LRS',
* 'Premium_LRS'
* @member {array} [dataDisks] Specifies the parameters that are used to add
* a data disk to a virtual machine. <br><br> For more information about
* disks, see [About disks and VHDs for Azure virtual
* machines](https://docs.microsoft.com/azure/virtual-machines/virtual-machines-windows-about-disks-vhds?toc=%2fazure%2fvirtual-machines%2fwindows%2ftoc.json).
*/
constructor() {
}
/**
* Defines the metadata of StorageProfile
*
* @returns {object} metadata of StorageProfile
*
*/
mapper() {
return {
required: false,
serializedName: 'StorageProfile',
type: {
name: 'Composite',
className: 'StorageProfile',
modelProperties: {
imageReference: {
required: false,
serializedName: 'imageReference',
type: {
name: 'Composite',
className: 'ImageReference'
}
},
osDisk: {
required: false,
serializedName: 'osDisk',
type: {
name: 'Composite',
className: 'OSDisk'
}
},
dataDisks: {
required: false,
serializedName: 'dataDisks',
type: {
name: 'Sequence',
element: {
required: false,
serializedName: 'DataDiskElementType',
type: {
name: 'Composite',
className: 'DataDisk'
}
}
}
}
}
}
};
}
} |
JavaScript | class PouchLink extends CozyLink {
constructor({ doctypes, client, initialSync } = {}) {
if (!doctypes) {
throw new Error(
"PouchLink must be instantiated with doctypes it manages. Ex: ['io.cozy.bills']"
)
}
if (!client) {
throw new Error('PouchLink must be instantiated with a client.')
}
super()
this.doctypes = doctypes
this.client = client
this.pouches = createPouches(this.doctypes)
this.indexes = {}
if (initialSync) {
this.syncAll()
}
}
getAllDBs() {
return Object.values(this.pouches).map(x => x.db)
}
resetAllDBs() {
return Promise.all(this.getAllDBs().map(db => db.destroy()))
}
getDBInfo(doctype) {
const dbInfo = this.pouches[doctype]
if (!dbInfo) {
throw new Error(`${doctype} not supported by cozy-pouch-link instance`)
}
return dbInfo
}
getDB(doctype) {
return this.getDBInfo(doctype).db
}
syncOne(doctype) {
return new Promise((resolve, reject) => {
const info = this.getDBInfo(doctype)
if (info.syncing) {
return resolve(info.syncing)
} else {
const replication = info.db.replicate.from(
this.getReplicationUrl(doctype),
{
batch_size: 1000 // we have mostly small documents
}
)
replication.on('error', err => {
console.warn('Error while syncing', err)
reject('Error while syncing')
})
info.syncing = replication.on('complete', () => {
info.syncing = null
resolve()
})
}
})
}
syncAll() {
return Promise.all(
this.doctypes.map(doctype => this.syncOne(doctype))
).then(pipe(() => this.onSync()))
}
onSync() {
this.synced = true
}
getReplicationUrl(doctype) {
const client = this.client
const basicAuth = client.token.toBasicAuth()
return (client.uri + '/data/' + doctype).replace('//', `//${basicAuth}`)
}
supportsOperation(operation) {
const impactedDoctype = getDoctypeFromOperation(operation)
return !!this.pouches[impactedDoctype]
}
request(operation, result = null, forward = doNothing) {
if (!this.synced) {
return forward(operation)
}
// Forwards if doctype not supported
if (!this.supportsOperation(operation)) {
return forward(operation)
}
if (operation.mutationType) {
return this.executeMutation(operation)
} else {
return this.executeQuery(operation)
}
}
hasIndex(name) {
return Boolean(this.indexes[name])
}
async ensureIndex(doctype, query) {
const fields = getIndexFields(query)
const name = getIndexNameFromFields(fields)
const absName = `${doctype}/${name}`
const db = this.getDB(doctype)
if (this.indexes[absName]) {
return this.indexes[absName]
} else {
const index = await db.createIndex({
index: {
fields: fields
}
})
this.indexes[absName] = index
return index
}
}
async executeQuery({ doctype, selector, sort, fields, limit }) {
const db = this.getDB(doctype)
let res
if (!selector && !fields && !sort) {
res = await db.allDocs({
include_docs: true
})
} else {
const findOpts = {
sort,
selector,
fields,
limit
}
await this.ensureIndex(doctype, findOpts)
res = await db.find(findOpts)
}
return pouchResToJSONAPI(res, true, doctype)
}
async executeMutation(mutation, result, forward) {
let pouchRes
switch (mutation.mutationType) {
case MutationTypes.CREATE_DOCUMENT:
pouchRes = await this.createDocument(mutation)
break
case MutationTypes.UPDATE_DOCUMENT:
pouchRes = await this.updateDocument(mutation)
break
case MutationTypes.DELETE_DOCUMENT:
pouchRes = await this.deleteDocument(mutation)
break
case MutationTypes.ADD_REFERENCES_TO:
pouchRes = await this.addReferencesTo(mutation)
break
case MutationTypes.UPLOAD_FILE:
return forward(mutation, result)
default:
throw new Error(`Unknown mutation type: ${mutation.mutationType}`)
}
return pouchResToJSONAPI(pouchRes, false, getDoctypeFromOperation(mutation))
}
createDocument(mutation) {
return this.dbMethod('post', mutation)
}
async updateDocument(mutation) {
return this.dbMethod('put', mutation)
}
async deleteDocument(mutation) {
return this.dbMethod('remove', mutation)
}
async dbMethod(method, mutation) {
const doctype = getDoctypeFromOperation(mutation)
const { document } = mutation
const db = this.getDB(doctype)
const res = await db[method](sanitized(document))
if (res.ok) {
return parseMutationResult(document, res)
} else {
throw new Error('Coud not apply mutation')
}
}
} |
JavaScript | class ExtensionNavigateRequest extends WebRequestBase {
async authorize () {
// allow anonymous users to access this
return true;
}
async process () {
await this.showNavigate();
}
async showNavigate () {
const templateProps = {
ides: ides,
navigate: this.request.params.navigate,
queryString: {
q: this.request.query.q,
ide: 'default',
debug: this.request.query.debug === 'true'
},
segmentKey: this.api.config.telemetry.segment.webToken,
partial_launcher_model: this.createLauncherModel(undefined),
};
await super.render('ext_navigate', templateProps);
}
} |
JavaScript | class SequenceInLayer extends React.Component{
render() {
const {isDragging, connectDragSource, entity} = this.props
return connectDragSource(
// View card
<div className="sequenceInLayer" style={{opacity: isDragging ? 0.5 : 1}}>
{entity.name}
</div>
)
}
} |
JavaScript | class CodePipeline {
constructor(pipeline) {
this.pipeline = pipeline;
}
bind(_rule, _id) {
return {
id: '',
arn: this.pipeline.pipelineArn,
role: util_1.singletonEventRole(this.pipeline, [new iam.PolicyStatement({
resources: [this.pipeline.pipelineArn],
actions: ['codepipeline:StartPipelineExecution'],
})]),
targetResource: this.pipeline,
};
}
} |
JavaScript | class Component {
constructor(props, context) {
this.props = props;
this.context = context;
this.refs = {};
}
setState(partialState, callback) {
this.updater.setState(this, partialState, callback);
}
forceUpdate(callback) {
this.updater.forceUpdate(this, callback);
}
} |
JavaScript | class GeneralWidgets extends react__WEBPACK_IMPORTED_MODULE_0__["Component"] {
render() {
return react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("div", {
className: "general-widgets-wrapper"
}, react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(Components_PageTitleBar_PageTitleBar__WEBPACK_IMPORTED_MODULE_2__["default"], {
title: react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(Util_IntlMessages__WEBPACK_IMPORTED_MODULE_3__["default"], {
id: "sidebar.general"
}),
match: this.props.match
}), react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("div", {
className: "dash-cards"
}, react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("div", {
className: "row"
}, react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("div", {
className: "col-xs-12 col-sm-6 col-md-3 col-xl-3 w-xs-half-block"
}, react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(Components_Widgets__WEBPACK_IMPORTED_MODULE_1__["Reminders"], null)), react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("div", {
className: "col-xs-12 col-sm-6 col-md-3 col-xl-3 w-xs-half-block"
}, react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(Components_Widgets__WEBPACK_IMPORTED_MODULE_1__["ContactRequestWidget"], null)), react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("div", {
className: "col-xs-12 col-sm-6 col-md-3 col-xl-3 w-xs-half-block"
}, react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(Components_Widgets__WEBPACK_IMPORTED_MODULE_1__["Space"], {
data: _data__WEBPACK_IMPORTED_MODULE_5__["spaceUsed"]
})), react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("div", {
className: "col-xs-12 col-sm-6 col-md-3 col-xl-3 w-xs-half-block"
}, react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(Components_Widgets__WEBPACK_IMPORTED_MODULE_1__["WeatherWidget"], null)))), react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("div", {
className: "social-card-wrapper"
}, react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("div", {
className: "row"
}, react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("div", {
className: "col-sm-6 col-md-3 col-lg-3 w-xs-half-block"
}, react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(Components_Widgets__WEBPACK_IMPORTED_MODULE_1__["SocialFeedsWidget"], {
type: "facebook",
friendsCount: "89k",
icon: "ti-facebook",
feedsCount: "459"
})), react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("div", {
className: "col-sm-6 col-md-3 col-lg-3 w-xs-half-block"
}, react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(Components_Widgets__WEBPACK_IMPORTED_MODULE_1__["SocialFeedsWidget"], {
type: "twitter",
friendsCount: "89k",
feedsCount: "459",
icon: "ti-twitter"
})), react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("div", {
className: "col-sm-6 col-md-3 col-lg-3 w-xs-half-block"
}, react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(Components_Widgets__WEBPACK_IMPORTED_MODULE_1__["SocialFeedsWidget"], {
type: "linkedin",
friendsCount: "89k",
feedsCount: "459",
icon: "ti-linkedin"
})), react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("div", {
className: "col-sm-6 col-md-3 col-lg-3 w-xs-half-block"
}, react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(Components_Widgets__WEBPACK_IMPORTED_MODULE_1__["SocialFeedsWidget"], {
type: "google",
friendsCount: "89k",
feedsCount: "459",
icon: "ti-google"
})))), react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("div", {
className: "row"
}, react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(Components_RctCollapsibleCard_RctCollapsibleCard__WEBPACK_IMPORTED_MODULE_4__["default"], {
colClasses: "col-sm-12 col-md-7 col-xl-7 b-100 w-xs-full",
heading: react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(Util_IntlMessages__WEBPACK_IMPORTED_MODULE_3__["default"], {
id: "widgets.newEmails"
}),
collapsible: true,
reloadable: true,
closeable: true,
fullBlock: true
}, react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(Components_Widgets__WEBPACK_IMPORTED_MODULE_1__["NewEmailsWidget"], null)), react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(Components_RctCollapsibleCard_RctCollapsibleCard__WEBPACK_IMPORTED_MODULE_4__["default"], {
colClasses: "col-sm-12 col-md-5 col-xl-5 b-100 w-xs-full",
heading: react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(Util_IntlMessages__WEBPACK_IMPORTED_MODULE_3__["default"], {
id: "widgets.employeePayroll"
}),
collapsible: true,
reloadable: true,
closeable: true,
fullBlock: true
}, react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(Components_Widgets__WEBPACK_IMPORTED_MODULE_1__["EmployeePayrollWidget"], null))), react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(Components_RctCollapsibleCard_RctCollapsibleCard__WEBPACK_IMPORTED_MODULE_4__["default"], {
heading: react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(Util_IntlMessages__WEBPACK_IMPORTED_MODULE_3__["default"], {
id: "widgets.orderStatus"
}),
collapsible: true,
reloadable: true,
closeable: true,
fullBlock: true
}, react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(Components_Widgets__WEBPACK_IMPORTED_MODULE_1__["OrderStatusWidget"], null)), react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("div", {
className: "row"
}, react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(Components_RctCollapsibleCard_RctCollapsibleCard__WEBPACK_IMPORTED_MODULE_4__["default"], {
colClasses: "col-sm-6 col-md-4 col-lg-4 w-xs-half-block",
heading: react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(Util_IntlMessages__WEBPACK_IMPORTED_MODULE_3__["default"], {
id: "widgets.discoverPeople"
}),
collapsible: true,
reloadable: true,
closeable: true,
fullBlock: true
}, react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(Components_Widgets__WEBPACK_IMPORTED_MODULE_1__["DiscoverPeoplesWidget"], null)), react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(Components_RctCollapsibleCard_RctCollapsibleCard__WEBPACK_IMPORTED_MODULE_4__["default"], {
colClasses: "col-sm-6 col-md-4 col-lg-4 w-xs-half-block",
heading: react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(Util_IntlMessages__WEBPACK_IMPORTED_MODULE_3__["default"], {
id: "widgets.productReports"
}),
collapsible: true,
reloadable: true,
closeable: true,
fullBlock: true
}, react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(Components_Widgets__WEBPACK_IMPORTED_MODULE_1__["ProductReportsWidget"], null)), react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(Components_RctCollapsibleCard_RctCollapsibleCard__WEBPACK_IMPORTED_MODULE_4__["default"], {
colClasses: "col-sm-12 col-md-4 col-lg-4 w-xs-full",
heading: react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(Util_IntlMessages__WEBPACK_IMPORTED_MODULE_3__["default"], {
id: "widgets.recentActivities"
}),
collapsible: true,
reloadable: true,
closeable: true
}, react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(Components_Widgets__WEBPACK_IMPORTED_MODULE_1__["RecentActivity"], null))), react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("div", {
className: "row"
}, react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(Components_RctCollapsibleCard_RctCollapsibleCard__WEBPACK_IMPORTED_MODULE_4__["default"], {
colClasses: "col-sm-12 col-md-8 w-xs-full",
heading: react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(Util_IntlMessages__WEBPACK_IMPORTED_MODULE_3__["default"], {
id: "widgets.ComposeEmail"
}),
collapsible: true,
reloadable: true,
closeable: true,
fullBlock: true
}, react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(Components_Widgets__WEBPACK_IMPORTED_MODULE_1__["ComposeEmailWidget"], null)), react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("div", {
className: "col-sm-12 col-md-4 w-xs-full"
}, react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(Components_Widgets__WEBPACK_IMPORTED_MODULE_1__["CurrentTimeLocation"], null), react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(Components_Widgets__WEBPACK_IMPORTED_MODULE_1__["CurrentDateWidget"], null), react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(Components_Widgets__WEBPACK_IMPORTED_MODULE_1__["TodayOrdersStatsWidget"], null))), react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("div", {
className: "row"
}, react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("div", {
className: "col-sm-6 col-md-4 col-lg-4 w-8-half-block"
}, react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(Components_Widgets__WEBPACK_IMPORTED_MODULE_1__["BlogLayoutOne"], null)), react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("div", {
className: "col-sm-6 col-md-4 col-lg-4 w-8-half-block"
}, react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(Components_Widgets__WEBPACK_IMPORTED_MODULE_1__["BlogLayoutTwo"], null)), react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("div", {
className: "col-sm-6 col-md-4 col-lg-4 w-8-full"
}, react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(Components_Widgets__WEBPACK_IMPORTED_MODULE_1__["BlogLayoutThree"], null))), react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("div", {
className: "row"
}, react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(Components_RctCollapsibleCard_RctCollapsibleCard__WEBPACK_IMPORTED_MODULE_4__["default"], {
colClasses: "col-sm-12 col-md-6 w-xs-full",
fullBlock: true
}, react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(Components_Widgets__WEBPACK_IMPORTED_MODULE_1__["WeatherWidgetV2"], {
city: "Chandigarh"
}))));
}
// @ts-ignore
__reactstandin__regenerateByEval(key, code) {
// @ts-ignore
this[key] = eval(code);
}
} |
JavaScript | class Menu extends Component {
render() {
return (
<NavBar brand="AS Sykkelutleie">
<NavBar.Link to="/bikes">Sykler</NavBar.Link>
<NavBar.Link to="/customers">Kunder</NavBar.Link>
<NavBar.Link to="/eqpts">Utstyr</NavBar.Link>
<NavBar.Link to="/towns">Utleiested</NavBar.Link>
<NavBar.Link to="/Bookings">Bookinger</NavBar.Link>
</NavBar>
);
}
} |
JavaScript | class MeshHeader {
/** A magic number used to detect compatibility of navigation tile data. */
static DT_NAVMESH_MAGIC = 'D' << 24 | 'N' << 16 | 'A' << 8 | 'V';
/** A version number used to detect compatibility of navigation tile data.*/
static DT_NAVMESH_VERSION = 7;
static DT_NAVMESH_VERSION_RECAST4J = 0x8807;
/** A magic number used to detect the compatibility of navigation tile states.*/
static DT_NAVMESH_STATE_MAGIC = 'D' << 24 | 'N' << 16 | 'M' << 8 | 'S';
/** A version number used to detect compatibility of navigation tile states.*/
static DT_NAVMESH_STATE_VERSION = 1;
/** < Tile magic number. (Used to identify the data format.)*/
magic;
/** < Tile data format version number.*/
version;
/** < The x-position of the tile within the dtNavMesh tile grid. (x, y, layer)*/
x;
/** < The y-position of the tile within the dtNavMesh tile grid. (x, y, layer)*/
y;
/** < The layer of the tile within the dtNavMesh tile grid. (x, y, layer)*/
layer;
/** < The user defined id of the tile.*/
userId;
/** < The number of polygons in the tile.*/
polyCount;
/** < The number of vertices in the tile.*/
vertCount;
/** < The number of allocated links.*/
maxLinkCount;
/** < The number of sub-meshes in the detail mesh.*/
detailMeshCount;
/** The number of unique vertices in the detail mesh. (In addition to the polygon vertices.)*/
detailVertCount;
/** < The number of triangles in the detail mesh.*/
detailTriCount;
/** < The number of bounding volume nodes. (Zero if bounding volumes are disabled.)*/
bvNodeCount;
/** < The number of off-mesh connections.*/
offMeshConCount;
/** < The index of the first polygon which is an off-mesh connection.*/
offMeshBase;
/** < The height of the agents using the tile.*/
walkableHeight;
/** < The radius of the agents using the tile.*/
walkableRadius;
/** < The maximum climb height of the agents using the tile.*/
walkableClimb;
/** < The minimum bounds of the tile's AABB. [(x, y, z)]*/
bmin = new Array(3);
/** < The maximum bounds of the tile's AABB. [(x, y, z)]*/
bmax = new Array(3);
/** The bounding volume quantization factor.*/
bvQuantFactor;
} |
JavaScript | class BaseNavbarComponent {
constructor() { }
/**
* @return {?}
*/
ngOnInit() {
}
} |
JavaScript | class Context {
/**
* Context errors.
*/
#errors = [];
/**
* Context tokens.
*/
#tokens = [];
/**
* Context symbol table.
*/
#table = new table_1.default();
/**
* Context main node.
*/
#node;
/**
* Context name.
*/
#name;
/**
* Default constructor.
* @param name Context name.
*/
constructor(name) {
this.#node = new node_1.default(new fragment_1.default('', 0, 0, new location_1.default(name, 0, 0)), 0x00, this.#table);
this.#name = name;
}
/**
* Get the error list.
*/
get errors() {
return this.#errors;
}
/**
* Get the token list.
*/
get tokens() {
return this.#tokens;
}
/**
* Get the symbol table.
*/
get table() {
return this.#table;
}
/**
* Get the root node.
*/
get node() {
return this.#node;
}
/**
* Get the context name.
*/
get name() {
return this.#name;
}
/**
* Add a new error in the context.
* @param fragment Error fragment.
* @param value Error value.
*/
addError(fragment, value) {
this.#errors.push(new error_1.default(fragment, value));
}
} |
JavaScript | class TextBoxDirective {
constructor(renderer, inputElement) {
this.renderer = renderer;
this.inputElement = inputElement;
this.hostClass = true;
/**
* @hidden
*/
this.onFocus = new EventEmitter();
/**
* @hidden
*/
this.onBlur = new EventEmitter();
/**
* @hidden
*/
this.onValueChange = new EventEmitter();
this.listeners = [];
}
/**
* @hidden
*/
set value(text) {
if (!this.inputElement) {
return;
}
this.inputElement.nativeElement.value = (text === undefined || text === null) ? '' : text;
this.onValueChange.emit();
}
/**
* @hidden
*/
get value() {
return this.inputElement.nativeElement.value;
}
get id() {
return this.inputElement.nativeElement.id;
}
set id(id) {
this.renderer.setAttribute(this.inputElement.nativeElement, 'id', id);
}
ngAfterViewInit() {
const input = this.inputElement.nativeElement;
this.listeners = [
this.renderer.listen(input, 'focus', () => this.onFocus.emit()),
this.renderer.listen(input, 'blur', () => this.onBlur.emit())
];
}
ngOnDestroy() {
this.listeners.forEach(listener => listener());
}
} |
JavaScript | class StartMining {
static async startMining() {
let numThreads = 6;
//TestUtils.getWalletRpc().startMining(numThreads, false, true);
let daemon = await TestUtils.getDaemonRpc();
await daemon.startMining("56SWsnhejUTbgNs2EgyXdfNXUawymMMuAC9voZZSQrHzJHNxGsAvMnoUja7JcKVtPwNc1oKAkoAt1cv6EmtKRQ22U37B7cT", numThreads, false, false); // random subaddress
}
} |
JavaScript | class DeviceGeneric {
/**
* Creates a new generic device
* @param {String} name Device's name
* @param {String} ip Device's ip address
* @param {String} mac Device's mac address
*/
constructor(name, ip, mac) {
this.name = name;
this.ip = ip;
this.mac = mac;
}
} |
JavaScript | class WebRtcPeer {
constructor(localId, remoteId, sendSignalFunc) {
this.localId = localId;
this.remoteId = remoteId;
this.sendSignalFunc = sendSignalFunc;
this.open = false;
this.channelLabel = 'networked-aframe-channel';
this.pc = this.createPeerConnection();
this.channel = null;
}
setDatachannelListeners(openListener, closedListener, messageListener, trackListener) {
this.openListener = openListener;
this.closedListener = closedListener;
this.messageListener = messageListener;
this.trackListener = trackListener;
}
offer(options) {
const self = this;
// reliable: false - UDP
this.setupChannel(this.pc.createDataChannel(this.channelLabel, { reliable: false }));
// If there are errors with Safari implement this:
// https://github.com/OpenVidu/openvidu/blob/master/openvidu-browser/src/OpenViduInternal/WebRtcPeer/WebRtcPeer.ts#L154
if (options.sendAudio) {
options.localAudioStream.getTracks().forEach(track => self.pc.addTrack(track, options.localAudioStream));
}
this.pc.createOffer(
sdp => {
self.handleSessionDescription(sdp);
},
error => {
NAF.log.error('WebRtcPeer.offer: ' + error);
},
{
offerToReceiveAudio: true,
offerToReceiveVideo: false,
},
);
}
handleSignal(signal) {
// ignores signal if it isn't for me
if (this.localId !== signal.to || this.remoteId !== signal.from) return;
switch (signal.type) {
case 'offer':
this.handleOffer(signal);
break;
case 'answer':
this.handleAnswer(signal);
break;
case 'candidate':
this.handleCandidate(signal);
break;
default:
NAF.log.error('WebRtcPeer.handleSignal: Unknown signal type ' + signal.type);
break;
}
}
send(type, data) {
if (this.channel === null || this.channel.readyState !== 'open') {
return;
}
this.channel.send(JSON.stringify({ type: type, data: data }));
}
getStatus() {
if (this.channel === null) return WebRtcPeer.NOT_CONNECTED;
switch (this.channel.readyState) {
case 'open':
return WebRtcPeer.IS_CONNECTED;
case 'connecting':
return WebRtcPeer.CONNECTING;
case 'closing':
case 'closed':
default:
return WebRtcPeer.NOT_CONNECTED;
}
}
/*
* Privates
*/
createPeerConnection() {
const self = this;
const RTCPeerConnection =
window.RTCPeerConnection ||
window.webkitRTCPeerConnection ||
window.mozRTCPeerConnection ||
window.msRTCPeerConnection;
if (RTCPeerConnection === undefined) {
throw new Error('WebRtcPeer.createPeerConnection: This browser does not seem to support WebRTC.');
}
const pc = new RTCPeerConnection({ iceServers: WebRtcPeer.ICE_SERVERS });
pc.onicecandidate = function (event) {
if (event.candidate) {
self.sendSignalFunc({
from: self.localId,
to: self.remoteId,
type: 'candidate',
sdpMLineIndex: event.candidate.sdpMLineIndex,
candidate: event.candidate.candidate,
});
}
};
// Note: seems like channel.onclose hander is unreliable on some platforms,
// so also tries to detect disconnection here.
pc.oniceconnectionstatechange = function () {
if (self.open && pc.iceConnectionState === 'disconnected') {
self.open = false;
self.closedListener(self.remoteId);
}
};
pc.ontrack = e => {
self.trackListener(self.remoteId, e.streams[0]);
};
return pc;
}
setupChannel(channel) {
const self = this;
this.channel = channel;
// received data from a remote peer
this.channel.onmessage = function (event) {
const data = JSON.parse(event.data);
self.messageListener(self.remoteId, data.type, data.data);
};
// connected with a remote peer
this.channel.onopen = function (_event) {
self.open = true;
self.openListener(self.remoteId);
};
// disconnected with a remote peer
this.channel.onclose = function (_event) {
if (!self.open) return;
self.open = false;
self.closedListener(self.remoteId);
};
// error occurred with a remote peer
this.channel.onerror = function (error) {
NAF.log.error('WebRtcPeer.channel.onerror: ' + error);
};
}
handleOffer(message) {
const self = this;
this.pc.ondatachannel = function (event) {
self.setupChannel(event.channel);
};
this.setRemoteDescription(message);
this.pc.createAnswer(
function (sdp) {
self.handleSessionDescription(sdp);
},
function (error) {
NAF.log.error('WebRtcPeer.handleOffer: ' + error);
},
);
}
handleAnswer(message) {
this.setRemoteDescription(message);
}
handleCandidate(message) {
const RTCIceCandidate = window.RTCIceCandidate || window.webkitRTCIceCandidate || window.mozRTCIceCandidate;
this.pc.addIceCandidate(
new RTCIceCandidate(message),
function () {},
function (error) {
NAF.log.error('WebRtcPeer.handleCandidate: ' + error);
},
);
}
handleSessionDescription(sdp) {
this.pc.setLocalDescription(
sdp,
function () {},
function (error) {
NAF.log.error('WebRtcPeer.handleSessionDescription: ' + error);
},
);
this.sendSignalFunc({
from: this.localId,
to: this.remoteId,
type: sdp.type,
sdp: sdp.sdp,
});
}
setRemoteDescription(message) {
const RTCSessionDescription =
window.RTCSessionDescription ||
window.webkitRTCSessionDescription ||
window.mozRTCSessionDescription ||
window.msRTCSessionDescription;
this.pc.setRemoteDescription(
new RTCSessionDescription(message),
function () {},
function (error) {
NAF.log.error('WebRtcPeer.setRemoteDescription: ' + error);
},
);
}
close() {
if (this.pc) {
this.pc.close();
}
}
} |
JavaScript | class WebrtcAdapter {
constructor() {
if (io === undefined) console.warn('It looks like socket.io has not been loaded before WebrtcAdapter. Please do that.');
this.app = 'default';
this.room = 'default';
this.occupantListener = null;
this.myRoomJoinTime = null;
this.myId = null;
this.peers = {}; // id -> WebRtcPeer
this.occupants = {}; // id -> joinTimestamp
this.audioStreams = {};
this.pendingAudioRequest = {};
this.serverTimeRequests = 0;
this.timeOffsets = [];
this.avgTimeOffset = 0;
}
setServerUrl(wsUrl) {
this.wsUrl = wsUrl;
}
setApp(appName) {
this.app = appName;
}
setRoom(roomName) {
this.room = roomName;
}
setWebRtcOptions(options) {
if (options.datachannel === false) {
NAF.log.error('WebrtcAdapter.setWebRtcOptions: datachannel must be true.');
}
if (options.audio === true) {
this.sendAudio = true;
}
if (options.video === true) {
NAF.log.warn('WebrtcAdapter does not support video yet.');
}
}
setServerConnectListeners(successListener, failureListener) {
this.connectSuccess = successListener;
this.connectFailure = failureListener;
}
setRoomOccupantListener(occupantListener) {
this.occupantListener = occupantListener;
}
setDataChannelListeners(openListener, closedListener, messageListener) {
this.openListener = openListener;
this.closedListener = closedListener;
this.messageListener = messageListener;
}
connect() {
const self = this;
this.updateTimeOffset().then(() => {
if (!self.wsUrl || self.wsUrl === '/') {
if (location.protocol === 'https:') {
self.wsUrl = 'wss://' + location.host;
} else {
self.wsUrl = 'ws://' + location.host;
}
}
NAF.log.write('Attempting to connect to socket.io');
const socket = (self.socket = io(self.wsUrl));
socket.on('connect', () => {
NAF.log.write('User connected', socket.id);
self.myId = socket.id;
self.joinRoom();
});
socket.on('connectSuccess', data => {
const { joinedTime } = data;
self.myRoomJoinTime = joinedTime;
NAF.log.write('Successfully joined room', self.room, 'at server time', joinedTime);
if (self.sendAudio) {
const mediaConstraints = {
audio: true,
video: false,
};
navigator.mediaDevices
.getUserMedia(mediaConstraints)
.then(localStream => {
self.storeAudioStream(self.myId, localStream);
self.connectSuccess(self.myId);
localStream.getTracks().forEach(track => {
Object.keys(self.peers).forEach(peerId => {
self.peers[peerId].pc.addTrack(track, localStream);
});
});
})
.catch(e => {
NAF.log.error(e);
console.error('Microphone is disabled due to lack of permissions');
self.sendAudio = false;
self.connectSuccess(self.myId);
});
} else {
self.connectSuccess(self.myId);
}
});
socket.on('error', err => {
console.error('Socket connection failure', err);
self.connectFailure();
});
socket.on('occupantsChanged', data => {
const { occupants } = data;
NAF.log.write('occupants changed', data);
self.receivedOccupants(occupants);
});
function receiveData(packet) {
const from = packet.from;
const type = packet.type;
const data = packet.data;
if (type === 'ice-candidate') {
self.peers[from].handleSignal(data);
return;
}
self.messageListener(from, type, data);
}
socket.on('send', receiveData);
socket.on('broadcast', receiveData);
});
}
joinRoom() {
NAF.log.write('Joining room', this.room);
this.socket.emit('joinRoom', { room: this.room });
}
receivedOccupants(occupants) {
delete occupants[this.myId];
this.occupants = occupants;
const self = this;
const localId = this.myId;
for (let key in occupants) {
const remoteId = key;
if (this.peers[remoteId]) continue;
const peer = new WebRtcPeer(localId, remoteId, data => {
self.socket.emit('send', {
from: localId,
to: remoteId,
type: 'ice-candidate',
data,
sending: true,
});
});
peer.setDatachannelListeners(
self.openListener,
self.closedListener,
self.messageListener,
self.trackListener.bind(self),
);
self.peers[remoteId] = peer;
}
this.occupantListener(occupants);
}
shouldStartConnectionTo(client) {
return (this.myRoomJoinTime || 0) <= (client || 0);
}
startStreamConnection(remoteId) {
NAF.log.write('starting offer process');
if (this.sendAudio) {
this.getMediaStream(this.myId).then(stream => {
const options = {
sendAudio: true,
localAudioStream: stream,
};
this.peers[remoteId].offer(options);
});
} else {
this.peers[remoteId].offer({});
}
}
closeStreamConnection(clientId) {
NAF.log.write('closeStreamConnection', clientId, this.peers);
this.peers[clientId].close();
delete this.peers[clientId];
delete this.occupants[clientId];
this.closedListener(clientId);
}
getConnectStatus(clientId) {
const peer = this.peers[clientId];
if (peer === undefined) return NAF.adapters.NOT_CONNECTED;
switch (peer.getStatus()) {
case WebRtcPeer.IS_CONNECTED:
return NAF.adapters.IS_CONNECTED;
case WebRtcPeer.CONNECTING:
return NAF.adapters.CONNECTING;
case WebRtcPeer.NOT_CONNECTED:
default:
return NAF.adapters.NOT_CONNECTED;
}
}
sendData(to, type, data) {
this.peers[to].send(type, data);
}
sendDataGuaranteed(to, type, data) {
const packet = {
from: this.myId,
to,
type,
data,
sending: true,
};
this.socket.emit('send', packet);
}
broadcastData(type, data) {
for (let clientId in this.peers) {
this.sendData(clientId, type, data);
}
}
broadcastDataGuaranteed(type, data) {
const packet = {
from: this.myId,
type,
data,
broadcasting: true,
};
this.socket.emit('broadcast', packet);
}
storeAudioStream(clientId, stream) {
this.audioStreams[clientId] = stream;
if (this.pendingAudioRequest[clientId]) {
NAF.log.write('Received pending audio for ' + clientId);
this.pendingAudioRequest[clientId](stream);
delete this.pendingAudioRequest[clientId](stream);
}
}
trackListener(clientId, stream) {
this.storeAudioStream(clientId, stream);
}
getMediaStream(clientId) {
const self = this;
if (this.audioStreams[clientId]) {
NAF.log.write('Already had audio for ' + clientId);
return Promise.resolve(this.audioStreams[clientId]);
} else {
NAF.log.write('Waiting on audio for ' + clientId);
return new Promise(resolve => {
self.pendingAudioRequest[clientId] = resolve;
});
}
}
updateTimeOffset() {
const clientSentTime = Date.now() + this.avgTimeOffset;
return fetch(document.location.href, { method: 'HEAD', cache: 'no-cache' }).then(res => {
const precision = 1000;
const serverReceivedTime = new Date(res.headers.get('Date')).getTime() + precision / 2;
const clientReceivedTime = Date.now();
const serverTime = serverReceivedTime + (clientReceivedTime - clientSentTime) / 2;
const timeOffset = serverTime - clientReceivedTime;
this.serverTimeRequests++;
if (this.serverTimeRequests <= 10) {
this.timeOffsets.push(timeOffset);
} else {
this.timeOffsets[this.serverTimeRequests % 10] = timeOffset;
}
this.avgTimeOffset = this.timeOffsets.reduce((acc, offset) => (acc += offset), 0) / this.timeOffsets.length;
if (this.serverTimeRequests > 10) {
setTimeout(() => this.updateTimeOffset(), 5 * 60 * 1000); // Sync clock every 5 minutes.
} else {
this.updateTimeOffset();
}
});
}
getServerTime() {
return new Date().getTime() + this.avgTimeOffset;
}
} |