language
stringclasses 5
values | text
stringlengths 15
988k
|
---|---|
JavaScript | class Car extends CarStructure {
constructor() {
this.Make = 2000;
this.Model = "Model";
this.Transmission_Type = "manual";
/*
Manual
Automatic
*/
this.Car_Size_Class = "Compact"
/*
Sport Car / Convertible
Luxury / SUV
Full-Size
Mid-Size / Van
Minivan
Compact
Subcompact
Micro
*/
super();
}
} |
JavaScript | class WriteConcern {
/**
* Constructs a WriteConcern from the write concern properties.
* @param w - request acknowledgment that the write operation has propagated to a specified number of mongod instances or to mongod instances with specified tags.
* @param wtimeout - specify a time limit to prevent write operations from blocking indefinitely
* @param j - request acknowledgment that the write operation has been written to the on-disk journal
* @param fsync - equivalent to the j option
*/
constructor(w, wtimeout, j, fsync) {
if (w != null) {
if (!Number.isNaN(Number(w))) {
this.w = Number(w);
}
else {
this.w = w;
}
}
if (wtimeout != null) {
this.wtimeout = wtimeout;
}
if (j != null) {
this.j = j;
}
if (fsync != null) {
this.fsync = fsync;
}
}
/** Construct a WriteConcern given an options object. */
static fromOptions(options, inherit) {
if (options == null)
return undefined;
inherit = inherit !== null && inherit !== void 0 ? inherit : {};
let opts;
if (typeof options === 'string' || typeof options === 'number') {
opts = { w: options };
}
else if (options instanceof WriteConcern) {
opts = options;
}
else {
opts = options.writeConcern;
}
const parentOpts = inherit instanceof WriteConcern ? inherit : inherit.writeConcern;
const { w = undefined, wtimeout = undefined, j = undefined, fsync = undefined, journal = undefined, wtimeoutMS = undefined } = {
...parentOpts,
...opts
};
if (w != null ||
wtimeout != null ||
wtimeoutMS != null ||
j != null ||
journal != null ||
fsync != null) {
return new WriteConcern(w, wtimeout !== null && wtimeout !== void 0 ? wtimeout : wtimeoutMS, j !== null && j !== void 0 ? j : journal, fsync);
}
return undefined;
}
} |
JavaScript | class Checkbox extends React.PureComponent {
state = {
value: this.props.value == null ? !!this.props.defaultChecked : !!this.props.value
}
componentWillReceiveProps (props) {
if (props.value !== this.state.value && props.value != null) {
this.setState({ value: props.value })
}
}
change = (event) => {
const value = event.target.checked
if (this.props.value == null) {
this.setState({ value })
}
if (this.props.onChange) {
this.props.onChange(value)
}
}
render () {
const { children, className, error, style, value, onChange, defaultChecked, ...passedProps } = this.props
const _value = this.state.value
const clsName = buildClassName(moduleName, className, { error })
return (
<label className={clsName} style={style}>
<input
type='checkbox'
onChange={this.change}
checked={_value}
{...passedProps}
/>
<span tabIndex={-1}>
<span>{children}</span>
</span>
</label>
)
}
} |
JavaScript | class Version3 {
/**
* Constructs a new <code>Version3</code>.
* @alias module:model/Version3
* @param id {String}
* @param name {String}
* @param createdAt {String}
* @param updatedAt {String}
* @param api {String}
* @param createdBy {String}
* @param updatedBy {String}
*/
constructor(id, name, createdAt, updatedAt, api, createdBy, updatedBy) {
Version3.initialize(this, id, name, createdAt, updatedAt, api, createdBy, updatedBy);
}
/**
* 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, id, name, createdAt, updatedAt, api, createdBy, updatedBy) {
obj['id'] = id;
obj['name'] = name;
obj['createdAt'] = createdAt;
obj['updatedAt'] = updatedAt;
obj['api'] = api;
obj['createdBy'] = createdBy;
obj['updatedBy'] = updatedBy;
}
/**
* Constructs a <code>Version3</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/Version3} obj Optional instance to populate.
* @return {module:model/Version3} The populated <code>Version3</code> instance.
*/
static constructFromObject(data, obj) {
if (data) {
obj = obj || new Version3();
if (data.hasOwnProperty('id')) {
obj['id'] = ApiClient.convertToType(data['id'], 'String');
}
if (data.hasOwnProperty('name')) {
obj['name'] = ApiClient.convertToType(data['name'], 'String');
}
if (data.hasOwnProperty('createdAt')) {
obj['createdAt'] = ApiClient.convertToType(data['createdAt'], 'String');
}
if (data.hasOwnProperty('updatedAt')) {
obj['updatedAt'] = ApiClient.convertToType(data['updatedAt'], 'String');
}
if (data.hasOwnProperty('api')) {
obj['api'] = ApiClient.convertToType(data['api'], 'String');
}
if (data.hasOwnProperty('createdBy')) {
obj['createdBy'] = ApiClient.convertToType(data['createdBy'], 'String');
}
if (data.hasOwnProperty('updatedBy')) {
obj['updatedBy'] = ApiClient.convertToType(data['updatedBy'], 'String');
}
}
return obj;
}
} |
JavaScript | class Modal extends Component {
componentDidMount() {
// whenever the component gets rendered to the screen, we gonna create a new div and assign to this modal target
this.modalTarget = document.createElement('div');
this.modalTarget.className = 'modal';
document.body.appendChild(this.modalTarget);
this._render();
}
componentWillUpdate() {
this._render();
}
componentWillUnmount() {
ReactDOM.unmountComponentAtNode(this.modalTarget);
document.body.removeChild(this.modalTarget);
}
_render() {
ReactDOM.render(
<Provider store={store}>
<div>{this.props.children}</div>
</Provider>,
this.modalTarget
);
}
render() {
return <noscript />; // means render nothing
}
} |
JavaScript | class More {
/*
* Constructor
* -----------
*/
constructor( args ) {
/*
* Public variables
* ----------------
*/
this.next = null;
this.nextContainer = null; // no pagination
this.prev = null; // pagination
this.current = null; // pagination
this.tot = null; // pagination
this.filters = [];
this.filtersForm = null;
this.loaders = [];
this.noResults = {
containers: [],
buttons: []
};
this.error = null;
this.url = '';
this.data = {};
this.ppp = 0; // per page
this.page = 1; // pagination
this.total = 0; // pagination total pages else total number of items
this.insertInto = null;
this.insertLocation = 'beforeend';
this.onInsert = () => {};
this.afterInsert = () => {};
this.filterPushUrlParams = () => [];
this.filterPostData = () => this._data;
/*
* Internal variables
* ------------------
*/
// for pushState
this._urlSupported = true;
this._url = '';
// if prev and pagination
this._pagination = false;
// for scrolling back to top for pagination
this._insertIntoY = 0;
// store initial count
this._initCount = 0;
// buttons for setLoaders
this._controls = [];
// merge default variables with args
mergeObjects( this, args );
/*
* Initialize
* ----------
*/
let init = this._initialize();
if( !init )
return false;
}
/*
* Initialize
* ----------
*/
_initialize() {
// check that required variables not null
if( !this.next ||
!this.url ||
!this.ppp ||
!this.total ||
!this.insertInto )
return false;
// check if URL constructor supported
if( typeof window.URL !== 'function' ||
typeof URL.createObjectURL !== 'function' ||
typeof URL.revokeObjectURL !== 'function' )
this._urlSupported = false;
if( this._urlSupported )
this._url = new URL( window.location );
// check for pagination
if( this.prev && this.current ) {
this._pagination = true;
this.prev.setAttribute( 'data-pag-prev', '' );
this.next.setAttribute( 'data-pag-next', '' );
}
// for hiding when nothing more to load
if( !this.nextContainer && !this._pagination )
this.nextContainer = this.next;
if( !this._pagination ) {
// set buttons for setLoaders
this._controls.push( this.next );
if( this.prev )
this._controls.push( this.prev );
}
// data
this._initCount = this.insertInto.children.length;
this._data = {
ppp: this.ppp,
total: this.total,
count: this._initCount,
filters: {}
};
if( this._pagination ) {
this._data.page = this.page;
this._data.count = this._getCount();
} else {
this._data.offset = this._initCount;
}
// append public data
for( let d in this.data )
this._data[d] = this.data[d];
// add event listeners
this.next.addEventListener( 'click', this._load.bind( this ) );
if( this.prev )
this.prev.addEventListener( 'click', this._load.bind( this ) );
if( this._pagination )
window.onpopstate = this._popState.bind( this );
// set filters
if( this.filters.length ) {
this.filters.forEach( f => {
let type = this._getType( f );
if( type == 'listbox' ) {
f.onChange( ( ff, val ) => {
this._data.filters[ff.id] = {
value: val
};
this._load( 'reset' );
} );
} else {
let args = { currentTarget: f };
if( type === 'search' ) {
let submitSearchSelector = f.getAttribute( 'data-submit-selector' );
if( submitSearchSelector ) {
let submitSearch = document.querySelector( submitSearchSelector );
if( submitSearch )
submitSearch.addEventListener( 'click', () => {
this._filter( args );
} );
}
f.addEventListener( 'keydown', e => {
let key = e.key || e.keyCode || e.which || e.code;
if( [13, 'Enter'].indexOf( key ) !== -1 )
this._filter( args );
} );
} else {
f.addEventListener( 'change', this._filter.bind( this ) );
}
// init ( if selected add to data filter attribute )
this._filter( args, 'init' );
}
} );
// disable if no items to start
if( !this._initCount )
this._disableFilters( true );
}
// back to all results
if( this.noResults.buttons ) {
this.noResults.buttons.forEach( b => {
b.addEventListener( 'click', () => {
this._data.filters = {};
// clear filters
if( this.filters.length ) {
this.filters.forEach( f => {
this._setFilter( f, 'null' );
} );
}
this._load( 'reset-no-res' );
} );
} );
}
// push for initial state
this._pushState( 'init', this.insertInto.innerHTML );
// set controls for initial state + get insert y
window.addEventListener( 'load', () => {
this._setControls();
this._getInsertIntoY();
} );
if( this._pagination ) {
let resizeTimer;
window.addEventListener( 'resize', () => {
// throttles resize event
clearTimeout( resizeTimer );
resizeTimer = setTimeout( () => {
this._getInsertIntoY();
}, 100 );
} );
}
return true;
}
/*
* Getters
* -------
*/
// get input type
_getType( input ) {
let type = '',
loadMoreType = input.getAttribute( 'data-load-more-type' );
if( !loadMoreType ) {
if( input.type == 'listbox' ) {
type = 'listbox';
} else {
type = input.tagName.toLowerCase();
if( type === 'input' )
type = input.type;
}
input.setAttribute( 'data-load-more-type', type );
} else {
type = loadMoreType;
}
return type;
}
// get item count
_getCount() {
let c = this.insertInto.children.length;
// for page beyond first add previous page item counts
if( this._pagination ) {
if( this._data.page > 1 )
c += this.ppp * ( this._data.page - 1 );
}
return c;
}
// get insertInto y position
_getInsertIntoY() {
this._insertIntoY = this.insertInto.getBoundingClientRect().y + getScrollY();
}
/*
* Setters
* -------
*/
// set filter input
_setFilter( f, compareValue = undefined, state = 'default' ) { // if compareValue undefined than clear input
let id = f.id,
value = f.value,
operator = f.getAttribute( 'data-operator' ),
type = this._getType( f );
if( type == 'radio' )
id = f.name;
if( state === 'init' ) {
compareValue = 'null';
switch( type ) {
case 'checkbox':
if( f.checked )
compareValue = value;
break;
case 'radio':
let r = Array.from( document.querySelectorAll( `[name="${ id }"]` ) );
r.forEach( rr => {
if( rr.checked )
compareValue = rr.value;
} );
break;
default:
if( value )
compareValue = value;
}
}
let equalToCompareVal = value === compareValue;
if( equalToCompareVal ) {
// selected
this._data.filters[id] = {
value: value,
operator: operator
};
}
if( type == 'listbox' ) {
if( !equalToCompareVal )
f.clear();
// if value...
} else {
switch( type ) {
case 'checkbox':
case 'radio':
f.checked = equalToCompareVal;
break;
case 'select':
let opts = Array.from( f.options );
opts.forEach( o => {
o.selected = o.value === compareValue;
} );
break;
default:
f.value = equalToCompareVal ? value : '';
}
}
}
// set display/disable of prev/next
_setControls() {
if( this._data.count >= this._data.total ) {
if( this.nextContainer )
this.nextContainer.style.display = 'none';
if( this._pagination ) {
this.next.disabled = true;
this.prev.disabled = this._data.page == 1 ? true : false; // account for one page
}
} else {
if( this.nextContainer )
this.nextContainer.style.display = 'block';
if( this._pagination ) {
this.next.disabled = false;
this.prev.disabled = this._data.page == 1 ? true : false; // account for one page
}
}
// no items disable both
if( !this._data.count && this._pagination ) {
this.next.disabled = true;
this.prev.disabled = true;
}
}
// add output to insertInto element
_setOutput( output = '', done = () => {} ) {
let table = this.insertInto.tagName == 'TBODY',
docFragment = document.createDocumentFragment(),
div = document.createElement( table ? 'TBODY' : 'DIV' );
div.innerHTML = output;
let imgs = Array.from( div.getElementsByTagName( 'img' ) ),
insertedItems = Array.from( div.children );
assetsLoaded( imgs, data => {
this.onInsert.call( this, insertedItems );
if( table ) {
insertedItems.forEach( item => {
this.insertInto.appendChild( item );
} );
} else {
insertedItems.forEach( item => {
docFragment.appendChild( item );
} );
if( this._pagination )
this.insertInto.innerHTML = '';
this.insertInto.appendChild( docFragment );
}
done();
setTimeout( () => {
this.afterInsert.call( this, insertedItems );
}, 0 );
} );
}
// set pagination numbers
_setPagNum( total ) {
if( this.current )
this.current.textContent = total ? this._data.page : 0;
if( this.tot )
this.tot.textContent = Math.ceil( total / this.ppp );
}
/*
* No results
* ----------
*/
// when filters change reset offset/page and count
_reset() {
this._data.count = 0;
if( this._pagination ) {
this._data.page = 1;
} else {
this._data.offset = 0;
}
}
// disable/enable filters
_disableFilters( show = true ) {
if( this.filters.length ) {
if( this.filtersForm )
this.filtersForm.setAttribute( 'data-disabled', show ? 'true' : 'false' );
this.filters.forEach( f => {
let type = this._getType( f );
if( type == 'listbox' ) {
f.disable( show ? true : false );
} else {
f.disabled = show ? true : false;
f.setAttribute( 'aria-disabled', show ? 'true' : 'false' );
}
} );
}
}
// when no results
_noResults( show = true ) {
this._disableFilters( show );
if( show )
this.insertInto.innerHTML = '';
// show nothing found message
if( this.noResults.containers.length ) {
this.noResults.containers.forEach( c => {
c.style.display = show ? 'block' : 'none';
} );
}
}
// when error
_error( show = true ) {
this._disableFilters( show );
if( this.error )
this.error.style.display = show ? 'block' : 'none';
}
/*
* Push to browser history if pagination
* -------------------------------------
*/
// add url and data to browser history
_pushState( state, output ) {
if( !this._pagination )
return;
let url = '',
data = {
data: this._data,
state: state,
html: output ? this.insertInto.innerHTML : ''
};
if( this._urlSupported && this._url ) {
let params = this.filterPushUrlParams( state, this._data );
for( let u in params ) {
let v = params[u];
if( v == 'load_more_delete_param' ) {
this._url.searchParams.delete( u );
} else {
this._url.searchParams.set( u, v );
}
}
url = this._url;
}
if( url ) {
window.history.pushState( data, '', url );
} else {
window.history.pushState( data, '' );
}
}
/*
* Update state after response
* ---------------------------
*/
// after response set vars/items
_afterResponse( args = {} ) {
let a = Object.assign( {
reset: false,
total: 0,
state: 'default',
output: ''
}, args );
this._data.count = this._getCount();
// get new total
if( a.reset )
this._data.total = a.total;
this._setControls();
this._setPagNum( a.total );
setLoaders( this.loaders, this._controls, false );
// history entry
this._pushState( a.state, a.output );
}
/*
* Event handlers
* --------------
*/
_filter( e, state = 'default' ) {
let f = e.currentTarget,
compareValue = f.value;
this._setFilter( f, compareValue, state );
if( state !== 'init' )
this._load( 'reset' );
}
_popState( e ) {
if( !this._pagination )
return;
if( e.state ) {
this._data = Object.assign( this._data, e.state.data );
// output
this._history = e.state.html;
this._load( 'history' );
if( this.filters.length ) {
this.filters.forEach( f => {
let id = f.id,
type = this._getType( f );
if( type == 'radio' )
id = f.name;
let compareValue = 'null';
if( this._data.filters.hasOwnProperty( id ) )
compareValue = this._data.filters[id].value;
this._setFilter( f, compareValue );
} );
}
}
}
_load( e ) {
// if pagination
let nextPag = false;
if( e !== undefined && !( typeof e == 'string' || e instanceof String ) ) {
e.preventDefault();
nextPag = e.currentTarget.hasAttribute( 'data-pag-next' );
}
// set states
let state = 'default',
reset = false;
if( typeof e == 'string' || e instanceof String )
state = e;
if( e === 'reset' || e === 'reset-no-res' )
reset = true;
// reset
if( reset )
this._reset();
this._noResults( false );
this._error( false );
setLoaders( this.loaders, this._controls, true );
if( e == 'history' ) {
this.insertInto.innerHTML = '';
if( this._history ) {
this._setOutput( this._history );
} else {
this._noResults();
}
this._setControls();
setLoaders( this.loaders, this._controls, false );
} else {
// update page fetching
if( this._pagination ) {
if( nextPag ) {
this._data.page += 1;
} else {
this._data.page -= 1;
if( this._data.page < 1 )
this._data.page = 1;
}
}
// get data as url encoded string
let encodedData = urlEncode( this.filterPostData( this._data ) );
console.log( 'DATA', this._data );
setTimeout( () => {
// fetch more items
request( {
method: 'POST',
url: this.url,
headers: { 'Content-type': 'application/x-www-form-urlencoded' },
body: encodedData
} )
.then( response => {
if( !response ) {
if( reset )
this._noResults();
this._afterResponse( {
reset: reset,
total: 0,
state: state
} );
return;
}
let result = JSON.parse( response ),
rowCount = result.row_count,
output = result.output,
total = parseInt( result.total );
console.log( 'RESULT', result );
if( reset )
this.insertInto.innerHTML = '';
if( rowCount > 0 && output != '' ) {
if( !this._pagination )
this._data.offset += this.ppp;
this._setOutput( output, () => {
if( this._pagination ) {
document.documentElement.setAttribute( 'data-load-scroll', '' );
window.scrollTo( 0, this._insertIntoY );
setTimeout( () => {
document.documentElement.removeAttribute( 'data-load-scroll' );
}, 0 );
}
setTimeout( () => {
this._afterResponse( {
reset: reset,
total: total,
state: state,
output: output
} );
}, 0 );
} );
} else {
if( reset )
this._noResults();
this._afterResponse( {
reset: reset,
total: total,
state: state
} );
}
} )
.catch( xhr => {
console.log( 'ERROR', xhr );
this._data.total = 0;
this._data.count = 0;
this._data.page = 1;
this._setControls();
this._setPagNum( 0 );
this._error( true );
setLoaders( this.loaders, this._controls, false );
} );
}, 0 );
}
}
} // end More |
JavaScript | class PaymentPending extends React.PureComponent {
static propTypes = {
/** @ignore */
themeName: PropTypes.string.isRequired,
/** @ignore */
history: PropTypes.shape({
push: PropTypes.func.isRequired,
location: PropTypes.object.isRequired,
}).isRequired,
/** @ignore */
t: PropTypes.func.isRequired,
/** @ignore */
isFetchingTransactionDetails: PropTypes.bool.isRequired,
/** @ignore */
hasErrorFetchingTransactionDetails: PropTypes.bool.isRequired,
/** @ignore */
activeTransaction: PropTypes.object,
/** @ignore */
fetchTransactionDetails: PropTypes.func.isRequired,
};
constructor(props) {
super(props);
const { t } = props;
this.state = {
subtitle: t('moonpay:paymentPendingExplanation'),
buttonText: t('moonpay:viewReceipt'),
hasErrorFetchingTransactionDetails: false,
};
this.onButtonPress = this.onButtonPress.bind(this);
}
componentDidMount() {
const { activeTransaction, t } = this.props;
const status = get(activeTransaction, 'status');
if (status === MOONPAY_TRANSACTION_STATUSES.completed) {
this.props.history.push('/exchanges/moonpay/payment-success');
} else if (status === MOONPAY_TRANSACTION_STATUSES.failed) {
this.props.history.push('/exchanges/moonpay/payment-failure');
} else if (status === MOONPAY_TRANSACTION_STATUSES.waitingAuthorization) {
this.setState({
subtitle: t('moonpay:pleaseComplete3DSecure'),
buttonText: t('global:continue'),
});
}
}
componentWillReceiveProps(nextProps) {
const { activeTransaction, t } = nextProps;
if (this.props.isFetchingTransactionDetails && !nextProps.isFetchingTransactionDetails) {
if (nextProps.hasErrorFetchingTransactionDetails) {
this.setState({
subtitle: t('moonpay:errorGettingTransactionDetails'),
buttonText: t('moonpay:tryAgain'),
hasErrorFetchingTransactionDetails: true,
});
} else {
const status = get(activeTransaction, 'status');
if (status === MOONPAY_TRANSACTION_STATUSES.completed) {
this.props.history.push('/exchanges/moonpay/payment-success');
} else if (status === MOONPAY_TRANSACTION_STATUSES.failed) {
this.props.history.push('/exchanges/moonpay/payment-failure');
} else if (status === MOONPAY_TRANSACTION_STATUSES.waitingAuthorization) {
window.open(get(activeTransaction, 'redirectUrl'));
this.setState({
subtitle: t('moonpay:pleaseComplete3DSecure'),
buttonText: t('global:continue'),
});
} else if (status === MOONPAY_TRANSACTION_STATUSES.pending) {
this.setState({
subtitle: t('moonpay:paymentPendingExplanation'),
buttonText: t('moonpay:viewReceipt'),
});
}
}
}
}
/**
* Renders buttons in case of errors
*
* @method renderButtons
*
* @returns {void}
*/
renderButtons() {
const { history, activeTransaction, t } = this.props;
const transactionId = get(history.location, 'state.transactionId');
return (
<div>
<Button
id="to-cancel"
onClick={() => this.props.history.push('/wallet')}
className="square"
variant="dark"
>
{t('global:close')}
</Button>
<Button
id="try-again"
onClick={() => {
this.props.fetchTransactionDetails(transactionId || get(activeTransaction, 'id'));
this.setState({
hasErrorFetchingTransactionDetails: false,
});
}}
className="square"
variant="primary"
>
{t('global:tryAgain')}
</Button>
</div>
);
}
/**
* On (Single) button press callback handler
*
* @method onButtonPress
*
* @returns {void}
*/
onButtonPress() {
const { activeTransaction } = this.props;
const transactionId = get(history.location, 'state.transactionId');
if (get(activeTransaction, 'status') === MOONPAY_TRANSACTION_STATUSES.waitingAuthorization) {
this.props.fetchTransactionDetails(transactionId || get(activeTransaction, 'id'));
} else {
this.props.history.push('/exchanges/moonpay/purchase-receipt');
}
}
render() {
const { t, themeName, isFetchingTransactionDetails } = this.props;
const { hasErrorFetchingTransactionDetails, subtitle, buttonText } = this.state;
return (
<form>
<section className={css.long}>
<div>
<React.Fragment>
<p>{t('moonpay:paymentPending')}</p>
<Lottie
width={250}
height={250}
data={getAnimation('onboardingComplete', themeName)}
loop={false}
/>
</React.Fragment>
<p>{subtitle}</p>
</div>
</section>
<footer className={css.choiceDefault}>
{hasErrorFetchingTransactionDetails ? (
this.renderButtons()
) : (
<div>
<Button
loading={isFetchingTransactionDetails}
id="to-purchase-receipt"
onClick={this.onButtonPress}
className="square"
variant="primary"
>
{buttonText}
</Button>
</div>
)}
</footer>
</form>
);
}
} |
JavaScript | class SearchController extends IUToolsController {
constructor(config) {
super(config);
}
// Setup handler methods for different HTML elements specified in the config.
attachHtmlElements() {
this.setEventHandler("btnSearch", "click", this.onSearch);
this.onReturnKey("txtQuery", this.onSearch);
}
onSearch() {
Debug.getTraceLogger("SearchController.onSearch").trace("Invoked");
this.expandQueryThenSearch();
}
expandQueryThenSearch() {
var isValid = this.validateQueryInput();
if (isValid) {
var divMessage = this.elementForProp("divMessage"); divMessage.html("retrieveAllHitsFromService---");
this.setBusy(true);
this.clearResults();
var data = this.getSearchRequestData();
if (!this.isDuplicateEvent("expandQueryThenSearch", data)) {
this.invokeExpandQueryService(data,
this.expandQuerySuccessCallback, this.expandQueryFailureCallback)
}
}
}
clearResults() {
this.elementForProp('divError').empty();
this.elementForProp('divResults').empty();
}
invokeExpandQueryService(jsonRequestData, _successCbk, _failureCbk) {
var tracer = Debug.getTraceLogger("SearchController.invokeExpandQueryService");
tracer.trace("invoked with jsonRequestData="+JSON.stringify(jsonRequestData));
var controller = this;
var fctSuccess =
function(resp) {
_successCbk.call(controller, resp);
};
var fctFailure =
function(resp) {
_failureCbk.call(controller, resp);
};
// this line is for development only, allowing to present results without calling Bing.
//var jsonResp = this.mockSrvSearch();fctSuccess(jsonResp);
this.userActionStart("SEARCH_WEB", 'srv2/search/expandquery',
jsonRequestData, fctSuccess, fctFailure)
}
validateQueryInput() {
var isValid = true;
var query = this.elementForProp("txtQuery").val();
if (query == null || query === "") {
isValid = false;
this.error("You need to enter something in the query field");
}
return isValid;
}
expandQuerySuccessCallback(resp) {
var tracer = Debug.getTraceLogger("SearchController.expandQuerySuccessCallback");
tracer.trace('resp= '+JSON.stringify(resp));
if (resp.errorMessage != null) {
this.expandQueryFailureCallback(resp);
} else {
var expandedQuery = resp.expandedQuery;
this.setQuery(expandedQuery);
this.launchGoogleSearch(resp.expandedQuerySyll);
}
this.setBusy(false);
this.userActionEnd("SEARCH_WEB", resp);
}
expandQueryFailureCallback(resp) {
if (! resp.hasOwnProperty("errorMessage")) {
// Error condition comes from tomcat itself, not from our servlet
resp.errorMessage =
"Server generated a "+resp.status+" error:\n\n" +
resp.responseText;
}
this.error(resp.errorMessage);
this.setBusy(false);
}
relatedWordsResp2ExpandedQuery(resp) {
var words = [];
var relatedWordsInfo = resp.relatedWords;
for (var ii=0; ii < relatedWordsInfo.length; ii++) {
words.push(relatedWordsInfo[ii].word)
}
var query = '('+words.join(' OR ')+')';
return query;
}
launchGoogleSearch(query) {
var url = "https://www.google.com/search?q="+query;
window.open(url, "_self");
}
setBusy(flag) {
this.busy = flag;
if (flag) {
this.disableSearchButton();
this.showSpinningWheel('divMessage', "Searching");
this.error("");
} else {
this.enableSearchButton();
this.hideSpinningWheel('divMessage');
}
}
getSearchRequestData() {
var request = {
origQuery: this.elementForProp("txtQuery").val()
};
var jsonInputs = JSON.stringify(request);
return jsonInputs;
}
disableSearchButton() {
this.elementForProp('btnSearch').attr("disabled", true);
}
enableSearchButton() {
this.elementForProp('btnSearch').attr("disabled", false);
}
error(err) {
this.elementForProp('divError').html(err);
this.elementForProp('divError').show();
}
setQuery(query) {
this.elementForProp("txtQuery").val(query);
}
} |
JavaScript | class DashboardTx extends React.Component {
/**
* transactions {Array} Array of transactions to show in the dashboard
* blocks {Array} Array of blocks to show in the dashboard
*/
state = { transactions: [], blocks: [] };
componentDidMount = () => {
this.getInitialData();
hathorLib.WebSocketHandler.on('network', this.handleWebsocket);
}
componentWillUnmount = () => {
hathorLib.WebSocketHandler.removeListener('network', this.handleWebsocket);
}
/**
* Get initial data to fill the screen and update the state with this data
*/
getInitialData = () => {
hathorLib.txApi.getDashboardTx(DASHBOARD_BLOCKS_COUNT, DASHBOARD_TX_COUNT, (data) => {
this.updateData(data.transactions, data.blocks);
}, (e) => {
// Error in request
console.log(e);
});
}
/**
* Handle websocket message to see if should update the list
*/
handleWebsocket = (wsData) => {
if (wsData.type === 'network:new_tx_accepted') {
this.updateListWs(wsData);
}
}
/**
* Update list because a new element arrived
*/
updateListWs = (tx) => {
if (tx.is_block) {
let blocks = this.state.blocks;
blocks = hathorLib.helpers.updateListWs(blocks, tx, DASHBOARD_BLOCKS_COUNT);
// Finally we update the state again
this.setState({ blocks });
} else {
let transactions = this.state.transactions;
transactions = hathorLib.helpers.updateListWs(transactions, tx, DASHBOARD_TX_COUNT);
// Finally we update the state again
this.setState({ transactions });
}
}
/**
* Update state data for transactions and blocks
*/
updateData = (transactions, blocks) => {
this.setState({ transactions, blocks });
}
/**
* Go to specific transaction or block page after clicking on the link
*/
goToList = (e, to) => {
e.preventDefault();
this.props.history.push(to);
}
render() {
const renderTableBody = () => {
return (
<tbody>
{this.state.blocks.length ?
<tr className="tr-title"><td colSpan="2">Blocks <a href="/blocks/">(See all blocks)</a></td></tr>
: null}
{renderRows(this.state.blocks)}
{this.state.transactions.length ?
<tr className="tr-title"><td colSpan="2">Transactions <a href="/transactions/">(See all transactions)</a></td></tr>
: null}
{renderRows(this.state.transactions)}
</tbody>
);
}
const renderRows = (elements) => {
return elements.map((tx, idx) => {
return (
<TxRow key={tx.tx_id} tx={tx} />
);
});
}
return (
<div className="content-wrapper">
<div className="table-responsive">
<table className="table" id="tx-table">
<thead>
<tr>
<th className="d-none d-lg-table-cell">Hash</th>
<th className="d-none d-lg-table-cell">Timestamp</th>
<th className="d-table-cell d-lg-none" colSpan="2">Hash<br/>Timestamp</th>
</tr>
</thead>
{renderTableBody()}
</table>
</div>
</div>
);
}
} |
JavaScript | class User extends Password(BaseModel) {
/**
* Get table name
* @return {string}
*/
static get tableName() {
return `${schema}.${USERS_TABLE}`;
}
} |
JavaScript | class CreatedObject1 extends ObjectInterface {
tellType() {
console.log('This is an obj 1');
}
} |
JavaScript | class CreatedObject2 extends ObjectInterface {
tellType() {
console.log('This is an obj 2');
}
} |
JavaScript | class SpeedyKeypoint
{
/**
* Constructor
* @param {number} x X position
* @param {number} y Y position
* @param {number} [lod] Level-of-detail
* @param {number} [rotation] Rotation in radians
* @param {number} [score] Cornerness measure
* @param {?SpeedyKeypointDescriptor} [descriptor] Keypoint descriptor, if any
*/
constructor(x, y, lod = 0.0, rotation = 0.0, score = 0.0, descriptor = null)
{
this._position = new SpeedyPoint2(+x, +y);
this._lod = +lod;
this._rotation = +rotation;
this._score = +score;
this._descriptor = descriptor;
return Object.freeze(this);
}
/**
* Converts this keypoint to a descriptive string
* @returns {string}
*/
toString()
{
return `SpeedyKeypoint(${this.x},${this.y})`;
}
/**
* The position of this keypoint
* @returns {SpeedyPoint2}
*/
get position()
{
return this._position;
}
/**
* The x-position of this keypoint
* @returns {number}
*/
get x()
{
return this._position.x;
}
/**
* The y-position of this keypoint
* @returns {number}
*/
get y()
{
return this._position.y;
}
/**
* The pyramid level-of-detail from which this keypoint was extracted
* @returns {number}
*/
get lod()
{
return this._lod;
}
/**
* Scale: 2^lod
* @returns {number}
*/
get scale()
{
return Math.pow(2, this._lod);
}
/**
* The orientation of the keypoint, in radians
* @returns {number} Angle in radians
*/
get rotation()
{
return this._rotation;
}
/**
* Score: a cornerness measure
* @returns {number} Score
*/
get score()
{
return this._score;
}
/**
* Keypoint descriptor
* @return {?SpeedyKeypointDescriptor}
*/
get descriptor()
{
return this._descriptor;
}
} |
JavaScript | class Employee {
// Just like constructor functions, classes can accept arguments
constructor(name, id, email) {
this.name = name;
this.id = id;
this.email=email;
}
getName(){return this.name};
getId(){return this.id};
getEmail(){return this.email};
getRole(){return 'Employee'};
} |
JavaScript | class Model extends common_1.ServiceObject {
constructor(dataset, id) {
const methods = {
/**
* @callback DeleteModelCallback
* @param {?Error} err Request error, if any.
* @param {object} apiResponse The full API response.
*/
/**
* Delete the model.
*
* See {@link https://cloud.google.com/bigquery/docs/reference/rest/v2/models/delete| Models: delete API Documentation}
*
* @method Model#delete
* @param {DeleteModelCallback} [callback] The callback function.
* @param {?error} callback.err An error returned while making this
* request.
* @param {object} callback.apiResponse The full API response.
* @returns {Promise}
*
* @example
* ```
* const {BigQuery} = require('@google-cloud/bigquery');
* const bigquery = new BigQuery();
* const dataset = bigquery.dataset('my-dataset');
* const model = dataset.model('my-model');
*
* model.delete((err, apiResponse) => {});
*
* ```
* @example If the callback is omitted we'll return a Promise.
* ```
* const [apiResponse] = await model.delete();
* ```
* @example If successful, the response body is empty.
* ```
* ```
*/
delete: true,
/**
* @callback ModelExistsCallback
* @param {?Error} err Request error, if any.
* @param {boolean} exists Indicates if the model exists.
*/
/**
* @typedef {array} ModelExistsResponse
* @property {boolean} 0 Indicates if the model exists.
*/
/**
* Check if the model exists.
*
* @method Model#exists
* @param {ModelExistsCallback} [callback] The callback function.
* @param {?error} callback.err An error returned while making this
* request.
* @param {boolean} callback.exists Whether the model exists or not.
* @returns {Promise<ModelExistsResponse>}
*
* @example
* ```
* const {BigQuery} = require('@google-cloud/bigquery');
* const bigquery = new BigQuery();
* const dataset = bigquery.dataset('my-dataset');
* const model = dataset.model('my-model');
*
* model.exists((err, exists) => {});
*
* ```
* @example If the callback is omitted we'll return a Promise.
* ```
* const [exists] = await model.exists();
* ```
*/
exists: true,
/**
* @callback GetModelCallback
* @param {?Error} err Request error, if any.
* @param {Model} model The model.
* @param {object} apiResponse The full API response body.
*/
/**
* @typedef {array} GetModelResponse
* @property {Model} 0 The model.
* @property {object} 1 The full API response body.
*/
/**
* Get a model if it exists.
*
* See {@link https://cloud.google.com/bigquery/docs/reference/rest/v2/models/get| Models: get API Documentation}
*
* @method Model#get:
* @param {GetModelCallback} [callback] The callback function.
* @param {?error} callback.err An error returned while making this
* request.
* @param {Model} callback.model The {@link Model}.
* @param {object} callback.apiResponse The full API response.
* @returns {Promise<GetModelResponse>}
*
* @example
* ```
* const {BigQuery} = require('@google-cloud/bigquery');
* const bigquery = new BigQuery();
* const dataset = bigquery.dataset('my-dataset');
* const model = dataset.model('my-model');
*
* model.get(err => {
* if (!err) {
* // `model.metadata` has been populated.
* }
* });
*
* ```
* @example If the callback is omitted we'll return a Promise.
* ```
* await model.get();
* ```
*/
get: true,
/**
* @callback GetModelMetadataCallback
* @param {?Error} err Request error, if any.
* @param {object} metadata The model metadata.
* @param {object} apiResponse The full API response.
*/
/**
* @typedef {array} GetModelMetadataResponse
* @property {object} 0 The model metadata.
* @property {object} 1 The full API response.
*/
/**
* Return the metadata associated with the model.
*
* See {@link https://cloud.google.com/bigquery/docs/reference/rest/v2/models/get| Models: get API Documentation}
*
* @method Model#getMetadata
* @param {GetModelMetadataCallback} [callback] The callback function.
* @param {?error} callback.err An error returned while making this
* request.
* @param {object} callback.metadata The metadata of the model.
* @param {object} callback.apiResponse The full API response.
* @returns {Promise<GetModelMetadataResponse>}
*
* @example
* ```
* const {BigQuery} = require('@google-cloud/bigquery');
* const bigquery = new BigQuery();
* const dataset = bigquery.dataset('my-dataset');
* const model = dataset.model('my-model');
*
* model.getMetadata((err, metadata, apiResponse) => {});
*
* ```
* @example If the callback is omitted we'll return a Promise.
* ```
* const [metadata, apiResponse] = await model.getMetadata();
* ```
*/
getMetadata: true,
/**
* @callback SetModelMetadataCallback
* @param {?Error} err Request error, if any.
* @param {object} metadata The model metadata.
* @param {object} apiResponse The full API response.
*/
/**
* @typedef {array} SetModelMetadataResponse
* @property {object} 0 The model metadata.
* @property {object} 1 The full API response.
*/
/**
* See {@link https://cloud.google.com/bigquery/docs/reference/rest/v2/models/patch| Models: patch API Documentation}
*
* @method Model#setMetadata
* @param {object} metadata The metadata key/value object to set.
* @param {SetModelMetadataCallback} [callback] The callback function.
* @param {?error} callback.err An error returned while making this
* request.
* @param {object} callback.metadata The updated metadata of the model.
* @param {object} callback.apiResponse The full API response.
* @returns {Promise<SetModelMetadataResponse>}
*
* @example
* ```
* const {BigQuery} = require('@google-cloud/bigquery');
* const bigquery = new BigQuery();
* const dataset = bigquery.dataset('my-dataset');
* const model = dataset.model('my-model');
*
* const metadata = {
* friendlyName: 'TheBestModelEver'
* };
*
* model.setMetadata(metadata, (err, metadata, apiResponse) => {});
*
* ```
* @example If the callback is omitted we'll return a Promise.
* ```
* const [metadata, apiResponse] = await model.setMetadata(metadata);
* ```
*/
setMetadata: true,
};
super({
parent: dataset,
baseUrl: '/models',
id,
methods,
});
this.dataset = dataset;
this.bigQuery = dataset.bigQuery;
}
createExtractJob(destination, optionsOrCallback, cb) {
let options = typeof optionsOrCallback === 'object' ? optionsOrCallback : {};
const callback = typeof optionsOrCallback === 'function' ? optionsOrCallback : cb;
options = extend(true, options, {
destinationUris: arrify(destination).map(dest => {
if (common_1.util.isCustomType(dest, 'storage/file')) {
return ('gs://' + dest.bucket.name + '/' + dest.name);
}
if (typeof dest === 'string') {
return dest;
}
throw new Error('Destination must be a string or a File object.');
}),
});
if (options.format) {
options.format = options.format.toUpperCase();
if (FORMATS.includes(options.format)) {
options.destinationFormat = options.format;
delete options.format;
}
else {
throw new Error('Destination format not recognized: ' + options.format);
}
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const body = {
configuration: {
extract: extend(true, options, {
sourceModel: {
datasetId: this.dataset.id,
projectId: this.bigQuery.projectId,
modelId: this.id,
},
}),
},
};
if (options.jobPrefix) {
body.jobPrefix = options.jobPrefix;
delete options.jobPrefix;
}
if (options.jobId) {
body.jobId = options.jobId;
delete options.jobId;
}
this.bigQuery.createJob(body, callback);
}
extract(destination, optionsOrCallback, cb) {
const options = typeof optionsOrCallback === 'object' ? optionsOrCallback : {};
const callback = typeof optionsOrCallback === 'function' ? optionsOrCallback : cb;
this.createExtractJob(destination, options, (err, job, resp) => {
if (err) {
callback(err, resp);
return;
}
job.on('error', callback).on('complete', metadata => {
callback(null, metadata);
});
});
}
} |
JavaScript | class Rush extends Component {
renderParagraph() {
return this.props.rush.map((paragraph) => {
return (
<p key={paragraph.text.substring(0,5)} className="row">{paragraph.text}</p>
);
});
}
render() {
return(
<div className="container">
<h2>About Rush</h2>
<p className="text-center text-muted">FALL 2018 - ALPHA THETA RUSH!</p>
<div className="container">
<img className="img-fluid px-2 w-50" src="../../resources/rush_front.jpg" />
<img className="img-fluid px-2 w-50" src="../../resources/rush_back.jpg" />
</div>
<div className="container">
{this.renderParagraph()}
</div>
</div>
);
}
} |
JavaScript | class App extends Component {
/**
* renders the App on site
* @return {[HTMLDivElement]} HTML to be displayed
*/
render() {
return (
<Router>
<div className="App">
<Header/>
</div>
<Switch>
<Route exact path='/' component={Home}/>
<Route exact path='/login' component={Login}/>
<Route path='/myplans' component={MyPlans}/>
<Route path='/planner' component={Planner}/>
</Switch>
</Router>
);
}
} |
JavaScript | class TrackPropertyCondition {
/**
* Create a TrackPropertyCondition.
* @member {string} property Track property type. Possible values include:
* 'Unknown', 'FourCC'
* @member {string} operation Track property condition operation. Possible
* values include: 'Unknown', 'Equal'
* @member {string} [value] Track proprty value
*/
constructor() {
}
/**
* Defines the metadata of TrackPropertyCondition
*
* @returns {object} metadata of TrackPropertyCondition
*
*/
mapper() {
return {
required: false,
serializedName: 'TrackPropertyCondition',
type: {
name: 'Composite',
className: 'TrackPropertyCondition',
modelProperties: {
property: {
required: true,
serializedName: 'property',
type: {
name: 'String'
}
},
operation: {
required: true,
serializedName: 'operation',
type: {
name: 'String'
}
},
value: {
required: false,
serializedName: 'value',
type: {
name: 'String'
}
}
}
}
};
}
} |
JavaScript | class DepthCalculator {
calculateDepth(arr, level = 1) {
let currentLevel;
let maxLevel = level;
for(let i = 0; i < arr.length; i++){
if(arr[i] instanceof Array){
currentLevel = this.calculateDepth(arr[i], level+1);
maxLevel = (maxLevel < currentLevel) ? currentLevel : maxLevel;
}
}
return maxLevel;
}
} |
JavaScript | class TgaTexture extends texture_1.default {
constructor(bufferOrImage, resourceData) {
super(resourceData);
let image;
if (bufferOrImage instanceof image_1.default) {
image = bufferOrImage;
}
else {
image = new image_1.default();
image.load(bufferOrImage);
}
let width = image.width;
let height = image.height;
let gl = this.viewer.gl;
let id = gl.createTexture();
gl.bindTexture(gl.TEXTURE_2D, id);
gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, image.data);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
if (math_1.isPowerOfTwo(width) && math_1.isPowerOfTwo(height)) {
gl.generateMipmap(gl.TEXTURE_2D);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR_MIPMAP_LINEAR);
}
else {
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
}
this.webglResource = id;
this.width = width;
this.height = height;
}
} |
JavaScript | class App extends Component {
constructor (props) {
super(props);
let downloader = new Downloader(new Parser({}));
let uri = 'https://raw.githubusercontent.com/patill/lukudiplomi-pori-datasources/master/lukudiplomi-config.txt';
this.config = new ConfigDatasource(uri, downloader);
}
componentDidMount () {
SplashScreen.hide();
// First, check if there's current grade set; if not, navigate to the grade
// selection screen to set the grade.
let grade = this.config.getCurrentGrade();
grade.then((value) => {
if (!value) {
this.navigator && this.navigator.dispatch(
NavigationActions.navigate({ routeName: 'GradeSelect' })
);
return null;
}
}).catch((error) => {});
}
render () {
return (
<Navigation
ref={(ref) => { this.navigator = ref; }}
style={Styles.tabNavigator}
/>
);
}
} |
JavaScript | class PriorityQueue {
/**
* Creates a PRIORITY-QUEUE data-structure
* @example
* const { PriorityQueue } = require('data-structures-algorithms-js');
* const pq = new PriorityQueue();
*/
constructor() {
this._priorityQueue = [];
}
/**
* Adds a element at the Priority-Queue
* @param {*} element Element passed to insert
* @param {Integer} priority Priority can be any integer number
* @example
* const { PriorityQueue } = require('data-structures-algorithms-js');
* const pq = new PriorityQueue();
*
* pq.push(10, 2); //inserts element 10 with priority 2
*/
push(element, priority = 0) {
element = [element, priority]
if (this.size() === 0) {
this._priorityQueue.push(element);
} else {
let flag = false;
for (let i = 0; i < this.size(); i++) {
if (element[1] > this._priorityQueue[i][1]) {
this._priorityQueue.splice(i, 0, element);
flag = true;
break;
}
}
if (!flag) this._priorityQueue.push(element);
}
}
/**
* removes the first element at the Priority Queue
* @example
* const { PriorityQueue } = require('data-structures-algorithms-js');
* const pq = new PriorityQueue();
*
* pq.push(3, 8);
* pq.push(9, 10);
*
* pq.pop(); //removes number 9 from the Priority Queue
*/
pop() {
if (this.size() === 0) return undefined;
return this._priorityQueue.shift()[0];
}
/**
* Returns the element at the back of Priority Queue
* @returns {*} The element at the back
* @example
* const { PriorityQueue } = require('data-structures-algorithms-js');
* const pq = new PriorityQueue();
*
* pq.push(6);
* pq.push(3, -2);
*
* pq.back(); //returns 3;
*/
back() {
if (this.size() === 0) return undefined;
return this._priorityQueue[this.size() - 1][0];
}
/**
* Returns the element at the front of the Priority Queue
* @returns {*} The element at the front
* @example
* const { PriorityQueue } = require('data-structures-algorithms-js');
* const pq = new PriorityQueue();
*
* pq.push(6);
* pq.push(3);
*
* pq.front(); //returns 6;
*/
front() {
if (this.size() === 0) return undefined;
return this._priorityQueue[0][0];
}
/**
* Returns the size of the Priority Queue
* @returns {Number} The number of elements in the Priority Queue
* @example
* const { PriorityQueue } = require('data-structures-algorithms-js');
* const pq = new PriorityQueue();
*
* pq.size(); // returns 0;
*
* pq.push(8, 10);
*
* pq.size(); //returns 1;
*/
size() {
return this._priorityQueue.length;
}
/**
* Returns if the Priority Queue is empty
* @returns {Boolean}
* @example
* const { PriorityQueue } = require('data-structures-algorithms-js');
* const pq = new PriorityQueue();
*
* pq.isEmpty(); // returns true;
*
* pq.push(23, 9);
*
* pq.isEmpty(); //returns false;
*/
isEmpty() {
return this.size() === 0;
}
/**
* Resets the the Priority Queue
* @example
* const { PriorityQueue } = require('data-structures-algorithms-js');
* const pq = new PriorityQueue();
*
* pq.push(15);
*
* pq.clear(); // now Priority Queue is empty
*/
clear() {
this._priorityQueue = [];
}
} |
JavaScript | class LipsumFilter extends Filter
{
/**
* @inheritDoc
*/
constructor()
{
super();
this._name = 'lipsum';
}
/**
* @inheritDoc
*/
static get className()
{
return 'nunjucks.filter/LipsumFilter';
}
/**
* @inheritDoc
*/
filter(value)
{
const scope = this;
return function (value, unit, minCount, maxCount)
{
// Prepare
const options =
{
units: 'words',
count: 1
};
// Unit
if (unit == 's')
{
options.units = 'sentences';
}
if (unit == 'p')
{
options.units = 'paragraphs';
}
// Count
const min = minCount || 1;
const max = maxCount || 10;
options.count = min + ((max - min) * Math.random());
// Generate
return scope.applyCallbacks(uppercaseFirst(lorem(options)), arguments, options);
};
}
} |
JavaScript | class PriorityQueue extends MinHeap {
constructor() {
super();
this.priorities = {};
this.compare = new Comparator(this.comparePriority.bind(this));
}
/**
* @param {*} item
* @param {number} [priority]
* @return {PriorityQueue}
*/
add(item, priority = 0) {
this.priorities[item] = priority;
super.add(item);
return this;
}
/**
* @param {*} item
* @param {Comparator} [customFindingComparator]
* @return {PriorityQueue}
*/
remove(item, customFindingComparator) {
super.remove(item, customFindingComparator);
delete this.priorities[item];
return this;
}
/**
* @param {*} item
* @param {number} priority
* @return {PriorityQueue}
*/
changePriority(item, priority) {
this.remove(item, new Comparator(this.compareValue));
this.add(item, priority);
return this;
}
/**
* @param {*} item
* @return {Number[]}
*/
findByValue(item) {
return this.find(item, new Comparator(this.compareValue));
}
/**
* @param {*} item
* @return {boolean}
*/
hasValue(item) {
return this.findByValue(item).length > 0;
}
/**
* @param {*} a
* @param {*} b
* @return {number}
*/
comparePriority(a, b) {
if (this.priorities[a] === this.priorities[b]) {
return 0;
}
return this.priorities[a] < this.priorities[b] ? -1 : 1;
}
/**
* @param {*} a
* @param {*} b
* @return {number}
*/
compareValue(a, b) {
if (a === b) {
return 0;
}
return a < b ? -1 : 1;
}
} |
JavaScript | class Video extends ModelBase {
/**
* Constructor for video model.
*
* @augments ModelBase
*
* @constructor
*/
constructor() {
super({ dbName: dbName });
const oThis = this;
oThis.tableName = 'videos';
}
/**
* Format Db data.
*
* @param {object} dbRow
* @param {number} dbRow.id
* @param {string} dbRow.url_template
* @param {string} dbRow.resolutions
* @param {number} dbRow.poster_image_id
* @param {number} dbRow.status
* @param {number} dbRow.kind
* @param {number} dbRow.compression_status
* @param {string} dbRow.extra_data
* @param {string} dbRow.created_at
* @param {string} dbRow.updated_at
*
* @return {object}
* @private
*/
_formatDbData(dbRow) {
const oThis = this;
const formattedData = {
id: dbRow.id,
urlTemplate: dbRow.url_template,
resolutions: JSON.parse(dbRow.resolutions),
extraData: JSON.parse(dbRow.extra_data),
posterImageId: dbRow.poster_image_id,
status: videoConstants.statuses[dbRow.status],
kind: videoConstants.kinds[dbRow.kind],
compressionStatus: videoConstants.compressionStatuses[dbRow.compression_status],
createdAt: dbRow.created_at,
updatedAt: dbRow.updated_at
};
return oThis.sanitizeFormattedData(formattedData);
}
/**
* Format resolutions hash.
*
* @param {object} resolution
*
* @returns {object}
* @private
*/
_formatResolution(resolution) {
const oThis = this;
const formattedData = {
url: resolution.u,
size: resolution.s,
height: resolution.h,
width: resolution.w
};
return oThis.sanitizeFormattedData(formattedData);
}
/**
* Formats the complete resolution hash.
*
* @param {object} resolutions
* @param {string} urlTemplate
*
* @returns {object}
* @private
*/
_formatResolutions(resolutions, urlTemplate) {
const oThis = this;
const responseResolutionHash = {};
for (const resolution in resolutions) {
const longResolutionKey = videoConstants.invertedResolutionKeyToShortMap[resolution];
responseResolutionHash[longResolutionKey] = oThis._formatResolution(resolutions[resolution]);
const url = responseResolutionHash[longResolutionKey].url
? responseResolutionHash[longResolutionKey].url
: urlTemplate;
responseResolutionHash[longResolutionKey].url = shortToLongUrl.getFullUrl(url, longResolutionKey);
}
return responseResolutionHash;
}
/**
* Fetch video by id.
*
* @param {integer} id
*
* @returns {object}
*/
async fetchById(id) {
const oThis = this;
const dbRows = await oThis.fetchByIds([id]);
return dbRows[id] || {};
}
/**
* Fetch videos for given ids.
*
* @param {array} ids
*
* @returns {object}
*/
async fetchByIds(ids) {
const oThis = this;
const response = {};
const dbRows = await oThis
.select('*')
.where(['id IN (?)', ids])
.fire();
for (let index = 0; index < dbRows.length; index++) {
const formatDbRow = oThis._formatDbData(dbRows[index]);
formatDbRow.resolutions = oThis._formatResolutions(formatDbRow.resolutions, formatDbRow.urlTemplate);
response[formatDbRow.id] = formatDbRow;
}
return response;
}
/**
* Insert into videos.
*
* @param {object} params
* @param {object} params.resolutions
* @param {number} params.posterImageId
* @param {string} params.status
* @param {string} params.kind
* @param {string} params.compressionStatus
* @param {string} params.extraData
*
* @return {Promise<object>}
*/
async insertVideo(params) {
const oThis = this;
const resolutions = oThis._formatResolutionsToInsert(params.resolutions);
return oThis
.insert({
resolutions: JSON.stringify(resolutions),
poster_image_id: params.posterImageId,
status: videoConstants.invertedStatuses[params.status],
kind: videoConstants.invertedKinds[params.kind],
compression_status: videoConstants.invertedCompressionStatuses[params.compressionStatus],
extra_data: params.extraData
})
.fire();
}
/**
* Update videos table.
*
* @param {object} params
* @param {number/string} params.id
* @param {string} params.urlTemplate
* @param {object} params.resolutions
* @param {object} params.extraData
* @param {string} [params.status]
* @param {string} [params.compressionStatus]
*
* @return {Promise<object>}
*/
async updateVideo(params) {
const oThis = this;
const resolutions = oThis._formatResolutionsToUpdate(params.resolutions);
const updateParams = {
url_template: params.urlTemplate,
resolutions: JSON.stringify(resolutions)
};
if (params.status) {
updateParams.status = videoConstants.invertedStatuses[params.status];
}
if (params.compressionStatus) {
updateParams.compression_status = videoConstants.invertedCompressionStatuses[params.compressionStatus];
}
if (params.extraData) {
updateParams.extra_data = JSON.stringify(params.extraData);
}
return oThis
.update(updateParams)
.where({ id: params.id })
.fire();
}
/**
* Mark videos deleted.
*
* @param {object} params
* @param {array<number/string>} params.ids
*
* @return {Promise<object>}
*/
async markVideosDeleted(params) {
const oThis = this;
await oThis
.update({
status: videoConstants.invertedStatuses[videoConstants.deletedStatus]
})
.where({
id: params.ids
})
.fire();
await Video.flushCache({ ids: params.ids });
}
/**
* Format resolutions to insert.
*
* @param {object} resolutions
*
* @returns {object}
* @private
*/
_formatResolutionsToInsert(resolutions) {
const oThis = this;
const responseResolutionHash = {};
for (const resolution in resolutions) {
const shortResolutionKey = videoConstants.resolutionKeyToShortMap[resolution];
responseResolutionHash[shortResolutionKey] = oThis._formatResolutionToInsert(resolutions[resolution]);
// While inserting original url has to be present in original resolutions hash only.
if (resolution === videoConstants.originalResolution) {
responseResolutionHash[shortResolutionKey] = responseResolutionHash[shortResolutionKey] || {};
responseResolutionHash[shortResolutionKey].u = resolutions[resolution].url;
}
}
return responseResolutionHash;
}
/**
* Format resolutions to update.
*
* @param {object} resolutions
* @private
*/
_formatResolutionsToUpdate(resolutions) {
const oThis = this;
const responseResolutionHash = {};
for (const resolution in resolutions) {
const shortResolutionKey = videoConstants.resolutionKeyToShortMap[resolution];
responseResolutionHash[shortResolutionKey] = oThis._formatResolutionToInsert(resolutions[resolution]);
}
return responseResolutionHash;
}
/**
* Format resolution to insert.
*
* @param {object} resolution
*
* @returns {object}
* @private
*/
_formatResolutionToInsert(resolution) {
const oThis = this;
const formattedData = {
s: resolution.size,
h: resolution.height,
w: resolution.width
};
return oThis.sanitizeFormattedData(formattedData);
}
/**
* Flush cache.
*
* @param {object} params
* @param {number} [params.id]
* @param {array<number>} [params.ids]
*
* @returns {Promise<*>}
*/
static async flushCache(params) {
const promisesArray = [];
const VideoByIds = require(rootPrefix + '/lib/cacheManagement/multi/VideoByIds');
if (params.id) {
promisesArray.push(new VideoByIds({ ids: [params.id] }).clear());
}
if (params.ids) {
promisesArray.push(new VideoByIds({ ids: params.ids }).clear());
}
await Promise.all(promisesArray);
}
} |
JavaScript | class Simple extends Display {
constructor() {
super();
/**
* @type undefined|jQuery
* @private
*/
this.imgNode = undefined;
/**
* @type undefined|meteoJS/thermodynamicDiagram.ThermodynamicDiagram
* @private
*/
this.thermodynamicDiagram = undefined;
/**
* @type undefined|jQuery
* @protected
*/
this.resourceNode = undefined;
}
/**
* @override
*/
onInit() {
if (this.parentNode !== undefined) {
this.resourceNode = $(this.parentNode);
this.resourceNode.empty();
}
}
/**
* @override
*/
onChangeVisibleResource() {
if (this.resourceNode === undefined)
return;
let visibleResource = this.container.visibleResource;
if ('url' in visibleResource) {
if (this.thermodynamicDiagram !== undefined) {
this.thermodynamicDiagram = undefined;
this.resourceNode.empty();
}
if (this.imgNode === undefined) {
this.resourceNode.empty();
this.imgNode = $('<img>');
this.resourceNode.append(this.imgNode);
}
this.imgNode.attr('src', visibleResource.url);
this.imgNode.css({ 'max-width': '100%' });
}
else if ('sounding' in visibleResource) {
if (this.imgNode !== undefined) {
this.imgNode = undefined;
this.resourceNode.empty();
}
if (this.thermodynamicDiagram === undefined)
this.thermodynamicDiagram = new ThermodynamicDiagram({
renderTo: this.resourceNode
});
let isAppended = false;
this.thermodynamicDiagram.soundings.forEach(sounding => {
if (sounding.getSounding() === visibleResource.sounding) {
isAppended = true;
sounding.visible(true);
}
else
sounding.visible(false);
});
if (!isAppended)
this.thermodynamicDiagram.addSounding(visibleResource.sounding);
}
else {
this.imgNode = undefined;
this.resourceNode.empty();
}
}
} |
JavaScript | class ProtectedLambdaStack extends cdk.Stack {
/**
* @param {cdk.App} scope
* @param {string} id
* @param {cdk.StackProps} props
*/
constructor(scope, id, props) {
super(scope, id, props);
// First, create a test lambda
const myLambda = new lambda.Function(this, 'hello', {
runtime: lambda.Runtime.NODEJS_12_X,
code: lambda.Code.fromAsset('lambda'),
handler: 'hello.handler',
});
// IMPORTANT: Lambda grant invoke to APIGateway
myLambda.grantInvoke(new ServicePrincipal('apigateway.amazonaws.com'));
// Then, create the API construct, integrate with lambda
const api = new apigw.RestApi(this, 'hello-api', { deploy: false });
const integration = new apigw.LambdaIntegration(myLambda);
// api.root.addMethod('GET', integration);
const proxy = api.root.addProxy({anyMethod: false});
proxy.addMethod('GET', integration);
// Then create an explicit Deployment construct
const deployment = new apigw.Deployment(this, 'my_deployment', { api });
// And different stages
const prodStage = new apigw.Stage(this, `prod_stage`, {
deployment,
stageName: 'prod',
throttlingBurstLimit: 2,
throttlingRateLimit: 4,
methodOptions: {
'//GET': {
throttlingBurstLimit: 1,
throttlingRateLimit: 1,
},
'/some-path/GET': {
throttlingBurstLimit: 1,
throttlingRateLimit: 1,
},
},
});
api.deploymentStage = prodStage;
new cdk.CfnOutput(this, 'ApiURL', {
value: api.url,
});
}
} |
JavaScript | class Inputs extends Component {
state = {
effectiveDate: 0,
maritalStatus: 0,
spAidandAttendance: 0,
depParents: 0,
depChildren18: 0,
depChildrenSchool: 0,
compEval: 0,
monthlyRate: 0
};
componentDidMount() {
this.setState({
effectiveDate: "20181201",
maritalStatus: "single",
spAidandAttendance: "no",
depParents: "0",
depChildren18: "0",
depChildrenSchool: "0",
compEval: 0,
monthlyRate: "0.00"
});
};
handleChange = event => {
this.setState(
{ [event.target.name]: event.target.value },
() => {
this.updateRate()
}
);
};
// this function handles the marital toggle
handleMaritalButton = () => {
let currentMx = this.state.maritalStatus;
if (currentMx === "single") {
this.setState(
{ maritalStatus: "married" },
() => {
this.updateRate()
}
)
} else if (currentMx === "married") {
this.setState(
{ maritalStatus: "single" },
() => {
this.updateRate()
}
)
} else console.log("something went wrong");
}
updateRate = () => {
this.setState(
{
monthlyRate: rate.lookUp(this.state.effectiveDate, this.state.compEval, this.state.maritalStatus, this.state.depParents, this.state.depChildren18, this.state.depChildrenSchool,
this.state.spAidandAttendance)
}
)
}
// this function handles the spouse aid and attendance toggle
handleSpAAButton = () => {
let currentAA = this.state.spAidandAttendance;
if (currentAA === "no") {
this.setState(
{ spAidandAttendance: "yes" },
() => {
this.updateRate()
}
)
} else if (currentAA === "yes") {
this.setState(
{ spAidandAttendance: "no" },
() => {
this.updateRate()
}
)
} else console.log("something went wrong");
}
render() {
return (
<div className="wrapper">
<div className="row">
<div className="col-md-6 offset-md-3 input-box">
<div className="container">
{/* Effective Date Selector */}
<div className="row inputs-section">
<div className="col-md-12 text-center">
<p>Effective Date</p>
<div className="form-group">
<select className="form-control" id="effective-date"
name="effectiveDate"
onChange={this.handleChange}
>
<option value="20181201">12/01/2018</option>
<option value="20171201">12/01/2017</option>
<option value="20161201">12/01/2016</option>
<option value="20141201">12/01/2015</option>
<option value="20141201">12/01/2014</option>
</select>
</div>
</div>
</div>
{/* Two toggle switches */}
<div className="row inputs-section">
<div className="col-md-6 text-center">
<Marital maritalStatus = {this.state.maritalStatus} />
<p className="spacer"> </p>
<div className="custom-control custom-switch">
<input type="checkbox" className="custom-control-input" id="maritalStatus"
name="maritalStatus"
onChange={this.handleMaritalButton}
/>
<label className="custom-control-label" for="maritalStatus"></label>
</div>
</div>
<div className="col-md-6 text-center">
<p>Spouse Aid and Attendance</p>
<AidAttend aidAttend = {this.state.spAidandAttendance}/>
<div className="custom-control custom-switch">
<input type="checkbox" className="custom-control-input" id="spAA"
name="spAidandAttendance"
onChange={this.handleSpAAButton}
/>
<label className="custom-control-label" for="spAA"></label>
</div>
</div>
</div>
{/* Radio buttons for dependent parents */}
<div className="row inputs-section">
<div className="col-md-12 text-center">
<p>Dependent Parents</p>
<div className="form-check form-check-inline">
<input className="form-check-input" type="radio" name="depParents" id="inlineRadio1" value="0" onChange={this.handleChange} defaultChecked="true"/>
<label className="form-check-label" htmlFor="inlineRadio1">None</label>
</div>
<div className="form-check form-check-inline">
<input className="form-check-input" type="radio" name="depParents" id="inlineRadio2" value="1" onChange={this.handleChange} />
<label className="form-check-label" htmlFor="inlineRadio2">One</label>
</div>
<div className="form-check form-check-inline">
<input className="form-check-input" type="radio" name="depParents" id="inlineRadio3" value="2" onChange={this.handleChange} />
<label className="form-check-label" htmlFor="inlineRadio3">Two</label>
</div>
</div>
</div>
{/* Scroll selectors for children */}
<div className="row inputs-section">
<div className="col-md-6 text-center">
<p>Minor Children</p>
<form>
<div className="col-auto my-1">
<label className="mr-sm-2 sr-only" htmlFor="depChildren18">Dependent Children Under 18</label>
<select className="custom-select mr-sm-2" id="depChildren18"
name="depChildren18"
onChange={this.handleChange}
>
<option selected value="0">0</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
</select>
</div>
</form>
</div>
<div className="col-md-6 text-center">
<p>School Children</p>
<form>
<div className="col-auto my-1">
<label className="mr-sm-2 sr-only" for="depChildrenSchool">Dependent Children Under 18</label>
<select className="custom-select mr-sm-2" id="depChildrenSchool"
name="depChildrenSchool"
onChange={this.handleChange}
>
<option selected value="0">0</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
</select>
</div>
</form>
</div>
</div>
{/* Slider for combined evaluation for compensation percentage */}
<div className="row inputs-section">
<div className="col-md-12">
<label for="compRating">Combined Evaluation for Compensation: <b>{this.state.compEval}%</b></label>
<input type="range" className="custom-range" min="0" max="100" step="10" defaultValue="0" id="compRating"
name="compEval"
onChange={this.handleChange}></input>
</div>
</div>
</div>
</div>
</div>
<Results
result={this.state.monthlyRate}>
</Results>
<Footer
text = "Disclaimer: The VA Disability Compensation Estimator is not affiliated with the U.S. Department of Veterans Affairs, and is intended for educational purposes only. Any estimate displayed is unofficial and should not be construed as a promise of monetary benefits.">
</Footer>
</div>
)
}
} |
JavaScript | class Sequence extends React.Component {
render() {
const {
sequence,
hideBps,
charWidth,
containerStyle = {},
children,
isReverse,
height,
className,
startOffset = 0,
chunkSize = 100,
scrollData,
showDnaColors,
// getGaps,
alignmentData
} = this.props;
// the fudge factor is used to position the sequence in the middle of the <text> element
const fudge = charWidth - realCharWidth;
const gapsBeforeSequence = 0;
const seqReadWidth = 0;
const seqLen = sequence.length;
if (alignmentData) {
// gapsBeforeSequence = getGaps(0).gapsBefore;
// sequence = sequence.replace(/-/g, " ")
// seqReadWidth = charWidth * sequence.length;
}
const style = {
position: "relative",
height,
left: gapsBeforeSequence * charWidth,
...containerStyle
};
const width = seqLen * charWidth;
let coloredRects = null;
if (showDnaColors) {
coloredRects = <ColoredSequence {...{ ...this.props, width }} />;
}
const numChunks = Math.ceil(seqLen / chunkSize);
const chunkWidth = chunkSize * charWidth;
if (scrollData) {
//we're in the alignment view alignments only
const { visibleStart, visibleEnd } = getVisibleStartEnd({
scrollData,
width
});
return (
<div
style={style}
className={(className ? className : "") + " ve-row-item-sequence"}
>
{!hideBps && (
<svg
style={{
left: startOffset * charWidth,
height,
position: "absolute"
}}
ref="rowViewTextContainer"
className="rowViewTextContainer"
height={Math.max(0, Number(height))}
>
{times(numChunks, (i) => {
const seqChunk = getChunk(sequence, chunkSize, i);
const textLength = charWidth * seqChunk.length;
const x = i * chunkWidth;
if (x > visibleEnd || x + textLength < visibleStart)
return null;
return (
<text
key={i}
className={
"ve-monospace-font " +
(isReverse ? " ve-sequence-reverse" : "")
}
{...{
textLength: textLength - fudge - fudge2,
x: x + fudge / 2,
y: height - height / 4,
lengthAdjust: "spacing"
}}
>
{seqChunk}
</text>
);
})}
</svg>
)}
{coloredRects}
{children}
</div>
);
} else {
return (
<div
style={style}
className={(className ? className : "") + " ve-row-item-sequence"}
>
{!hideBps && (
<svg
style={{
left: startOffset * charWidth,
height,
position: "absolute"
}}
ref="rowViewTextContainer"
className="rowViewTextContainer"
height={Math.max(0, Number(height))}
>
<text
className={
"ve-monospace-font " +
(isReverse ? " ve-sequence-reverse" : "")
}
{...{
x: 0 + fudge / 2,
y: height - height / 4,
textLength:
(alignmentData ? seqReadWidth : width) - fudge - fudge2
}}
>
{sequence}
</text>
</svg>
)}
{coloredRects}
{children}
</div>
);
}
}
} |
JavaScript | class App extends Component {
render() {
return (
<Router>
<Switch>
<Route path = "/home" component = {Home}></Route>
<Redirect exact from="/" to="/home"/>
<Redirect to={{pathname: "/"}}/>
</Switch>
</Router>
);
}
} |
JavaScript | class AzureFirewallNatRule {
/**
* Create a AzureFirewallNatRule.
* @property {string} [name] Name of the NAT rule.
* @property {string} [description] Description of the rule.
* @property {array} [sourceAddresses] List of source IP addresses for this
* rule.
* @property {array} [destinationAddresses] List of destination IP addresses
* for this rule.
* @property {array} [destinationPorts] List of destination ports.
* @property {array} [protocols] Array of AzureFirewallNetworkRuleProtocols
* applicable to this NAT rule.
* @property {string} [translatedAddress] The translated address for this NAT
* rule.
* @property {string} [translatedPort] The translated port for this NAT rule.
*/
constructor() {
}
/**
* Defines the metadata of AzureFirewallNatRule
*
* @returns {object} metadata of AzureFirewallNatRule
*
*/
mapper() {
return {
required: false,
serializedName: 'AzureFirewallNatRule',
type: {
name: 'Composite',
className: 'AzureFirewallNatRule',
modelProperties: {
name: {
required: false,
serializedName: 'name',
type: {
name: 'String'
}
},
description: {
required: false,
serializedName: 'description',
type: {
name: 'String'
}
},
sourceAddresses: {
required: false,
serializedName: 'sourceAddresses',
type: {
name: 'Sequence',
element: {
required: false,
serializedName: 'StringElementType',
type: {
name: 'String'
}
}
}
},
destinationAddresses: {
required: false,
serializedName: 'destinationAddresses',
type: {
name: 'Sequence',
element: {
required: false,
serializedName: 'StringElementType',
type: {
name: 'String'
}
}
}
},
destinationPorts: {
required: false,
serializedName: 'destinationPorts',
type: {
name: 'Sequence',
element: {
required: false,
serializedName: 'StringElementType',
type: {
name: 'String'
}
}
}
},
protocols: {
required: false,
serializedName: 'protocols',
type: {
name: 'Sequence',
element: {
required: false,
serializedName: 'AzureFirewallNetworkRuleProtocolElementType',
type: {
name: 'String'
}
}
}
},
translatedAddress: {
required: false,
serializedName: 'translatedAddress',
type: {
name: 'String'
}
},
translatedPort: {
required: false,
serializedName: 'translatedPort',
type: {
name: 'String'
}
}
}
}
};
}
} |
JavaScript | class NoImageInPdfError extends Error {
/**
* @param {string=} message
* @public
*/
constructor(message = 'Failed to find image in pdf') {
super(message);
this.name = this.constructor.name;
}
} |
JavaScript | class InvalidBlobTypeError extends Error {
/**
* @param {string} type
* @public
*/
constructor(type) {
super(`Invalid thumbnailer blob input type: ${type}`);
this.name = this.constructor.name;
}
} |
JavaScript | class SlotImage extends ActiveImage {
constructor(config) {
super(config);
this.i = config.i;
// If the pointer is over the slot and the button is clicked. A pointer event qualifies as a click if the pointerdown and pointerup event happened over the same slot even if it wasn't over it the whole time.
this.on('click', function () {
// If the player already picked up an item to place to somewhere else.
if (this.scene.heldItem) {
// Get the attributes of the picked up item.
let item = this.scene.heldItem.data;
// If the item cannot be equipped on this slot.
if (!this.equips(item)) {
// Don't let the player place the item on this slot.
return;
}
// If the picked up item is two-handed, this slot is either of the hands and there is already a one-handed item in the other hand.
if (item.equips === 'hands'
&& ((this.frame.name === 'rightHand'
&& this.targetActor.equipped.leftHand !== undefined)
|| (this.frame.name === 'leftHand'
&& this.targetActor.equipped.rightHand !== undefined))) {
// Don't let the player place the item on this slot.
return;
}
// If the picked up item is one-handed, this slot is either of the hands and there is already a two-handed item on the other hand.
if (item.equips === 'hand'
&& ((this.frame.name === 'rightHand'
&& this.targetActor.equipped.leftHand !== undefined
&& this.targetActor.equipped.leftHand.equips === 'hands')
|| (this.frame.name === 'leftHand'
&& this.targetActor.equipped.rightHand !== undefined
&& this.targetActor.equipped.rightHand.equips === 'hands'))) {
// Don't let the player place the item on this slot.
return;
}
// If there is already an item on this slot.
if (this.itemImage) {
// Swap the held item images.
this.scene.heldItem.setFrame(this.getItem().frame);
// Swap the item config data.
this.scene.heldItem.data = this.getItem();
// If the slot is empty.
} else {
// Remove the config data about the held item.
this.scene.heldItem.data = null;
// Remove the image of the held item.
this.scene.heldItem.destroy();
// Remove the reference of the held item.
this.scene.heldItem = undefined;
}
// Place the item on this slot.
this.targetActor.setItem(item, this.targetActor[this.targetAttribute], this.i);
// If there is an item on this slot.
} else if (this.itemImage) {
// Create the copy as the item to serve as an indicator of it being picked up.
this.scene.heldItem = this.scene.add.image(
this.x,
this.y,
'tiles',
this.getItem().frame
);
// Add the item config data to the image.
this.scene.heldItem.data = this.getItem();
// Remove the original item from the slot.
this.targetActor.setItem(undefined, this.targetActor[this.targetAttribute], this.i);
}
});
this.scene.add.existing(this);
this.targetScene.events.on('GUIUpdate', function () {
this.targetActor = this.targetScene[this.config.targetActor];
this.draw();
}.bind(this));
this.draw();
}
showTooltip() {
let item = this.getItem();
let notes = '';
if (item) {
this.highlightEquipmentSlot(item);
this.tooltip = item.name;
for (let attribute in item) {
if (item.hasOwnProperty(attribute) &&
attribute !== 'name' &&
attribute !== 'frame' &&
attribute !== 'effect') {
if (attribute === 'damageRanged') {
this.tooltip += '\n ranged damage: +' + item[attribute];
} else if (attribute === 'manaCost') {
this.tooltip += '\n mana cost: ' + item[attribute];
} else if (attribute === 'damageMod') {
this.tooltip += '\n damage: ' +
(item[attribute] > 0 ? '+' : '') + item[attribute];
} else if (attribute === 'health') {
this.tooltip += '\n health: ' +
(item[attribute] > 0 ? '+' : '') + item[attribute];
} else if (attribute === 'walksOn') {
this.tooltip += '\n walk on: ' + item[attribute];
} else if (attribute === 'healthRegen') {
this.tooltip += '\n health regeneration: ' + item[attribute];
} else if (attribute === 'manaRegen') {
this.tooltip += '\n mana regeneration: ' + item[attribute];
} else if (attribute === 'healthMax') {
this.tooltip += '\n maximum health: +' + item[attribute];
} else if (attribute === 'manaMax') {
this.tooltip += '\n maximum mana: +' + item[attribute];
} else if (attribute === 'speedBase') {
this.tooltip += '\n speed: +' + item[attribute];
} else if (attribute === 'speedFix') {
this.tooltip += '\n fix speed: ' + item[attribute];
} else if (attribute === 'speedMod') {
this.tooltip += '\n speed: ' +
(item[attribute] > 0 ? '+' : '') + item[attribute];
} else if (attribute === 'strengthBase') {
this.tooltip += '\n strength: +' + item[attribute];
} else if (attribute === 'agilityBase') {
this.tooltip += '\n agility: ' +
(item[attribute] > 0 ? '+' : '') + item[attribute];
} else if (attribute === 'wisdomBase') {
this.tooltip += '\n wisdom: ' +
(item[attribute] > 0 ? '+' : '') + item[attribute];
} else if (
attribute === 'damage' ||
attribute === 'defense' ||
attribute === 'agility' ||
attribute === 'speed' ||
attribute === 'strength' ||
attribute === 'wisdom' ||
attribute === 'xp'
) {
this.tooltip += '\n ' + attribute + ': +' + item[attribute];
} else if (attribute === 'note') {
notes += '\n ' + item[attribute];
} else if (item[attribute] !== true) {
this.tooltip += '\n ' + attribute + ': ' + item[attribute];
} else {
notes += {
'arrow': '\n Required for bows!',
'consumable': '\n Single use only!',
'ranged': '\n Ranged attack!',
'returns': '\n Returns after every shot!',
'throwable': '\n Throwable!',
'usesArrow': '\n Requires arrows!'
}[attribute];
}
}
}
this.tooltip += notes;
super.showTooltip();
} else {
this.tooltip = this.config.tooltip;
if (this.tooltip) {
super.showTooltip();
}
}
}
hideTooltip() {
super.hideTooltip();
let item = this.getItem();
if (item) {
if (this.scene.gui[item.equips]) {
this.scene.gui[item.equips].clearTint();
} else if (item.equips === 'hand' || item.equips === 'hands') {
this.scene.gui.leftHand.clearTint();
this.scene.gui.rightHand.clearTint();
}
}
}
highlightEquipmentSlot(item) {
if (this.scene.gui[item.equips]) {
this.scene.gui[item.equips].setTint(0xffff00);
} else if (item.equips === 'hand' || item.equips === 'hands') {
this.scene.gui.leftHand.setTint(0xffff00);
this.scene.gui.rightHand.setTint(0xffff00);
}
}
/**
* Returns true if the item can be placed on this slot.
* @param {*} item
* @returns {boolean} True if the item is placable.
* @memberof SlotImage
*/
equips(item) {
// If this is either an inventory or a ground slot.
if (this.frame.name === 'slot') {
// Return true.
return true;
}
// Else if this is an equipment slot that matches the equips condition of the item.
if (this.frame.name === item.equips) {
// Return true.
return true;
}
// Else return true if this is either a left or a right hand slot and the items is one-handed or two-handed.
return (this.frame.name === 'leftHand' || this.frame.name === 'rightHand')
&& (item.equips === 'hand' || item.equips === 'hands');
}
/**
* Returns the item that is held by the attribute of the target actor linked to this slot.
* @returns {string} The held item.
* @memberof SlotImage
*/
getItem() {
// If there is no target attribute.
if (this.targetActor[this.targetAttribute] === null
|| this.targetActor[this.targetAttribute] === undefined) {
// Return nothing.
return undefined;
}
// If there is an item in this slot.
if (this.targetActor[this.targetAttribute][this.i] !== undefined) {
// Return the item held in the specified index of the target attribute.
return this.targetActor[this.targetAttribute][this.i];
}
}
/**
* Updates the view of this slot based on the current state of the target attribute.
* @memberof SlotImage
*/
draw() {
// If there is an item on this slot.
if (this.getItem() !== undefined) {
// If an item has already been displayed on this slot before.
if (this.itemImage) {
// Update the view of the item.
this.itemImage.setFrame(this.getItem().frame);
// Else if this item got placed on this slot recently.
} else {
// Display the image of the item.
this.itemImage = this.scene.add.image(
this.x,
this.y,
'tiles',
this.getItem().frame
);
}
// Else if there is no item on this slot but it's image is still visible.
} else if (this.itemImage !== undefined) {
// Remove the image of the item.
this.itemImage.destroy();
// Remove the reference of the image.
this.itemImage = undefined;
}
}
} |
JavaScript | class KIP17 {
/**
* Creates an instance of KIP17 api.
* @constructor
* @param {ApiClient} client - The Api client to use to connect with KAS.
* @param {AccessOptions} accessOptions - An instance of AccessOptions including `chainId`, `accessKeyId` and `secretAccessKey`.
*/
constructor(client, accessOptions) {
this.accessOptions = accessOptions
this.apiInstances = {}
if (client) {
this.apiInstances = {
kip17: new KIP17Api(client),
}
}
}
/**
* @type {string}
*/
get auth() {
return this.accessOptions.auth
}
/**
* @type {string}
*/
get accessKeyId() {
return this.accessOptions.accessKeyId
}
/**
* @type {string}
*/
get secretAccessKey() {
return this.accessOptions.secretAccessKey
}
/**
* @type {string}
*/
get chainId() {
return this.accessOptions.chainId
}
/**
* @type {AccessOptions}
*/
get accessOptions() {
return this._accessOptions
}
set accessOptions(accessOptions) {
this._accessOptions = accessOptions
}
/**
* @type {object}
*/
get apiInstances() {
return this._apiInstances
}
set apiInstances(apiInstances) {
this._apiInstances = apiInstances
}
/**
* @type {object}
*/
get client() {
return this.apiInstances.kip17.apiClient
}
set client(client) {
this.apiInstances = {
kip17: new KIP17Api(client),
}
}
/**
* @type {KIP17Api}
*/
get kip17Api() {
return this.apiInstances.kip17
}
/**
* Deploy KIP-17 token contract with a Klaytn account in KAS. <br>
* POST /v1/contract
* @example
* const ret = await caver.kas.kip17.deploy('Jasmine', 'JAS', 'jasmine-alias')
*
* @param {string} name The name of KIP-17 token.
* @param {string} symbol The symbol of KIP-17 token.
* @param {string} alias The alias of KIP-17 token. Your `alias` must only contain lowercase alphabets, numbers and hyphens and begin with an alphabet.
* @param {Function} [callback] The callback function to call.
* @return {Kip17TransactionStatusResponse}
*/
deploy(name, symbol, alias, callback) {
if (!this.accessOptions || !this.kip17Api) throw new Error(NOT_INIT_API_ERR_MSG)
if (!_.isString(name) || !_.isString(symbol)) throw new Error(`The name and symbol of KIP-17 token contract should be string type.`)
if (!_.isString(alias)) throw new Error(`The alias of KIP-17 token contract should be string type.`)
const opts = {
body: DeployKip17ContractRequest.constructFromObject({ name, symbol, alias }),
}
return new Promise((resolve, reject) => {
this.kip17Api.deployContract(this.chainId, opts, (err, data, response) => {
if (err) {
reject(err)
}
if (callback) callback(err, data, response)
resolve(data)
})
})
}
/**
* Search the list of deployed KIP-17 contracts using the Klaytn account in KAS. <br>
* GET /v1/contract
* @example
* // without query parameter
* const ret = await caver.kas.kip17.getContractList()
*
* // with query parameter
* const ret = await caver.kas.kip17.getContractList({ size: 1, cursor: 'eyJjc...' })
*
* @param {KIP17QueryOptions} [queryOptions] Filters required when retrieving data. `size`, and `cursor`.
* @param {Function} [callback] The callback function to call.
* @return {Kip17ContractListResponse}
*/
getContractList(queryOptions, callback) {
if (!this.accessOptions || !this.kip17Api) throw new Error(NOT_INIT_API_ERR_MSG)
if (_.isFunction(queryOptions)) {
callback = queryOptions
queryOptions = {}
}
queryOptions = KIP17QueryOptions.constructFromObject(queryOptions || {})
if (!queryOptions.isValidOptions(['size', 'cursor'])) throw new Error(`Invalid query options: 'size', and 'cursor' can be used.`)
return new Promise((resolve, reject) => {
this.kip17Api.listContractsInDeployerPool(this.chainId, queryOptions, (err, data, response) => {
if (err) {
reject(err)
}
if (callback) callback(err, data, response)
resolve(data)
})
})
}
/**
* Retrieves KIP-17 contract information by either contract address or alias. <br>
* GET /v1/contract/{contract-address-or-alias}
* @example
* // with contract address
* const ret = await caver.kas.kip17.getContract('0x9ad4163329aa90eaf52a27ac8f5e7981becebc16')
*
* // with contract alias
* const ret = await caver.kas.kip17.getContract('jasmine-alias')
*
* @param {string} addressOrAlias The contract address (hexadecimal, starting with 0x) or alias.
* @param {Function} [callback] The callback function to call.
* @return {Kip17ContractInfoResponse}
*/
getContract(addressOrAlias, callback) {
if (!this.accessOptions || !this.kip17Api) throw new Error(NOT_INIT_API_ERR_MSG)
if (!_.isString(addressOrAlias)) throw new Error(`The address and alias of KIP-17 token contract should be string type.`)
return new Promise((resolve, reject) => {
this.kip17Api.getContract(this.chainId, addressOrAlias, (err, data, response) => {
if (err) {
reject(err)
}
if (callback) callback(err, data, response)
resolve(data)
})
})
}
/**
* Mints a new token on the requested KIP-17 contract. The target contract can be requested by either contract address or alias.<br>
* POST /v1/contract/{contract-address-or-alias}/token
* @example
* // with contract address and token id in hex
* const ret = await caver.kas.kip17.mint('0x9ad4163329aa90eaf52a27ac8f5e7981becebc16', '0x6650d7f9bfb13561a37b15707b486f103f3a15cd', '0x1', 'uri')
*
* // with contract alias and token id in number
* const ret = await caver.kas.kip17.mint('jasmine-alias', '0x6650d7f9bfb13561a37b15707b486f103f3a15cd', 1, 'uri string')
*
* @param {string} addressOrAlias The contract address (hexadecimal, starting with 0x) or alias.
* @param {string} to The address of recipient EOA account for the newly minted token.
* @param {string|number} tokenId The token ID for the newly minted token. This cannot be overlapped with an existing ID.
* @param {string} tokenURI The token URI for the newly minted token.
* @param {Function} [callback] The callback function to call.
* @return {Kip17TransactionStatusResponse}
*/
mint(addressOrAlias, to, tokenId, tokenURI, callback) {
if (!this.accessOptions || !this.kip17Api) throw new Error(NOT_INIT_API_ERR_MSG)
if (!_.isString(addressOrAlias)) throw new Error(`The address and alias of KIP-17 token contract should be string type.`)
if (!utils.isAddress(to)) throw new Error(`Invalid address format: ${to}`)
if (!_.isString(tokenURI)) throw new Error(`The token URI should be string type.`)
if (!_.isString(tokenId) && !_.isNumber(tokenId)) throw new Error(`The token Id should be hexadecimal string or number type.`)
tokenId = utils.toHex(tokenId)
const opts = {
body: MintKip17TokenRequest.constructFromObject({ to, uri: tokenURI, id: tokenId }),
}
return new Promise((resolve, reject) => {
this.kip17Api.mintToken(this.chainId, addressOrAlias, opts, (err, data, response) => {
if (err) {
reject(err)
}
if (callback) callback(err, data, response)
resolve(data)
})
})
}
/**
* Return all tokens minted from a particular KIP-17 contract. <br>
* GET /v1/contract/{contract-address-or-alias}/token
* @example
* // with contract address and without query parameter
* const ret = await caver.kas.kip17.getTokenList('0x9ad4163329aa90eaf52a27ac8f5e7981becebc16')
*
* // with contract alias and query parameter
* const ret = await caver.kas.kip17.getTokenList('jasmine-alias', { size: 1, cursor: 'eyJjc...' })
*
* @param {string} addressOrAlias The contract address (hexadecimal, starting with 0x) or alias.
* @param {KIP17QueryOptions} [queryOptions] Filters required when retrieving data. `size`, and `cursor`.
* @param {Function} [callback] The callback function to call.
* @return {ListKip17TokensResponse}
*/
getTokenList(addressOrAlias, queryOptions, callback) {
if (!this.accessOptions || !this.kip17Api) throw new Error(NOT_INIT_API_ERR_MSG)
if (!_.isString(addressOrAlias)) throw new Error(`The address and alias of KIP-17 token contract should be string type.`)
if (_.isFunction(queryOptions)) {
callback = queryOptions
queryOptions = {}
}
queryOptions = KIP17QueryOptions.constructFromObject(queryOptions || {})
if (!queryOptions.isValidOptions(['size', 'cursor'])) throw new Error(`Invalid query options: 'size', and 'cursor' can be used.`)
return new Promise((resolve, reject) => {
this.kip17Api.listTokens(this.chainId, addressOrAlias, queryOptions, (err, data, response) => {
if (err) {
reject(err)
}
if (callback) callback(err, data, response)
resolve(data)
})
})
}
/**
* Retrieves the requested token information of a parcitular KIP-17 contract. <br>
* GET /v1/contract/{contract-address-or-alias}/token/{token-id}
* @example
* // with contract address and token id in hex
* const ret = await caver.kas.kip17.getToken('0x9ad4163329aa90eaf52a27ac8f5e7981becebc16', '0x1')
*
* // with contract alias and token id in number
* const ret = await caver.kas.kip17.getToken('jasmine-alias', 1)
*
* @param {string} addressOrAlias The contract address (hexadecimal, starting with 0x) or alias.
* @param {string|number} tokenId The token ID to retreive.
* @param {Function} [callback] The callback function to call.
* @return {GetKip17TokenResponse}
*/
getToken(addressOrAlias, tokenId, callback) {
if (!this.accessOptions || !this.kip17Api) throw new Error(NOT_INIT_API_ERR_MSG)
if (!_.isString(addressOrAlias)) throw new Error(`The address and alias of KIP-17 token contract should be string type.`)
if (!_.isString(tokenId) && !_.isNumber(tokenId)) throw new Error(`The token Id should be hexadecimal string or number type.`)
tokenId = utils.toHex(tokenId)
return new Promise((resolve, reject) => {
this.kip17Api.getToken(this.chainId, addressOrAlias, tokenId, (err, data, response) => {
if (err) {
reject(err)
}
if (callback) callback(err, data, response)
resolve(data)
})
})
}
/**
* Transfers a token. If `sender` and `owner` are not the same, then `sender` must have been approved for this token transfer. <br>
* POST /v1/contract/{contract-address-or-alias}/token/{token-id}
* @example
* const sender = '0x6650d7f9bfb13561a37b15707b486f103f3a15cd'
* const owner = '0x0c12a8f720f721cb3879217ee45709c2345c8446'
* const to = '0x661e2075de14d267c0f141e917a76871d3b299ad'
*
* // with contract address and token id in hex
* const ret = await caver.kas.kip17.transfer('0x9ad4163329aa90eaf52a27ac8f5e7981becebc16', sender, owner, to, '0x1')
*
* // with contract alias and token id in number
* const ret = await caver.kas.kip17.transfer('jasmine-alias', sender, owner, to, 1)
*
* @param {string} addressOrAlias The contract address (hexadecimal, starting with 0x) or alias.
* @param {string} sender The address of the account sending the transaction to transfer the token. The sender must be the owner of the token or have been approved by the owner for the token to be transfered.
* @param {string} owner The address of the account that owns the token.
* @param {string} to The address of account to receive tokens.
* @param {string|number} tokenId The token ID to transfer.
* @param {Function} [callback] The callback function to call.
* @return {Kip17TransactionStatusResponse}
*/
transfer(addressOrAlias, sender, owner, to, tokenId, callback) {
if (!this.accessOptions || !this.kip17Api) throw new Error(NOT_INIT_API_ERR_MSG)
if (!_.isString(addressOrAlias)) throw new Error(`The address and alias of KIP-17 token contract should be string type.`)
if (!_.isString(tokenId) && !_.isNumber(tokenId)) throw new Error(`The token Id should be hexadecimal string or number type.`)
if (!utils.isAddress(sender)) throw new Error(`Invalid address format: ${sender}`)
if (!utils.isAddress(owner)) throw new Error(`Invalid address format: ${owner}`)
if (!utils.isAddress(to)) throw new Error(`Invalid address format: ${to}`)
tokenId = utils.toHex(tokenId)
const opts = {
body: TransferKip17TokenRequest.constructFromObject({ sender, owner, to }),
}
return new Promise((resolve, reject) => {
this.kip17Api.transferToken(this.chainId, addressOrAlias, tokenId, opts, (err, data, response) => {
if (err) {
reject(err)
}
if (callback) callback(err, data, response)
resolve(data)
})
})
}
/**
* Burns a token. If `from` is not the owner or has been approved for this operation, then the transaction submitted from this API will be reverted. <br>
* DELETE /v1/contract/{contract-address-or-alias}/token/{token-id}
* @example
* const from = '0x661e2075de14d267c0f141e917a76871d3b299ad'
*
* // with contract address and token id in hex
* const ret = await caver.kas.kip17.burn('0x9ad4163329aa90eaf52a27ac8f5e7981becebc16', from, '0x1')
*
* // with contract alias and token id in number
* const ret = await caver.kas.kip17.burn('jasmine-alias', from, 1)
*
* @param {string} addressOrAlias The contract address (hexadecimal, starting with 0x) or alias.
* @param {string} from The address of sender or owner. If the from that burns the token is not the owner, the sender that sends the transaction to burn the token must have been approved by the owner.
* @param {string|number} tokenId The token ID to burn.
* @param {Function} [callback] The callback function to call.
* @return {Kip17TransactionStatusResponse}
*/
burn(addressOrAlias, from, tokenId, callback) {
if (!this.accessOptions || !this.kip17Api) throw new Error(NOT_INIT_API_ERR_MSG)
if (!_.isString(addressOrAlias)) throw new Error(`The address and alias of KIP-17 token contract should be string type.`)
if (!_.isString(tokenId) && !_.isNumber(tokenId)) throw new Error(`The token Id should be hexadecimal string or number type.`)
if (!utils.isAddress(from)) throw new Error(`Invalid address format: ${from}`)
tokenId = utils.toHex(tokenId)
const opts = {
body: BurnKip17TokenRequest.constructFromObject({ from }),
}
return new Promise((resolve, reject) => {
this.kip17Api.burnToken(this.chainId, addressOrAlias, tokenId, opts, (err, data, response) => {
if (err) {
reject(err)
}
if (callback) callback(err, data, response)
resolve(data)
})
})
}
/**
* Approves an EOA, `to`, to perform token operations on a particular token of a contract which `from` owns. <br>
* If `from` is not the owner, then the transaction submitted from this API will be reverted. <br>
* POST /v1/contract/{contract-address-or-alias}/approve/{token-id}
* @example
* const from = '0x0c12a8f720f721cb3879217ee45709c2345c8446'
* const to = '0x661e2075de14d267c0f141e917a76871d3b299ad'
*
* // with contract address and token id in hex
* const ret = await caver.kas.kip17.approve('0x9ad4163329aa90eaf52a27ac8f5e7981becebc16', from, to, '0x1')
*
* // with contract alias and token id in number
* const ret = await caver.kas.kip17.approve('jasmine-alias', from, to, 1)
*
* @param {string} addressOrAlias The contract address (hexadecimal, starting with 0x) or alias.
* @param {string} from The address of owner.
* @param {string} to The address of EOA to be approved.
* @param {string|number} tokenId The token ID to approve.
* @param {Function} [callback] The callback function to call.
* @return {Kip17TransactionStatusResponse}
*/
approve(addressOrAlias, from, to, tokenId, callback) {
if (!this.accessOptions || !this.kip17Api) throw new Error(NOT_INIT_API_ERR_MSG)
if (!_.isString(addressOrAlias)) throw new Error(`The address and alias of KIP-17 token contract should be string type.`)
if (!_.isString(tokenId) && !_.isNumber(tokenId)) throw new Error(`The token Id should be hexadecimal string or number type.`)
if (!utils.isAddress(from)) throw new Error(`Invalid address format: ${from}`)
if (!utils.isAddress(to)) throw new Error(`Invalid address format: ${to}`)
tokenId = utils.toHex(tokenId)
const opts = {
body: ApproveKip17TokenRequest.constructFromObject({ from, to }),
}
return new Promise((resolve, reject) => {
this.kip17Api.approveToken(this.chainId, addressOrAlias, tokenId, opts, (err, data, response) => {
if (err) {
reject(err)
}
if (callback) callback(err, data, response)
resolve(data)
})
})
}
/**
* Approves an EOA, `to`, to perform token operations on all token of a contract which `from` owns. <br>
* POST /v1/contract/{contract-address-or-alias}/approveall
* @example
* const from = '0x0c12a8f720f721cb3879217ee45709c2345c8446'
* const to = '0x661e2075de14d267c0f141e917a76871d3b299ad'
*
* // with contract address
* const ret = await caver.kas.kip17.approveAll('0x9ad4163329aa90eaf52a27ac8f5e7981becebc16', from, to, true)
*
* // with contract alias
* const ret = await caver.kas.kip17.approveAll('jasmine-alias', from, to, true)
*
* @param {string} addressOrAlias The contract address (hexadecimal, starting with 0x) or alias.
* @param {string} from The address of owner.
* @param {string} to The address of EOA to be approved.
* @param {boolean} approved A boolean value to set; true for approval, false for revocation.
* @param {Function} [callback] The callback function to call.
* @return {Kip17TransactionStatusResponse}
*/
approveAll(addressOrAlias, from, to, approved, callback) {
if (!this.accessOptions || !this.kip17Api) throw new Error(NOT_INIT_API_ERR_MSG)
if (!_.isString(addressOrAlias)) throw new Error(`The address and alias of KIP-17 token contract should be string type.`)
if (!utils.isAddress(from)) throw new Error(`Invalid address format: ${from}`)
if (!utils.isAddress(to)) throw new Error(`Invalid address format: ${to}`)
const opts = {
body: ApproveAllKip17Request.constructFromObject({ from, to, approved }),
}
return new Promise((resolve, reject) => {
this.kip17Api.approveAll(this.chainId, addressOrAlias, opts, (err, data, response) => {
if (err) {
reject(err)
}
if (callback) callback(err, data, response)
resolve(data)
})
})
}
/**
* Lists all tokens of the same owner (`owner-address`) of a contract. <br>
* GET /v1/contract/{contract-address-or-alias}/owner/{owner-address}
* @example
* const owner = '0x0c12a8f720f721cb3879217ee45709c2345c8446'
*
* // without query parameter
* const ret = await caver.kas.kip17.getTokenListByOwner('0x9ad4163329aa90eaf52a27ac8f5e7981becebc16', owner)
*
* // with query parameter
* const ret = await caver.kas.kip17.getTokenListByOwner('jasmine-alias', owner, { size: 1, cursor: 'eyJjc...' })
*
* @param {string} addressOrAlias The contract address (hexadecimal, starting with 0x) or alias.
* @param {string} owner The address of owner.
* @param {KIP17QueryOptions} [queryOptions] Filters required when retrieving data. `size`, and `cursor`.
* @param {Function} [callback] The callback function to call.
* @return {GetOwnerKip17TokensResponse}
*/
getTokenListByOwner(addressOrAlias, owner, queryOptions, callback) {
if (!this.accessOptions || !this.kip17Api) throw new Error(NOT_INIT_API_ERR_MSG)
if (!_.isString(addressOrAlias)) throw new Error(`The address and alias of KIP-17 token contract should be string type.`)
if (_.isFunction(queryOptions)) {
callback = queryOptions
queryOptions = {}
}
queryOptions = KIP17QueryOptions.constructFromObject(queryOptions || {})
if (!queryOptions.isValidOptions(['size', 'cursor'])) throw new Error(`Invalid query options: 'size', and 'cursor' can be used.`)
return new Promise((resolve, reject) => {
this.kip17Api.getOwnerTokens(this.chainId, addressOrAlias, owner, queryOptions, (err, data, response) => {
if (err) {
reject(err)
}
if (callback) callback(err, data, response)
resolve(data)
})
})
}
/**
* Lists token transfer histories starting from the time the requested token was minted, where each entry of the response items shows a transfer record. <br>
* GET /v1/contract/{contract-address-or-alias}/token/{token-id}/history
* @example
* // with token id in hex and without query parameter
* const ret = await caver.kas.kip17.getContractList('0x9ad4163329aa90eaf52a27ac8f5e7981becebc16', '0x1')
*
* // with token id in number and query parameter
* const ret = await caver.kas.kip17.getContractList('jasmine-alias', 1, { size: 1, cursor: 'eyJjc...' })
*
* @param {string} addressOrAlias The contract address (hexadecimal, starting with 0x) or alias.
* @param {string|number} tokenId The token ID to search transfer history.
* @param {KIP17QueryOptions} [queryOptions] Filters required when retrieving data. `size`, and `cursor`.
* @param {Function} [callback] The callback function to call.
* @return {GetKip17TokenHistoryResponse}
*/
getTransferHistory(addressOrAlias, tokenId, queryOptions, callback) {
if (!this.accessOptions || !this.kip17Api) throw new Error(NOT_INIT_API_ERR_MSG)
if (!_.isString(addressOrAlias)) throw new Error(`The address and alias of KIP-17 token contract should be string type.`)
if (!_.isString(tokenId) && !_.isNumber(tokenId)) throw new Error(`The token Id should be hexadecimal string or number type.`)
tokenId = utils.toHex(tokenId)
if (_.isFunction(queryOptions)) {
callback = queryOptions
queryOptions = {}
}
queryOptions = KIP17QueryOptions.constructFromObject(queryOptions || {})
if (!queryOptions.isValidOptions(['size', 'cursor'])) throw new Error(`Invalid query options: 'size', and 'cursor' can be used.`)
return new Promise((resolve, reject) => {
this.kip17Api.getTokenHistory(this.chainId, addressOrAlias, tokenId, queryOptions, (err, data, response) => {
if (err) {
reject(err)
}
if (callback) callback(err, data, response)
resolve(data)
})
})
}
} |
JavaScript | class TestSequence extends __WEBPACK_IMPORTED_MODULE_0__Test_js__["a" /* Test */] {
/**
Creates a new TestSequence instance.
@param {string} name - The name of the test sequence.
*/
constructor(name) {
super(name)
this.tests = [ ]
}
/**
Executes the test.
@returns {Promise} a Promise that will provide the outcome of the
test.
*/
doRun(configuration, observer) {
let self = this
let testOutcomePromise = new Promise(function(resolve, reject) {
let allTestsCompletePromise = null
if (configuration.parallelExecution) {
// Start all tests in the sequence
let testPromises = [ ];
for (let i = 0; i < self.tests.length; i++) {
let test = self.tests[i]
let testPromise = Promise.resolve(test.run({ configuration: configuration, observer: observer }))
testPromises.push(testPromise)
}
allTestsCompletePromise = Promise.all(testPromises)
} else {
allTestsCompletePromise = new Promise(function(resolve, reject) {
runNextTest(self.tests, 0, configuration, observer, resolve)
})
}
// Wait for all tests to complete and update the
// test sequence result
allTestsCompletePromise.then(function() {
let result = __WEBPACK_IMPORTED_MODULE_1__TestResultOutcome_js__["a" /* TestResultOutcome */].eUnknown
for (let i = 0; i < self.tests.length; i++) {
let test = self.tests[i]
let outcome = test.result.outcome
if (i == 0) {
// The first test determines the initial value of the result
result = outcome
} else if (result == __WEBPACK_IMPORTED_MODULE_1__TestResultOutcome_js__["a" /* TestResultOutcome */].eUnknown) {
// If the current sequence outcome is unknown it can only get worse and be set
// to exception or failed (if the outcome we are adding is exception or failed)
if ((outcome == __WEBPACK_IMPORTED_MODULE_1__TestResultOutcome_js__["a" /* TestResultOutcome */].eFailed) || (outcome == __WEBPACK_IMPORTED_MODULE_1__TestResultOutcome_js__["a" /* TestResultOutcome */].eException)) {
result = outcome;
}
} else if (result == __WEBPACK_IMPORTED_MODULE_1__TestResultOutcome_js__["a" /* TestResultOutcome */].ePassed) {
// If the current sequence outcome is passed it stays at this state only if the
// result we are adding is passed, else it will be 'unknown',
// 'passedButMemoryLeaks', 'exception' or 'failed'.
// depending on the outcome of the result we are adding.
result = outcome;
}
}
resolve(result)
})
})
return testOutcomePromise
}
append(test) {
// We need to update the number of the test
if (this.tests.length == 0) {
let newNumber = this.number().clone();
test.information.number = newNumber.deeperNumber()
} else {
let newNumber = this.tests[this.tests.length - 1].number().clone();
test.information.number = newNumber.increase()
}
this.tests.push(test)
}
} |
JavaScript | class Test {
/**
Creates a new Test instance.
@param {string} name - The name of the test.
*/
constructor(name) {
this.information = new __WEBPACK_IMPORTED_MODULE_0__TestInformation_js__["a" /* TestInformation */](name)
this.result = new __WEBPACK_IMPORTED_MODULE_1__TestResult_js__["a" /* TestResult */](this)
}
number() {
return this.information.number
}
name() {
return this.information.name
}
passed() {
return this.result.passed()
}
/**
<p>Executes the test.</p>
<p>This method should not be overriden. Override
doRun().</p>
@param {TestObserver=} observer - An observer that
will monitor the execution of the test.
@returns {Promise} A promise that will indicate when
the test is complete.
*/
run({ configuration = new __WEBPACK_IMPORTED_MODULE_3__TestConfiguration_js__["a" /* TestConfiguration */](), observer = null } = { }) {
let self = this
let timeout = null
let testPromise = new Promise(function(resolve, reject) {
self.notify(__WEBPACK_IMPORTED_MODULE_4__ObserverEventType_js__["a" /* ObserverEventType */].eTestStart, observer)
let outcomePromise = Promise.resolve(self.tryDoRun(configuration, observer))
if (outcomePromise) {
outcomePromise
.then(function(outcome) {
let keyFound = false
var keys = Object.keys(__WEBPACK_IMPORTED_MODULE_2__TestResultOutcome_js__["a" /* TestResultOutcome */])
for (let i = 0; i < keys.length; i++) {
if (__WEBPACK_IMPORTED_MODULE_2__TestResultOutcome_js__["a" /* TestResultOutcome */][keys[i]] == outcome) {
keyFound = true
break
}
}
if (keyFound) {
self.result.outcome = outcome
} else {
self.result.outcome = __WEBPACK_IMPORTED_MODULE_2__TestResultOutcome_js__["a" /* TestResultOutcome */].eExecutionError
}
self.notify(__WEBPACK_IMPORTED_MODULE_4__ObserverEventType_js__["a" /* ObserverEventType */].eTestEnd, observer)
if (timeout) {
clearTimeout(timeout)
}
resolve()
})
.catch(function(err) {
self.result.outcome = __WEBPACK_IMPORTED_MODULE_2__TestResultOutcome_js__["a" /* TestResultOutcome */].eException
self.result.exception = err
self.notify(__WEBPACK_IMPORTED_MODULE_4__ObserverEventType_js__["a" /* ObserverEventType */].eTestEnd, observer)
if (timeout) {
clearTimeout(timeout)
}
resolve()
})
} else {
self.result.outcome = __WEBPACK_IMPORTED_MODULE_2__TestResultOutcome_js__["a" /* TestResultOutcome */].eExecutionError
self.notify(__WEBPACK_IMPORTED_MODULE_4__ObserverEventType_js__["a" /* ObserverEventType */].eTestEnd, observer)
if (timeout) {
clearTimeout(timeout)
}
resolve()
}
})
let timeoutPromise = new Promise(function(resolve, reject) {
timeout = setTimeout(function() {
if (self.result.outcome == __WEBPACK_IMPORTED_MODULE_2__TestResultOutcome_js__["a" /* TestResultOutcome */].eUnknown) {
self.result.outcome = __WEBPACK_IMPORTED_MODULE_2__TestResultOutcome_js__["a" /* TestResultOutcome */].eExecutionTimeout
self.notify(__WEBPACK_IMPORTED_MODULE_4__ObserverEventType_js__["a" /* ObserverEventType */].eTestEnd, observer)
}
resolve()
},
configuration.timeout)
})
let testPromiseWithTimeout = Promise.race([ testPromise, timeoutPromise ])
return testPromiseWithTimeout
}
tryDoRun(configuration, observer) {
try {
return this.doRun(configuration, observer)
} catch(err) {
return Promise.reject(err);
}
}
/**
<p>Called by {@link Test#run} to execute the test. Do not
call this function directly.</p>
<p>This function is meant to be overriden by specific
test classes.The base class implementation always
returns TestResultOutcome.eFailed.</p>
<p>If the test is asynchronous this function should
return a Promise with an executor function that
passes the outcome of the test to the resolve
function. So even even if the test fails resolve
should be used, not reject. Use reject to indicate
the test couldn't be run.</p>
@virtual
@returns {TestResultOutcome|Promise} The outcome of the
test or a Promise that will provide the outcome of the
test.
@see FunctionBasedTest
@see FileComparisonTest
*/
doRun(configuration, observer) {
return __WEBPACK_IMPORTED_MODULE_2__TestResultOutcome_js__["a" /* TestResultOutcome */].eFailed
}
notify(type, observer) {
if (observer) {
observer.notify(type, this)
}
}
} |
JavaScript | class TestProgressObserverConfiguration {
constructor(enabled = true, exceptionDetails = true) {
this.enabled = enabled
this.exceptionDetails = exceptionDetails
this.console = true
this.filepath = null
}
} |
JavaScript | class TestConfiguration {
/**
Creates a new TestConfiguration instance.
@param {boolean} [parallelExecution=true] - Initial value for this.parallelExecution.
@param {number} [timeout=10000] - Initial value for this.timeout.
@param {TestOutputConfiguration} [outputConfiguration=new TestOutputConfiguration()] - Initial value
for this.outputConfiguration.
*/
constructor(parallelExecution = true, timeout = 10000, outputConfiguration = new __WEBPACK_IMPORTED_MODULE_0__TestOutputConfiguration_js__["a" /* TestOutputConfiguration */]()) {
this.parallelExecution = parallelExecution
this.timeout = timeout
this.outputConfiguration = outputConfiguration
}
/**
Reads the configuration from a JSON file.
@param {string} path - The path of the configuration file.
*/
readFromFile(path) {
let file = fs.readFileSync(path, 'utf8')
let config = JSON.parse(file)
if (config.parallelExecution != null) {
this.parallelExecution = config.parallelExecution
}
if (config.timeout != null) {
this.timeout = config.timeout
}
}
} |
JavaScript | class TestOutputConfiguration {
constructor(progressObserverConfiguration = new __WEBPACK_IMPORTED_MODULE_0__TestProgressObserverConfiguration_js__["a" /* TestProgressObserverConfiguration */]()) {
this.progressObserverConfiguration = progressObserverConfiguration
}
} |
JavaScript | class TestProgressObserver {
constructor(configuration = new __WEBPACK_IMPORTED_MODULE_0__TestProgressObserverConfiguration_js__["a" /* TestProgressObserverConfiguration */]()) {
this.configuration = configuration
if (this.configuration.filepath != null) {
this.file = fs.openSync(this.configuration.filepath, "w")
}
this[nesting] = ""
}
notify(eventType, test) {
switch (eventType) {
case __WEBPACK_IMPORTED_MODULE_1__ObserverEventType_js__["a" /* ObserverEventType */].eTestStart:
if (this.configuration.console) {
console.log(this[nesting] + formatNumber(test.number()) + " " + test.name() + " started")
}
if (this.file != null) {
fs.appendFileSync(this.file, this[nesting] + formatNumber(test.number()) + " " + test.name() + " started\n")
}
this[nesting] += " "
break
case __WEBPACK_IMPORTED_MODULE_1__ObserverEventType_js__["a" /* ObserverEventType */].eTestEnd:
if (this[nesting].length >= 4) {
this[nesting] = this[nesting].substring(0, (this[nesting].length - 4))
}
if (this.configuration.console) {
console.log(this[nesting] + formatNumber(test.number()) + " " + test.name() +
" completed, result is " + formatResult(test.result, this.configuration, test instanceof __WEBPACK_IMPORTED_MODULE_3__TestSequence_js__["a" /* TestSequence */]))
}
if (this.file != null) {
fs.appendFileSync(this.file, this[nesting] + formatNumber(test.number()) + " " + test.name() +
" completed, result is " + formatResult(test.result, this.configuration, test instanceof __WEBPACK_IMPORTED_MODULE_3__TestSequence_js__["a" /* TestSequence */]) + "\n")
}
break
}
}
} |
JavaScript | class TestResult {
/**
Creates a new TestResult instance. The outcome is
set to TestResultOutcome.eUnknown.
*/
constructor(test) {
this.test = test
this.outcome = __WEBPACK_IMPORTED_MODULE_0__TestResultOutcome_js__["a" /* TestResultOutcome */].eUnknown
this.exception = null
}
/**
Checks whether the test passed.
@returns True if this.outcome is TestResultOutcome.ePassed,
False in all other cases.
*/
passed() {
return (this.outcome == __WEBPACK_IMPORTED_MODULE_0__TestResultOutcome_js__["a" /* TestResultOutcome */].ePassed)
}
getPassRate() {
let passed = 0
let failed = 0
let total = 0
if (this.test instanceof __WEBPACK_IMPORTED_MODULE_1__TestSequence_js__["a" /* TestSequence */]) {
for (let test of this.test.tests) {
let localPassRate = test.result.getPassRate()
passed += localPassRate.passed
failed += localPassRate.failed
total += localPassRate.total
}
} else {
switch (this.outcome) {
case __WEBPACK_IMPORTED_MODULE_0__TestResultOutcome_js__["a" /* TestResultOutcome */].ePassed:
passed = 1
break
case __WEBPACK_IMPORTED_MODULE_0__TestResultOutcome_js__["a" /* TestResultOutcome */].eFailed:
failed = 1
break
}
total = 1
}
return { "passed": passed, "failed": failed, "total": total }
}
} |
JavaScript | class TestHarness {
/**
Creates a new TestHarness instance.
@param {string} name - The title of the test suite.
*/
constructor(name) {
this.environment = new __WEBPACK_IMPORTED_MODULE_3__TestEnvironment_js__["a" /* TestEnvironment */]()
this[topSequence] = new __WEBPACK_IMPORTED_MODULE_4__TopTestSequence_js__["a" /* TopTestSequence */](name)
}
/**
Executes the tests in the test suite.
*/
run() {
let self = this
console.log("Test Suite: " + self[topSequence].name())
console.log()
let configuration = new __WEBPACK_IMPORTED_MODULE_0__TestConfiguration_js__["a" /* TestConfiguration */](false)
// We load the configuration from file first so that
// any command line arguments override the configuration
// from the file
if (argv.config != null) {
configuration.readFromFile(argv.config)
} else {
// If no configuration file is explicitly specified
// then check if a "testconfig.json" file is present
// and load it
try {
configuration.readFromFile("testconfig.json")
} catch(err) {
// Ignore any errors while trying to load default
// config
}
}
if (argv.parallel != null) {
configuration.parallelExecution = (argv.parallel == "true")
}
if (argv.exceptionDetails != null) {
configuration.outputConfiguration.progressObserverConfiguration.exceptionDetails = !(argv.exceptionDetails == "false")
}
let progressObserver = null
if (configuration.outputConfiguration.progressObserverConfiguration.enabled) {
progressObserver = new __WEBPACK_IMPORTED_MODULE_1__TestProgressObserver_js__["a" /* TestProgressObserver */](configuration.outputConfiguration.progressObserverConfiguration)
}
let testPromise = Promise.resolve(self[topSequence].run({ configuration: configuration, observer: progressObserver }))
testPromise.then(function() {
let passRate = self[topSequence].result.getPassRate()
if (!self[topSequence].passed()) {
console.log("Test Suite FAILED!!! (" + passRate.passed
+ " passed, " + passRate.failed + " failed, "
+ passRate.total + " total)")
} else {
console.log("Test Suite passed (" + passRate.passed
+ " passed, " + passRate.failed + " failed, "
+ passRate.total + " total)")
}
})
}
appendTestSequence(name) {
let newTestSequence = new __WEBPACK_IMPORTED_MODULE_2__TestSequence_js__["a" /* TestSequence */](name)
this[topSequence].append(newTestSequence)
return newTestSequence
}
} |
JavaScript | class TestInformation {
constructor(name) {
this.number = new __WEBPACK_IMPORTED_MODULE_0__TestNumber_js__["a" /* TestNumber */]()
this.name = name
}
} |
JavaScript | class TestNumber {
constructor() {
this.number = [ ]
}
clone() {
let newNumber = new TestNumber()
for (let i = 0; i < this.number.length; i++) {
newNumber.number.push(this.number[i])
}
return newNumber
}
depth() {
return this.number.length
}
part(i) {
return this.number[i]
}
deeperNumber() {
this.number.push(1)
return this
}
increase() {
if (this.number.length) {
this.number[this.number.length - 1]++
}
return this
}
} |
JavaScript | class TestEnvironment {
/** Creates a new TestEnvironment instance. */
constructor() {
this.testDataDirectories = { }
}
/**
Adds or updates a test data directory. If no id
is specified then it is considered to be the id
of the default test data directory: "(default)".
@param {string} path - The path of the test
data directory.
@param {string=} id - The identifier of this
test data directory.
*/
setTestDataDirectory(path, id) {
if (id == null) {
id = "(default)"
}
this.testDataDirectories[id] = path
}
} |
JavaScript | class FunctionBasedTest extends __WEBPACK_IMPORTED_MODULE_0__Test_js__["a" /* Test */] {
constructor(name, runFct, parentSequence) {
super(name)
this.runFct = runFct
if (parentSequence) {
parentSequence.append(this)
}
}
doRun(configuration, observer) {
let self = this
let testPromise = new Promise(function(resolve, reject) {
self.runFct(resolve, reject)
})
return testPromise
}
} |
JavaScript | class FileComparisonTest extends __WEBPACK_IMPORTED_MODULE_0__Test_js__["a" /* Test */] {
/**
Callback that implements a specific test case.
@callback FileComparisonTestRunFct
@return {TestResultOutcome} The outcome of the test.
*/
/**
Creates a new FileComparisonTest instance.
@param {string} name - The name of the test.
@param {FileComparisonTestRunFct} runFct - The callback that
will run the test and should generate the file
that will be compared to the reference file.
@param {TestSequence=} parentSequence - A test
sequence to which the new test will be appended.
*/
constructor(name, runFct, parentSequence) {
super(name)
this.runFct = runFct
if (parentSequence) {
parentSequence.append(this)
}
}
setOutputFilePath(path) {
this.outputFilePath = path;
}
setReferenceFilePath(path){
this.referenceFilePath = path;
}
doRun(configuration, observer) {
let self = this
let runFctPromise = new Promise(function(resolve, reject) {
if (self.runFct) {
self.runFct(resolve, reject, self)
} else {
resolve(__WEBPACK_IMPORTED_MODULE_1__TestResultOutcome_js__["a" /* TestResultOutcome */].ePassed)
}
})
let testPromise = new Promise(function(resolve, reject) {
runFctPromise.then(function(outcome) {
if (outcome == __WEBPACK_IMPORTED_MODULE_1__TestResultOutcome_js__["a" /* TestResultOutcome */].ePassed) {
if (self.outputFilePath && self.referenceFilePath) {
let outputContents = fs.readFileSync(self.outputFilePath)
let referenceContents = fs.readFileSync(self.referenceFilePath)
if (outputContents.equals(referenceContents)) {
resolve(__WEBPACK_IMPORTED_MODULE_1__TestResultOutcome_js__["a" /* TestResultOutcome */].ePassed)
} else {
resolve(__WEBPACK_IMPORTED_MODULE_1__TestResultOutcome_js__["a" /* TestResultOutcome */].eFailed)
}
} else {
resolve(__WEBPACK_IMPORTED_MODULE_1__TestResultOutcome_js__["a" /* TestResultOutcome */].eExecutionError)
}
} else {
resolve(outcome)
}
})
})
return testPromise;
}
} |
JavaScript | class InCellEditingDirective extends EditingDirectiveBase {
constructor(grid, localDataChangesService) {
super(grid, localDataChangesService);
this.grid = grid;
this.localDataChangesService = localDataChangesService;
}
// Need mixin
createModel(args) {
return this.createFormGroup(args);
}
saveModel({ dataItem, formGroup, isNew }) {
if (!formGroup.dirty && !isNew) {
return;
}
if (formGroup.valid) {
this.editService.assignValues(dataItem, formGroup.value);
return dataItem;
}
markAllAsTouched(formGroup);
}
/**
* @hidden
*/
ngOnInit() {
super.ngOnInit();
this.subscriptions.add(this.grid.cellClick.subscribe(this.cellClickHandler.bind(this)));
this.subscriptions.add(this.grid.cellClose.subscribe(this.cellCloseHandler.bind(this)));
}
removeHandler(args) {
super.removeHandler(args);
this.grid.cancelCell();
}
cellClickHandler(args) {
if (!args.isEdited && args.type !== 'contextmenu') {
this.grid.editCell(args.rowIndex, args.columnIndex, this.createFormGroup(args));
}
}
cellCloseHandler(args) {
const { formGroup, dataItem } = args;
if (!formGroup.valid) {
args.preventDefault();
}
else if (formGroup.dirty) {
this.editService.assignValues(dataItem, formGroup.value);
this.editService.update(dataItem);
}
}
} |
JavaScript | class LinkedStack {
constructor() {
this.topNode = null;
this.length = 0;
}
push(data) {
this.topNode = {
value: data,
prev: this.topNode,
};
this.length++;
return this.length;
}
pop() {
if (this.isEmpty()) {
return undefined;
}
this.topNode = this.topNode.prev;
this.length--;
}
top() {
if (!this.topNode) {
return undefined;
} else {
return this.topNode.value;
}
}
height() {
return this.length;
}
isEmpty() {
return this.length === 0;
}
} |
JavaScript | class UArrayStack {
constructor() {
this.stack = [];
}
push(data) {
return this.stack.push(data);
}
pop() {
this.stack.pop();
}
top() {
return this.stack[this.stack.length - 1];
}
height() {
return this.stack.length;
}
isEmpty() {
return this.stack.length === 0;
}
} |
JavaScript | class BArrayStack {
constructor(size = 100) {
this.stack = [];
for (let i = 0; i < size; i++) {
this.stack[i] = null;
}
this.topIndex = -1;
}
height() {
return this.topIndex + 1;
}
isEmpty() {
return this.topIndex === -1;
}
isFull() {
return this.topIndex === this.stack.length - 1;
}
push(item) {
if (!this.isFull()) {
this.topIndex++;
this.stack[this.topIndex] = item;
return this.height();
} else {
throw new Error('Stack too deep');
}
}
pop() {
if (!this.isEmpty()) {
this.stack[this.topIndex] = null;
this.topIndex--;
} else {
throw new Error('Stack already empty');
}
}
top() {
if (!this.isEmpty()) {
return this.stack[this.topIndex];
} else {
return undefined;
}
}
} |
JavaScript | class IdeWrapper extends React.Component {
/**
*
* @param {object} props properties of component
*/
constructor(props) {
super(props);
this.onClick = this.onClick.bind(this);
this.onDownloadErrorNoticed = this.onDownloadErrorNoticed.bind(this);
this.getAndSetEmbedMetadata = this.getAndSetEmbedMetadata.bind(this);
this.onClick = this.onClick.bind(this);
this.state = {
codeData: null,
embedName: '',
embedLang: '',
embedType: '',
isDownloading: false,
IdeComponent: null,
error: null,
errorType: null,
project: null,
messageList: null
};
this.project = null;
this.messageList = null;
}
/**
* Will be executed after rendering component. State changes won't trigger a re-rendering.
* IdeWrapper use it to get meta data of embed for showing it without loading the whole.
*
* @returns {void}
*/
componentDidMount() {
this.getAndSetEmbedMetadata();
}
/**
* Resets the error state
*
* @returns {void}
*/
onDownloadErrorNoticed() {
this.setState({
error: null,
errorType: null
});
}
/**
* Sets the embed data by given data.
* Also it resets the isDownloading state.
*
* @param {object} data date of loaded embed
* @returns {void}
*/
onProjectLoaded(data) {
this.setState({
codeData: data,
isDownloading: false
});
}
/**
* Sets the isDownloading state, loads the ide component as well the embed data.
* Sets the embed data automatically after downloading them.
*
* @returns {void}
*/
onClick() {
this.setState({
codeData: null,
isDownloading: true
});
if (this.state.IdeComponent === null) {
import(/* webpackChunkName: "ide" */ './Ide').then(Ide => {
this.setState({ IdeComponent: Ide.default });
}).catch(err => {
debug('Failed to load Ide component', err);
});
}
API.embed.getEmbed({ id: this.props.codeID }).then(data => {
if (!data.error) {
if (data.INITIAL_DATA.meta.embedType != EmbedTypes.Sourcebox && data.INITIAL_DATA.meta.embedType != EmbedTypes.Skulpt) {
debug(data.INITIAL_DATA.meta.embedType);
this.setErrorState('Nicht unterstütztes Beispielformat.');
}
if (typeof Sk === 'undefined') {
require.ensure([], require => {
require('exports-loader?Sk!../../../public/skulpt/skulpt.min.js');
require('exports-loader?Sk!../../../public/skulpt/skulpt-stdlib.js');
this.onProjectLoaded(data);
});
} else {
this.onProjectLoaded(data);
}
} else {
//quick fix for englisch error message
data.error.title = (data.error.title === 'Unauthorized') ? 'Bitte melden Sie sich an, um dieses Beispiel zu bearbeiten.' : data.error.title;
this.setErrorState(data.error.title);
}
}).catch(err => {
this.setErrorState(err);
debug(err);
});
}
/**
* Sets the error state with given error message.
* Resets the isDownloading state if the error occurred while downloading embed
*
* @param {string} err specific message of occurred error
* @param {ErrorTypes} type type of the error to set
* @returns {void}
*/
setErrorState(err, type) {
this.setState({
error: err,
errorType: type,
isDownloading: false
});
}
/**
* Receives and set meta data
* @returns {void}
*/
getAndSetEmbedMetadata() {
// check if reloading meta data
if (this.state.error != null) {
this.setState({
isDownloading: true
});
}
// Call API to get metadata for this embed
API.embed.getEmbedMetadata({ id: this.props.codeID }).then(data => {
this.setState({
embedName: data.meta.name,
embedLang: data.meta.language,
embedType: data.meta.embedType,
});
}).catch(err => {
this.setErrorState('Fehler beim Laden der Metadaten', ErrorTypes.EmbedLoadingError);
debug(err);
});
}
/**
* Generates svg of code line pattern
* @param {number} xOffset horizontal offset of code lines
* @param {number} yOffset vertical offset of code lines
* @param {number} patternHeight for additional vertical offset (currently used for creating multiple patterns in a loop). Might be replaced by yOffset
* @param {number} patternMulti multiplicator of patternHeight. Will be removed if patternHeight is removed
* @returns {Array} containing svg code elements of pattern
*/
generatePattern(xOffset, yOffset, patternHeight, patternMulti) {
const pattern = [];
const offset = patternMulti * patternHeight + yOffset;
pattern.push(<rect key={`${this.props.codeID}-pattern-rect-1`} x={0 + xOffset} y={0 + offset} width="67.0175439" height="11.9298746" rx="2"></rect>);
pattern.push(<rect key={`${this.props.codeID}-pattern-rect-2`} x={76.8421053 + xOffset} y={0 + offset} width="140.350877" height="11.9298746" rx="2"></rect>);
pattern.push(<rect key={`${this.props.codeID}-pattern-rect-3`} x={18.9473684 + xOffset} y={47.7194983 + offset} width="100.701754" height="11.9298746" rx="2"></rect>);
pattern.push(<rect key={`${this.props.codeID}-pattern-rect-4`} x={0 + xOffset} y={71.930126 + offset} width="37.8947368" height="11.9298746" rx="2"></rect>);
pattern.push(<rect key={`${this.props.codeID}-pattern-rect-5`} x={127.017544 + xOffset} y={48.0703769 + offset} width="53.3333333" height="11.9298746" rx="2"></rect>);
pattern.push(<rect key={`${this.props.codeID}-pattern-rect-6`} x={187.719298 + xOffset} y={48.0703769 + offset} width="72.9824561" height="11.9298746" rx="2"></rect>);
pattern.push(<rect key={`${this.props.codeID}-pattern-rect-7`} x={17.8947368 + xOffset} y={23.8597491 + offset} width="140.350877" height="11.9298746" rx="2"></rect>);
pattern.push(<rect key={`${this.props.codeID}-pattern-rect-8`} x={166.315789 + xOffset} y={23.8597491 + offset} width="173.684211" height="11.9298746" rx="2"></rect>);
return pattern;
}
/**
* Generates svg Overlay
* @param {number} height height of the whole svg graphic
* @param {string} headline text which shall be showed in the headline
* @param {string} headlineColor background color of the headline text in form of #rrggbb
* @param {string} fontColor font color of the headline text in form of #rrggbb
* @param {string} state state of the overlay to render things like loader
* @return {void}
*/
generateSVGOverlay(height, headline, headlineColor, fontColor, state) {
const draw = [];
const patternHeight = 96;
let stateDraw;
switch (state) {
case 'downloading': {
stateDraw = '';
break;
}
case 'notLoaded': {
stateDraw = <image xlinkHref="/public/img/download.png" x="50%" y="50%" height="75" width="75" transform="translate(-37.5,-37.5)"/>;
break;
}
default: {
stateDraw = '';
break;
}
}
headlineColor = (headlineColor) ? headlineColor : '#ececec';
fontColor = (fontColor) ? fontColor : '#000';
for (let i = 0; i < ((height - 58) / patternHeight) - 1; i++) {
draw.push(this.generatePattern(55, 40, patternHeight, i));
}
const svg = <svg aria-hidden="true" width="100%" height={height} version="1.1" xmlns="http://www.w3.org/2000/svg" xmlnsXlink="http://www.w3.org/1999/xlink" className="diff-placeholder-svg position-absolute bottom-0">
<rect className="js-diff-placeholder" x="0" y="0" width="100%" height="35" fill={headlineColor} fillRule="evenodd" />
<text x="50%" y="25" fill={fontColor} fontSize="18" fontWeight="700" textAnchor="middle">{headline}</text>
<rect className="js-diff-placeholder" x="0" y="35" width="44" height={height - 58} fill="#e8e8e8" fillRule="evenodd"></rect>
<path className="js-diff-placeholder" clipPath={`url(#diff-placeholder-${this.props.codeID})`} d={`M0 0h1200v${height}H0z`} fill="#ccc" fillRule="evenodd"></path>
<clipPath id={`diff-placeholder-${this.props.codeID}`}>
{draw}
</clipPath>
<rect className="js-diff-placeholder" x="0" y={height - 24} width="100%" height={24} fill="#007ACC" fillRule="evenodd"></rect>
{stateDraw}
</svg>;
return svg;
}
/**
* Generates embed window to render. Content depens on the current state
* @returns {React.Node} embed window
*/
generateEmbedWindowByState() {
let stateIndicator = '';
let classNames = '';
let headlineMessage = '';
let overlay = '';
let clickEvent = null;
classNames = (!this.state.codeData) ? 'downloadEmbed' : '';
if (this.state.error == null) {
stateIndicator = (!this.state.isDownloading) ? '' : <Loader type="line-scale" />;
headlineMessage = `${this.state.embedName} - ${this.state.embedLang}`;
clickEvent = this.onClick;
overlay = this.generateSVGOverlay(this.props.height, headlineMessage, null, null, (!this.state.isDownloading) ? 'notLoaded' : 'downloading');
} else if (this.state.errorType == ErrorTypes.EmbedLoadingError) {
stateIndicator = (!this.state.isDownloading) ? <i className="fa fa-3x fa-repeat" aria-hidden="true"></i> : <Loader type="line-scale" />;
headlineMessage = this.state.error;
clickEvent = this.getAndSetEmbedMetadata;
overlay = this.generateSVGOverlay(this.props.height, headlineMessage, '#f00', '#fff');
} else {
stateIndicator = <span className="lead">Ok</span>;
headlineMessage = this.state.error;
clickEvent = this.onDownloadErrorNoticed;
overlay = this.generateSVGOverlay(this.props.height, headlineMessage, '#f00', '#fff');
}
return <div className={`container ${classNames}`} style={{ height: `${this.props.height}px` }} onClick={clickEvent}>
{stateIndicator}
{overlay}
</div>;
}
/**
* Creates html code to render depending on current state.
* @returns {React.Node} IdeWrapper Node
*/
renderIdeWrapper() {
let toRender;
if ((this.state.codeData == null || this.state.IdeComponent == null) || this.state.error != null) { // check if embed data has been loaded
return this.generateEmbedWindowByState();
} else {
// save the messageListModel in the state, and use only one => do not recreate
if (this.messageList == null) {
this.messageList = new MessageListModel(usageConsole);
}
const projectData = {
embed: this.state.codeData.INITIAL_DATA,
user: this.state.codeData.USER_DATA,
messageList: this.messageList,
remoteDispatcher: this.context.remoteDispatcher,
};
// Get project out of state, as it might be possible that this components does rerender
// if we recreate the project, it might happen that the other components do not unmount and therefore
// do not update their event listeners causing the UI to freeze!
//let project = this.state.project;
if (this.project == null) {
if (this.state.embedType === EmbedTypes.Sourcebox) {
this.project = new SourceboxProject(projectData, {
auth: this.state.codeData.sourcebox.authToken,
server: this.state.codeData.sourcebox.server,
transports: this.state.codeData.sourcebox.transports || ['websocket']
});
} else if (this.state.embedType === EmbedTypes.Skulpt) {
this.project = new SkulptProject(projectData);
}
}
toRender = <div className="col-12" id={`ide-container-${this.props.codeID}`} style={{ height: `${this.props.height}px` }}><Ide project={this.project} messageList={this.messageList} noWindowHandlers={true}/></div>;
}
return toRender;
}
/**
* Renders component
*
* @returns {React.Node} rendered node
*/
render() {
return this.renderIdeWrapper();
}
} |
JavaScript | class CircIdenticon {
constructor(name) {
this.name = name;
this.colors = [
"AliceBlue",
"AntiqueWhite",
"Aqua",
"Aquamarine",
"Azure",
"Beige",
"Bisque",
"BlanchedAlmond",
"Blue",
"BlueViolet",
"Brown",
"BurlyWood",
"CadetBlue",
"Chartreuse",
"Chocolate",
"Coral",
"CornflowerBlue",
"Cornsilk",
"Crimson",
"Cyan",
"DodgerBlue",
"FloralWhite",
"ForestGreen",
"Fuschia",
"Gainsboro",
"GhostWhite",
"Gold",
"GoldenRod",
"Green",
"GreenYellow",
"HoneyDew",
"HotPink",
"IndianRed",
"Ivory",
"Khaki",
"Lavender",
"LavenderBlush",
"LawnGreen",
"LemonChiffon",
"LightBlue",
"LightCoral",
"LightCyan",
"LightGoldenRodYellow",
"LightGray",
"LightGreen",
"LightPink",
"LightSalmon",
"LightSeaGreen",
"LightSkyBlue",
"LightSlateGray",
"LightYellow",
"Lime",
"LimeGreen",
"Linen",
"Magenta",
"Yellow",
"YellowGreen",
"Red",
"Salmon",
"SandyBrown",
"SeaGreen",
"SlateBlue",
"Teal",
"Violet",
"Purple",
"Plum"
];
this.bgColors = [
"Black",
"DarkSlateGrey",
"DarkBlue",
"DarkSlateBlue",
"DarkOliveGreen",
"LightSteeleBlue",
"DimGray",
"FireBrick",
"Indigo",
"Maroon",
"Navy",
"DimGrey",
"MidnightBlue",
"DarkGreen"
];
this.symmetrical = true;
this.petals=[];
}
buildSVG() {
var result = `<svg version="1.1" id="identicon" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 100 100" enable-background="new 0 0 100 100" xml:space="preserve">`;
result += this.createIdenticon() + "</svg>";
return result;
}
getPoint(angle, r) {
var result = {};
if (r == null) {
r = 50;
}
result.x = 50 + (r * Math.cos(angle));
result.y = 50 + (r * Math.sin(angle));
return result
}
selColor(rng, c) {
var index = Math.floor(rng() * c.length);
return c[index];
};
drawItem(item) {
return `<path d="M 50,50 Q ${item.leftP.x},${item.leftP.y} ${item.mainP.x},${item.mainP.y} z M 50,50 Q ${item.rightP.x},${item.rightP.y} ${item.mainP.x},${item.mainP.y} z" fill="${item.color}" stroke="${item.color}" stroke-width="1"/>`;
};
createIdenticon() {
var radius = 48;
var rng = new Math.seedrandom(this.name);
var count = Math.round(rng() * 4) + 3;
this.petals = [];
for (var i = 0; i < count; ++i) {
var item = {}
var mainAngle = rng() * Math.PI * 2;
var leftAngle = 0;
var rightAngle = 0;
if (this.symmetrical) {
var delta = (Math.PI / 8) * rng();
leftAngle = mainAngle - (Math.PI / 8) - delta;
rightAngle = mainAngle + (Math.PI / 8) + delta;
item.delta = delta;
} else {
leftAngle = mainAngle - (Math.PI / 8) - ((Math.PI / 8) * rng());
rightAngle = mainAngle + (Math.PI / 8) + ((Math.PI / 8) * rng());
}
item.leftRad = rng()*radius;
item.rightRad = (this.symmetrical) ? item.leftRad : rng()*radius;
item.mainP = this.getPoint(mainAngle, rng()*(radius/2)+(radius/2));
item.leftP = this.getPoint(leftAngle, item.leftRad);
item.rightP = this.getPoint(rightAngle, item.rightRad);
item.color = this.selColor(rng, this.colors);
item.mainAngle = mainAngle;
item.leftAngle = leftAngle;
item.rightAngle = rightAngle;
this.petals.push(item);
}
var bgColor = this.selColor(rng, this.bgColors);
var strokeColor = "Black";
if (rng() > 0.5) {
strokeColor = bgColor
}
var html = `<circle cx="50" cy="50" r="${radius}" fill="${bgColor}" stroke="${strokeColor}" stroke-width="2.5" />`;
if (rng() > 0.25) {
var cent = rng() * ((radius-6)/1.6);
var delta = rng() * Math.min(cent, radius - cent);
var bandColor = bgColor;
while (bandColor == bgColor) {
bandColor = this.selColor(rng,this.bgColors);
}
var band = `<circle cx="50" cy="50" r="${cent + delta + 6}" fill="${bandColor}" />`;
band += `<circle cx="50" cy="50" r="${cent - delta + 6}" fill="${bgColor}" />`;
html += band;
}
var curve = "";
for (var i = 0; i < count; ++i ) {
curve += this.drawItem(this.petals[i]);
}
return html + curve + `<circle cx="50" cy="50" r="${radius / 8}" fill="${strokeColor}" />`;
};
} |
JavaScript | class PropertyFeatures {
/**
* Constructs a new <code>PropertyFeatures</code>.
* @alias module:model/PropertyFeatures
* @param requiredFeatures {module:model/RequiredFeatures}
*/
constructor(requiredFeatures) {
PropertyFeatures.initialize(this, requiredFeatures);
}
/**
* 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, requiredFeatures) {
obj['requiredFeatures'] = requiredFeatures;
}
/**
* Constructs a <code>PropertyFeatures</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/PropertyFeatures} obj Optional instance to populate.
* @return {module:model/PropertyFeatures} The populated <code>PropertyFeatures</code> instance.
*/
static constructFromObject(data, obj) {
if (data) {
obj = obj || new PropertyFeatures();
if (data.hasOwnProperty('requiredFeatures')) {
obj['requiredFeatures'] = RequiredFeatures.constructFromObject(data['requiredFeatures']);
}
if (data.hasOwnProperty('additionalFeatures')) {
obj['additionalFeatures'] = AdditionalFeatures.constructFromObject(data['additionalFeatures']);
}
}
return obj;
}
} |
JavaScript | class CanvasFeature extends Feature {
/**
* Constructs a new Canvas feature.
*/
constructor() {
super("Canvas");
/**
* Indicates whether the Canvas feature is supported.
*
* @type {Boolean}
*/
this.supported = (this.root.CanvasRenderingContext2D !== undefined);
}
} |
JavaScript | class Person {
constructor(name,age) {
this.name = name;
this.age = age;
}
print(){
console.log(this.name,this.age);
}
info(){
return this.name,this.age;
}
} |
JavaScript | class DotNode extends Circle {
/**
* @param {number} pageNumber - page number that the dot is associated with
* @param {number} radius
* @param {Object} [options]
*/
constructor( pageNumber, radius, options ) {
super( radius, options );
this.pageNumber = pageNumber; // @public (read-only)
}
} |
JavaScript | class BubbleSort extends SortingAlgorithm {
/**
* Creates a new BubbleSort instance.
*/
constructor() {
super();
}
/**
* Sorts the given array and updates statistics/description fields.
* @param {toSort} toSort - Object containing array to be sorted, and additional parameters
* @returns void
*/
async sort(toSort) {
super.sort(toSort);
await this.bsort(toSort.arr);
this.info.calculateRuntime();
}
/**
* Returns a description of the bubble sort algorithm.
* @returns {Object} - See {@link AlgorithmStats}
*/
getDescriptions() {
return {
name: 'Bubble Sort',
about: "Often used as a teaching tool, bubble sort is very slow. It sorts a given array by comparing neighboring elements and 'bubbling' the larger element up towards the final position. Even with some optimizations, this still lacks efficiency and is not often used in practice.",
best: 'n',
avg: '1/2 n^2',
worst: '1/2 n^2',
inPlace: true,
stable: true,
}
}
/**
* Sorts the given array using the bubble sort algorithm.
* Also manages the state of items for display purposes.
* @param {number[]} arr - Array to be sorted
* @returns void
*/
async bsort(arr) {
let n = arr.length;
this.states.fill('being sorted');
while (n > 1) {
let sortedAfterIndex = 0;
for (let i = 1; i < n; i++) {
if (arr[i - 1] > arr[i]) await exchange(arr, i - 1, i, this);
this.info.compares++;
sortedAfterIndex = i;
}
this.states[sortedAfterIndex] = 'default';
n = sortedAfterIndex;
}
}
} |
JavaScript | class YearPicker extends CalendarPart {
static get metadata() {
return metadata;
}
static get styles() {
return styles;
}
static get template() {
return YearPickerTemplate;
}
onBeforeRendering() {
this._buildYears();
}
_buildYears() {
if (this._hidden) {
return;
}
const oYearFormat = DateFormat.getDateInstance({ format: "y", calendarType: this._primaryCalendarType }, getLocale());
this._calculateFirstYear();
this._lastYear = this._firstYear + PAGE_SIZE - 1;
const calendarDate = this._calendarDate; // store the value of the expensive getter
const minDate = this._minDate; // store the value of the expensive getter
const maxDate = this._maxDate; // store the value of the expensive getter
const tempDate = new CalendarDate(calendarDate, this._primaryCalendarType);
tempDate.setYear(this._firstYear);
const intervals = [];
let timestamp;
/* eslint-disable no-loop-func */
for (let i = 0; i < PAGE_SIZE; i++) {
timestamp = tempDate.valueOf() / 1000;
const isSelected = this.selectedDates.some(itemTimestamp => {
const date = CalendarDate.fromTimestamp(itemTimestamp * 1000, this._primaryCalendarType);
return date.getYear() === tempDate.getYear();
});
const isFocused = tempDate.getYear() === calendarDate.getYear();
const isDisabled = tempDate.getYear() < minDate.getYear() || tempDate.getYear() > maxDate.getYear();
const year = {
timestamp: timestamp.toString(),
_tabIndex: isFocused ? "0" : "-1",
focusRef: isFocused,
selected: isSelected,
ariaSelected: isSelected ? "true" : "false",
year: oYearFormat.format(tempDate.toLocalJSDate()),
disabled: isDisabled,
classes: "ui5-yp-item",
};
if (isSelected) {
year.classes += " ui5-yp-item--selected";
}
if (isDisabled) {
year.classes += " ui5-yp-item--disabled";
}
const intervalIndex = parseInt(i / ROW_SIZE);
if (intervals[intervalIndex]) {
intervals[intervalIndex].push(year);
} else {
intervals[intervalIndex] = [year];
}
tempDate.setYear(tempDate.getYear() + 1);
}
this._years = intervals;
}
_calculateFirstYear() {
const absoluteMaxYear = getMaxCalendarDate(this._primaryCalendarType).getYear(); // 9999
const currentYear = this._calendarDate.getYear();
// 1. If first load - center the current year (set first year to be current year minus half page size)
if (!this._firstYear) {
this._firstYear = currentYear - PAGE_SIZE / 2;
}
// 2. If out of range - change by a page (20) - do not center in order to keep the same position as the last page
if (currentYear < this._firstYear) {
this._firstYear -= PAGE_SIZE;
} else if (currentYear >= this._firstYear + PAGE_SIZE) {
this._firstYear += PAGE_SIZE;
}
// 3. If the date was changed by more than 20 years - reset _firstYear completely
if (Math.abs(this._firstYear - currentYear) >= PAGE_SIZE) {
this._firstYear = currentYear - PAGE_SIZE / 2;
}
// Keep it in the range between the min and max year
this._firstYear = Math.max(this._firstYear, this._minDate.getYear());
this._firstYear = Math.min(this._firstYear, this._maxDate.getYear());
// If first year is > 9980, make it 9980 to not show any years beyond 9999
if (this._firstYear > absoluteMaxYear - PAGE_SIZE + 1) {
this._firstYear = absoluteMaxYear - PAGE_SIZE + 1;
}
}
onAfterRendering() {
if (!this._hidden) {
this.focus();
}
}
_onkeydown(event) {
let preventDefault = true;
if (isEnter(event)) {
this._selectYear(event);
} else if (isSpace(event)) {
event.preventDefault();
} else if (isLeft(event)) {
this._modifyTimestampBy(-1);
} else if (isRight(event)) {
this._modifyTimestampBy(1);
} else if (isUp(event)) {
this._modifyTimestampBy(-ROW_SIZE);
} else if (isDown(event)) {
this._modifyTimestampBy(ROW_SIZE);
} else if (isPageUp(event)) {
this._modifyTimestampBy(-PAGE_SIZE);
} else if (isPageDown(event)) {
this._modifyTimestampBy(PAGE_SIZE);
} else if (isHome(event) || isEnd(event)) {
this._onHomeOrEnd(isHome(event));
} else if (isHomeCtrl(event)) {
this._setTimestamp(parseInt(this._years[0][0].timestamp)); // first year of first row
} else if (isEndCtrl(event)) {
this._setTimestamp(parseInt(this._years[PAGE_SIZE / ROW_SIZE - 1][ROW_SIZE - 1].timestamp)); // last year of last row
} else {
preventDefault = false;
}
if (preventDefault) {
event.preventDefault();
}
}
_onHomeOrEnd(homePressed) {
this._years.forEach(row => {
const indexInRow = row.findIndex(item => CalendarDate.fromTimestamp(parseInt(item.timestamp) * 1000).getYear() === this._calendarDate.getYear());
if (indexInRow !== -1) { // The current year is on this row
const index = homePressed ? 0 : ROW_SIZE - 1; // select the first (if Home) or last (if End) year on the row
this._setTimestamp(parseInt(row[index].timestamp));
}
});
}
/**
* Sets the timestamp to an absolute value
* @param value
* @private
*/
_setTimestamp(value) {
this._safelySetTimestamp(value);
this.fireEvent("navigate", { timestamp: this.timestamp });
}
/**
* Modifies timestamp by a given amount of years and, if necessary, loads the prev/next page
* @param amount
* @private
*/
_modifyTimestampBy(amount) {
// Modify the current timestamp
this._safelyModifyTimestampBy(amount, "year");
// Notify the calendar to update its timestamp
this.fireEvent("navigate", { timestamp: this.timestamp });
}
_onkeyup(event) {
if (isSpace(event)) {
this._selectYear(event);
}
}
/**
* User clicked with the mouser or pressed Enter/Space
* @param event
* @private
*/
_selectYear(event) {
event.preventDefault();
if (event.target.className.indexOf("ui5-yp-item") > -1) {
const timestamp = this._getTimestampFromDom(event.target);
this._safelySetTimestamp(timestamp);
this.fireEvent("change", { timestamp: this.timestamp });
}
}
/**
* Called from Calendar.js
* @protected
*/
_hasPreviousPage() {
return this._firstYear > this._minDate.getYear();
}
/**
* Called from Calendar.js
* @protected
*/
_hasNextPage() {
return this._firstYear + PAGE_SIZE - 1 < this._maxDate.getYear();
}
/**
* Called by Calendar.js
* User pressed the "<" button in the calendar header (same as PageUp)
* @protected
*/
_showPreviousPage() {
this._modifyTimestampBy(-PAGE_SIZE);
}
/**
* Called by Calendar.js
* User pressed the ">" button in the calendar header (same as PageDown)
* @protected
*/
_showNextPage() {
this._modifyTimestampBy(PAGE_SIZE);
}
} |
JavaScript | class LoadingOverlay extends Component {
static propTypes = {
style: PropTypes.object,
showSpinner: PropTypes.bool,
dataQa: PropTypes.string
};
static defaultProps = {
showSpinner: true
};
render() {
const {
showSpinner,
style,
dataQa
} = this.props;
return (
<div className='view-state-wrapper-overlay' style={style} data-qa={dataQa}>
{showSpinner && <Spinner />}
</div>
);
}
} |
JavaScript | class ArrowDirectionButton extends Base {
get updates() {
const style = Object.assign(
{
background: '',
color: 'rgba(255, 255, 255, 0.7)'
},
this.state.hover && !this.state.innerAttributes.disabled && {
background: 'rgba(255, 255, 255, 0.2)',
color: 'rgba(255, 255, 255, 0.8)',
cursor: 'pointer'
},
this.state.innerAttributes.disabled && {
color: 'rgba(255, 255, 255, 0.3)'
}
);
return merge(super.updates, {
style
});
}
get [symbols.template]() {
return `
<style>
:host {
display: flex;
-webkit-tap-highlight-color: transparent;
}
#inner {
background: transparent;
border: none;
box-sizing: border-box;
color: inherit;
fill: currentColor;
flex: 1;
font-family: inherit;
font-size: inherit;
font-weight: inherit;
margin: 0;
outline: none;
padding: 0;
position: relative;
}
</style>
<button id="inner">
<slot></slot>
</button>
`;
}
} |
JavaScript | class Database {
constructor() {
this.connection = mysql.createConnection({
host: '127.0.0.1',
user: 'root',
password: '12345678',
database: 'tracker_db'
});
}
//Made query() to a promise
query(sql, args) {
return new Promise((resolve, reject) => {
this.connection.query(sql, args, (err, rows) => {
if (err)
return reject(err);
resolve(rows);
});
});
}
//Made end() to a promise
close() {
return new Promise((resolve, reject) => {
this.connection.end(err => {
if (err)
return reject(err);
resolve();
});
});
}
} |
JavaScript | class effectTimer {
/**
*
* @param {number} time
* @param {number} frequency
* @param {Function} action
* @param {Function} uncast
*/
constructor(time, frequency, cast, uncast, action) {
const ticks = Math.floor(time / TICK_INTERVAL);
this.cast = cast;
this.uncast = uncast;
this.action = action;
if (ticks < 1)
throw new Error(`some error has occur`);
this._frequency = frequency;
this._frequencyLeft = frequency;
this._ticksLeft = ticks;
this._maxTicks = ticks;
}
tick(target) {
if (this._frequencyLeft) {
this._ticksLeft--;
if (this._ticksLeft === 0) {
if (this._frequencyLeft) {
this._ticksLeft = this._maxTicks;
this._frequencyLeft--;
this.action(target);
if (this._frequencyLeft === 0) {
this.uncast(target);
}
}
}
}
}
} |
JavaScript | class Skill extends effectContainer {
constructor() {
super();
}
spellTo(target) {
for (let effect of this.effectsList) {
effect.cast(target);
}
}
tick() {
for (let effect of this.effectsList) {
effect.tick();
}
}
} |
JavaScript | class ContentDetail extends Component {
constructor(props) {
super(props);
/* Get the content from the props and save it in the local state */
let new_object = Object.assign({}, props.content)
this.state = {
// Content that can be removed in this component
content: new_object
}
}
/**
* Hides the remove button for this content
* calls the unClickContent function of the parent via props
*/
closeDetails() {
this.props.unClickContent();
}
/**
* The content that is selected gets removed in the backend
* via the removeContentSuperuser action (Superuser -> ContentList -> ContentDetail)
*/
removeContent() {
/* Get the token from the cookie for superuser authorization */
let token = cookies.get('token');
/* Call the removeContentSuperuser action via props */
this.props.removeContentSuperuser(this.state.content.id, token)
}
render() {
return(
<div className="superuser-userdetail">
<div className="btn-group">
<button onClick={() => this.removeContent()} className="btn btn-red">Remove content</button>
<button onClick={() => this.closeDetails()} className="btn btn-green">Close Details</button>
</div>
</div>
)
}
} |
JavaScript | class TouchSensor extends Sensor {
/**
* TouchSensor constructor.
* @constructs TouchSensor
* @param {HTMLElement[]|NodeList|HTMLElement} containers - Containers
* @param {Object} options - Options
*/
constructor(containers = [], options = {}) {
super(containers, options);
/**
* Closest scrollable container so accidental scroll can cancel long touch
* @property currentScrollableParent
* @type {HTMLElement}
*/
this.currentScrollableParent = null;
/**
* TimeoutID for managing delay
* @property tapTimeout
* @type {Number}
*/
this.tapTimeout = null;
/**
* touchMoved indicates if touch has moved during tapTimeout
* @property touchMoved
* @type {Boolean}
*/
this.touchMoved = false;
/**
* Save pageX coordinates for delay drag
* @property {Numbre} pageX
* @private
*/
this.pageX = null;
/**
* Save pageY coordinates for delay drag
* @property {Numbre} pageY
* @private
*/
this.pageY = null;
this[onTouchStart] = this[onTouchStart].bind(this);
this[onTouchEnd] = this[onTouchEnd].bind(this);
this[onTouchMove] = this[onTouchMove].bind(this);
this[startDrag] = this[startDrag].bind(this);
this[onDistanceChange] = this[onDistanceChange].bind(this);
}
/**
* Attaches sensors event listeners to the DOM
*/
attach() {
document.addEventListener('touchstart', this[onTouchStart]);
}
/**
* Detaches sensors event listeners to the DOM
*/
detach() {
document.removeEventListener('touchstart', this[onTouchStart]);
}
/**
* Touch start handler
* @private
* @param {Event} event - Touch start event
*/
[onTouchStart](event) {
const container = closest(event.target, this.containers);
if (!container) {
return;
}
if (this.options.handle && event.target && !closest(event.target, this.options.handle)) {
return;
}
const originalSource = closest(event.target, this.options.draggable);
if (!originalSource) {
return;
}
const {distance = 0} = this.options;
const {delay} = this;
const {pageX, pageY} = touchCoords(event);
Object.assign(this, {pageX, pageY});
this.onTouchStartAt = Date.now();
this.startEvent = event;
this.currentContainer = container;
this.originalSource = originalSource;
document.addEventListener('touchend', this[onTouchEnd]);
document.addEventListener('touchcancel', this[onTouchEnd]);
document.addEventListener('touchmove', this[onDistanceChange]);
container.addEventListener('contextmenu', onContextMenu);
if (distance) {
preventScrolling = true;
}
this.tapTimeout = window.setTimeout(() => {
this[onDistanceChange]({touches: [{pageX: this.pageX, pageY: this.pageY}]});
}, delay.touch);
}
/**
* Start the drag
* @private
*/
[startDrag]() {
const startEvent = this.startEvent;
const container = this.currentContainer;
const touch = touchCoords(startEvent);
const originalSource = this.originalSource;
const dragStartEvent = new DragStartSensorEvent({
clientX: touch.pageX,
clientY: touch.pageY,
target: startEvent.target,
container,
originalSource,
originalEvent: startEvent,
});
this.trigger(this.currentContainer, dragStartEvent);
this.dragging = !dragStartEvent.canceled();
if (this.dragging) {
document.addEventListener('touchmove', this[onTouchMove]);
}
preventScrolling = this.dragging;
}
/**
* Touch move handler prior to drag start.
* @private
* @param {Event} event - Touch move event
*/
[onDistanceChange](event) {
const {distance} = this.options;
const {startEvent, delay} = this;
const start = touchCoords(startEvent);
const current = touchCoords(event);
const timeElapsed = Date.now() - this.onTouchStartAt;
const distanceTravelled = euclideanDistance(start.pageX, start.pageY, current.pageX, current.pageY);
Object.assign(this, current);
clearTimeout(this.tapTimeout);
if (timeElapsed < delay.touch) {
// moved during delay
document.removeEventListener('touchmove', this[onDistanceChange]);
} else if (distanceTravelled >= distance) {
document.removeEventListener('touchmove', this[onDistanceChange]);
this[startDrag]();
}
}
/**
* Mouse move handler while dragging
* @private
* @param {Event} event - Touch move event
*/
[onTouchMove](event) {
if (!this.dragging) {
return;
}
const {pageX, pageY} = touchCoords(event);
const target = document.elementFromPoint(pageX - window.scrollX, pageY - window.scrollY);
const dragMoveEvent = new DragMoveSensorEvent({
clientX: pageX,
clientY: pageY,
target,
container: this.currentContainer,
originalEvent: event,
});
this.trigger(this.currentContainer, dragMoveEvent);
}
/**
* Touch end handler
* @private
* @param {Event} event - Touch end event
*/
[onTouchEnd](event) {
clearTimeout(this.tapTimeout);
preventScrolling = false;
document.removeEventListener('touchend', this[onTouchEnd]);
document.removeEventListener('touchcancel', this[onTouchEnd]);
document.removeEventListener('touchmove', this[onDistanceChange]);
if (this.currentContainer) {
this.currentContainer.removeEventListener('contextmenu', onContextMenu);
}
if (!this.dragging) {
return;
}
document.removeEventListener('touchmove', this[onTouchMove]);
const {pageX, pageY} = touchCoords(event);
const target = document.elementFromPoint(pageX - window.scrollX, pageY - window.scrollY);
event.preventDefault();
const dragStopEvent = new DragStopSensorEvent({
clientX: pageX,
clientY: pageY,
target,
container: this.currentContainer,
originalEvent: event,
});
this.trigger(this.currentContainer, dragStopEvent);
this.currentContainer = null;
this.dragging = false;
this.startEvent = null;
}
} |
JavaScript | class MarkdownExternalUrlChecker {
static async execute() {
const files = glob.sync("./source/**/@(*.md|*.mdx)", {
ignore: excludedFolders,
});
console.log(`Found ${files.length} markdown files. Collecting all external urls...`);
const filesWithUrls = [];
files.forEach((file) => {
const result = this.retrieveAllUrls(file);
if (result) {
filesWithUrls.push(result);
}
});
const results = await this.testUrls(filesWithUrls);
const hasInvalidUrls = this.logResults(results);
if (hasInvalidUrls) {
core.setFailed("Found invalid URLs. Please check the log output for more details.");
}
process.exit(hasInvalidUrls ? 1 : 0);
}
//----------------------------------
// Methods
//----------------------------------
static async testUrls(files) {
browser = await puppeteer.launch({
args: ["--no-sandbox", "--disable-setuid-sandbox"],
headless: true,
});
let urlInc = 0;
const numUrls = files.map((obj) => obj.urls.length).reduce((partial, sum) => partial + sum, 0);
core.startGroup(`Found ${numUrls} urls within ${files.length} files. Validating URLs...`);
const responseCache = {};
for (let f = 0, flen = files.length; f < flen; f++) {
const { urls } = files[f];
for (let u = 0, ulen = urls.length; u < ulen; u++) {
const url = urls[u];
if (!responseCache[url]) {
responseCache[url] = await this.evaluateUrl(url);
await this.sleep(SITE_REQUEST_INTERVAL);
}
files[f].urls[u] = { url, response: responseCache[url] };
urlInc += 1;
const percentage = Math.round((urlInc / numUrls) * 100);
console.log(`Progress: ${percentage}% (${urlInc}/${numUrls})`);
}
}
await browser.close();
core.endGroup();
browser = null;
return files;
}
static evaluateUrl(url, originStatus = null) {
return new Promise(async (resolve) => {
const page = await browser.newPage();
page.once("response", async (response) => {
const status = response.status();
const headers = response.headers();
if ([301, 307].includes(status)) {
const resp = await this.evaluateUrl(headers.location, status);
resolve(resp);
} else if (originStatus) {
resolve({ status: originStatus, redirectionStatus: response.status(), redirection: response.url() });
} else {
resolve({ status: response.status() });
}
});
page.once("pageerror", async (err) => {
resolve({ error: err.message });
});
try {
await page.goto(url, { waitUntil: "load" });
} catch (err) {
resolve({ error: err.message });
}
await page.close();
resolve({ error: "Unknown exception occured" });
});
}
static retrieveAllUrls(path) {
const urls = [];
const md = fs.readFileSync(path, { encoding: "utf-8" });
const matches = md.match(/\[(.+)]\((http[^ ]+?)( "(.+)")?\)/gm);
if (matches) {
matches.forEach((url) => {
urls.push(url.replace(/\[.*]\(|\)/gm, ""));
});
}
return urls.length > 0 ? { path, urls } : null;
}
//----------------------------------
// Helper Methods
//----------------------------------
static sleep(ms) {
return new Promise((resolve) => {
setTimeout(resolve, ms);
});
}
static logResults(results) {
let hasInvalidUrls = false;
results.forEach((file) => {
const messages = [];
file.urls.forEach((obj) => {
const url = obj.url;
const response = obj.response;
let message = null;
switch (response.status) {
case 502: {
hasInvalidUrls = true;
message = {
type: "error",
msg: `${style.red.open}${style.bold.open}Bad Gateway (502):${style.bold.close}${style.red.close} ${url}`,
};
break;
}
case 404: {
hasInvalidUrls = true;
message = {
type: "error",
msg: `${style.red.open}${style.bold.open}Not Found (404):${style.bold.close}${style.red.close} ${url}`,
};
break;
}
case 301: {
message = {
type: "warn",
msg: `${url} ${style.yellow.open}${style.bold.open}moved permanently (301) to:${style.bold.close}${style.yellow.close} ${response.redirection}`,
};
break;
}
case 307: {
message = {
type: "info",
msg: `${url} ${style.cyan.open}${style.bold.open}moved temporarily (307) to:${style.bold.close}${style.cyan.close} ${response.redirection}`,
};
break;
}
case 429: {
message = {
type: "info",
msg: `${style.cyan.open}${style.bold.open}Too Many Requests (429):${style.bold.close}${style.cyan.close} ${url}`,
};
break;
}
default: {
// nothing to see here
}
}
if (message) {
messages.push(message);
}
});
if (messages.length > 0) {
const hasError = messages.find((msg) => msg.type === "error");
const hasWarning = messages.find((msg) => msg.type === "warn");
const hasInfo = messages.find((msg) => msg.type === "info");
if (hasError) {
core.startGroup(
style.bold.open +
style.red.open +
"━ FAIL ━ " +
style.red.close +
style.bold.close +
style.bgRed.open +
style.black.open +
file.path +
style.black.close +
style.bgRed.close,
);
} else if (hasWarning) {
core.startGroup(
style.bold.open +
style.yellow.open +
"━ WARN ━ " +
style.yellow.close +
style.bold.close +
style.bgYellow.open +
style.black.open +
file.path +
style.black.close +
style.bgYellow.close,
);
} else if (hasInfo) {
core.startGroup(
style.bold.open +
style.cyan.open +
"━ INFO ━ " +
style.cyan.close +
style.bold.close +
style.bgCyan.open +
style.black.open +
file.path +
style.black.close +
style.bgCyan.close,
);
} else {
core.startGroup(
style.bold.open +
style.white.open +
"━ PASS ━ " +
style.white.close +
style.bold.close +
style.bgWhite.open +
style.black.open +
file.path +
style.black.close +
style.bgWhite.close,
);
}
messages.forEach((message) => {
if (message.type === "error") {
console.log(`${style.red.open}${style.bold.open} ━ ${style.bold.close}${style.red.close}${message.msg}`);
} else if (message.type === "warn") {
console.log(`${style.yellow.open}${style.bold.open} ━ ${style.bold.close}${style.yellow.close}${message.msg}`);
} else if (message.type === "info") {
console.log(`${style.cyan.open}${style.bold.open} ━ ${style.bold.close}${style.cyan.close}${message.msg}`);
} else {
console.log(` ━ ${message.msg}`);
}
});
core.endGroup();
}
});
return hasInvalidUrls;
}
} |
JavaScript | class GlobalExtends {
constructor() {
this.extendsGlobalNode = undefined;
this.detectors = [
new ExtendsGlobalDetector()
];
}
/**
* Process a node and return inheritance details if found.
* @param {Object} node
* @param {Object} parent
* @returns {Object/undefined} m
* {String} m.className
* {Node} m.superClass
* {Object[]} m.relatedExpressions
*/
process(node, parent) {
let m;
if (parent && parent.type === 'Program' && (m = this.detectExtendsGlobalNode(node))) {
this.extendsGlobalNode = m;
}
else if (this.extendsGlobalNode && (m = this.matchExtendsGlobal(node))) {
return {
className: m.className,
superClass: m.superClass,
relatedExpressions: [{node, parent}]
};
}
}
detectExtendsGlobalNode(node) {
for (const detector of this.detectors) {
let inheritsNode;
if ((inheritsNode = detector.detect(node))) {
return inheritsNode;
}
}
}
// Discover usage of this.extendsGlobalNode
//
// Matches: __extends(<className>, <superClass>);
matchExtendsGlobal(node) {
return matches({
type: 'ExpressionStatement',
expression: {
type: 'CallExpression',
callee: this.extendsGlobalNode,
arguments: [
{
type: 'Identifier',
name: extractAny('className')
},
extractAny('superClass')
]
}
}, node);
}
} |
JavaScript | class ZeebeAPI {
constructor(backend) {
this.backend = backend;
}
checkConnectivity(rawEndpoint) {
const endpoint = this.extractEndpoint({ endpoint: rawEndpoint });
return this.backend.send('zeebe:checkConnectivity', { endpoint });
}
deploy(parameters) {
const endpoint = this.extractEndpoint(parameters);
return this.backend.send('zeebe:deploy', { ...parameters, endpoint });
}
run(parameters) {
const endpoint = this.extractEndpoint(parameters);
return this.backend.send('zeebe:run', { ...parameters, endpoint });
}
extractEndpoint(parameters) {
const {
authType,
audience,
targetType,
clientId,
clientSecret,
oauthURL,
contactPoint,
camundaCloudClientId,
camundaCloudClientSecret,
camundaCloudClusterId
} = parameters.endpoint;
if (targetType === 'selfHosted') {
if (authType === 'none') {
return {
type: 'selfHosted',
url: contactPoint || '',
};
} else if (authType === 'oauth') {
return {
type: 'oauth',
url: contactPoint,
oauthURL,
audience,
clientId,
clientSecret
};
}
} else if (targetType === 'camundaCloud') {
return {
type: 'camundaCloud',
clientId: camundaCloudClientId,
clientSecret: camundaCloudClientSecret,
clusterId: camundaCloudClusterId
};
}
}
} |
JavaScript | class businessProfile extends React.Component {
/**
* @param {object} props - props no need to pass any arguments
*/
constructor(props) {
super(props);
this.state = {
visible: false,
jobList: [],
companyName: null,
companyWebsite: null,
companyPhone: null,
companyEmail: null,
companyType: null,
headquarter: null,
videoURL: null,
companyAddress: {
addressLine1: "2968 Avenue S",
addressLine2: "",
city: "New York",
state: "NY",
postalCode: "12345"
},
ceoPic: null,
ceo: null,
size: null,
revenue: null,
timeline: [],
jobAmount: 0,
description: null,
companyLogo: null,
companyPic: "no",
value: 0,
allowEdit: false
}
}
/**
* fetch all data from AWS by companyID, if the companyID is matching
* the login userid, it will render edit buttons
*/
componentWillMount = async () => {
//check if the visitor is the page owner
let companyID = this.props.userID;
let currentUser = await Auth.currentAuthenticatedUser();
const { attributes } = currentUser;
if (companyID === attributes.sub)
this.setState({ allowEdit: true });
else
this.setState({ allowEdit: false });
//set up companyID
let employerData;
try {
employerData = await API.graphql(graphqlOperation(queries.getEmployer, { id: companyID }));
this.setState({ companyID: companyID });
//set up other employer info
employerData = employerData.data.getEmployer;
for (let item in employerData) {
if (employerData[item] && item != "timeline" && item != "companyAddress" && item != "job" && item != "id") {
this.setState({ [item]: employerData[item] });
}
}
/**
* set up other employer info within nested object
* */
console.log("employer", employerData);
if (employerData.timeline.items.length >= 1)
this.setState({ timeline: employerData.timeline.items });
if (employerData.job.items.length >= 1) {
this.setState({ jobList: employerData.job.items });
this.setState({ jobAmount: employerData.job.items.length })
}
//set up the address data
if (employerData.companyAddress) {
let addressLine1 = employerData.companyAddress.line1;
let addressLine2 = employerData.companyAddress.line2;
let city = employerData.companyAddress.city;
let postalCode = employerData.companyAddress.postalCode;
let state = employerData.companyAddress.state;
let id = employerData.companyAddress.id;
let companyAddress = {
id,
addressLine1,
addressLine2,
city,
postalCode,
state
}
this.setState({ companyAddress });
}
//fetch company logo pic
if (this.state.companyPic === 'yes') {
Storage.get('profilePic', {
level: 'protected',
identityId: this.state.userID// the identityId of that user
})
.then(result => {
this.setState({ companyLogo: result, memory: true });
console.log("set up", this.state);
})
.catch(err => console.log(err));
}
else
this.setState({ memory: true })
} catch (err) {
console.log("couldn't get employer data: ", err);
}
}
/**
* set show modal to true
*/
showModal = () => {
this.setState({
visible: true,
});
}
/**
* set visible to false for the modal component, when click ok
*/
handleOk = (e) => {
this.setState({
visible: false,
});
}
/**
* set visible to false for the modal component,when click cancel
*/
handleCancel = (e) => {
this.setState({
visible: false,
});
}
render() {
if (!this.state.memory) {
// Just wait for the memory to be available
return <Spin style={{ position: "absolute", left: "45%", top: "30%" }} tip="Please wait for a moment" />;
}
return (
<div >
<div className="bannerOne">
</div>
<div style={bodyStyle}>
<div className="secBanner">
<BusinessPicture companyLogo={this.state.companyLogo} />
<div className="companyHeader">
<h1 style={{ fontSize: "4em" }}>{this.state.companyName}</h1>
<h2 className="companyLocation">{this.state.companyAddress.city +
" " + this.state.companyAddress.state}</h2>
</div>
{this.state.allowEdit ?
<div className="busButtonGroup">
<Button className="busEditButton" onClick={this.showModal}>
{I18n.get('Edit Profile')}
</Button>
<PhotoUpload isBusiness={true} />
</div>
: null
}
</div>
<div style={{ padding: "0px 60px" }}>
<Tabs defaultActiveKey="1" >
<TabPane tab={I18n.get('Profile')} key="1" >
<div>
<div >
<EditProfileForm
data={this.state}
visible={this.state.visible}
onOk={this.handleOk}
onCancel={this.handleCancel}
/>
</div>
<div className="row1">
<div style={{ width: "65%" }}>
<About
description={this.state.description}
/>
</div>
<BriefInfo
companyWebsite={this.state.companyWebsite}
size={this.state.size}
revenue={this.state.revenue}
jobAmount={this.state.jobAmount}
companyType={this.state.companyType}
headquarter={this.state.headquarter}
/>
</div>
<div className="row2">
<Timeline timeline={this.state.timeline} />
<div style={{ width: "50%" }}>
<CeoPic
ceo={this.state.ceo}
ceoPic={this.state.ceoPic}
/>
<CompanyVideo videoURL={this.state.videoURL} videoPic={this.state.videoPic} />
</div>
</div>
</div>
</TabPane>
<TabPane tab={I18n.get('Jobs') + "(" + this.state.jobAmount + ")"} key="2">
<div >
<PostJob
jobList={this.state.jobList}
companyLogo={this.state.companyLogo} />
</div>
</TabPane>
</Tabs>
</div>
</div>
<Footer style={{ textAlign: 'center' }}>
{I18n.get('JobFirst')} ©2019 {I18n.get('Created by JobFirst Group')}
</Footer>
</div>
);
}
} |
JavaScript | class Person {
constructor(name) {
this.name = name;
}
walk() {
console.log("walk");
}
} |
JavaScript | class controlPropertyEvent {
constructor(property) {
// list of all registered callbacks on the event
this.callbacks = [];
this.property = property;
}
// register a new callback on the event
register(callback, onInit) {
this.callbacks.push({
callback,
onInit
});
}
// invoke all the callbacks
invoke(args) {
for (let i = 0; i < this.callbacks.length; ++i)
this.callbacks[i].callback(this.property, args);
}
invokeInitCallback(args) {
for (let i = 0; i < this.callbacks.length; ++i) {
if (this.callbacks[i].onInit)
this.callbacks[i].callback(this.property, args);
}
}
} |
JavaScript | class controlProperty {
constructor(control, name, value) {
// event invoked when the value is changed from the server
this.onChangedFromServer = new controlPropertyEvent(this);
// event invoked when the value is changed from the client
this.onChangedFromClient = new controlPropertyEvent(this);
this.control = control;
this.value = value;
this.name = name;
}
// calle this from the client side to send the update to the server
updateValue(newValue) {
var old = this.value;
this.value = newValue;
this.onChangedFromClient.invoke({
old: old,
new: newValue
});
core.manager.addPropertyUpdate(this);
}
callInitCallbacks() {
this.onChangedFromServer.invokeInitCallback({
old: null,
new: this.value
});
}
} |
JavaScript | class SprayTool extends ToolButton{
renderOptions(){
let div = document.getElementById(`div_${this.id}`);
if(div) return;
let numOfPointsDefault = 15;
let maxNumOfPoints = 500;
let minNumOfPoints = 10;
let spreadDefault = 15;
let maxSpread = 50;
let minSpread = 5;
let thicknessDefault = 1;
let minThickness = 1;
let maxThickness = 5;
let html =
`
<div class="tb_option">
<label for="ctrl_${this.id}_thickness">Thickness:</label>
<input type="range" min="${minThickness}" max="${maxThickness}" value="${thicknessDefault}" class="slider" id="ctrl_${this.id}_thickness">
<output id="out_${this.id}_thickness">${thicknessDefault}</output>
</div>
<div class="tb_option">
<label for="ctrl_${this.id}_numOfPoints">Number of points:</label>
<input type="range" min="${minNumOfPoints}" max="${maxNumOfPoints}" value="${numOfPointsDefault}" class="slider" id="ctrl_${this.id}_numOfPoints">
<output id="out_${this.id}_numOfPoints">${numOfPointsDefault}</output>
</div>
<div class="tb_option">
<label for="ctrl_${this.id}_spread">Spread:</label>
<input type="range" min="${minSpread}" max="${maxSpread}" value="${spreadDefault}" class="slider" id="ctrl_${this.id}_spread">
<output id="out_${this.id}_spread">${spreadDefault}</output>
</div>
`;
div = document.createElement("div");
div.id = `div_${this.id}`;
div.className = 'tb_option_container';
div.innerHTML = html;
let options = document.getElementById('options');
options.appendChild(div);
//Set thickness controls
let thicknessSlider = document.getElementById(`ctrl_${this.id}_thickness`);
let thicknessOutput = document.getElementById(`out_${this.id}_thickness`);
thicknessSlider.oninput = (event) => { //arrow function
thicknessOutput.value = event.target.value;
this.command.thickness = event.target.value;
// this.command.context.chain.strokeWeight(event.target.value);
};
//Set Number of points controls
let numOfPointsSlider = document.getElementById(`ctrl_${this.id}_numOfPoints`);
let numOfPointsOutput = document.getElementById(`out_${this.id}_numOfPoints`);
numOfPointsSlider.oninput = (event) => { //arrow function
numOfPointsOutput.value = event.target.value;
this.command.numOfPoints = event.target.value;
};
//set spread controls
let spreadSlider = document.getElementById(`ctrl_${this.id}_spread`);
let spreadOutput = document.getElementById(`out_${this.id}_spread`);
spreadSlider.oninput = (event) => { //arrow function
spreadOutput.value = event.target.value;
this.command.spread = event.target.value;
};
//get the tips div
let tips = document.getElementById('tip_content');
//prepare the html to inject into the tips div
let tipHtml = (tip)=> { return `<div id="tip_${this.id}">${tip}</div>`; };
//attach an observer to the command to detect changes in the current Tip
if(!this.command.newTipAvailableObserver){
this.command.newTipAvailableObserver = (tip)=>{
tips.innerHTML = tipHtml(tip);
};
}
//read the initial value for the tip
tips.innerHTML = tipHtml(this.command.currentTip);
this.command.numOfPoints = numOfPointsSlider.value;
this.command.spread = spreadSlider.value;
this.command.thickness = thicknessSlider.value;
// this.command.context.chain.strokeWeight(thicknessSlider.value);
}
/** Clear the placeholder for the Options in the dedicated space in the UI. */
clearOptions(){
let element = p5Instance.select(`#div_${this.id}`);
if(element){
element.remove();
this.command.context.chain.strokeWeight(1);
}
//clear tips div
let tipDiv = document.getElementById(`tip_${this.id}`);
if(tipDiv){
tipDiv.remove();
}
}
} |
JavaScript | class Employee extends Person {
static get tableName() { return 'Employee'; }
static get label() { return 'employees'; }
/** @type {Object} Working days as an object */
get workingDays() {
return {
sunday: this.working_sunday,
monday: this.working_monday,
tuesday: this.working_tuesday,
wednesday: this.working_wednesday,
thursday: this.working_thursday,
friday: this.working_friday,
saturday: this.working_saturday,
};
}
set workingDays(obj) {
for (const day in obj) {
if (Object.prototype.hasOwnProperty.call(obj, day)) {
this[`working_${day}`] = obj[day];
}
}
}
/** @type {boolean[]} */
get workingDaysArray() {
return Object.keys(this.workingDays)
.map(day => this.workingDays[day]);
}
set workingDaysArray(arr) {
this.working_sunday = arr[0];
this.working_monday = arr[1];
this.working_tuesday = arr[2];
this.working_wednesday = arr[3];
this.working_thursday = arr[4];
this.working_friday = arr[5];
this.working_saturday = arr[6];
}
/** @type {Date[]} */
get holiday() { this.holidayDays.map(n => new Date(n)); }
set holiday(dates) { this.holidayDays = dates.map(d => d.getTime()); }
/** @type {Date[]} */
get sick() { this.sickDays.map(n => new Date(n)); }
set sick(dates) { this.sickDays = dates.map(d => d.getTime()); }
/** @type {Date[]} */
get paidLeave() { this.paidLeaveDays.map(n => new Date(n)); }
set paidLeave(dates) { this.paidLeaveDays = dates.map(d => d.getTime()); }
static get jsonSchema() {
return Object.assign(super.jsonSchema, {
hourlyPay: { type: 'integer' },
fullOrPartTime: { type: 'boolean' },
holidayDays: { type: 'array', unqiueItems: true },
sickDays: { type: 'array', unqiueItems: true },
paidLeaveDays: { type: 'array', unqiueItems: true },
inLieuHours: { type: 'array', unqiueItems: true },
medicalLeaveTime: { type: 'array', unqiueItems: true },
working_sunday: { type: 'boolean' },
working_monday: { type: 'boolean' },
working_tuesday: { type: 'boolean' },
working_wednesday: { type: 'boolean' },
working_thursday: { type: 'boolean' },
working_friday: { type: 'boolean' },
working_saturday: { type: 'boolean' },
emergencyContactName: {
type: 'string',
},
emergencyContactNumber: {
type: 'string',
minLength: 15,
maxLength: 15,
},
});
}
static get relationMappings() {
return Object.assign({
assignments: {
relation: Model.ManyToManyRelation,
modelClass: Task,
join: {
from: 'Employee.id',
through: {
modelClass: Assignment,
from: 'Assignment.assigned_employee',
to: 'Assignment.assigned_task',
},
to: 'Task.id',
},
},
}, super.relationMappings);
}
} |
JavaScript | class Assignment extends Model {
static get tableName() { return 'Assignment'; }
static get relationMappings() {
return {
assignedEmployee: {
relation: Model.HasManyRelation,
modelClass: Employee,
join: {
from: 'Assignment.assigned_employee',
to: 'Employee.id',
},
},
assignedTask: {
relation: Model.HasManyRelation,
modelClass: Task,
join: {
from: 'Assignment.assigned_task',
to: 'Task.id',
},
},
};
}
} |
JavaScript | class GSSAPI extends AuthProvider {
/**
* Implementation of authentication for a single connection
* @override
*/
_authenticateSingleConnection(sendAuthCommand, connection, credentials, callback) {
const source = credentials.source;
const username = credentials.username;
const password = credentials.password;
const mechanismProperties = credentials.mechanismProperties;
const gssapiServiceName =
mechanismProperties['gssapiservicename'] ||
mechanismProperties['gssapiServiceName'] ||
'mongodb';
GSSAPIInitialize(
this,
kerberos.processes.MongoAuthProcess,
source,
username,
password,
source,
gssapiServiceName,
sendAuthCommand,
connection,
mechanismProperties,
callback
);
}
/**
* Authenticate
* @override
* @method
*/
auth(sendAuthCommand, connections, credentials, callback) {
if (kerberos == null) {
try {
kerberos = retrieveKerberos();
} catch (e) {
return callback(e, null);
}
}
super.auth(sendAuthCommand, connections, credentials, callback);
}
} |
JavaScript | class BaseDbObject {
constructor(initialValue) {
if (this.isCollection) {
const proxy = new Proxy(this, collectionProxyHandler);
if (initialValue) {
for (let i = 0; i < initialValue.length; i++) {
this.append(initialValue[i]);
}
}
return proxy;
} else if (initialValue) {
Object.assign(this, initialValue);
}
}
// extend class with promisified functions
_extend(oracledb) {
this._oracledb = oracledb;
}
// return as a plain object
_toPojo() {
if (this.isCollection) {
return this.getValues();
}
const result = {};
for (let name in this.attributes) {
let value = this[name];
if (value instanceof BaseDbObject) {
value = value._toPojo();
}
result[name] = value;
}
return result;
}
// custom inspection routine
[util.inspect.custom](depth, options) {
return '[' + this.fqn + '] ' + util.inspect(this._toPojo(), options);
}
[Symbol.iterator]() {
if (this.isCollection) {
const values = this.getValues();
return values[Symbol.iterator]();
}
throw TypeError("obj is not iterable");
}
[Symbol.toPrimitive](hint) {
switch (hint) {
case 'number':
return NaN;
default:
return '[' + this.fqn + '] ' + util.inspect(this._toPojo(), {});
}
}
toJSON() {
return this._toPojo();
}
} |
JavaScript | class Poller extends EventEmitter {
constructor(fd) {
logger('Creating poller')
super()
this.poller = new FDPoller(fd, handleEvent.bind(this))
}
/**
* Wait for the next event to occur
* @param {string} event ('readable'|'writable'|'disconnect')
* @returns {Poller} returns itself
*/
once(event) {
switch (event) {
case 'readable':
this.poll(EVENTS.UV_READABLE)
break
case 'writable':
this.poll(EVENTS.UV_WRITABLE)
break
case 'disconnect':
this.poll(EVENTS.UV_DISCONNECT)
break
}
return EventEmitter.prototype.once.apply(this, arguments)
}
/**
* Ask the bindings to listen for an event, it is recommend to use `.once()` for easy use
* @param {EVENTS} eventFlag polls for an event or group of events based upon a flag.
* @returns {undefined}
*/
poll(eventFlag) {
eventFlag = eventFlag || 0
if (eventFlag & EVENTS.UV_READABLE) {
logger('Polling for "readable"')
}
if (eventFlag & EVENTS.UV_WRITABLE) {
logger('Polling for "writable"')
}
if (eventFlag & EVENTS.UV_DISCONNECT) {
logger('Polling for "disconnect"')
}
this.poller.poll(eventFlag)
}
/**
* Stop listening for events and cancel all outstanding listening with an error
* @returns {undefined}
*/
stop() {
logger('Stopping poller')
this.poller.stop()
this.emitCanceled()
}
destroy() {
logger('Destroying poller')
this.poller.destroy()
this.emitCanceled()
}
emitCanceled() {
const err = new Error('Canceled')
err.canceled = true
this.emit('readable', err)
this.emit('writable', err)
this.emit('disconnect', err)
}
} |
JavaScript | class Quiz extends Component {
constructor( props ) {
debug( 'Instantiating quiz component...' );
super( props );
this.id = props.id || uid( props );
let questions = props.questions;
if ( !props.questions ) {
questions = [];
}
let current = null;
if ( questions.length > 0 ) {
const indices = incrspace( 0, questions.length, 1 );
this.sample = sample.factory( indices, {
size: 1,
mutate: true,
replace: false
});
current = this.sample()[ 0 ];
}
this.state = {
answers: new Array( questions.length ),
answered: false,
confidences: new Array( questions.length ),
current,
count: props.count || questions.length,
counter: 0,
finished: false,
answerSelected: false,
last: false,
selectedConfidence: null,
showInstructorView: false,
showFinishModal: false,
questions: [],
questionIDs: []
};
}
static getDerivedStateFromProps( nextProps, prevState ) {
if (
nextProps.questions &&
nextProps.questions.length !== prevState.questions.length
) {
const len = nextProps.questions.length;
const questionIDs = new Array( len );
for ( let i = 0; i < len; i++ ) {
const question = nextProps.questions[ i ];
if ( question.props && question.props.id ) {
questionIDs[ i ] = question.props.id;
} else {
questionIDs[ i ] = `${prevState.id}-${i}`;
}
}
const newState = {
questions: nextProps.questions,
questionIDs
};
return newState;
}
return null;
}
componentDidUpdate( prevProps ) {
debug( 'Component did update...' );
if (
this.props.count !== prevProps.count ||
( this.props.questions && this.props.questions.length !== prevProps.questions.length )
) {
debug( 'Resetting component...' );
const indices = incrspace( 0, this.props.questions.length, 1 );
this.sample = sample.factory( indices, {
size: 1,
mutate: true
});
this.setState({
count: this.props.count || this.prop.questions.length
});
}
}
toggleFinishModal = () => {
this.setState({
showFinishModal: !this.state.showFinishModal
});
}
handleFinishClick = () => {
this.setState({
counter: this.state.count
}, () => {
this.handleNextClick();
});
}
handleNextClick = () => {
// Submit all questions on the current page:
const elems = this.quizBody.getElementsByClassName( 'submit-button' );
for ( let i = 0; i < elems.length; i++ ) {
elems[ i ].click();
}
debug( 'Display next question...' );
const elem = this.state.questions[ this.state.current ];
const session = this.context;
if ( !this.state.answered ) {
session.log({
id: elem.props.id,
type: QUESTION_SKIPPED,
value: true
});
}
// Save chosen confidence level:
if ( elem.props && elem.props.id && this.state.selectedConfidence ) {
session.log({
id: elem.props.id+'_confidence',
type: QUESTION_CONFIDENCE,
value: this.state.selectedConfidence
});
}
this.props.onSubmit();
const newState = {};
let counter = this.state.counter;
counter += 1;
if ( counter >= this.state.count ) {
debug( 'No further questions should be shown...' );
newState.finished = true;
session.log({
id: this.id,
type: QUIZ_FINISHED,
value: true
});
this.props.onFinished();
} else {
if ( counter === this.state.count-1 ) {
newState.last = true;
}
newState.current = this.sample()[ 0 ];
debug( 'Selected question at index '+newState.current );
}
newState.answered = false;
newState.selectedConfidence = null;
newState.answerSelected = false;
newState.counter = counter;
this.setState( newState);
}
markSelected = () => {
debug( 'Mark answer as selected...' );
this.setState({
answerSelected: true
});
}
handleSubmission = ( val ) => {
const elem = this.state.questions[ this.state.current ];
const answers = this.state.answers.slice();
let answer;
let solution;
if ( elem.props ) {
if (
// Case: 'MultipleChoiceQuestion'
isArray( elem.props.answers ) && ( elem.props.solution !== void 0 )
) {
answer = elem.props.answers[ val ].content;
const correct = elem.props.solution;
if ( isArray( correct ) ) {
solution = '';
for ( let i = 0; i < correct.length; i++ ) {
solution += elem.props.answers[ correct[ i ] ];
solution += '; ';
}
} else {
solution = elem.props.answers[ correct ].content;
}
}
else if (
// Case: 'MatchListQuestion'
isArray( elem.props.elements )
) {
debug( 'Create answer and solution string for <MatchListQuestion />' );
answer = '';
solution = '';
for ( let i = 0; i < elem.props.elements.length; i++ ) {
const e = elem.props.elements[ i ];
for ( let j = 0; j < val.length; j++ ) {
const userElem = val[ j ];
if ( userElem.a === e.a ) {
answer += `${userElem.a}:${userElem.b}; `;
break;
}
}
solution += `${e.a}:${e.b}; `;
}
}
else if (
// Case: 'OrderQuestion'
isArray( elem.props.options )
) {
answer = '';
solution = '';
for ( let i = 0; i < elem.props.options.length; i++ ) {
const e = elem.props.options[ i ];
const userElem = val[ i ];
solution += `${e.text}; `;
answer += `${userElem.text}; `;
}
}
else {
// Case: Other question types...
answer = val;
solution = elem.props.solution;
if ( isArray( solution ) ) {
answer = answer.join( ', ' );
solution = solution.join( ', ' );
}
}
answers[ this.state.current ] = {
question: elem.props ? elem.props.question : null,
answer,
solution,
counter: this.state.counter
};
}
this.setState({
answered: true,
answers: answers
});
}
downloadResponsesFactory( answers ) {
return () => {
const doc = {
content: [
{
text: this.props.t('answer-for', { id: this.id }),
style: 'header',
alignment: 'center'
}
],
styles: DOC_STYLES
};
const session = this.context;
if ( !isEmptyObject( session.user ) ) {
doc.content.push({
text: `${this.props.t('by')} ${session.user.name} (${session.user.email})`,
style: 'author'
});
}
const date = new Date();
doc.content.push({
text: `${date.toLocaleDateString()} - ${date.toLocaleTimeString()}`,
style: 'date'
});
for ( let i = 0; i < answers.length; i++ ) {
let { question, answer, solution, confidence } = answers[ i ];
question = isString( question ) ? question : innerText( question );
answer = isString( answer ) ? answer : innerText( answer );
solution = isString( solution ) ? solution : innerText( solution );
doc.content.push({
text: question,
style: 'question'
});
doc.content.push({
text: `${this.props.t('answer')}:`,
style: 'boldTitle'
});
doc.content.push({
text: answer,
style: {
color: answer === solution ? '#3c763d' : '#d9534f',
margin: [0, 0, 0, 10]
}
});
if ( confidence ) {
doc.content.push({
text: `${this.props.t('your-confidence')}:`,
style: 'boldTitle'
});
doc.content.push({
text: confidence
});
}
doc.content.push({
text: `${this.props.t('solution')}:`,
style: 'boldTitle'
});
doc.content.push({
text: isString( solution ) ? solution : innerText( solution )
});
}
pdfMake.createPdf( doc ).download( 'responses.pdf' );
};
}
renderScoreboard() {
debug( 'Rendering scoreboard...' );
if ( !this.props.provideFeedback ) {
return <h3>{this.props.t('quiz-finished')}</h3>;
}
let answers = this.state.answers.slice();
for ( let i = 0; i < answers.length; i++ ) {
if ( answers[ i ] ) {
answers[ i ].confidence = this.state.confidences[ i ];
}
}
answers.sort( ( a, b ) => a.counter > b.counter );
answers = answers.filter( x => isObject( x ) );
return ( <div>
<p>{ this.props.duration ? this.props.t('time-up') : this.props.t('quiz-finished') }{this.props.t('summary-label')}:</p>
<table className="table table-bordered" >
<thead>
<tr>
<th>{this.props.t('question')}</th>
<th>{this.props.t('your-answer')}</th>
<th>{this.props.t('solution')}</th>
{ this.props.confidence ? <th>{this.props.t('your-confidence')}</th> : null }
</tr>
</thead>
<tbody>
{answers.map( ( elem, idx ) => {
let className;
if ( elem.answer === elem.solution ) {
className = 'quiz-right-answer';
} else {
className = 'quiz-wrong-answer';
}
let question = elem.question;
if ( isHTMLConfig( question ) ) {
question = convertJSONtoJSX( question );
}
let answer = elem.answer;
if ( isHTMLConfig( answer ) ) {
answer = convertJSONtoJSX( answer );
}
let solution = elem.solution;
if ( isHTMLConfig( solution ) ) {
solution = convertJSONtoJSX( solution );
}
return ( <tr className={className} key={idx}>
<td>{question}</td>
<td>{answer}</td>
<td>{solution}</td>
{ this.props.confidence ?
<td>{elem.confidence}</td> :
null
}
</tr> );
})}
</tbody>
</table>
{this.props.downloadButton ? <Button onClick={this.downloadResponsesFactory( answers )} >
{this.props.t('download-pdf')}
</Button> : null}
</div> );
}
renderQuestion( config, id ) {
if ( !config ) {
return null;
}
const props = config.props || {};
if ( isHTMLConfig( props.question ) ) {
debug( 'Question property is an object, convert to JSX...' );
props.question = convertJSONtoJSX( props.question );
}
switch ( config.component ) {
case 'Fragment':
case 'div':
return convertJSONtoJSX( config );
case 'FreeTextQuestion':
return <FreeTextQuestion disableSubmitNotification feedback={false} provideFeedback={false} {...props} onChange={this.markSelected} onSubmit={this.handleSubmission} id={id} />;
case 'MultipleChoiceQuestion':
return <MultipleChoiceQuestion disableSubmitNotification feedback={false} provideFeedback="none" {...props} onChange={this.markSelected} onSubmit={this.handleSubmission} id={id} />;
case 'MatchListQuestion':
return <MatchListQuestion disableSubmitNotification feedback={false} showSolution={false} {...props} onChange={this.markSelected} onSubmit={this.handleSubmission} id={id} />;
case 'NumberQuestion':
return <NumberQuestion disableSubmitNotification feedback={false} provideFeedback={false} {...props} onChange={this.markSelected} onSubmit={this.handleSubmission} id={id} />;
case 'OrderQuestion':
return <OrderQuestion disableSubmitNotification feedback={false} provideFeedback={false} {...props} onChange={this.markSelected} onSubmit={this.handleSubmission} id={id} />;
case 'RangeQuestion':
return <RangeQuestion disableSubmitNotification feedback={false} provideFeedback={false} {...props} onChange={this.markSelected} onSubmit={this.handleSubmission} id={id} />;
case 'SelectQuestion':
return <SelectQuestion disableSubmitNotification feedback={false} provideFeedback={false} {...props} onChange={this.markSelected} onSubmit={this.handleSubmission} id={id} />;
default:
// Case: `config` already is a React component, clone it to pass in submit handler:
return <config.type {...config.props} {...props} disableSubmitNotification feedback={false} provideFeedback={false} onChange={this.markSelected} onSubmit={this.handleSubmission} id={id} />;
}
}
handleConfidenceChange = ( event ) => {
const confidence = event.target.value;
debug( 'Choosing confidence: '+confidence );
const confidences = this.state.confidences.slice();
confidences[ this.state.current ] = confidence;
this.setState({
selectedConfidence: confidence,
confidences: confidences
});
}
toggleInstructorView =() => {
this.setState({
showInstructorView: !this.state.showInstructorView
});
}
renderConfidenceSurvey() {
if ( !this.props.confidence ) {
return null;
}
return (
<Card className="center" style={{ width: '75%' }}>
<FormGroup className="center" >
<Form.Label>
{this.props.t('confidence-prompt')}
</Form.Label>
<br />
<Form.Check
type="radio"
label={this.props.t('guessed')}
checked={this.state.selectedConfidence === 'Guessed'}
value="Guessed"
inline
onClick={this.handleConfidenceChange}
/>
{' '}
<Form.Check
type="radio"
label={this.props.t('somewhat-sure')}
checked={this.state.selectedConfidence === 'Somewhat sure'}
value="Somewhat sure"
inline
onClick={this.handleConfidenceChange}
/>
{' '}
<Form.Check
type="radio"
label={this.props.t('confident')}
checked={this.state.selectedConfidence === 'Confident'}
value="Confident"
inline
onClick={this.handleConfidenceChange}
/>
</FormGroup>
</Card>
);
}
renderFooterNodes( elem, idx ) {
let id;
if ( elem.props ) {
id = elem.props.id;
}
if ( !id ) {
id = `${this.id}-${idx}`;
}
return React.Children.map( this.props.footerNodes, ( child, idx ) => {
return React.cloneElement( child, {
id: `${child.props.id}-footer-${id}`, // eslint-disable-line i18next/no-literal-string
key: `${this.state.current}-${idx}`
});
});
}
render() {
debug( 'Rendering component...' );
let showButton;
if ( this.state.finished ) {
showButton = false;
} else {
showButton = this.state.answered || this.state.answerSelected || this.props.skippable;
}
if ( this.state.showInstructorView ) {
return ( <Card className="quiz">
<Card.Header>
<span>
<h3 style={{ display: 'inline-block' }}>{this.props.t('instructor-view')}</h3>
<Button
variant="secondary"
style={{ float: 'right' }}
onClick={this.toggleInstructorView}
>
{this.props.t('close-instructor-view')}
</Button>
</span>
</Card.Header>
<Card.Body>
{this.state.questions.map( ( elem, idx ) => {
const id = this.state.questionIDs[ idx ];
return ( <div key={idx}>
<h3>{this.props.t('question')} {idx+1}:</h3>
{this.renderQuestion( elem, id )}
{this.renderFooterNodes( elem, idx )}
</div> );
})}
</Card.Body>
<Button
className="quiz-button"
variant="secondary"
onClick={this.toggleInstructorView}
>
{this.props.t('close-instructor-view')}
</Button>
</Card> );
}
const currentConfig = this.state.questions[ this.state.current ];
const currentID = this.state.questionIDs[ this.state.current ];
return (
<Fragment>
{this.props.duration ?
<Timer
invisible
id={this.id}
active={this.props.active}
duration={this.props.duration}
onTimeUp={() => {
debug( 'Time is up...' );
const session = this.context;
session.log({
id: this.id,
type: QUIZ_FINISHED,
value: true
});
this.setState({
finished: true
}, () => {
this.props.onFinished();
});
}}
/> :
null
}
<Card className="quiz" >
<Card.Header>
{ this.state.finished ?
<h3>{this.props.t('answer-summary')}</h3> :
<h3>{this.props.t('question')} {this.state.counter+1}/{this.state.count}</h3>
}
</Card.Header>
<Card.Body>
<div ref={( card ) => {
this.quizBody = card;
}} >
{ this.state.finished ?
this.renderScoreboard() :
<span key={this.state.current}>{this.renderQuestion( currentConfig, currentID )}</span>
}
{ !this.state.finished ? this.renderConfidenceSurvey() : null }
{currentConfig ? this.renderFooterNodes( currentConfig ) : null}
<ButtonGroup style={{ float: 'right' }}>
<Gate owner banner={null} >
<Button
className="quiz-button"
variant="secondary"
onClick={this.toggleInstructorView}
style={{ marginRight: 10 }}
>
{this.props.t('open-instructor-view')}
</Button>
</Gate>
{
( this.props.showFinishButton || this.state.last ) &&
!this.state.finished ?
<Button
style={{ marginRight: 10 }}
className="quiz-button"
variant="secondary"
onClick={this.state.last ? this.handleFinishClick : this.toggleFinishModal}
>
{this.props.finishLabel || this.props.t('finish-label')}
</Button> : null
}
{ showButton && !this.state.last ?
<Button
className="quiz-button"
variant="primary"
onClick={this.handleNextClick}
disabled={this.props.forceConfidence && !this.state.selectedConfidence && this.state.answerSelected}
>
{this.props.nextLabel || this.props.t('next-question')}
</Button> :
null
}
</ButtonGroup>
</div>
</Card.Body>
</Card>
<FinishModal
show={this.state.showFinishModal}
onSubmit={this.handleFinishClick}
onHide={this.toggleFinishModal}
t={this.props.t}
/>
</Fragment>
);
}
} |
JavaScript | class AnimatedSprite extends Sprite {
/**
* The name of the current animation
* @returns {string}
*/
get CurrentAnimation(){
return privateProperties[this.name].currentAnimation;
}
/**
* Set the current animation to a assigned set of instructions.
*
* @param {string} animation
*/
set CurrentAnimation(animation){
if(utilities.exists(privateProperties[this.name].animations.has(animation))){
this.messageToSubEntity(privateProperties[this.name].currentAnimation, "disable");
privateProperties[this.name].currentAnimation = animation;
this.messageToSubEntity(privateProperties[this.name].currentAnimation, "enable");
}
}
/**
* Create a new Animated Sprite
* @param {Object} params
* @param {EntityManager} EntityManager
*/
constructor(params, EntityManager){
super(params, EntityManager);
privateProperties[this.name] = {};
privateProperties[this.name].animations = new Map();
privateProperties[this.name].currentAnimation = "default";
let names = Object.keys(params.animations);
names.forEach((name, i)=>{
this.addAnimation(name, params.animations[name]);
});
}
/**
* Add animation instructions to the Animated Sprite
*
* @param {String} name
* @param {Object} animation
*/
addAnimation(name, animation){
let animator = this.EntityManager.create("Animator", Object.assign({}, {
name: name,
// When the sprite's frame has changed, tell the entity to set the sprite to the next frame.
onFrameChange: nextFrame=>{
if(privateProperties[this.name].currentAnimation === name){
this.setSprite(nextFrame);
}
}
},
animation));
if(name !== "default") {
animator.disable();
}
privateProperties[this.name].animations[name] = true;
this.attachSubEntity(name, animator);
}
} |
JavaScript | class AlpacaStreamClient extends events.EventEmitter {
constructor(opts = {}) {
super();
this.defaultOptions = {
// A list of subscriptions to subscribe to on connection
subscriptions: [],
// Whether the library should reconnect automatically
reconnect: true,
// Reconnection backoff: if true, then the reconnection time will be initially
// reconnectTimeout, then will double with each unsuccessful connection attempt.
// It will not exceed maxReconnectTimeout
backoff: true,
// Initial reconnect timeout (seconds) a minimum of 1 will be used if backoff=false
reconnectTimeout: 0,
// The maximum amount of time between reconnect tries (applies to backoff)
maxReconnectTimeout: 30,
// The amount of time to increment the delay between each reconnect attempt
backoffIncrement: 0.5,
// If true, client outputs detailed log messages
verbose: false,
// If true we will use the polygon ws data source, otherwise we use
// alpaca ws data source
usePolygon: false,
};
// Set minimum reconnectTimeout of 1s if backoff=false
if (!opts.backoff && opts.reconnectTimeout < 1) {
opts.reconnectTimeout = 1;
}
// Merge supplied options with defaults
this.session = Object.assign(this.defaultOptions, opts);
this.session.url = this.session.url.replace(/^http/, "ws") + "/stream";
if (this.session.apiKey.length === 0 && this.session.oauth.length === 0) {
throw new Error(ERROR.MISSING_API_KEY);
}
if (
this.session.secretKey.length === 0 &&
this.session.oauth.length === 0
) {
throw new Error(ERROR.MISSING_SECRET_KEY);
}
// Keep track of subscriptions in case we need to reconnect after the client
// has called subscribe()
this.subscriptionState = {};
this.session.subscriptions.forEach((x) => {
this.subscriptionState[x] = true;
});
this.currentState = STATE.WAITING_TO_CONNECT;
// Register internal event handlers
// Log and emit every state change
Object.keys(STATE).forEach((s) => {
this.on(STATE[s], () => {
this.currentState = STATE[s];
this.log("info", `state change: ${STATE[s]}`);
this.emit(EVENT.STATE_CHANGE, STATE[s]);
});
});
// Log and emit every error
Object.keys(ERROR).forEach((e) => {
this.on(ERROR[e], () => {
this.log("error", ERROR[e]);
this.emit(EVENT.CLIENT_ERROR, ERROR[e]);
});
});
}
connect() {
// Reset reconnectDisabled since the user called connect() again
this.reconnectDisabled = false;
this.emit(STATE.CONNECTING);
this.conn = new WebSocket(this.session.url);
this.conn.once("open", () => {
this.authenticate();
});
this.conn.on("message", (data) => this.handleMessage(data));
this.conn.once("error", (err) => {
this.emit(ERROR.CONNECTION_REFUSED);
});
this.conn.once("close", () => {
this.emit(STATE.DISCONNECTED);
if (this.session.reconnect && !this.reconnectDisabled) {
this.reconnect();
}
});
}
_ensure_polygon(channels) {
if (this.polygon.connectCalled) {
if (channels) {
this.polygon.subscribe(channels);
}
return;
}
this.polygon.connect(channels);
}
_unsubscribe_polygon(channels) {
if (this.polygon.connectCalled) {
if (channels) {
this.polygon.unsubscribe(channels);
}
}
}
subscribe(keys) {
let wsChannels = [];
let polygonChannels = [];
keys.forEach((key) => {
const poly = ["Q.", "T.", "A.", "AM."];
let found = poly.filter((channel) => key.startsWith(channel));
if (found.length > 0) {
polygonChannels.push(key);
} else {
wsChannels.push(key);
}
});
if (wsChannels.length > 0) {
const subMsg = {
action: "listen",
data: {
streams: wsChannels,
},
};
this.send(JSON.stringify(subMsg));
}
if (polygonChannels.length > 0) {
this._ensure_polygon(polygonChannels);
}
keys.forEach((x) => {
this.subscriptionState[x] = true;
});
}
unsubscribe(keys) {
// Currently, only Polygon channels can be unsubscribed from
let polygonChannels = [];
keys.forEach((key) => {
const poly = ["Q.", "T.", "A.", "AM."];
let found = poly.filter((channel) => key.startsWith(channel));
if (found.length > 0) {
polygonChannels.push(key);
}
});
if (polygonChannels.length > 0) {
this._unsubscribe_polygon(polygonChannels);
}
keys.forEach((x) => {
this.subscriptionState[x] = false;
});
}
subscriptions() {
// if the user unsubscribes from certain equities, they will still be
// under this.subscriptionState but with value "false", so we need to
// filter them out
return Object.keys(this.subscriptionState).filter(
(x) => this.subscriptionState[x]
);
}
onConnect(fn) {
this.on(STATE.CONNECTED, () => fn());
}
onDisconnect(fn) {
this.on(STATE.DISCONNECTED, () => fn());
}
onStateChange(fn) {
this.on(EVENT.STATE_CHANGE, (newState) => fn(newState));
}
onError(fn) {
this.on(EVENT.CLIENT_ERROR, (err) => fn(err));
}
onOrderUpdate(fn) {
this.on(EVENT.ORDER_UPDATE, (orderUpdate) => fn(orderUpdate));
}
onAccountUpdate(fn) {
this.on(EVENT.ACCOUNT_UPDATE, (accountUpdate) => fn(accountUpdate));
}
onPolygonConnect(fn) {
this.polygon.on(STATE.CONNECTED, () => fn());
}
onPolygonDisconnect(fn) {
this.polygon.on(STATE.DISCONNECTED, () => fn());
}
onStockTrades(fn) {
if (this.session.usePolygon) {
this.polygon.on(EVENT.STOCK_TRADES, function (subject, data) {
fn(subject, data);
});
} else {
this.on(EVENT.STOCK_TRADES, function (subject, data) {
fn(subject, data);
});
}
}
onStockQuotes(fn) {
if (this.session.usePolygon) {
this.polygon.on(EVENT.STOCK_QUOTES, function (subject, data) {
fn(subject, data);
});
} else {
this.on(EVENT.STOCK_QUOTES, function (subject, data) {
fn(subject, data);
});
}
}
onStockAggSec(fn) {
this.polygon.on(EVENT.STOCK_AGG_SEC, function (subject, data) {
fn(subject, data);
});
}
onStockAggMin(fn) {
if (this.session.usePolygon) {
this.polygon.on(EVENT.STOCK_AGG_MIN, function (subject, data) {
fn(subject, data);
});
} else {
this.on(EVENT.STOCK_AGG_MIN, function (subject, data) {
fn(subject, data);
});
}
}
send(data) {
this.conn.send(data);
}
disconnect() {
this.reconnectDisabled = true;
this.conn.close();
if (this.polygon) {
this.polygon.close();
}
}
state() {
return this.currentState;
}
get(key) {
return this.session[key];
}
reconnect() {
setTimeout(() => {
if (this.session.backoff) {
this.session.reconnectTimeout += this.session.backoffIncrement;
if (this.session.reconnectTimeout > this.session.maxReconnectTimeout) {
this.session.reconnectTimeout = this.session.maxReconnectTimeout;
}
}
this.connect();
}, this.session.reconnectTimeout * 1000);
this.emit(STATE.WAITING_TO_RECONNECT, this.session.reconnectTimeout);
}
authenticate() {
this.emit(STATE.AUTHENTICATING);
const authMsg = {
action: "authenticate",
data: {
key_id: this.session.apiKey,
secret_key: this.session.secretKey,
},
};
this.send(JSON.stringify(authMsg));
}
handleMessage(data) {
// Heartbeat
const bytes = new Uint8Array(data);
if (bytes.length === 1 && bytes[0] === 1) {
return;
}
let message = JSON.parse(data);
const subject = message.stream;
if ("error" in message.data) {
console.log(message.data.error);
}
switch (subject) {
case "authorization":
this.authResultHandler(message.data.status);
break;
case "listening":
this.log(`listening to the streams: ${message.data.streams}`);
break;
case "trade_updates":
this.emit(EVENT.ORDER_UPDATE, message.data);
break;
case "account_updates":
this.emit(EVENT.ACCOUNT_UPDATE, message.data);
break;
default:
if (message.stream.startsWith("T.")) {
this.emit(
EVENT.STOCK_TRADES,
subject,
entity.AlpacaTrade(message.data)
);
} else if (message.stream.startsWith("Q.")) {
this.emit(
EVENT.STOCK_QUOTES,
subject,
entity.AlpacaQuote(message.data)
);
} else if (message.stream.startsWith("AM.")) {
this.emit(
EVENT.STOCK_AGG_MIN,
subject,
entity.AggMinuteBar(message.data)
);
} else {
this.emit(ERROR.PROTOBUF);
}
}
}
authResultHandler(authResult) {
switch (authResult) {
case "authorized":
this.emit(STATE.CONNECTED);
break;
case "unauthorized":
this.emit(ERROR.BAD_KEY_OR_SECRET);
this.disconnect();
break;
default:
break;
}
}
log(level, ...msg) {
if (this.session.verbose) {
console[level](...msg);
}
}
} |
JavaScript | class TaskRuns extends Component {
componentDidMount() {
this.fetchTaskRuns();
}
componentDidUpdate(prevProps) {
const { filters, namespace, webSocketConnected } = this.props;
const {
filters: prevFilters,
namespace: prevNamespace,
webSocketConnected: prevWebSocketConnected
} = prevProps;
if (
!isEqual(filters, prevFilters) ||
namespace !== prevNamespace ||
(webSocketConnected && prevWebSocketConnected === false)
) {
this.fetchTaskRuns();
}
}
cancel = taskRun => {
const { name, namespace } = taskRun.metadata;
cancelTaskRun({ name, namespace });
};
deleteTask = taskRun => {
const { name, namespace } = taskRun.metadata;
deleteTaskRun({ name, namespace });
};
handleAddFilter = labelFilters => {
const queryParams = `?${new URLSearchParams({
labelSelector: labelFilters
}).toString()}`;
const currentURL = this.props.match.url;
const browserURL = currentURL.concat(queryParams);
this.props.history.push(browserURL);
};
handleDeleteFilter = filter => {
const currentQueryParams = new URLSearchParams(this.props.location.search);
const labelFilters = currentQueryParams.getAll('labelSelector');
const labelFiltersArray = labelFilters.toString().split(',');
const index = labelFiltersArray.indexOf(filter);
labelFiltersArray.splice(index, 1);
const currentURL = this.props.match.url;
if (labelFiltersArray.length === 0) {
this.props.history.push(currentURL);
} else {
const newQueryParams = `?${new URLSearchParams({
labelSelector: labelFiltersArray
}).toString()}`;
const browserURL = currentURL.concat(newQueryParams);
this.props.history.push(browserURL);
}
};
taskRunActions = () => {
const { intl } = this.props;
return [
{
actionText: intl.formatMessage({
id: 'dashboard.cancelTaskRun.actionText',
defaultMessage: 'Stop'
}),
action: this.cancel,
disable: resource => {
const { reason, status } = getStatus(resource);
return !isRunning(reason, status);
},
modalProperties: {
heading: intl.formatMessage({
id: 'dashboard.cancelTaskRun.heading',
defaultMessage: 'Stop TaskRun'
}),
primaryButtonText: intl.formatMessage({
id: 'dashboard.cancelTaskRun.primaryText',
defaultMessage: 'Stop TaskRun'
}),
secondaryButtonText: intl.formatMessage({
id: 'dashboard.modal.cancelButton',
defaultMessage: 'Cancel'
}),
body: resource =>
intl.formatMessage(
{
id: 'dashboard.cancelTaskRun.body',
defaultMessage:
'Are you sure you would like to stop TaskRun {name}?'
},
{ name: resource.metadata.name }
)
}
},
{
actionText: intl.formatMessage({
id: 'dashboard.deleteTaskRun.actionText',
defaultMessage: 'Delete'
}),
action: this.deleteTask,
disable: resource => {
const { reason, status } = getStatus(resource);
return isRunning(reason, status);
},
modalProperties: {
heading: intl.formatMessage({
id: 'dashboard.deleteTaskRun.heading',
defaultMessage: 'Delete TaskRun'
}),
primaryButtonText: intl.formatMessage({
id: 'dashboard.deleteTaskRun.primaryText',
defaultMessage: 'Delete TaskRun'
}),
secondaryButtonText: intl.formatMessage({
id: 'dashboard.modal.cancelButton',
defaultMessage: 'Cancel'
}),
body: resource =>
intl.formatMessage(
{
id: 'dashboard.deleteTaskRun.body',
defaultMessage:
'Are you sure you would like to delete TaskRun {name}?'
},
{ name: resource.metadata.name }
)
}
}
];
};
fetchTaskRuns() {
const { filters, namespace } = this.props;
this.props.fetchTaskRuns({
filters,
namespace
});
}
render() {
const {
error,
filters,
loading,
taskRuns,
namespace: selectedNamespace
} = this.props;
const taskRunActions = this.taskRunActions();
sortRunsByStartTime(taskRuns);
if (error) {
return (
<InlineNotification
kind="error"
hideCloseButton
lowContrast
title="Error loading TaskRuns"
subtitle={getErrorMessage(error)}
/>
);
}
return (
<>
<h1>TaskRuns</h1>
<LabelFilter
filters={filters}
handleAddFilter={this.handleAddFilter}
handleDeleteFilter={this.handleDeleteFilter}
/>
<TaskRunsList
loading={loading}
selectedNamespace={selectedNamespace}
taskRuns={taskRuns}
taskRunActions={taskRunActions}
/>
</>
);
}
} |
JavaScript | class SearchBar extends React.Component{ //Defining a class called SearchBar which is allowed a bunch of functionalities from React.Component
constructor(props) {
super(props);
this.state = { term: '' };
this.setInputState = this.setInputState.bind(this);
this.searchingTerm = "";
}
setInputState(event) {
this.setState({ term: event.target.value });
}
onInputChange(term){
this.setState({term:term});
this.props.onSearchTermChange(term);
}
render() {
return (
<div className="class_cmp_search_bar">
<button className="home" onClick={event=>this.onInputChange("")}>YT</button>
<input
onChange={event=>this.setState({searchingTerm:event.target.value})}/>
<button onClick={event=>(this.onInputChange(this.state.searchingTerm)
)}>Search</button>
</div>
);
}
} |
JavaScript | class EmbedBuilder {
constructor(embed = {}) {
/**
* Embed Title
* @type {String}
*/
this.title = embed.title;
/**
* The embed description
* @type {String}
*/
this.description = embed.description;
/**
* The color of the embed
* @type {Number}
*/
this.color = embed.color;
/**
* Embed fields in an array.
* @type {Array}
*/
this.fields = embed.fields || [];
/**
* The Embed Footer
* @type {Object}
*/
this.footer = {
text: embed.footer.text,
icon_url: embed.footer.iconURL
}
}
/**
* Sets the embed title.
* @param {String} title - The embed title to set, must not exceed 256 characters or an error is thrown.
* @returns {EmbedBuilder}
*/
setTitle(title) {
title = String(title);
if(title.length > 256) {
throw new RangeError("Embed title must not exceed 256 characters!");
}
this.title = title
return this; // return embed object every set so its possible to chain multiple .set like .setTitle().setDescription() etc
}
/**
* Set the embed description.
* @param {String} description - The description to set, must not exceed 2048 Characters or an error is thrown.
* @returns {EmbedBuilder}
*/
setDescription(description) {
description = String(description);
if(description.length > 2048) {
throw new RangeError("Embed Description must not exceed 2048 characters!");
}
this.description = description;
return this;
}
/**
* Set the embed color
* @param {Number} color - the Embed's color in bitwise integer.
* @returns {EmbedBuilder}
* @example
* .setColor(0x00FF00) // sets color to green.
*/
setColor(color) {
color = parseInt(color);
this.color = color;
return this;
}
/**
* Add a field, the field is then pushed to fields array.
* fields must not exceed 25 fields or an error is thrown.
* @param {String} name - The field's name, must not exceed 256 characters or an error is thrown.
* @param {String} value - The field's value, must not exceed 1024 Characters or an error is thrown.
* @param {Boolean} inline=false - Wether the field must have an inline or not.
* @returns {EmbedBuilder}
*/
addField(name, value, inline = false) {
if(typeof inline !== 'boolean') throw new TypeError("Inline can be a boolean only");
if(name.length > 256) throw new RangeError("Embed field values must not exceed 256 characters");
if(value.length > 1024) throw new RangeError("Embed field values must not exceed 1024 characters");
if(this.fields.length > 25) throw new RangeError("Fields can only be upto 25 fields");
this.fields.push({name, value, inline});
return this;
}
/**
* Sets the Embed footer.
* @param {String} text - The text for footer to set.
* @param {String} iconURL - Icon URL for footer. optional
* @returns {EmbedBuilder}
*/
setFooter(text, iconURL) {
this.footer.text = text;
this.footer.icon_url = iconURL;
return this;
}
} |
JavaScript | class GridSelectionColumnElement extends GridColumnElement {
static get is() {
return 'vaadin-grid-selection-column';
}
static get properties() {
return {
/**
* Width of the cells for this column.
*/
width: {
type: String,
value: '58px'
},
/**
* Flex grow ratio for the cell widths. When set to 0, cell width is fixed.
* @attr {number} flex-grow
* @type {number}
*/
flexGrow: {
type: Number,
value: 0
},
/**
* When true, all the items are selected.
* @attr {boolean} select-all
* @type {boolean}
*/
selectAll: {
type: Boolean,
value: false,
notify: true
},
/**
* When true, the active gets automatically selected.
* @attr {boolean} auto-select
* @type {boolean}
*/
autoSelect: {
type: Boolean,
value: false
},
/** @private */
__indeterminate: Boolean,
/**
* The previous state of activeItem. When activeItem turns to `null`,
* previousActiveItem will have an Object with just unselected activeItem
* @private
*/
__previousActiveItem: Object,
/** @private */
__selectAllHidden: Boolean
};
}
static get observers() {
return [
'__onSelectAllChanged(selectAll)',
'_onHeaderRendererOrBindingChanged(_headerRenderer, _headerCell, path, header, selectAll, __indeterminate, __selectAllHidden)'
];
}
constructor() {
super();
this.__boundOnActiveItemChanged = this.__onActiveItemChanged.bind(this);
this.__boundOnDataProviderChanged = this.__onDataProviderChanged.bind(this);
this.__boundOnSelectedItemsChanged = this.__onSelectedItemsChanged.bind(this);
}
/** @protected */
disconnectedCallback() {
this._grid.removeEventListener('active-item-changed', this.__boundOnActiveItemChanged);
this._grid.removeEventListener('data-provider-changed', this.__boundOnDataProviderChanged);
this._grid.removeEventListener('filter-changed', this.__boundOnSelectedItemsChanged);
this._grid.removeEventListener('selected-items-changed', this.__boundOnSelectedItemsChanged);
super.disconnectedCallback();
}
/** @protected */
connectedCallback() {
super.connectedCallback();
if (this._grid) {
this._grid.addEventListener('active-item-changed', this.__boundOnActiveItemChanged);
this._grid.addEventListener('data-provider-changed', this.__boundOnDataProviderChanged);
this._grid.addEventListener('filter-changed', this.__boundOnSelectedItemsChanged);
this._grid.addEventListener('selected-items-changed', this.__boundOnSelectedItemsChanged);
}
}
/**
* Renders the Select All checkbox to the header cell.
*
* @override
*/
_defaultHeaderRenderer(root, _column) {
let checkbox = root.firstElementChild;
if (!checkbox) {
checkbox = document.createElement('vaadin-checkbox');
checkbox.setAttribute('aria-label', 'Select All');
checkbox.classList.add('vaadin-grid-select-all-checkbox');
checkbox.addEventListener('checked-changed', this.__onSelectAllCheckedChanged.bind(this));
root.appendChild(checkbox);
}
const checked = this.__isChecked(this.selectAll, this.__indeterminate);
checkbox.__rendererChecked = checked;
checkbox.checked = checked;
checkbox.hidden = this.__selectAllHidden;
checkbox.indeterminate = this.__indeterminate;
}
/**
* Renders the Select Row checkbox to the body cell.
*
* @override
*/
_defaultRenderer(root, _column, { item, selected }) {
let checkbox = root.firstElementChild;
if (!checkbox) {
checkbox = document.createElement('vaadin-checkbox');
checkbox.setAttribute('aria-label', 'Select Row');
checkbox.addEventListener('checked-changed', this.__onSelectRowCheckedChanged.bind(this));
root.appendChild(checkbox);
}
checkbox.__item = item;
checkbox.__rendererChecked = selected;
checkbox.checked = selected;
}
/** @private */
__onSelectAllChanged(selectAll) {
if (selectAll === undefined || !this._grid) {
return;
}
if (!this.__selectAllInitialized) {
// The initial value for selectAll property was applied, avoid clearing pre-selected items
this.__selectAllInitialized = true;
return;
}
if (this._selectAllChangeLock) {
return;
}
this._grid.selectedItems = selectAll && Array.isArray(this._grid.items) ? this.__getRootLevelItems() : [];
}
/**
* Return true if array `a` contains all the items in `b`
* We need this when sorting or to preserve selection after filtering.
* @private
*/
__arrayContains(a, b) {
for (var i = 0; a && b && b[i] && a.indexOf(b[i]) >= 0; i++); // eslint-disable-line
return i == b.length;
}
/**
* Enables or disables the Select All mode once the Select All checkbox is switched.
* The listener handles only user-fired events.
*
* @private
*/
__onSelectAllCheckedChanged(e) {
// Skip if the state is changed by the renderer.
if (e.target.checked === e.target.__rendererChecked) {
return;
}
this.selectAll = this.__indeterminate || e.target.checked;
}
/**
* Selects or deselects the row once the Select Row checkbox is switched.
* The listener handles only user-fired events.
*
* @private
*/
__onSelectRowCheckedChanged(e) {
// Skip if the state is changed by the renderer.
if (e.target.checked === e.target.__rendererChecked) {
return;
}
if (e.target.checked) {
this._grid.selectItem(e.target.__item);
} else {
this._grid.deselectItem(e.target.__item);
}
}
/**
* iOS needs indeterminated + checked at the same time
* @private
*/
__isChecked(selectAll, indeterminate) {
return indeterminate || selectAll;
}
/** @private */
__onActiveItemChanged(e) {
const activeItem = e.detail.value;
if (this.autoSelect) {
const item = activeItem || this.__previousActiveItem;
if (item) {
this._grid._toggleItem(item);
}
}
this.__previousActiveItem = activeItem;
}
/** @private */
__getRootLevelItems() {
const rootCache = this._grid._cache;
return [...Array(rootCache.size)].map((_, idx) => rootCache.items[idx]);
}
/** @private */
__onSelectedItemsChanged() {
this._selectAllChangeLock = true;
if (Array.isArray(this._grid.items)) {
if (!this._grid.selectedItems.length) {
this.selectAll = false;
this.__indeterminate = false;
} else if (this.__arrayContains(this._grid.selectedItems, this.__getRootLevelItems())) {
this.selectAll = true;
this.__indeterminate = false;
} else {
this.selectAll = false;
this.__indeterminate = true;
}
}
this._selectAllChangeLock = false;
}
/** @private */
__onDataProviderChanged() {
this.__selectAllHidden = !Array.isArray(this._grid.items);
}
} |
JavaScript | class App extends Component {
componentDidMount() {
this.props.fetchResorts();
}
componentWillReceiveProps() {
}
render() {
if (this.props.resortsStatus === 'fetching') {
return (
<div className="App-wrapper">
<LoadingIndicator />
<Footer />
</div>
);
}
let emailSignup;
if (this.props.showEmailSignup) {
emailSignup = (
<EmailSignup />
);
}
return (
<div>
<Switch>
<Route exact path="/privacy" component={Privacy} />
<Route
path="/"
render={() => (
<div className="App-wrapper">
{emailSignup}
<WeatherBanner />
<OpenSourceBanner />
<div className="App-content">
<Switch>
<Route
exact
path="/"
component={() => (
<Redirect to="/resorts" />
)}
/>
<Redirect exact from="/" to="/resorts" />
<Redirect exact from="/resorts/squaw-valley" to="/resorts/palisades-tahoe" />
<Route exact path="/resorts/:shortName?" component={Main} />
<Route component={FourOhFour} />
</Switch>
<Route exact path="/resorts/:shortName?" component={SideNav} />
</div>
<Footer />
</div>
)}
/>
</Switch>
</div>
);
}
} |
JavaScript | class MessageAndDuration {
constructor(publisher_id, sequence_number, latency_ms) {
this.publisher_id = publisher_id;
this.sequence_number = sequence_number;
this.latency_ms = latency_ms;
}
} |
JavaScript | class WT_OAuthPkce {
// eslint-disable-next-line no-var
static sha256(r) { function t(r, t) { return r >>> t | r << 32 - t; } for (var h, n, o = Math.pow, e = o(2, 32), f = "", a = [], l = 8 * r.length, g = h = h || [], c = k = k || [], i = c.length, s = {}, u = 2; i < 64; u++)
if (!s[u]) {
for (h = 0; h < 313; h += u)
s[h] = u;
g[i] = o(u, .5) * e | 0, c[i++] = o(u, 1 / 3) * e | 0;
} for (r += ""; r.length % 64 - 56;)
r += "\0"; for (h = 0; h < r.length; h++) {
if ((n = r.charCodeAt(h)) >> 8)
return;
a[h >> 2] |= n << (3 - h) % 4 * 8;
} for (a[a.length] = l / e | 0, a[a.length] = l, n = 0; n < a.length;) {
var v = a.slice(n, n += 16), k = g;
for (g = g.slice(0, 8), h = 0; h < 64; h++) {
var d = v[h - 15], p = v[h - 2], w = g[0], A = g[4], C = g[7] + (t(A, 6) ^ t(A, 11) ^ t(A, 25)) + (A & g[5] ^ ~A & g[6]) + c[h] + (v[h] = h < 16 ? v[h] : v[h - 16] + (t(d, 7) ^ t(d, 18) ^ d >>> 3) + v[h - 7] + (t(p, 17) ^ t(p, 19) ^ p >>> 10) | 0);
(g = [C + ((t(w, 2) ^ t(w, 13) ^ t(w, 22)) + (w & g[1] ^ w & g[2] ^ g[1] & g[2])) | 0].concat(g))[4] = g[4] + C | 0;
}
for (h = 0; h < 8; h++)
g[h] = g[h] + k[h] | 0;
} for (h = 0; h < 8; h++)
for (n = 3; n + 1; n--) {
var M = g[h] >> 8 * n & 255;
f += (M < 16 ? 0 : "") + M.toString(16);
} return f; }
static getRandomBytes(length) {
const bytes = new Uint8Array(length);
window.crypto.getRandomValues(bytes);
return bytes;
}
static arrayBufferToBase64(buffer) {
const bytes = new Uint8Array(buffer);
const binary = bytes.reduce((previousValue, currentValue) => {
return previousValue + String.fromCharCode(currentValue);
}, "");
return btoa(binary);
}
static base64URLEncode(str) {
return WT_OAuthPkce.arrayBufferToBase64(str)
.replace(/\+/g, '-')
.replace(/\//g, '_')
.replace(/=/g, '');
}
static hexStringToBytes(str) {
return Array.from(str.match(/.{1,2}/g), (byte) => {
return parseInt(byte, 16);
});
}
static getChallenge(len) {
const verifier = WT_OAuthPkce.base64URLEncode(WT_OAuthPkce.getRandomBytes(len));
const challenge = WT_OAuthPkce.base64URLEncode(WT_OAuthPkce.hexStringToBytes(WT_OAuthPkce.sha256(verifier)));
return { "code_verifier": verifier, "code_challenge": challenge };
}
} |
JavaScript | class DisplayView {
/** @type {Electron.Display} */
display;
ipc = ipcRenderer;
/** @type {HTMLDivElement} */
container;
/** @type {HTMLElement} */
fileDisplay;
/** @type {string} */
fileStorageKey;
/** @type {string} */
file;
/**
*
* @param {Electron.Display} display to view information about and user settings editor
* @param {Element} parent element to attach view to
*/
constructor(display, parent) {
console.log(`${this.constructor.name}(${display.id})`);
this.display = display;
this.fileStorageKey = `${this.display.id}-file`;
this.file = window.localStorage.getItem(this.fileStorageKey);
/** @type {HTMLDivElement} */
this.container = createAndAppend('div', {
parent: parent,
className: 'display'
});
const topRow = createAndAppend('div', {
parent: this.container,
className: 'row'
});
createAndAppend('h2', {
parent: topRow,
className: 'title',
text: this.display.id
});
createAndAppend('span', {
parent: topRow,
className: 'size',
text: `${this.display.workAreaSize.width} * ${this.display.workAreaSize.height} @ ${this.display.workArea.x}, ${this.display.workArea.y}`
});
const fileRow = createAndAppend('div', {
parent: this.container,
className: 'row'
});
createAndAppend('button', {
parent: fileRow,
className: 'button',
text: 'Choose file'
}).onclick = () => {
this.openFile();
};
this.fileDisplay = createAndAppend('span', {
parent: fileRow,
className: 'displayfile',
text: this.file
});
this.fileDisplay.title = this.file;
if (this.file) {
this.configStorageKey = `${this.display.id}-${crypto.createHash('md5').update(this.file).digest('hex')}-config`;
this.ipc.send(this.fileStorageKey, this.file);
}
}
/**
* Calls setFile if showDialog wasn't canceled
*/
openFile() {
this.showDialog()
.then((result) => {
console.log(`${this.constructor.name}(${this.display.id}) Dialog: canceled=${result.canceled}`);
if (result.canceled) {
console.log(`${this.constructor.name}(${this.display.id}) Dialog: canceled=${result.canceled}`);
} else {
console.log(`${this.constructor.name}(${this.display.id}) Dialog: file=${result.filePaths[0]}`);
this.setFile(result.filePaths[0]);
}
}).catch((err) => {
console.error(`Error showing Open File Dialog: ${err}`, err);
});
}
/**
* to open a file, e.g. web pages, images, movies or any file. Defaults to this.file or "My Documents"
* @returns {Promise<Electron.OpenDialogReturnValue>}
*/
showDialog() {
return remote.dialog.showOpenDialog({
properties: ['openFile'],
defaultPath: this.file ? this.file : remote.app.getPath('documents'),
filters: [
{
name: 'Web pages',
extensions: ['html', 'htm']
},
{
name: 'Images',
extensions: ['jpg', 'png', 'gif']
},
{
name: 'Movies',
extensions: ['mkv', 'avi', 'mp4']
},
{
name: 'All Files',
extensions: ['*']
}
]
});
}
/**
* sets fileDisplay, stores the file URL and does IPC to the main thread to load the file
* @param {string} file URL
*/
setFile(file) {
this.file = file;
this.fileDisplay.textContent = this.file;
window.localStorage.setItem(this.fileStorageKey, this.file);
this.ipc.send(this.fileStorageKey, this.file);
}
} |
JavaScript | class bingAutosuggestV7 extends commonService {
/**
* Constructor.
*
* @param {Object} obj
* @param {string} obj.apiKey
*/
constructor({ apiKey }) {
const endpoint = "api.cognitive.microsoft.com";
super({ apiKey, endpoint });
this.endpoints = [
endpoint
];
}
/**
* Provides suggestions for a given query or partial query.
* @returns {Promise.<object>}
*/
suggestions ({ parameters, headers }) {
const operation = {
"path": "bing/v7.0/Suggestions",
"method": "GET",
"headers": [{
"name": "Accept",
"description": "Optional request header.",
"default": "application/json",
"options": [
"application/json",
"application/ld+json"
],
"required": false,
"typeName": "string"
}, {
"name": "Accept-Language",
"description": "A comma-delimited list of languages to use for user interface strings. The list is in decreasing order of preference.",
"default": null,
"required": false,
"typeName": "string"
}, {
"name": "User-Agent",
"description": "The user agent originating the request. Bing uses the user agent to provide mobile users with an optimized experience.",
"default": null,
"required": false,
"typeName": "string"
}, {
"name": "X-MSEdge-ClientID",
"description": "Bing uses this header to provide users with consistent behavior across Bing API calls. Bing often flights new features and improvements, and it uses the client ID as a key for assigning traffic on different flights. If you do not use the same client ID for a user across multiple requests, then Bing may assign the user to multiple conflicting flights.",
"default": null,
"required": false,
"typeName": "string"
}, {
"name": "X-Search-ClientIP",
"description": "Optional request header. The IPv4 or IPv6 address of the client device. The IP address is used to discover the user's location. Bing uses the location information to determine safe search behavior.",
"default": null,
"required": false,
"typeName": "string"
}, {
"name": "X-Search-Location",
"description": "Optional request header. A semicolon-delimited list of key/value pairs that describe the client's geographical location.",
"default": null,
"required": false,
"typeName": "string"
}],
"parameters": [{
"name": "cc",
"description": "A 2-character country code of the country where the results come from.",
"value": "",
"required": false,
"type": "queryStringParam",
"typeName": "string"
}, {
"name": "mkt",
"description": "The market where the results come from. Typically, mkt is the country where the user is making the request from. ",
"value": "",
"required": false,
"type": "queryStringParam",
"typeName": "string"
}, {
"name": "q",
"description": "The user's search query string.",
"value": "",
"required": false,
"type": "queryStringParam",
"typeName": "string"
}, {
"name": "setLang",
"description": "The language to use for user interface strings. Specify the language using the ISO 639-1 2-letter language code. For example, the language code for English is EN.",
"value": "",
"required": false,
"type": "queryStringParam",
"typeName": "string"
}]
};
return this.makeRequest({
operation: operation,
parameters: parameters,
headers: headers
})
};
} |
JavaScript | class Logger {
constructor(writer, prefix) {
this._indentLevel = 0;
this._indentSize = 4;
this._atLineStart = false;
this._writer = writer;
this._prefix = prefix;
}
logDebug(message) {
Utils.logDebug(message);
}
_appendCore(message) {
if (this._atLineStart) {
if (this._indentLevel > 0) {
const indent = ' '.repeat(this._indentLevel * this._indentSize);
this._writer(indent);
}
if (this._prefix) {
this._writer(`[${this._prefix}] `);
}
this._atLineStart = false;
}
this._writer(message);
}
increaseIndent() {
this._indentLevel += 1;
}
decreaseIndent() {
if (this._indentLevel > 0) {
this._indentLevel -= 1;
}
}
append(message) {
message = message || '';
this._appendCore(message);
}
appendLine(message) {
message = message || '';
this._appendCore(message + os.EOL);
this._atLineStart = true;
}
} |
JavaScript | class MainSearch extends React.Component {
constructor(props) {
super(props);
this.state = {
search_value: example.promoted_question,
match_loading: false, dataSource: example.promoted_data,
ifDist: true, ifTree: true, ifGraph: true, filter_drawer_visible: false,
filters: [], filters_visible: {}, filters_content: {}, showQuickButtons: false
};
this.handleSearch = this.handleSearch.bind(this);
this.handleSearchChange = this.handleSearchChange.bind(this);
}
componentDidMount() {
getTaskAndData(this);
}
// Autocompletion
handleSearchChange = (value) => {
let self = this;
self.setState({ search_value: value, dataSource: [], match_loading: true });
fetch(botmakerUrl + "/v1/search/autocomplete", {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': process.env.QUERY_API_KEY
},
body: JSON.stringify(
{
query: {
query: value,
n_best: 5,
query_args: {
func_type: "lm"
}
},
uid: "soco_preview_template"
}
)
})
.then(function (response) {
return response.json();
})
.then(function (json) {
self.setState({dataSource: json, match_loading: false})
});
};
// Save search history and redirect to search result page
handleSearch = (value, source) => {
let self = this;
fetch(socoUrl + '/api/feedback/save_log', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(
{
query: value,
meta: {"source": source},
query_api_key: process.env.QUERY_API_KEY
}
)
})
.then(function (response) {
return response.json();
})
.then(function (json) {
self.props.history.push('/search/result?query=' + value + "&filters_content=" + JSON.stringify(self.state.filters_content));
});
};
// Open/Close filter drawer
handleFiltersVisible = (type) => {
let filters_visible = {...this.state.filters_visible};
filters_visible[type] = !filters_visible[type];
this.setState({ filters_visible });
}
// Handle filter changes
handleCheckedFilters = (type, label, checked) => {
let filters_content = {...this.state.filters_content};
if (!filters_content.hasOwnProperty(type))
filters_content[type] = [];
if (label === "No " + type)
label = ""
if (checked)
if (!filters_content[type].includes(label))
filters_content[type].push(label);
else {}
else
filters_content[type] = filters_content[type].filter(l => l !== label);
if (filters_content[type].length === 0)
delete filters_content[type];
this.setState({ filters_content })
}
render() {
const {
search_value, match_loading, dataSource, showQuickButtons,
ifDist, ifTree, ifGraph, filter_drawer_visible, filters, filters_visible, filters_content
} = this.state;
return (
<div style={{background: "#fff", height: "100vh"}} className="soco-preview-page">
{filters.length !== 0 &&
<FilterDrawer
filter_drawer_visible={filter_drawer_visible} filters={filters} filters_visible={filters_visible} filters_content={filters_content}
onDrawerClose={() => this.setState({filter_drawer_visible: false})}
handleFiltersVisible={this.handleFiltersVisible} handleCheckedFilters={this.handleCheckedFilters}
/>
}
<div
className={"soco-list"}
style={{
backgroundColor: "#ffffff",
height: "60px",
}}
>
<div className="soco-list" style={{marginLeft: "20px", justifyContent: "flex-start"}}>
</div>
<div className="soco-list" style={{justifyContent: "flex-end"}}>
<div className={"soco-list"} style={{margin: window.innerWidth >= 768? "0 30px 0 0" : "-20px 20px 0 0", justifyContent: "flex-start", cursor: filters.length > 0 ? "pointer" : "not-allowed"}} onClick={() => {
this.setState({filter_drawer_visible: true});
}}>
<div className={"soco-list_item"}><img src="pic/svg/filter.svg" alt={"soco-filter"} /></div>
<div className={"soco-list_item"} style={{margin: "2px 0 0 15px", fontSize: "16px", color: "#000"}}>Filter</div>
</div>
</div>
</div>
<div
className={"search-main-page"}
style={{paddingBottom: window.innerWidth >= 768? "150px" : "100px"}}
>
<div
className={"soco-main-search"}
>
<div style={{}} className={"soco-logo"}>
<a href="https://www.soco.ai" target={"_blank"}>
<img
className={"soco-image_logo"}
src={"pic/SOCO_with_company_name.png"}
alt={"soco-logo"}
width={window.innerWidth >= 768? window.innerWidth * 0.2 : "250px"}
/>
</a>
</div>
<AutoComplete
className={"search-box-main"}
dataSource={
match_loading?
[1, 2, 3, 4, 5].map(s => <AutoComplete.Option key={"loading-" + s} style={{width: "100%"}}>
<Skeleton loading={match_loading} active title={false} paragraph={{rows: 1, width: "100%"}} ></Skeleton>
</AutoComplete.Option>)
: dataSource.map((item, i) => (
<AutoComplete.Option key={item.text}>{item.text}</AutoComplete.Option>
))
}
size="large"
onChange={(e) => this.handleSearchChange(e)}
onSelect={(value) => this.handleSearch(value, "autocomplete")}
onMouseDown={() => {}}
onBlur={() => {}}
value={search_value}
defaultActiveFirstOption={false}
>
<Input
className="soco-preview-search"
size="large"
placeholder={"Ask a question in natural language"}
onPressEnter={() => this.handleSearch(search_value, "search_bar")}
/>
</AutoComplete>
{/* Quick Buttons to Check Init Search Result and Also Soco Python Package Documentation */}
{ showQuickButtons && <div className={"search-faq-container soco-list"} style={{justifyContent: "center", fontSize: "16px", flexDirection: "column"}}>
<div className="soco-init-search soco-list" style={{}}>
<div
className="soco-list_item soco-init-search_item"
style={{cursor: ifDist? "pointer" : "not-allowed", color: ifDist? "rgba(0, 0, 0, 0.65)" : "#979797", width: window.innerWidth >= 768? "50%" : "90%"}}
onClick={() => {
if (ifDist)
this.props.history.push('/search/result?tab=md')
}}
>
{ifDist? <span><span className="soco-init-search_icon"><img src="pic/svg/mdist.svg" /></span><span>Meta Distribution</span></span>
: <Tooltip placement="bottom" title={"Please check if you set config values in setting page to hide the meta distribution."}>
<span className="soco-init-search_icon"><img src="pic/svg/mdist_grey.svg" /></span><span>Meta Distribution</span>
</Tooltip>
}
</div>
{window.innerWidth >= 768 && <div
className="soco-list_item"
style={{cursor: ifTree? "pointer" : "not-allowed", color: ifTree? "rgba(0, 0, 0, 0.65)" : "#979797", width: "50%"}}
onClick={() => {
if (ifTree)
this.props.history.push('/search/result?tab=kt')
}}
>
{ifTree? <span style={{marginLeft: "80px"}}><span className="soco-init-search_icon"><img src="pic/svg/ktree.svg" /></span><span>Knowledge Tree</span></span>
: <Tooltip placement="bottom" title={"Please check if you set config values in setting page to hide the knowledge tree."}>
<span style={{marginLeft: "80px"}}><span className="soco-init-search_icon"><img src="pic/svg/ktree_grey.svg" /></span><span>Knowledge Tree</span></span>
</Tooltip>
}
</div>}
</div>
<div className="soco-init-search soco-list" style={{marginTop: window.innerWidth >= 768? "40px" : "initial"}}>
{window.innerWidth >= 768 && <div
className="soco-list_item"
style={{cursor: ifGraph? "pointer" : "not-allowed", color: ifTree? "rgba(0, 0, 0, 0.65)" : "#979797", width: "50%"}}
onClick={() => {
if (ifGraph)
this.props.history.push('/search/result?tab=kg')
}}
>
{ifGraph? <span><span className="soco-init-search_icon"><img src="pic/svg/kgraph.svg" /></span><span>Knowledge Graph</span></span>
: <Tooltip placement="bottom" title={"Please check if you set config values in setting page to hide the knowledge graph."}>
<span className="soco-init-search_icon"><img src="pic/svg/kgraph_grey.svg" /></span><span>Knowledge Graph</span>
</Tooltip>
}
</div>}
<a className="soco-list_item soco-init-search_item" style={{width: window.innerWidth >= 768? "50%" : "90%"}} href="https://docs.soco.ai/" target="_blank" style={{color: "rgba(0, 0, 0, 0.65)", marginLeft: window.innerWidth >= 768? "80px" : "initial"}} >
<span className="soco-init-search_icon"><img src="pic/svg/tutorial.svg" /></span><span>How to Use Soco</span>
</a>
</div>
</div>}
</div>
</div>
</div>
)
};
} |
JavaScript | class MediaManagerServer {
constructor() {
this._nextClientId = 1;
this._logger = debug('MediaManagerServer');
this._clients = [];
this._logger('ctor');
bind(
this,
'_handleRegisterMediaManager',
);
this._channelListener = otherWindowIPC.createChannel('mediaManager');
this._channelListener.on('connect', this._handleRegisterMediaManager);
}
_handleRegisterMediaManager(stream) {
const id = this._nextClientId++;
this._logger('registerMediaManager: id =', id);
const client = new MediaClientProxy(id, stream, this);
this._clients.push(client);
stream.on('disconnect', () => {
const ndx = this._clients.indexOf(client);
if (ndx >= 0) {
this._clients.splice(ndx, 1);
}
});
}
close() {
this._clients.slice().forEach((client) => {
client.close();
});
this._channelListener.close();
}
} |
JavaScript | class ArticleBodyComponent extends Component {
initialize(options) {
this.imageContainerSelector = ".stack__article__image-container";
this.poiData = options.poiData;
this.loadImages().then(() => {
this.gallery = new ImageGallery({
el: this.$el
});
});
if (this.poiData) {
matchMedia(`(min-width: ${breakpoints.min["1200"]})`, (query) => {
if (query.matches) {
this.loadPoiCallout(this.poiData);
} else {
if (typeof this.poiCallout !== "undefined") {
this.poiCallout.destroy();
}
}
});
}
let featuredImage = this.el.find(this.imageContainerSelector);
let $paragraphs = this.$el.find("p");
let showAd = $paragraphs.length >= 2 || featuredImage.length;
if (showAd) {
matchMedia(`(max-width: ${breakpoints.max["480"]})`, (query) => {
if (query.matches) {
this._appendAd($paragraphs, featuredImage);
}
});
}
this.formatDate();
this.loadVideos();
}
loadVideos() {
this.$el.find("[data-op-video-id]")
.addClass("is-visible")
.each((i, el) => {
Video.addPlayer(el, {
insertPixel: false,
playsInline: true,
}).then((player) => {
const description = player.getVideoProperty("description") || "";
$(player.videoEl).after(`<span class="copy--caption">${description}</span>`);
});
});
}
/**
* Loads all the images in the body of the article
* @return {Promise} A promise for when all of the images have loaded
*/
loadImages() {
let promises = [];
this.$el.find(this.imageContainerSelector).each((index, el) => {
let $img = $(el).find("img"),
$a = $(el).find("a").eq(0),
$span = $(el).find("span"),
src = $($img).attr("src");
let promise = this.loadImage(src).then((image) => {
if (!$a.length) {
$img.wrap(`<a class="copy--body__link" href="${src}" data-size="${image.width}x${image.height}" />`);
} else {
$a.attr("data-size", `${image.width}x${image.height}`);
}
if(image.width > 1000 && $img.hasClass("is-landscape")) {
$(el).addClass("is-wide");
}
$(el).addClass("is-visible");
if (!$span.length) {
$(el).contents().filter(function() {
return this.nodeType === 3 && $.trim(this.nodeValue).length;
}).wrap("<span class=\"copy--caption\" />");
}
});
promises.push(promise);
});
return Promise.all(promises).catch((err) => {
rizzo.logger.log(err);
});
}
/**
* Preload an image
* @param {String} url Url of the image to load
* @return {Promise} A promise for when the image loads
*/
loadImage(url) {
let image = new Image();
return new Promise((resolve, reject) => {
image.src = url;
image.onload = function() {
resolve(image);
};
image.onerror = function() {
reject(url);
};
if (!url) {
reject(url);
}
});
}
/**
* Format the post date with moment.js
*/
formatDate() {
let $footer = this.$el.siblings(".js-article-footer"),
date = $footer.find("time").attr("datetime"),
formattedDate = moment(date).format("MMMM YYYY");
$footer
.find("time").html(formattedDate)
.closest(".js-article-post-date").removeProp("hidden");
}
/**
* Creates a new instance of the POI callout
* @param {Object} data POI data
*/
loadPoiCallout(data) {
this.poiCallout = new PoiCallout({
el: this.$el,
pois: data
});
}
_appendAd($paragraphs, $featuredImage) {
const element = `
<div class="ad ad--inline ad--yieldmo ad--article">
<div class="ad--inline__container">
<div
id="ad-articles-yieldmo"
class="adunit--article"></div>
</div>
</div>`;
if($featuredImage.length) {
$featuredImage.eq(0).after(element);
} else {
$paragraphs.eq(1).after(element);
}
window.lp.ads.manager.load();
}
} |
JavaScript | class DisconnectedSearchResults extends React.Component {
constructor() {
super();
this.state = {
redirect: false,
title: ''
};
}
componentDidMount() {
return (
<div>
<h3>loading...</h3>
</div>
);
}
// onClick(filmTitle) {
// this.props.advancedSearch(urlFriendly(filmTitle));
// this.setState({redirect: true, title: filmTitle});
// }
render() {
if (!this.props.results.length) {
return <div />;
}
// if (this.state.redirect) {
// return (
// <Redirect
// to={`/advancedSearch/${this.state.title}`}
// props={this.state.props}
// />
// );
// }
return (
<div className="row">
{this.props.results.map(film => (
<div key={film.imdbid} className="card">
<Link to={`/advancedSearch/${film.title}`}>
<FilmView film={film} />
</Link>
<Route path={`/advancedSearch/${film.title}`} />
</div>
))}
</div>
);
}
} |
JavaScript | class FakeFirebaseRef {
constructor(val) {
this.val = val;
}
set(val) {
this.val = val;
}
} |
JavaScript | class RoleInfo extends Command {
/**
* @param {Client} client The instantiating client
* @param {CommandData} data The data for the command
*/
constructor(bot) {
super(bot, {
name: 'role-info',
guildOnly: true,
dirname: __dirname,
aliases: ['roleinfo'],
botPermissions: ['SEND_MESSAGES', 'EMBED_LINKS'],
description: 'Get information on a role.',
usage: 'role-info <role>',
cooldown: 2000,
examples: ['role-info roleID', 'role-info @mention', 'role-info name'],
slash: true,
options: [{
name: 'role',
description: 'Get information of the role.',
type: 'ROLE',
required: true,
}],
});
}
/**
* Function for recieving message.
* @param {bot} bot The instantiating client
* @param {message} message The message that ran the command
* @param {settings} settings The settings of the channel the command ran in
* @readonly
*/
async run(bot, message, settings) {
// Check to see if a role was mentioned
const roles = message.getRole();
// Make sure it's a role on the server
if (!roles[0]) {
if (message.deletable) message.delete();
// Make sure a poll was provided
return message.channel.error('misc:INCORRECT_FORMAT', { EXAMPLE: settings.prefix.concat(message.translate('guild/role-info:USAGE')) }).then(m => m.timedDelete({ timeout: 5000 }));
}
const embed = this.createEmbed(bot, message.guild, roles[0], message.author);
message.channel.send({ embeds: [embed] });
}
/**
* Function for recieving interaction.
* @param {bot} bot The instantiating client
* @param {interaction} interaction The interaction that ran the command
* @param {guild} guild The guild the interaction ran in
* @param {args} args The options provided in the command, if any
* @readonly
*/
async callback(bot, interaction, guild, args) {
const role = guild.roles.cache.get(args.get('role').value);
const user = interaction.member.user;
// send embed
const embed = this.createEmbed(bot, guild, role, user);
interaction.reply({ embeds: [embed] });
}
/**
* Function for creating embed of role information.
* @param {bot} bot The instantiating client
* @param {guild} Guild The guild the command was ran in
* @param {role} Role The role to get information from
* @param {user} User The user for embed#footer
* @returns {embed}
*/
createEmbed(bot, guild, role, user) {
// translate permissions
const permissions = role.permissions.toArray().map((p) => guild.translate(`permissions:${p}`)).join(' » ');
// Send information to channel
return new Embed(bot, guild)
.setColor(role.color)
.setAuthor({ name: user.tag, iconURL: user.displayAvatarURL() })
.setDescription(guild.translate('guild/role-info:NAME', { NAME: role.name }))
.addFields(
{ name: guild.translate('guild/role-info:MEMBERS'), value: role.members.size.toLocaleString(guild.settings.Language), inline: true },
{ name: guild.translate('guild/role-info:COLOR'), value: role.hexColor, inline: true },
{ name: guild.translate('guild/role-info:POSITION'), value: `${role.position}`, inline: true },
{ name: guild.translate('guild/role-info:MENTION'), value: `<@&${role.id}>`, inline: true },
{ name: guild.translate('guild/role-info:HOISTED'), value: `${role.hoist}`, inline: true },
{ name: guild.translate('guild/role-info:MENTIONABLE'), value: `${role.mentionable}`, inline: true },
{ name: guild.translate('guild/role-info:PERMISSION'), value: permissions },
{ name: guild.translate('guild/role-info:CREATED'), value: moment(role.createdAt).format('lll') },
)
.setTimestamp()
.setFooter('guild/role-info:FOOTER', { MEMBER: user.tag, ID: role.id });
}
} |
JavaScript | class InlineResponse20082Data {
/**
* Constructs a new <code>InlineResponse20082Data</code>.
* @alias module:model/InlineResponse20082Data
*/
constructor() {
InlineResponse20082Data.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>InlineResponse20082Data</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/InlineResponse20082Data} obj Optional instance to populate.
* @return {module:model/InlineResponse20082Data} The populated <code>InlineResponse20082Data</code> instance.
*/
static constructFromObject(data, obj) {
if (data) {
obj = obj || new InlineResponse20082Data();
if (data.hasOwnProperty('id')) {
obj['id'] = ApiClient.convertToType(data['id'], 'String');
}
if (data.hasOwnProperty('valueUnit')) {
obj['valueUnit'] = InlineResponse20079DataValueUnit.constructFromObject(data['valueUnit']);
}
if (data.hasOwnProperty('currency')) {
obj['currency'] = InlineResponse20079DataCurrency.constructFromObject(data['currency']);
}
if (data.hasOwnProperty('market')) {
obj['market'] = InlineResponse20079DataMarket.constructFromObject(data['market']);
}
if (data.hasOwnProperty('quality')) {
obj['quality'] = ApiClient.convertToType(data['quality'], 'String');
}
if (data.hasOwnProperty('bid')) {
obj['bid'] = InlineResponse20082Bid.constructFromObject(data['bid']);
}
if (data.hasOwnProperty('ask')) {
obj['ask'] = InlineResponse20082Ask.constructFromObject(data['ask']);
}
if (data.hasOwnProperty('status')) {
obj['status'] = InlineResponse20065Status.constructFromObject(data['status']);
}
}
return obj;
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.