language
stringclasses 5
values | text
stringlengths 15
988k
|
---|---|
JavaScript | class CSVCleaner extends Transform {
constructor(options) {
super(options);
}
_transform(chunk, encoding, next) {
for (let key in chunk) {
//trims whitespace
chunk[key] = chunk[key].trim();
}
//uses our csvStringifier to turn our chunk into a csv string
chunk = csvStringifier.stringifyRecords([chunk]);
this.push(chunk);
next();
}
} |
JavaScript | class PreferredChoice {
/**
* Creates a new PreferredChoice instance given the array of choices and array of interestIDs.
* @param choices
* @param interestIDs
*/
constructor(choices, interestIDs) {
this._rankedChoices = {};
let max = 0;
_.forEach(choices, (choice) => {
const score = _.intersection(choice.interestIDs, interestIDs).length;
if (score > max) {
max = score;
}
if (!this._rankedChoices[score]) {
this._rankedChoices[score] = [];
}
this._rankedChoices[score].push(choice);
});
this.max = max;
}
/**
* Returns an array of the choices that best match the interestIDs.
* @returns {*} an array of the choices that best match the interests.
*/
getBestChoices() {
return this._rankedChoices[this.max];
}
/**
* Returns an array with the best matches first.
* @returns {Array}
*/
getOrderedChoices() {
let choices = [];
for (let i = this.max; i >= 0; i--) {
if (this._rankedChoices[i]) {
choices = choices.concat(this._rankedChoices[i]);
}
}
// console.log(choices);
return choices;
}
/**
* Returns true if there are any preferences.
* @return {boolean} true if max !== 0.
*/
hasPreferences() {
return this.max !== 0;
}
} |
JavaScript | class LeadershipScreen extends Component {
render() {
return (
<StyleProvider style={getTheme(material)}>
<Container>
<Tabs tabBarUnderlineStyle={{ backgroundColor: '#00ffff' }}>
<Tab heading={ <TabHeading><Icon name="people" /><Text>Board</Text></TabHeading>}
>
<Text>Member</Text>
</Tab>
<Tab heading={ <TabHeading ><Text>Cypress</Text></TabHeading>}
>
<Text>Cypress</Text>
</Tab>
<Tab heading={ <TabHeading><Text>Cerritos</Text></TabHeading>}
>
<Text>Cerritos</Text>
</Tab>
</Tabs>
</Container>
</StyleProvider>
);
}
} |
JavaScript | class View {
/** Constructor */
constructor(options = {}) {
/** The subviews of this view */
this.subviews = []
/** The parent view, if any */
this.parentView = null
/** @private Private data goes in here. For private framework use only. */
this._ = {}
/** @private Stores visibility flag */
this._.visible = true
/** @private Exposed properties added by the theme */
this._.themeProperties = {}
/** @private The root element */
this._.element = document.createElement("div")
this._.element.style.cssText = "position: absolute; top: 0px; left: 0px; width: 100%; height: 100%; z-index: 1; overflow: hidden; "
/** @private The element which contains child views */
this._.contentElement = null
// Setup UI components
this.setup()
// Add content element to container
if (this._.contentElement)
this._.element.appendChild(this._.contentElement)
// Set default layout mode
this.layoutMode = View.LayoutModes.Absolute
// Load default theme
this.theme = View.defaultTheme
// Set properties passed by the user
for (var name in options)
this[name] = options[name]
}
/**
* Setup UI components. Subviews can override this and create their own `this._.contentElement` if it's a different
* type. This is only ever called once.
*
* @private
*/
setup() {
// Create default content element
this._.contentElement = document.createElement("div")
this._.contentElement.style.cssText = "position: absolute; top: 0px; left: 0px; width: 100%; height: 100%; "
}
/** The current theme in use. */
get theme() {
return this._.theme
}
set theme(v) {
// Set new theme
this._.theme = v
// Reset theme properties
this._.themeProperties = {}
// Remove all elements from the container element except our content element
// Themes often insert their own elements to the container element.
for (var i = 0 ; i < this._.element.children.length ; i++)
if (this._.element.children[i] != this._.contentElement)
this._.element.removeChild(this._.element.children[i--])
// Re-theme us
this._.theme.applyTo(this)
}
/** Get or set a theme property */
themeProperty(name, value) {
return this.theme.property(this, name, value)
}
/** Add this view to the specified view */
addTo(parent) {
parent.add(this)
}
/** Add the subview to this view */
add(subview) {
// Make sure this view is able to have subviews
if (!this._.contentElement || this._.contentElement.tagName.toLowerCase() != "div")
throw new Error("This view does not support subviews.")
// Make sure subview is the right type
if (!(subview instanceof View))
throw new Error("The specified subview was not an instance of View.")
// Check that the subview isn't already added to a view
if (subview.parentView)
throw new Error("This subview has already been added to another view.")
// Store in subviews array
this.subviews.push(subview)
// Append element
this._.contentElement.appendChild(subview._.element)
// Notify view it's parent changed
var oldParent = subview.parentView
subview.parentView = this
subview.onParentChanged(oldParent)
// Notify view if it became visible or not
// TODO: Proper visibility events!
if (!oldParent)
subview.onBecameVisible()
// First time layout
setTimeout(e => subview.onLayout(), 0)
}
/** True if the view is visible */
get visible() {
return this._.visible
}
set visible(v) {
this._.visible = v
this.onLayout()
}
/** Get view opacity */
get opacity() {
return parseFloat(this._.element.style.opacity) || 0
}
/** Set view opacity */
set opacity(v) {
this._.element.style.opacity = v
}
/** Get the current layout mode */
get layoutMode() {
return this._.layoutMode
}
/** Set the layout mode */
set layoutMode(v) {
this._.layoutMode = v
this.onLayout()
}
/** Gets the minimum size required to show all this view's content */
get contentSize() {
// Get maximum content size of subviews
var width = 0
var height = 0
for (var subview of this.subviews) {
width = Math.max(width, (subview.x || 0) + subview.contentSize.width)
height = Math.max(height, (subview.y || 0) + subview.contentSize.height)
}
return { width, height }
}
/** Called when the parent view changes */
onParentChanged(oldParent) {}
/** Called when the view becomes visible */
onBecameVisible() {}
/** Called when the view stops being visible */
onBecameHidden() {}
/** Called when the view size or position changes. */
onLayout() {
// Check visibility
if (!this._.visible) {
// Not visible
this._.element.style.display = "none"
} else if (this._.layoutMode == View.LayoutModes.InlineBlock) {
// Visible in inline-block layout mode
this._.element.style.display = "inline-block"
this._.element.style.top = "initial"
this._.element.style.left = "initial"
this._.element.style.width = "initial"
this._.element.style.height = "initial"
this._.element.style.position = "relative"
} else if (this._.layoutMode == View.LayoutModes.Block) {
// Visible in block layout mode
this._.element.style.display = "block"
this._.element.style.top = "initial"
this._.element.style.left = "initial"
this._.element.style.width = "initial"
this._.element.style.height = "initial"
this._.element.style.position = "relative"
} else if (this._.layoutMode == View.LayoutModes.Absolute) {
// Visible in absolute layout mode
this._.element.style.display = "block"
this._.element.style.top = this.top
this._.element.style.left = this.left
this._.element.style.width = this.width
this._.element.style.height = this.height
this._.element.style.position = "absolute"
}
// Notify child views as well
for (var view of this.subviews)
view.onLayout()
}
/** Get / set position CSS values. Only works in `LayoutMode.Absolute`. */
get top() { return this._.top || "0px" }
get left() { return this._.top || "0px" }
get top() { return this._.top || "0px" }
get top() { return this._.top || "0px" }
} |
JavaScript | class Message extends HTMLElement {
/**
* Indicate which attributes should trigger attributeChangedCallback
*/
static get observedAttributes() {
return ["text"];
}
constructor() {
super();
this.render();
}
/**
* When the observed attributes change, call render
*/
attributeChangedCallback() {
this.render();
}
/**
* Get the HTML to render.
* This function is a simple helper, to make the syntax cleaner.
*/
getHtml() {
const text = sanitize(this.getAttribute("text") || "");
const tag = sanitize(this.getAttribute("tag") || "");
if (!text) return "";
switch (tag) {
case "H1":
return `<h1>${text}</h1>`;
case "H2":
return `<h2>${text}</h2>`;
case "H3":
return `<h3>${text}</h3>`;
case "H4":
return `<h4>${text}</h4>`;
case "SPAN":
return `<span>${text}</span>`;
default:
return `<p>${text}</p>`;
}
}
/**
* Render the component HTML
*/
render() {
this.innerHTML = this.getHtml();
}
} |
JavaScript | class ConnectedSongDetail extends React.Component {
constructor() {
// Get access to 'this' as subclass.
super();
this.state = {
embedHtmlError: ''
};
// Set 'this' scope to this class for methods.
this.getSongEmbedHtml = this.getSongEmbedHtml.bind(this);
}
componentDidMount() {
// If we have not yet obtained the embed
// HTML for this song.
if (this.props.song.embedHtml === '')
this.getSongEmbedHtml();
}
getSongEmbedHtml() {
// Set the URL to call.
let url = 'https://soundcloud.com/oembed?format=json&maxwidth=480&maxheight=140&url=' + this.props.song.url;
// Create separate variable outside of fetch scope
// to store response.ok boolean, since we don't want
// to get into Promise-land hell.
let resOk;
// Call the API.
fetch(url, {
method: 'GET'
}).then((res) => {
// Store the ok boolean of the response.
resOk = res.ok;
// Parse response body as JSON.
//
// We use a promise here since the .json() method reads
// in the response body in a returned Promise.
return res.json();
}).then((res) => {
// Check if there was an HTTP code error
// (res.ok checks if 200 <= res.statusCode <= 299).
if (!resOk) {
this.setState({
embedHtmlError: 'Could not load embedded player for this song'
});
return;
}
// Dispatch success action.
this.props.getSongEmbedHtmlSuccess(this.props.song.id, res.html);
}).catch((err) => {
this.setState({
embedHtmlError: 'Could not load embedded player for this song'
});
});
}
render() {
return (
<div className={styles.detail}>
<Embed embedHtml={this.props.song.embedHtml} embedHtmlError={this.state.embedHtmlError} />
</div>
);
}
} |
JavaScript | class GitHubResolver extends URLResolver {
static getSourceHandlers(url) {
const sourceHandlers = [];
const repoInfo = this._parseURL(url);
if (repoInfo != null) {
const repoPath = `${repoInfo.owner}/${repoInfo.repoName}`;
sourceHandlers.push(new GitHubAPIHandler(apiBaseUrl, repoPath));
}
return sourceHandlers;
}
static _parseURL(url) {
const strippedURL = url.replace(stripHttp, '');
const matches = urlRegex.exec(strippedURL);
if (matches != null && matches.length === 3) {
return {
owner: matches[1],
repoName: matches[2],
};
}
return null;
}
} |
JavaScript | class TimeLine extends Component {
render() {
return (
<div className={this.props.classes.timeline}>
<VerticalTimeline>
{TimeLineInfo.map((element,key) =>
<VerticalTimelineElement
key={key}
date={element.date}
iconStyle={{ backgroundColor: element.bgColor, display: "flex"}}
icon={<Icon color="primary" style={{ margin: "auto", color: element.color}}>{element.icon}</Icon>}
>
<Typography variant="title" gutterBottom >{element.title}</Typography>
<Typography><b>{element.subtitle}</b></Typography>
<Typography align="justify">
{element.description}
<br/>
{element.link? <a href={element.link} target="_blank" rel="noopener noreferrer">{element.link}</a>: null}
<br/>
{element.tecnologies.map((value,k)=>
<Chip label={value} key={k}/>
)}
</Typography>
</VerticalTimelineElement>
)}
</VerticalTimeline>
</div>
);
}
} |
JavaScript | class OrderManagementApiService extends ApiService {
/**
* @constructor
* @param {AxiosInstance} httpClient
* @param {LoginService} loginService
*/
constructor(httpClient, loginService) {
super(httpClient, loginService, 'ratepay/order-management');
this.httpClient = httpClient;
this.loginService = loginService;
this.name = 'ratepayOrderManagementService';
}
load(orderId) {
return this.httpClient
.get(this.getApiBasePath() + '/load/' + orderId,
{
headers: this.getBasicHeaders()
}
).then(response => response.data)
}
doAction(action, orderId, items, updateStock) {
return this.httpClient
.post(this.getApiBasePath() + '/' + action + '/' + orderId,
{
items: items,
updateStock: typeof updateStock == 'boolean' ? updateStock : null
},
{
headers: this.getBasicHeaders()
}
).then(response => response.data)
}
addItem(orderId, name, grossAmount, taxId) {
return this.httpClient
.post(this.getApiBasePath() + '/addItem/' + orderId,
{
name,
grossAmount,
taxId
},
{
headers: this.getBasicHeaders()
}
).then(response => response.data)
}
} |
JavaScript | class AzureWorkloadSQLRestoreRequest extends models['AzureWorkloadRestoreRequest'] {
/**
* Create a AzureWorkloadSQLRestoreRequest.
* @member {boolean} [shouldUseAlternateTargetLocation] Default option set to
* true. If this is set to false, alternate data directory must be provided
* @member {boolean} [isNonRecoverable] SQL specific property where user can
* chose to set no-recovery when restore operation is tried
* @member {object} [targetInfo] Details of target database
* @member {string} [targetInfo.overwriteOption] Can Overwrite if Target
* DataBase already exists. Possible values include: 'Invalid',
* 'FailOnConflict', 'Overwrite'
* @member {string} [targetInfo.containerId] Resource Id name of the
* container in which Target DataBase resides
* @member {string} [targetInfo.databaseName] Database name
* InstanceName/DataBaseName for SQL or System/DbName for SAP Hana
* @member {array} [alternateDirectoryPaths] Data directory details
*/
constructor() {
super();
}
/**
* Defines the metadata of AzureWorkloadSQLRestoreRequest
*
* @returns {object} metadata of AzureWorkloadSQLRestoreRequest
*
*/
mapper() {
return {
required: false,
serializedName: 'AzureWorkloadSQLRestoreRequest',
type: {
name: 'Composite',
polymorphicDiscriminator: {
serializedName: 'objectType',
clientName: 'objectType'
},
uberParent: 'RestoreRequest',
className: 'AzureWorkloadSQLRestoreRequest',
modelProperties: {
objectType: {
required: true,
serializedName: 'objectType',
isPolymorphicDiscriminator: true,
type: {
name: 'String'
}
},
recoveryType: {
required: false,
serializedName: 'recoveryType',
type: {
name: 'String'
}
},
sourceResourceId: {
required: false,
serializedName: 'sourceResourceId',
type: {
name: 'String'
}
},
propertyBag: {
required: false,
serializedName: 'propertyBag',
type: {
name: 'Dictionary',
value: {
required: false,
serializedName: 'StringElementType',
type: {
name: 'String'
}
}
}
},
shouldUseAlternateTargetLocation: {
required: false,
serializedName: 'shouldUseAlternateTargetLocation',
type: {
name: 'Boolean'
}
},
isNonRecoverable: {
required: false,
serializedName: 'isNonRecoverable',
type: {
name: 'Boolean'
}
},
targetInfo: {
required: false,
serializedName: 'targetInfo',
type: {
name: 'Composite',
className: 'TargetRestoreInfo'
}
},
alternateDirectoryPaths: {
required: false,
serializedName: 'alternateDirectoryPaths',
type: {
name: 'Sequence',
element: {
required: false,
serializedName: 'SQLDataDirectoryMappingElementType',
type: {
name: 'Composite',
className: 'SQLDataDirectoryMapping'
}
}
}
}
}
}
};
}
} |
JavaScript | class evaluator {
/**
* Evaluate logic's
* @param {string} parentUuid Parent (Window / Process / Smart Browser)
*/
static evaluateLogic(objectToEvaluate) {
var defaultUndefined = false
if (objectToEvaluate.type === 'displayed') {
defaultUndefined = true
}
// empty logic
if (typeof objectToEvaluate.logic === 'undefined' ||
objectToEvaluate.logic === null ||
objectToEvaluate.logic.trim() === '') {
return defaultUndefined
}
var st = objectToEvaluate.logic.trim().replace('\n', '')
st = st.replace('|', '~')
var expr = /(~|&)/
var stList = st.split(expr)
var it = stList.length
if (((it / 2) - ((it + 1) / 2)) === 0) {
console.log(
'Logic does not comply with format "<expression> [<logic> <expression>]"' +
' --> ' + objectToEvaluate.logic
)
return defaultUndefined
}
var retValue = null
var logOp = ''
stList.forEach(function(element) {
if (element === '~' || element === '&') {
logOp = element
} else if (retValue === null) {
retValue = evaluator.evaluateLogicTuples({
...objectToEvaluate,
conditional: element
})
} else {
if (logOp === '&' && logOp !== '') {
retValue = retValue & evaluator.evaluateLogicTuples({
...objectToEvaluate,
conditional: element
})
} else if (logOp === '~' && logOp !== '') {
retValue = retValue | evaluator.evaluateLogicTuples({
...objectToEvaluate,
conditional: element
})
} else {
console.log("Logic operant '|' or '&' expected --> " + objectToEvaluate.logic)
return defaultUndefined
}
}
})
return Boolean(retValue)
} // evaluateLogic
/**
* Evaluate Logic Tuples
* @param {object} objectToEvaluate Complete object
* @param {string} logic If is displayed or not (mandatory and readonly)
* @return {boolean}
*/
static evaluateLogicTuples(objectToEvaluate) {
var _defaultUndefined = false
if (objectToEvaluate.type === 'displayed') {
_defaultUndefined = true
}
var logic = objectToEvaluate.conditional
// not context info, not logic
if (typeof logic === 'undefined') {
return _defaultUndefined
}
var expr = /^(['"@a-zA-Z0-9\-_]){0,}((!*={1})|(!{1})|(<{1})|(>{1}))(["'@a-zA-Z0-9\-_]){0,}$/i
var st = expr.test(logic)
if (!st) {
console.log(
".Logic tuple does not comply with format '@context@=value' where operand" +
" could be one of '=!^><' --> " + logic
)
return _defaultUndefined
}
expr = /(!*={1})/
st = logic.split(expr)
if (st.length === 1) {
expr = /(<{1})/
st = logic.split(expr)
}
if (st.length === 1) {
expr = /(>)/
st = logic.split(expr)
}
// First Part
var first = st[0]
var firstEval = first
expr = /@/
if (expr.test(first)) {
first = first.replace(/@/g, '').trim()
var value = objectToEvaluate.context.getContext({
parentUuid: objectToEvaluate.parentUuid,
containerUuid: objectToEvaluate.containerUuid,
columnName: first
})
// in context exists this column name
if (typeof value === 'undefined') {
console.log(
'.The column ' + first + ' not exists in context.'
)
return _defaultUndefined
}
firstEval = value // replace with it's value
}
if (firstEval === null) {
return _defaultUndefined
}
if (typeof firstEval !== 'boolean') {
firstEval = firstEval.replace(/['"]/g, '').trim() // strip ' and "
}
// Operator
var operand = st[1]
// Second Part
var second = st[2]
var secondEval = second
if (second.indexOf('@') !== -1) {
second = second.replace('@', ' ').trim() // strip tag
secondEval = objectToEvaluate.context.getContext({
parentUuid: objectToEvaluate.parentUuid,
containerUuid: objectToEvaluate.containerUuid,
columnName: first
}) // replace with it's value
}
secondEval = secondEval.replace(/['"]/g, '').trim() // strip ' and "
// Handling of ID compare (null => 0)
if (first.indexOf('_ID') !== -1 && firstEval.length === 0) { firstEval = '0' }
if (second.indexOf('_ID') !== -1 && secondEval.length === 0) { secondEval = '0' }
// Logical Comparison
var result = this.evaluateLogicTuple(firstEval, operand, secondEval)
return result
}
/**
* Evuale logic Tuple
* @param {string|number} value1 Value in Context
* @param {string} operand Comparison
* @param {string|number} value2 Value in Logic
* @return {boolean}
*/
static evaluateLogicTuple(value1, operand, value2) {
// Convert value 1 string value to boolean value
if (value1 === 'Y') {
value1 = true
} else if (value1 === 'N') {
value1 = false
}
// Convert value 2 string value to boolean value
if (value2 === 'Y') {
value2 = true
} else if (value2 === 'N') {
value2 = false
}
if (value1 == null || operand == null || value2 == null) {
return false
}
if (operand === '=') {
return value1 === value2
} else if (operand === '<') {
return value1 < value2
} else if (operand === '>') {
return value1 > value2
} else {
// interpreted as not
return value1 !== value2
}
}
/**
* Parse Depends or relations
* @param {string} parseString
* @return {array}
*/
static parseDepends(parseString) {
var listFields = []
if (parseString === null || typeof parseString === 'undefined') {
// return array empy
return listFields
}
let string = parseString.replace('@SQL=', '')
// while we have variables
while (string.indexOf('@') !== -1) {
let pos = string.indexOf('@')
// remove first @: @ExampleColumn@ = ExampleColumn@
string = string.substring(pos + 1)
pos = string.indexOf('@')
if (pos === -1) {
continue
} // error number of @@ not correct
// remove second @: ExampleColumn@ = ExampleColumn
const value = string.substring(0, pos)
// add column name in array
listFields.push(value)
}
return listFields
}
} |
JavaScript | class MainLogo extends React.Component {
static propTypes = {
siteIcon: PropTypes.string.isRequired,
deviceType: PropTypes.string.isRequired,
}
static defaultProps = {
}
constructor(props) {
super(props);
}
render() {
return (
<Image src={this.props.siteIcon} size={DeviceConstants.sizeForImage(this.props.deviceType)} floated='right' />
)
}
} |
JavaScript | class AddPLCommand extends Command {
/**
* Constructor.
* @param {ChatService} chatService - ChatService.
* @param {DbService} dbService - DbService.
* @param {SearchService} searchService - SearchService.
*/
constructor(chatService, dBService, searchService) {
super(
["pladd"],
"add a song to the specified playlist by url or query.",
"<prefix>pladd <pl name> <url | query>"
);
this.chatService = chatService;
this.dBService = dBService;
this.searchService = searchService;
}
/**
* Function to execute this command.
* @param {String} payload - Payload from the user message with additional information.
* @param {Message} msg - User message this function is invoked by.
*/
run(payload, msg) {
if (typeof payload === "undefined" || payload.length === 0 || payload.split(" ").length < 2) {
this.chatService.simpleNote(msg, "No URL or query found!", this.chatService.msgType.FAIL);
this.chatService.simpleNote(msg, `Usage: ${this.usage}`, this.chatService.msgType.INFO);
return;
}
const plName = payload.split(" ")[0];
const query = payload.substr(plName.length + 1);
this.searchService.search(query).
then(({note, songs}) => {
this.chatService.simpleNote(msg, note, this.chatService.msgType.MUSIC).
then((infoMsg) => infoMsg.delete({"timeout": 5000}));
if (songs.length > 1) {
const enrichedSongs = songs.map((song) => {
song.playlist = plName;
song.requester = msg.author.username;
return song;
});
this.dBService.addSongs(enrichedSongs, plName).then(() => {
const count = enrichedSongs.length;
const note2 = `${count} songs added to playlist: ${plName}`;
this.chatService.simpleNote(msg, note2, this.chatService.msgType.MUSIC);
}).
catch((error) => {
this.chatService.simpleNote(msg, error, this.chatService.msgType.FAIL);
});
} else {
songs[0].playlist = plName;
songs[0].requester = msg.author.username;
this.dBService.addSong(songs[0], plName).then(() => {
const note2 = `added song: ${songs[0].title} to playlist: ${plName}`;
this.chatService.simpleNote(msg, note2, this.chatService.msgType.MUSIC);
}).
catch((error) => {
this.chatService.simpleNote(msg, error, this.chatService.msgType.FAIL);
});
}
}).
catch((error) => this.chatService.simpleNote(msg, error, this.chatService.msgType.FAIL));
}
} |
JavaScript | class PhysicsTrench {
constructor(physicsWorld, scene, camera) {
this.physicsWorld = physicsWorld;
this.scene = scene;
this.camera = camera
this.mesh = undefined;
this.rigidBody = undefined;
this.groupMesh = undefined;
this.compoundShape = new Ammo.btCompoundShape();
}
create(_position={x:0,y:0,z:0}, _rotation={x:0,y:0,z:0}, _endWallEnabled=false, _length=25) {
this.compoundShape = new Ammo.btCompoundShape();
this.groupMesh = new THREE.Group()
this.groupMesh.position.set(0,0,0)
this._createTrench(this.groupMesh, _endWallEnabled, _length)
this.groupMesh.rotation.set(toRadians(_rotation.x), toRadians(_rotation.y), toRadians(_rotation.z));
this.groupMesh.position.set(_position.x, _position.y, _position.z);
this.groupMesh.scale.set(1.5, 1.5, 1.5);
this._initAmmo()
}
/**
* Based on https://threejs.org/docs/#api/en/geometries/LatheBufferGeometry
*/
_createTrench(_groupMesh, _endWallEnabled, _length){
let width=10, height=_length, depth = 0.625
// for (let arr=[width,height,depth])
this._addWall({x: 0, y:0 , z:0}, {w:width,h:height,d:depth}, _groupMesh, {x:90,y:0,z:90})
this._addWall({x: 0, y:width/4 , z:width/2-depth/2}, {w: width/2,h:height,d:depth}, _groupMesh, {x:0,y:0,z:90})
this._addWall({x: 0, y:width/4 , z:-width/2+depth/2}, {w:width/2,h:height,d:depth}, _groupMesh, {x:0,y:0,z:90})
if (_endWallEnabled)
this._addWall({x: height/2-depth/2, y:width/4 , z:0}, {w:width-depth*2,h:width/2,d:depth}, _groupMesh, {x:0,y:90,z:0})
}
/**
* Adds a wall to the scene with Ammo physics
*/
_addWall(_position={x: 0, y: 0, z: 0}, _size={w:1,h:1, d:1}, _groupMesh, _rotation={x: 0, y: 0, z: 0}, _invisible=false, _scale={x: 1, y: 1, z: 1}) {
let tWall = new THREE.TextureLoader().load('./assets/textures/OpenGameArt/Planks/test_128x128_6.png')
tWall.wrapS = THREE.RepeatWrapping;
tWall.wrapT = THREE.RepeatWrapping;
tWall.repeat.y = 2
tWall.repeat.x = 20
let wallMaterial = new THREE.MeshPhongMaterial( {side: THREE.DoubleSide, map: tWall} );
if (_invisible) {
wallMaterial = new THREE.MeshPhongMaterial( {side: THREE.DoubleSide, opacity: 0} );
wallMaterial.transparent = true;
}
let wallGeometry = new THREE.BoxBufferGeometry( _size.w, _size.h, _size.d, 1, 1);
let tempMesh = new THREE.Mesh(wallGeometry, wallMaterial)
tempMesh.position.set(_position.x, _position.y, _position.z)
tempMesh.rotation.x = toRadians(_rotation.x)
tempMesh.rotation.y = toRadians(_rotation.y)
tempMesh.rotation.z = toRadians(_rotation.z)
tempMesh.scale.set(_scale.x,_scale.y,_scale.z);
tempMesh.receiveShadow = true;
tempMesh.castShadow = true;
_groupMesh.add(tempMesh);
let ammoWallShape = new Ammo.btBoxShape(new Ammo.btVector3(_size.w/2, _size.h/2, _size.d/2));
let shapeWallTrans = new Ammo.btTransform();
shapeWallTrans.setIdentity();
shapeWallTrans.setOrigin(new Ammo.btVector3(tempMesh.position.x,tempMesh.position.y,tempMesh.position.z));
let shapeWallQuat = tempMesh.quaternion;
shapeWallTrans.setRotation( new Ammo.btQuaternion(shapeWallQuat.x, shapeWallQuat.y, shapeWallQuat.z, shapeWallQuat.w) );
this.compoundShape.addChildShape(shapeWallTrans, ammoWallShape);
}
/**
* Adds the labyrinth to the scene and initializes Ammo physics
*/
_initAmmo() {
let massTerrain = 0;
let compoundShapeTrans = new Ammo.btTransform();
compoundShapeTrans.setIdentity();
compoundShapeTrans.setOrigin(new Ammo.btVector3(this.groupMesh.position.x,this.groupMesh.position.y,this.groupMesh.position.z));
let quatCompound = this.groupMesh.quaternion;
compoundShapeTrans.setRotation( new Ammo.btQuaternion( quatCompound.x, quatCompound.y, quatCompound.z, quatCompound.w ) );
let motionState = new Ammo.btDefaultMotionState( compoundShapeTrans );
let localInertia = new Ammo.btVector3( 0, 0, 0 );
this.compoundShape.setLocalScaling(new Ammo.btVector3(this.groupMesh.scale.x,this.groupMesh.scale.y, this.groupMesh.scale.x));
this.compoundShape.calculateLocalInertia( massTerrain, localInertia );
let rbInfo = new Ammo.btRigidBodyConstructionInfo( massTerrain, motionState, this.compoundShape, localInertia );
this.rigidBodyCompound = new Ammo.btRigidBody(rbInfo);
this.rigidBodyCompound.setFriction(0.9);
this.rigidBodyCompound.setRestitution(0);
this.rigidBodyCompound.setCollisionFlags(this.rigidBodyCompound.getCollisionFlags() | 2); // BODYFLAG_KINEMATIC_OBJECT = 2 betyr kinematic object, masse=0 men kan flyttes!!
this.rigidBodyCompound.setActivationState(4); // Never sleep, BODYSTATE_DISABLE_DEACTIVATION = 4
// this.scene.add(this.groupMesh);
this.scene.add(this.groupMesh)
// Legg til physicsWorld:
this.physicsWorld.addRB( this.rigidBodyCompound, CONST.CollisionGroups.Tube,
CONST.CollisionMasks.Tube);
this.physicsWorld._updateSingleAabb(this.rigidBodyCompound) ;
this.groupMesh.userData.physicsBody = this.rigidBodyCompound;
this.physicsWorld.rigidBodies.push(this.groupMesh);
}
} |
JavaScript | class Actions extends Component {
/**
* Add/remove favorites
*
* @return {void}
*/
onFavoriteBtnPress() {
this.props.updateStats({
rowData: this.props.rowData,
colName: "favorites",
canRemove: true,
user: this.props.user
})
// Sound.enable(true)
// Sound.play('sounds-876-yep.aac')
}
/**
* Add/remove like.
*
* @return {object}
*/
onLikeBtnPress() {
this.props.updateStats({
rowData: this.props.rowData,
colName: "likes",
canRemove: true,
user: this.props.user
})
// Sound.enable(true)
// Sound.play('sounds-876-yep.aac')
}
/**
* Creates a new record when a feed item has been shared.
*
* @param {string} result - the response from the share (cancelled or success)
* @param {string} network - the social network the feed item has been shared on
* @return {void}
*/
onUpdateShareStats(result, network) {
if (result == "success") {
this.props.updateStats({
rowData: this.props.rowData,
clickItem: network,
clickItemColName: "network",
colName: "shares",
user: this.props.user
})
}
}
/**
* Share a feed item on Twitter.
*
* @return {void}
*/
onTwitterShare() {
this.refs.shareOptionsModal.onSetVisible()
KDSocialShare.tweet({
'text': this.props.rowData.title,
'link': 'http://godevine.com/',
'imagelink': 'https://artboost.com/apple-touch-icon-144x144.png'
}, (result) => this.onUpdateShareStats(result, "twitter"))
}
/**
* Share a feed item on Facebook.
*
* @return {void}
*/
onFacebookShare() {
this.refs.shareOptionsModal.onSetVisible()
const rowData = this.props.rowData
KDSocialShare.shareOnFacebook({
'text': rowData.title,
'link': 'http://godevine.com/',
'imagelink': 'https://artboost.com/apple-touch-icon-144x144.png'
}, (result) => this.onUpdateShareStats(result, "facebook"))
}
/**
* Share a feed item via text messaging.
*
* @return {void}
*/
onSmsShare() {
// Composer.composeMessageWithArgs({
// 'messageText': 'Hey I was browsing Devine and I found something you might like!',
// 'subject': 'Hey check this out on Devine',
// 'recipients': []
// }, (result) => this.onUpdateShareStats(result, "sms"))
}
/**
* Toggle share modal.
*
* @return {void}
*/
onShareBtnPress() {
if (this.props.rowData) {
this.refs.shareOptionsModal.setVisible()
}
}
/**
* Navigate to the message detail scene.
*
* @return {void}
*/
onMessageBtnPress() {
const { rowData } = this.props
const { stylist, boutique } = rowData
// if (boutique.shouldUseBoutiqueInbox || !stylist) {
// route.contact = boutique
// } else if (stylist) {
// route.contact = stylist
// } else {
// AlertIOS.alert("Failed to navigate to message view.")
// return
// }
this.props.actions.push({
name: 'messageDetail'
})
}
/**
* Return a single action icon.
*
* @param {object} props - icon props
* @return {object}
*/
getIcon(props) {
let iconColor = BaseStyles.textDark
let icon = props.icon
const likes = this.props.rowData.likes || []
const favorites = this.props.rowData.favorites || []
if (this.props.user) {
const userId = this.props.user.objectId
if (icon == "star-border" && (favorites.indexOf(userId) != -1 || this.props.hasFavored)) {
icon = props.activeIcon
iconColor = BaseStyles.textYellow
}
if (icon == "favorite-border" && (likes.indexOf(userId) != -1 || this.props.hasLiked)) {
icon = props.activeIcon
iconColor = BaseStyles.textPrimary
}
}
if (this.props.boutique) {
iconColor = BaseStyles.textMuted
}
return (
<MaterialIcon
name={icon}
style={[
FeedStyles.icon,
BaseStyles.fontLarge,
iconColor
]} />
)
}
/**
* Render a single action button.
*
* @param {object} props - button props
* @return {object} component
*/
getActionBtn(props) {
const icon = this.getIcon(props)
let onPress = props.onPress
// if (!this.props.user && props.shouldRequireLogin) {
// onPress = this.props.actions.routes.logIn()
// }
return (
<TouchableWithoutFeedback style={[
FeedStyles.actionPress,
BaseStyles.paddingHorz
]} onPress={onPress}>
{icon}
</TouchableWithoutFeedback>
)
}
/**
* An array of possible feed actions.
*
* @return {array}
*/
getActions() {
const routes = this.props.actions.routes
const rowData = this.props.rowData
const possibleOptions = {
likes: {icon: 'favorite-border', activeIcon: 'favorite', shouldRequireLogin: true, onPress: this.onLikeBtnPress.bind(this)},
favorites: {icon: 'star-border', activeIcon: 'star', shouldRequireLogin: true, onPress: this.onFavoriteBtnPress.bind(this)},
participants: {icon: 'star-border', activeIcon: 'star', shouldRequireLogin: true, onPress: this.onFavoriteBtnPress.bind(this)},
comments: {icon: 'comment', onPress: routes.comments(rowData)},
messages: {icon: 'store', shouldRequireLogin: true, onPress: this.onMessageBtnPress.bind(this)},
shares: {icon: 'share', shouldRequireLogin: true, onPress: this.onShareBtnPress.bind(this)},
}
const actions = this.props.showActions.map((actionName) => {
return possibleOptions[actionName]
})
return actions
}
/**
* Returns a list of possible social sharing options.
*
* @return {object}
*/
getShareOptions() {
return {
heading: 'Share On Social Media',
list: [
{icon: 'facebook', text: 'Facebook', onPress: this.onFacebookShare.bind(this)},
{icon: 'twitter', text: 'Twitter', onPress: this.onTwitterShare.bind(this)},
{icon: 'textsms', text: 'Text', onPress: this.onSmsShare.bind(this)}
]
}
}
/**
* Render feed action buttons.
*
* @return {object}
*/
render() {
return (
<View style={[
FeedStyles.actionContainer,
BaseStyles.paddingHorz,
BaseStyles.col1
]}>
<OptionPopup
ref="shareOptionsModal"
options={this.getShareOptions()} />
<View style={[
FeedStyles.iconContainer,
BaseStyles.marginBottom,
BaseStyles.row,
BaseStyles.justifiedCols
]}>
{this.getActions().map((action) => {
return this.getActionBtn(action)
}, this)}
</View>
</View>
)
}
} |
JavaScript | class ProjectContextEvents extends ResumableEventSource {
/**
* Constructor.
*
* @param {Tenant} tenant The tenant instance.
* @param {Project} project The project instance.
* @param {String} contextId The context id.
*/
constructor(tenant, project, contextId) {
super(tenant.getDirectUri(endpoint("projectContextEvents", project.projectId, contextId)));
/**
* The tenant.
* @type {Tenant}
*/
this.tenant = tenant;
/**
* The project.
* @type {Project}
*/
this.project = project;
/**
* The context.
* @type {String}
*/
this.contextId = contextId;
/**
* Event types enum.
* @type {ProjectContextEvent}
*/
this.type = ProjectContextEvent;
}
} |
JavaScript | class BaseItemsManager {
/**
* Creation.
* @param {Object} parent - Parent.
*/
constructor(parent) {
this.data = {};
this._parent = parent;
}
get values() {
return Object.values(this.data);
}
/**
* Add item.
* @param {string} name - Item name.
* @param {Object} item - Item instance.
*/
add(name, item) {
if (name in this.data) {
throw Error(`Item with name "${name}" already exists.`);
}
this.data[name] = item;
}
/**
* Remove item.
* @param {string} name - Item name.
*/
remove(name) {
if (!(name in this.data)) {
throw Error(`Item with name "${name}" does not exist.`);
}
this.data[name].remove();
delete this.data[name];
}
} |
JavaScript | class CanvasItemsManager extends BaseItemsManager {
/**
* Add item.
* @param {string} name - Item name.
* @param {Object} item - Item instance.
*/
add(name, item) {
super.add(name, item);
item.layer = this._parent;
item.draw();
}
/**
* Remove item.
* @param {string} name - Item name.
*/
remove(name) {
super.remove(name);
this._parent.refresh();
}
} |
JavaScript | class SVGItemsManager extends BaseItemsManager {
/**
* Add item.
* @param {string} name - Item name.
* @param {Object} item - Item instance.
*/
add(name, item) {
super.add(name, item);
this._parent.element.appendChild(item.element);
}
} |
JavaScript | class GarbageCan extends React.Component {
constructor(props) {
super(props);
}
render(){
return this.props.connectDropTarget(
<div className="garbageCan">
<span className="glyphicon glyphicon-trash"/>
</div>
);
}
} |
JavaScript | class Sampler {
constructor(dataset) {
if (new.target === Sampler) {
throw new TypeError('Sampler is abstract, extend it');
}
if (this[Symbol.iterator] === undefined) {
throw new TypeError('Override iterator method');
}
if (
Object.getOwnPropertyDescriptor(Object.getPrototypeOf(this), 'length')
.get === undefined
) {
throw new TypeError('Override length getter');
}
this.dataset = dataset;
}
} |
JavaScript | class SequentialSampler extends Sampler {
constructor(dataset) {
super(dataset);
}
*[Symbol.iterator]() {
for (let i = 0; i < this.dataset.length; i++) {
yield i;
}
}
get length() {
return this.dataset.length;
}
} |
JavaScript | class RandomSampler extends Sampler {
constructor(dataset) {
super(dataset);
}
*[Symbol.iterator]() {
// Create & shuffle list of dataset indices
const indices = [...Array(this.dataset.length).keys()];
for (let i = indices.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[indices[i], indices[j]] = [indices[j], indices[i]];
}
yield* indices;
}
get length() {
return this.dataset.length;
}
} |
JavaScript | class BatchSampler extends Sampler {
constructor(sampler, batchSize, dropLast) {
super();
this.sampler = sampler;
this.batchSize = batchSize;
this.dropLast = dropLast;
}
*[Symbol.iterator]() {
let batch = [];
for (let idx of this.sampler) {
batch.push(idx);
if (batch.length === this.batchSize) {
yield batch;
batch = [];
}
}
if (batch.length > 0 && !this.dropLast) {
yield batch;
}
}
get length() {
return Math[this.dropLast ? 'floor' : 'ceil'](
this.sampler.length / this.batchSize
);
}
} |
JavaScript | class ParamTemplateService extends require('./AttributeService') {
constructor(uid, context) {
super(
uid, context, '../dao/TemplateDao',
'../dao/ParamTemplateDao'
);
}
} |
JavaScript | class Ec2ServiceTerminateKlass extends Ec2ServiceBaseKlass {
/**
* Constructor for Ec2ServiceTerminateKlass .
*
* @augments Ec2ServiceBaseKlass
*
* @constructor
*/
constructor(params) {
super(params);
const oThis = this ;
}
/**
* validate passed parameters
*/
validate(options){
const oThis = this ;
super.validate(options);
if(!options.instanceIds || Array.isArray(options.instanceIds) === false){
throw oThis.getError(`Invalid instanceIds for ${oThis.constructor.name}`, 'err_ec2_si_v_1');
}
}
/**
* perform
*/
async perform(options){
const oThis = this ;
return super.perform(options);
}
/**
* asyncPerform
*/
asyncPerform(options){
const oThis = this ;
var params = {
InstanceIds: options.instanceIds
};
return oThis._awsServiceRequest('oThis.awsClient.ec2()', 'terminateInstances', params);
}
} |
JavaScript | class WithKeyValues extends React.Component {
keyValuesLast = false
keyValueGlobalsLast = false
keyValueMap = {}
keyValueGlobalMap = {}
constructor(props) {
super(props)
}
shouldComponentUpdate(nextProps, nextState) {
const ignoreToCompare = ['deleteKeyValueByKey', 'setKeyValue', 'setKeyValueGlobal', 'loading']
const keys = Object.keys(nextProps)
for (let i = 0; i < keys.length; i++) {
const key = keys[i]
if (ignoreToCompare.indexOf(key) === -1 && nextProps[key] !== this.props[key]) {
return true
}
}
return false
}
render() {
const {keyValues, keyValueGlobals, kvUser, loading, ...rest} = this.props
if (keys) {
if (!kvUser.isAuthenticated) {
// fallback: load keyValues from localstore
this.keyValueMap = getKeyValuesFromLS()
} else if (keyValues) {
if (keyValues !== this.keyValuesLast) {
this.keyValuesLast = keyValues
this.keyValueMap = {}
// create a keyvalue map
const {results} = keyValues
if (results) {
for (const i in results) {
const o = results[i]
try {
this.keyValueMap[o.key] = JSON.parse(o.value)
} catch (e) {
this.keyValueMap[o.key] = o.value
}
}
}
}
} else if (loading) {
// there is nothing in cache
if (!keyValueGlobals) {
return <NetworkStatusHandler/>
}
}
}
if (keyValueGlobals && keyValueGlobals !== this.keyValueGlobalsLast) {
const {results} = keyValueGlobals
this.keyValueGlobalsLast = keyValueGlobals
this.keyValueGlobalMap = {}
if (results) {
for (const i in results) {
const o = results[i]
try {
this.keyValueGlobalMap[o.key] = JSON.parse(o.value)
} catch (e) {
this.keyValueGlobalMap[o.key] = o.value
}
}
}
}
// ... and renders the wrapped component with the fresh data!
// Notice that we pass through any additional props
return <WrappedComponent keyValues={keyValues} keyValueMap={this.keyValueMap}
keyValueGlobalMap={this.keyValueGlobalMap} {...rest} />
}
} |
JavaScript | class Device {
/**
* Constructs a new device
* @param {string} deviceId Id of the new device
*/
constructor(deviceId) {
this._deviceId = deviceId;
this._name = "";
}
/**
* @param {string} value The optional name of this device instance.
*/
set name(value) {
this._name = value;
}
/**
* @param {string} value The optional description of the device instance.
*/
set description(value) {
this._description = value;
}
/**
* @param {THREE.Vector3} value The world position of this device instance.
*/
set position(value) {
this._position = value;
}
/**
* @param {string} value The last recorded activity time for
* this device instance, expressed as a string in UTC format.
*/
set lastActivityTime(value) {
this._lastActivityTime = value;
}
/**
* @returns {string} The ID of this device instance.
*/
get id() {
return this._deviceId;
}
/**
* @returns {string} The name of this device instance. If a name
* was not previously assigned, the device ID will be returned.
*/
get name() {
return this._name || this._deviceId;
}
/**
* @returns {string} The optional description of the device instance.
*/
get description() {
return this._description;
}
/**
* @returns {THREE.Vector3} The world position of this device instance.
*/
get position() {
return this._position;
}
/**
* @returns {string} The last recorded activity time for
* this device instance, expressed as a string in UTC format.
*/
get lastActivityTime() {
return this._lastActivityTime;
}
} |
JavaScript | class DeviceModel {
constructor(deviceModelId, adapterId) {
this._deviceModelId = deviceModelId;
this._adapterId = adapterId;
/** @type {Object.<string, DeviceProperty>}
* The properties belonging to this DeviceModel.
*/
this._properties = {};
/** @type {Object.<string, Device>}
* The list of devices belonging to this DeviceModel.
*/
this._devices = {};
}
/**
* The name of this device model, if any.
* @param {string} value The name of this device model, if any.
*/
set name(value) {
this._name = value;
}
/**
* The description of this device model, if any.
* @param {string} value The description of this device model, if any.
*/
set description(value) {
this._description = value;
}
/**
* The identifier of this instance of DeviceModel object.
* @returns {string} The identifier of this instance of DeviceModel object.
*/
get id() {
return this._deviceModelId;
}
/**
* The identifier of the DataAdapter that this instance
* of DeviceModel object originated from.
* @returns {string} The identifier of the DataAdapter that this instance
* of DeviceModel object originated from.
*/
get adapterId() {
return this._adapterId;
}
/**
* The name of this device model, if any.
* @returns {string} The name of this device model, if any.
*/
get name() {
return this._name;
}
/**
* The description of this device model, if any.
* @returns {string} The description of this device model, if any.
*/
get description() {
return this._description;
}
/**
* All property identifiers for this DeviceModel.
* @returns {string[]} All property identifiers for this DeviceModel.
*/
get propertyIds() {
return Object.keys(this._properties);
}
/**
* The properties belonging to this DeviceModel.
* @returns {DeviceProperty[]} The properties belonging to this DeviceModel.
*/
get properties() {
return Object.values(this._properties);
}
/**
* All device identifiers found within this DeviceModel.
* @returns {string[]} All device identifiers found within this DeviceModel.
*/
get deviceIds() {
return Object.keys(this._devices);
}
/**
* The list of devices belonging to this DeviceModel.
* @returns {Device[]} The list of devices belonging to this DeviceModel.
*/
get devices() {
return Object.values(this._devices);
}
/**
* Adds a new property to the device model given its ID and name. If a
* property with the same ID exists, this method thrown an exception. The
* caller should populate the resulting DeviceProperty object with further
* data (e.g. data type).
*
* @param {string} propId The ID of the property to add.
* @param {string} name The name of the property to add.
*
* @returns {DeviceProperty} The resulting DeviceProperty object that has
* been added to the device model.
*
* @throws {Error} Property with the same ID already exists.
* @memberof Autodesk.DataVisualization.Data
* @alias Autodesk.DataVisualization.Data.DeviceModel#addProperty
*/
addProperty(propId, name) {
if (this._properties[propId]) {
throw new Error(`Property with ID ${propId} already exists`);
}
const property = new DeviceProperty(propId, name);
this._properties[propId] = property;
return property;
}
/**
* Adds a new device to the device model. If a device with the same ID
* exists, this method thrown an exception. The caller should populate
* the resulting Device object with further data (e.g. data type).
*
* @param {string} deviceId The identifier of a device.
*
* @returns {Device} The Device object that is added to the model.
*
* @throws {Error} Device with the same ID already exists.
* @memberof Autodesk.DataVisualization.Data
* @alias Autodesk.DataVisualization.Data.DeviceModel#addDevice
*/
addDevice(deviceId) {
if (this._devices[deviceId]) {
throw new Error(`Device with ID ${deviceId} already exists`);
}
this._devices[deviceId] = new Device(deviceId);
return this._devices[deviceId];
}
/**
* Checks to see if a device belongs to this DeviceModel.
*
* @param {string} deviceId Identifier of the device.
*
* @returns {boolean} Returns true if the device with a given ID belongs
* to this DeviceModel, or false otherwise.
* @memberof Autodesk.DataVisualization.Data
* @alias Autodesk.DataVisualization.Data.DeviceModel#contains
*/
contains(deviceId) {
return !!this._devices[deviceId];
}
/**
* Gets the Device object given its identifier.
*
* @param {string} deviceId Identifier of the device.
* @returns {Device} The Device object if one is found
* or undefined otherwise.
* @memberof Autodesk.DataVisualization.Data
* @alias Autodesk.DataVisualization.Data.DeviceModel#getDevice
*/
getDevice(deviceId) {
return this._devices[deviceId];
}
} |
JavaScript | class FacultyDetail extends Component {
constructor(props) {
super(props);
this.state = {
Employee: {
employeeDetail: {},
projectes: [],
accessories: []
},
editable: false,
pro: {},
emp_id: null,
}
}
componentWillMount() {
var pro = this.props ? this.props.location.state.data : ""
console.log("data", pro);
if (pro.emp_id != undefined) {
this.setState({ emp_id: pro.emp_id })
}
let apiData = {
company_id: this.props.company_id,
branch_id: this.props.branch_id,
payload: {
"emp_id": pro.emp_id
}
}
let { Employee } = this.state;
this.props.getEmployeeDetail(apiData).then(() => {
console.log("res", this.props.employeeDetail);
let res = this.props.employeeDetail;
if (res && res.status == 200) {
Employee = { ...Employee, employeeDetail: res.data.response.empployeeDetails }
Employee = { ...Employee, projectes: res.data.response.projectInfo }
Employee = { ...Employee, accessories: res.data.response.accessoryInfo }
this.setState({ Employee })
}
})
}
validate() {
let professorDetail = this.state.Professor.professorDetail;
var isValidForm = true;
if (!this.state.professor && !this.state.admin) {
this.setState({ isRoleSelected: true });
isValidForm = false
}
return isValidForm;
}
backButton(event) {
this.props.history.push('/app/employee-directory')
}
onProfessorBatchAdd(payload) {
this.getEmpDetail()
$("#addBatch .close").click();
}
getEmpDetail(){
var pro = this.props ? this.props.location.state.data : ""
if (pro.emp_id != undefined) {
this.setState({ emp_id: pro.emp_id })
}
let apiData = {
company_id: this.props.company_id,
branch_id: this.props.branch_id,
payload: {
"emp_id": pro.emp_id
}
}
let { Employee } = this.state;
this.props.getEmployeeDetail(apiData).then(() => {
let res = this.props.employeeDetail;
if (res && res.status == 200) {
Employee = { ...Employee, projectes: res.data.response.projectInfo }
Employee = { ...Employee, accessories: res.data.response.accessoryInfo }
Employee = { ...Employee, employeeDetail: res.data.response.empployeeDetails }
this.setState({ Employee })
}
})
}
onDeleteModel(key, value) {
var pro = this.props ? this.props.location.state.data : ""
let data = {
company_id: this.props.company_id,
branch_id: this.props.branch_id,
payload: {
"project_id": value.project_id,
"emp_id":pro && pro.emp_id ?pro.emp_id:0,
"accessory_id": value.accessory_id,
}
}
if (key == "project") {
this.props.deleteProjectfromEmp(data).then(() => {
let res = this.props.deleteProject
if (res && res.data.status == 200) {
this.getEmpDetail()
successToste("project Deleted Successfully")
}
})
}else{
this.props.deleteAccessoriesfromEmp(data).then(() => {
let res = this.props.deleteAccessories
if (res && res.data.status == 200) {
this.getEmpDetail()
successToste("Accessories Deleted Successfully")
}
})
}
}
onDeleteProfessor() {
let pro = this.props ? this.props.location.state.data : "";
let data = {
company_id: this.props.company_id,
branch_id: this.props.branch_id,
payload: {
"emp_id":pro && pro.emp_id ?pro.emp_id:0,
}
}
this.props.deleteEmployee(data).then(()=>{
let res = this.props.deleteEmp;
if(res && res.data.status == 200 ){
this.props.history.push('/app/employee-directory');
successToste("Employee Deleted Successfully")
}else{
errorToste("Something Went Wrong");
}
})
}
renderBatch() {
let { Employee } = this.state;
return Employee.projectes.map((batch, index) => {
return (
<div key={"batch" + index} className="c-batchList">
<span className="c-batchList__title">
{batch.project_name}
<div className="card__elem__setting1">
<button style={{ marginRight: "-220px", marginTop: "-7px" }} onClick={this.onDeleteModel.bind(this, "project", batch)} className="act-delete pull-right"></button>
</div>
</span>
</div>
)
})
}
renderAccessories() {
let { Employee } = this.state;
return Employee.accessories.map((batch, index) => {
return (
<div key={"batch" + index} className="c-batchList">
<span className="c-batchList__title">
{batch.accessory_name}
<div className="card__elem__setting1">
<button style={{ marginRight: "-220px", marginTop: "-7px" }} onClick={this.onDeleteModel.bind(this,"accessories",batch)} className="act-delete pull-right"></button>
</div>
</span>
</div>
)
})
}
renderPersonalDetails() {
let { Employee } = this.state;
return (
<div>
<div className="c-card__form">
<div className="divider-container">
<div className="divider-block text--left">
<div className="form-group static-fld">
<label>Name</label>
<span className="info-type">{Employee.employeeDetail ? Employee.employeeDetail.emp_name : "Not Added Yet"}</span>
</div>
<div className="form-group static-fld">
<label>Address</label>
<span className="info-type">{Employee.employeeDetail ? Employee.employeeDetail.address : "Not Added Yet"}</span>
</div>
</div>
<div className="divider-block text--left">
<div className="c-user-pic">
<div className="user--img"><img src={"/images/avatars/Avatar_default.jpg"} alt="Avatar" /></div>
</div>
</div>
</div>
<div className="form-group static-fld">
<label>Email</label>
<span className="info-type">{Employee.employeeDetail ? Employee.employeeDetail.email : "Not Added Yet."}</span>
</div>
<div className="form-group static-fld">
<label>Designation</label>
<span className="info-type">{Employee.employeeDetail ? Employee.employeeDetail.designation : "Not Added Yet."}</span>
</div>
<div className="form-group static-fld">
<label>Date of Birth</label>
<span className="info-type">{Employee.employeeDetail ? moment(Employee.employeeDetail.DOB).format("DD-MM-YYYY") : "Not Added Yet"}</span>
</div>
<div className="form-group static-fld">
<label>Company Name</label>
<span className="info-type">{Employee.employeeDetail ? Employee.employeeDetail.designation : "Not Added Yet."}</span>
</div>
<div className="form-group static-fld">
<label>Contact Number</label>
<span className="info-type">{Employee.employeeDetail ? Employee.employeeDetail.mobile : "Not Added Yet."}</span>
</div>
</div>
<div className="c-card__btnCont">
</div>
</div>
)
}
renderBatchDetail() {
// if (this.state.Employee.projectes.length == 0 ) {
// return (
// <div style={{ height: "380px" }}>
// <div className="c-card__img">
// <img src="/images/card-img-3.png" alt="logo" />
// </div>
// <div className="c-card__info">No batches added yet.</div>
// </div>
// )
// } else {
return (
<div className="c-card__items">
<Scrollbars >
{this.renderBatch()}
{this.renderAccessories()}
</Scrollbars >
</div>
)
// }
}
render() {
var pro = this.props.location.state.data ? this.props.location.state.data : ""
return (
<div className="c-container clearfix">
<ToastContainer />
<div className="clearfix">
<div className="c-brdcrum">
<a className="linkbtn hover-pointer" onClick={this.backButton.bind(this)} >Back to Employee Directory</a>
</div>
<div className="divider-container">
<div className="divider-block text--left">
<span className="c-heading-lg nomargin">Employee Details</span>
</div>
</div>
</div>
<div className="clearfix">
<div className="divider-container">
<div className="divider-block text--left">
</div>
<div className="divider-block text--right">
<button className="c-btn grayshade" onClick={this.backButton.bind(this)}>Back</button>
<button className="c-btn prime" onClick={this.onDeleteProfessor.bind(this)}>Delete</button>
{/* // <button className="c-btn prime" onClick={this.onSaveChanges.bind(this)} >Save changes</button> */}
</div>
</div>
</div>
<div className="c-container__data">
<div className="card-container">
<div className="c-card">
<div className="c-card__title">
<span className="c-heading-sm card--title">
PERSONAL DETAILS
</span>
</div>
{this.renderPersonalDetails()}
</div>
{pro.designation != 'INSTITUTE' ? <div className="c-card">
<div className="c-card__title">
<span className="c-heading-sm card--title">
Project And Accessories
<span className="c-count filled">{this.state.Employee.projectes.length+this.state.Employee.accessories.length}</span>
</span>
</div>
{this.renderBatchDetail()}
<div className="c-card__btnCont">
{pro.designation == "INSTITUTE" ? "" : <button className="c-btn-large primary" data-toggle="modal" data-target="#addBatch">+ Add Project & Accessories</button>}
</div>
<AddStudentBatchModel emp_id={pro && pro.emp_id ? pro.emp_id : 0} onAddStudentBatch={(data) => { this.onProfessorBatchAdd(data) }} {...this.props} />
</div> : ""}
</div>
</div>
</div>
)
}
} |
JavaScript | class WPSWidget extends Widget {
/**
* @param {Object} config - Configuration object
* @param {String} config.title - Widget title
* @param {String} config.server - URL of map server
* @param {Object} config.namespace - Namespace object
* @param {String} config.namespace.name - Namespace to use
* @param {String} config.namespace.url - Namespace URL
* @param {String} config.layerName - Name of the layer to query
* @param {String} [config.geometryName=geom] - Name of the geometry column
* @param {Function} [config.format] - Function to parse and transform data fetched from server.
* This function should return a human friendly value as it will be shown as
* the widget current value.
*/
constructor(config) {
super(config);
this.layerName = config.layer;
this.geometryName = config.geometryName || 'geom';
this.server = `${config.server}/wps/`;
this.namespace = config.namespace;
this.template = template;
this.className = 'wps-widget';
}
/**
* Processes the widget value and returns a human friendly version.
* @returns {Object} - Current widget value prepared to be shown
* @protected
*/
format() {
return parseInt(this.value, 10);
}
/**
* Reloads the widget value using the formatted value.
*/
refresh() {
if (!this.manager.extent) {
return;
}
this.getData((data) => {
this.parseResponse(data);
super.refresh();
});
}
/**
* Sends query to server and parses response as JSON.
* @param {Function} callback - Callback function to call when data is fetched
* @private
*/
getData(callback) {
fetch(this.server, {
method: 'POST',
body: this.requestTemplate({
layer: this.layerName,
geometryName: this.geometryName,
property: this.property,
function: this.function,
category: this.categories ? this.categories.property : null,
extent: this.manager.extent,
filters: this.manager.filters,
namespace: this.namespace,
}),
headers: new Headers({
'Content-Type': 'text/xml',
}),
}).then(response => response.json()).then(callback);
}
} |
JavaScript | class Todos extends Component {
render() {
return (
this.props.todos.map((todo) => (
<TodoItem todo={todo} key={todo.id} toggleTodo={this.props.toggleTodo} deleteTodo={this.props.deleteTodo}/>
))
);
}
} |
JavaScript | class Engineer extends Employee {
constructor(name, id, email, github) {
// super keyword accesses and calls functions for object's parent which is Employee construtor items
super(name, id, email);
this.github = github;
}
getGithub() {
return this.github;
}
// default role to be Engineer if selected
getRole() {
return "Engineer";
}
} |
JavaScript | class CircleShape extends BaseStyle_1.BaseStyle {
constructor(canvas, ctx, name = "Circle_" + Math.floor(Math.random() * Number.MAX_SAFE_INTEGER)) {
super(canvas, ctx, name);
}
get type() { return interfaces_1.ShapeType.SHAPE; }
set width(v) { throw new ReferenceError(`LineShape width cannot be set (${v}).`); }
set height(v) { throw new ReferenceError(`LineShape height cannot be set (${v}).`); }
set radius(r) {
this.boundary.reset();
this.boundary.setPoint([-r, -r]);
this.boundary.setPoint([r, r]);
if (this.originToCenter) {
this.originToCenter = true;
}
}
get radius() {
return super.width / 2;
}
withRadius(r, duration = 0, tween, callback) {
if (duration > 1) {
this.tweenManager.addTween(this, tween, duration, [r], ["radius"], callback, 5);
}
else {
this.radius = r;
}
return this;
}
traceShape(ctx) {
ctx.beginPath();
ctx.arc(0 - this.originX, 0 - this.originY, this.radius, 0, MathPIx2);
if (this.styleManager.hasFill) {
ctx.fill();
}
if (this.styleManager.hasStroke) {
ctx.stroke();
}
}
customDraw() {
this.traceShape(this.ctx);
}
} |
JavaScript | class DomainQuery {
constructor(domain) {
this.domain = domain;
this.config = {
fields: []
};
this.criteria = undefined;
this.fields = [];
this.limitConfig = undefined;
this.sortConfig = undefined;
}
/**
* AQL query string.
*
* @returns {String}
*/
get query() {
let conf = this.config,
_fields = conf.fields.length > 0 ? `.include(${conf.fields.map(JSON.stringify).join(', ')})` : '',
_criteria = conf.criteria ? JSON.stringify(conf.criteria) : '',
_sort = conf.sort ? `.sort(${JSON.stringify(conf.sort)})` : '',
_limit = conf.limit ? `.limit(${JSON.stringify(conf.limit)})` : '',
_offset = conf.offset > 0 ? `.offset(${JSON.stringify(conf.offset)})` : '';
return `${this.domain}.find(${_criteria})${_fields}${_sort}${_offset}${_limit}`;
}
/**
* Find domain query with criteria.
*
* @param criteria
* @returns {DomainQuery}
*/
find(criteria) {
criteria && (this.config.criteria = Object.assign({}, criteria));
return this;
}
/**
* Include fields.
*
* domain.include("name", "repo")
*
* @returns {DomainQuery}
*/
include() {
var args = (arguments.length === 1 ? [arguments[0]] : Array.apply(null, arguments)),
schema = ['string'];
if (this._isValid(args, schema)) {
this.config.fields = this.config.fields.concat(args);
} else {
this._warn('Field configuration is not valid', args, schema);
}
return this;
}
/**
* Sort object
* @param sort
* @returns {DomainQuery}
*/
sort(sort) {
let schema = {
$asc: ['string'],
$dsc: ['string']
};
if (this._isValid(sort, schema)) {
this.config.sort = sort;
} else {
this._warn('Sort configuration is not valid', sort, schema);
}
return this;
}
/**
* Limit
* @param num
* @returns {DomainQuery}
*/
limit(num) {
let schema = 0;
if (this._isValid(num, schema)) {
this.config.limit = num;
} else {
this._warn('Limit configuration is not valid', num, schema);
}
return this;
}
/**
* Offset
* @param num
* @returns {DomainQuery}
*/
offset(num) {
let schema = 0;
if (this._isValid(num, schema)) {
this.config.offset = num;
} else {
this._warn('Offset configuration is not valid', num, schema);
}
return this;
}
/**
* Validate input objects with a schema.
*
* @param obj
* @param schema
* @returns {boolean}
* @private
*/
_isValid(obj, schema) {
let typeofObj = Array.isArray(obj) ? 'array' : typeof obj,
typeofSchema = Array.isArray(schema) ? 'array' : typeof schema;
if (typeofObj === typeofSchema) {
if (['string', 'boolean', 'number'].indexOf(typeofObj) > -1) {
return true;
} else if (typeofObj === 'array' && schema.length > 0 && obj.length > 0) {
return obj.every(elem => this._isValid(elem, schema[0]));
} else if (typeofObj === 'object') {
return Object.keys(obj).every(key => {
let isInSchema = Object.keys(schema).indexOf(key) > -1,
isValid = this._isValid(obj[key], schema[key]);
return isInSchema && isValid;
});
}
}
return false;
}
/**
* Console output.
*
* @param message
* @param obj
* @param schema
* @private
*/
_warn(message, obj, schema) {
console.warn(`AQL: ${message}: ${JSON.stringify(obj)}`);
console.warn(` Provided object : ${JSON.stringify(obj)}`);
console.warn(` Schema object : ${JSON.stringify(schema)}`);
}
} |
JavaScript | class IwpGraphWindowEditor extends React.Component {
constructor(props) {
super(props);
// -------------- Be sure to update these constants -----------------------
let objectType = "graphWindow";
let editorClass = "IwpGraphWindowEditor";
// -------------- ------------------ -----------------------
// Self-determine order
let objectOrder = props.animation.objects.findIndex( o => o.objectType === objectType );
let object = props.animation.objects[objectOrder];
this.state = {
editorClass: editorClass,
objectType: objectType,
object: object,
designRoute: [ "objects", "order", objectOrder ]
};
// This binding is necessary to make `this` work in the callback
this.onFieldChange = this.onFieldChange.bind(this);
}
/** Handle Field Changes Super Generically 2019Nov06 */
onFieldChange(event) {
const designCommand = { [event.target.name] : { $set : event.target.value } };
const designCommandNumerical = { [event.target.name] : { $set : +event.target.value } };
// console.log(this.state.editorClass + ":38> onFieldChange, designCommand: " , designCommand );
// Local State Management Immutable
this.setState({object: update(this.state.object, designCommand ) });
// Bubble Design Change Event
this.props.onDesignChange(this.state.editorClass, this.state.designRoute, designCommandNumerical);
}
render() {
const objectType = this.state.objectType;
return (
<div className={"iwp-"+objectType+"-editor"}>
<h3>Graph Window</h3>
<div>
<div className="iwp-editor-field">
<label>X Min</label>
<input type="text"
value={this.state.object.xmin}
name="xmin"
onChange={this.onFieldChange}/>
</div>
<div className="iwp-editor-field">
<label>X Max</label>
<input type="text"
value={this.state.object.xmax}
name="xmax"
onChange={this.onFieldChange}/>
</div>
<div className="iwp-editor-field">
<label>X Grid</label>
<input type="text"
value={this.state.object.xgrid}
name="xgrid"
onChange={this.onFieldChange}/>
</div>
<br/>
<div className="iwp-editor-field">
<label>Y Min</label>
<input type="text"
value={this.state.object.ymin}
readOnly={false}
name="ymin"
onChange={this.onFieldChange}/>
</div>
<div className="iwp-editor-field">
<label>Y Max</label>
<input type="text"
value={this.state.object.ymax}
readOnly={false}
name="ymax"
onChange={this.onFieldChange}/>
</div>
<div className="iwp-editor-field">
<label>Y Grid</label>
<input type="text"
value={this.state.object.ygrid}
readOnly={false}
name="ygrid"
onChange={this.onFieldChange}/>
</div>
</div>
</div>
);
}
} |
JavaScript | class Vec2 {
constructor(x, y) {
this.x = x ? x : 0;
this.y = y ? y : 0;
}
/**
* Returns a deep copy of this vector.
*
* @method copy
* @return {Vec2} Deep copy of this Vec2.
*/
copy() {
return new Vec2(this.x, this.y);
}
/**
* Compares the given Vec2 to this vector.
*
* @method equals
* @param {Vec2} vec2
* @return {Boolean} True if they are equal. False otherwise.
*/
equals(vec2) {
if (this.x === vec2.x && this.y === vec2.y)
return true;
return false;
}
/**
* Shifts this vector along the x and y axis by the amounts given.
*
* @method shift
* @param {Number} x
* @param {Number} y
* @return {Vec2} this
*/
shift(x, y) {
this.x += x;
this.y += y;
return this;
}
/**
* Scales the x and y values of this vector by the given multiplier.
*
* @method scale
* @param {Number} multiplier
* @return {Vec2} this
*/
scale(multiplier) {
this.x *= multiplier;
this.y *= multiplier;
return this;
}
/**
* Downscales the x and y values of this vector by dividing by the divisor
*
* @method downscale
* @param {Number} divisor
* @return {Vec2} this
*/
downscale(divisor) {
this.x /= divisor;
this.y /= divisor;
return this;
}
/**
* Calculates the magnitude of this vector.
*
* @method magnitude
* @return {Number} Magnitude of this vector
*/
magnitude() {
return Math.sqrt(this.x*this.x + this.y*this.y);
}
/**
* Normalises the vector by reducing the magnitude to 1.
*
* @method normalise
* @return {Vec2} this
*/
normalise() {
return this.downscale(this.magnitude());
}
/**
* Adds the x and y values of the given Vec2 to the x and y values respectively of this vector.
*
* @method add
* @param {Vec2} vec2
* @return {Vec2} this
*/
add(vec2) {
this.x += vec2.x;
this.y += vec2.y;
return this;
}
/**
* Subtracts the x and y values of the given Vec2 from the x and y values respectively of this vector.
*
* @method subtract
* @param {Vec2} vec2
* @return {Vec2} this
*/
subtract(vec2) {
this.x -= vec2.x;
this.y -= vec2.y;
return this;
}
/**
* Divides the fields of this vector by the respectives fields of the given Vec2.
*
* @method divide
* @param {Vec2} vec2
* @return {Vec2} this
*/
divide(vec2) {
this.x /= vec2.x;
this.y /= vec2.y;
return this;
}
/**
* Multiplies the fields of the given Vec2 with the respective fields of this vector.
*
* @method multiply
* @param {Vec2} vec2
* @return {Vec2} this
*/
multiply(vec2) {
this.x *= vec2.x;
this.y *= vec2.y;
return this;
}
/**
* Performs a dot product of this vector with the given Vec2.
*
* @method dot
* @param {Vec2} vec2
* @return {Number} Dot product result
*/
dot(vec2) {
return this.x*vec2.x + this.y*vec2.y;
}
/**
* Performs a cross product of this vector with the given Vec2
*
* @method cross
* @param {Vec2} vec2
* @return {Number} Cross product result
*/
cross(vec2) {
return this.x*vec2.y - this.y*vec2.x;
}
/**
* Calculates the angle of this vector counterclockwise from the positive x axis.
*
* @method angle
* @return {Number} Angle counterclockwise from the positive x axis [-PI,PI]
*/
angle() {
return Math.atan2(this.y, this.x);
}
/**
* Rotates the vector by the given angle in radians.
*
* @method rotate
* @param {Number} radians
* @return {Vec2} this
*/
rotate(radians) {
let x = this.x;
let y = this.y;
this.x = Math.cos(radians*x) - Math.sin(radians*y);
this.y = Math.sin(radians*x) + Math.cos(radians*y);
return this;
}
} |
JavaScript | class SSML {
/**
* Constructor
* @param {Array} initial the initial string array of outputs to populate with
*/
constructor(initial = []) {
this.phrases = initial;
}
/**
* Sets the SSML content to the supplied data, overwriting anything that came
* before it.
* @param {Mixed} input the input content
*/
set(input, props) {
this.phrases = [];
return this.add(input, props);
}
/**
* add - Add a phrase to the SSML output.
*
* @param {Mixed} item either a string or an array of phrases
* @param {Object} props The `props` allows for additional optional
* parameters to be sent, these include:
*
* repeat - Whether the output should be spoken when an action is
* repeated (either by fallback or user prompting it). Default is true
*
* fallback - Whether the output should only be said upon fallback
* (when the user response was not understood the first time). Default
* is false
*
* random - Indicates the `item` is an array of possible text outputs,
* every time that it is spoken a random item is picked. Including when
* the output is repeated
*/
add(input, props) {
const opts = Object.assign(
{
repeat: null,
fallback: null,
random: null,
},
props);
/* istanbul ignore else */
if (typeof input === 'string') {
this.phrases.push({
output: input,
repeat: opts.repeat,
fallback: opts.fallback,
});
} else if (Array.isArray(input)) {
if (opts.random) {
this.phrases.push({
output: input,
repeat: opts.repeat,
fallback: opts.fallback,
random: true,
});
} else {
for (let i = 0, len = input.length; i < len; i += 1) {
if (typeof input[i] === 'string') {
this.phrases.push({
output: input[i],
repeat: opts.repeat,
fallback: opts.fallback,
random: false,
});
} else {
let repeat = true;
if (opts.repeat !== null) {
repeat = input[i].repeat === false ? false : opts.repeat;
} else if (input[i].repeat !== null) {
repeat = input[i].repeat;
}
this.phrases.push({
output: input[i].output,
repeat,
fallback:
opts.fallback !== null
? opts.fallback
: input[i].fallback || false,
random:
opts.random !== null ? opts.random : input[i].random || false,
});
}
}
}
} else if (input instanceof SSML) {
// If is an SSML instance
this.add(input.list(), props);
}
return this;
}
/**
* audio - description
*
* @param {String} url the absolute path to the audio clip
* @param {Object} props optional properties
*/
audio(url, props) {
const opts = Object.assign({ fallbackText: '' }, props);
this.add(`<audio src="${url}">${opts.fallbackText}</audio>`, opts);
return this;
}
/**
* Add a pause to the SSML speech output
*
* @param {Number} time the duration of the pause, in seconds
*/
pause(time = 1, props) {
this.add(`<break time="${time}s"/>`, props);
return this;
}
/**
* Returns the list of phrases that have been added
*
* @return {Array} the phrases
*/
list() {
return this.phrases;
}
/**
* Filter repeatable items from the phrases list
*
* @param {Array} input the input content
*/
filterRepeatable(input) {
const final = [];
let list;
if (Array.isArray(input)) {
list = input;
} else if (input instanceof SSML) {
list = input.list();
}
if (!Array.isArray(list)) return input;
for (let i = 0, len = list.length; i < len; i += 1) {
const item = Object.assign({}, list[i]);
/* istanbul ignore next */
if (
item.output.indexOf('<break time') === 0 &&
(item.repeat || (item.repeat === null || item.repeat === undefined))
) {
final.push({
output: '<break time="0.5s"/>',
repeat: item.repeat,
random: item.random,
});
} else if (
item.repeat ||
(item.repeat === null || item.repeat === undefined) ||
item.fallback
) {
if (item.fallback) item.fallback = false;
final.push(item);
}
}
return final;
}
/**
* Output the SSML
*/
output() {
const final = [];
for (let i = 0, len = this.phrases.length; i < len; i += 1) {
if (!this.phrases[i].fallback) {
if (this.phrases[i].random) {
final.push(random(this.phrases[i].output));
} else {
final.push(this.phrases[i].output);
}
}
}
return `<speak>${final.join(' ')}</speak>`;
}
} |
JavaScript | class ServiceRestartCommand extends ServiceCommand {
/**
* @inheritdoc
*/
get name() {
return 'service:restart';
}
/**
* @inheritdoc
*/
get description() {
return `Restart service [${this.SERVICES.join(', ')}].`;
}
/**
* @inheritdoc
*/
async handle() {
const { message } = await this.service.restart(this.parameter('serviceVersion'));
this.success(message);
}
} |
JavaScript | class RequestWrapper {
/**
* Constructor for RequestWrapper.
* @param {Object} input
* @param {string} [input.cacheName] The name of the cache to use for Handlers
* that involve caching. If none is provided, a default name that
* includes the current service worker scope will be used.
* @param {Array.<Object>} [input.plugins] Any plugins that should be
* invoked.
* @param {Object} [input.fetchOptions] Values passed along to the
* [`init`](https://developer.mozilla.org/en-US/docs/Web/API/GlobalFetch/fetch#Parameters)
* of all `fetch()` requests made by this wrapper.
* @param {Object} [input.matchOptions] Values passed along to the
* [`options`](https://developer.mozilla.org/en-US/docs/Web/API/Cache/match#Parameters)
* of all cache `match()` requests made by this wrapper.
*/
constructor({cacheName, plugins, fetchOptions, matchOptions} = {}) {
if (cacheName) {
assert.isType({cacheName}, 'string');
this.cacheName = cacheName;
} else {
this.cacheName = defaultCacheName;
}
if (fetchOptions) {
assert.isType({fetchOptions}, 'object');
this.fetchOptions = fetchOptions;
}
if (matchOptions) {
assert.isType({matchOptions}, 'object');
this.matchOptions = matchOptions;
}
this.pluginCallbacks = {};
if (plugins) {
assert.isArrayOfType({plugins}, 'object');
plugins.forEach((plugin) => {
for (let callbackName of pluginCallbacks) {
if (typeof plugin[callbackName] === 'function') {
if (!this.pluginCallbacks[callbackName]) {
this.pluginCallbacks[callbackName] = [];
}
this.pluginCallbacks[callbackName].push(
plugin[callbackName].bind(plugin));
}
}
});
}
if (this.pluginCallbacks.cacheWillUpdate) {
if (this.pluginCallbacks.cacheWillUpdate.length !== 1) {
throw ErrorFactory.createError('multiple-cache-will-update-plugins');
}
}
if (this.pluginCallbacks.cacheWillMatch) {
if (this.pluginCallbacks.cacheWillMatch.length !== 1) {
throw ErrorFactory.createError('multiple-cache-will-match-plugins');
}
}
}
/**
* Opens a cache and maintains a reference to that cache
* for future use.
*
* @example
* requestWrapper.getCache()
* .then((openCache) => {
* ...
* });
*
* @return {Promise<Cache>} An open `Cache` instance based on the configured
* `cacheName`.
*/
async getCache() {
if (!this._cache) {
this._cache = await caches.open(this.cacheName);
}
return this._cache;
}
/**
* Wraps `cache.match()`, using the previously configured cache name and match
* options.
*
* @example
* requestWrapper.match({event.request})
* .then((response) => {
* if (!response) {
* // No response in cache.
* return;
* }
* ...
* });
*
* @param {Object} input
* @param {Request|string} input.request The key for the cache lookup.
* @return {Promise.<Response>} The cached response.
*/
async match({request}) {
assert.atLeastOne({request});
const cache = await this.getCache();
let cachedResponse = await cache.match(request, this.matchOptions);
if (this.pluginCallbacks.cacheWillMatch) {
cachedResponse = this.pluginCallbacks.cacheWillMatch[0](
{cachedResponse});
}
return cachedResponse;
}
/**
* Wraps `fetch()`, calls all `requestWillFetch` before making the network
* request, and calls any `fetchDidFail` callbacks from the
* registered plugins if the request fails.
*
* @example
* requestWrapper.fetch({
* request: event.request
* })
* .then((response) => {
* ...
* })
* .catch((err) => {
* ...
* });
*
* @param {Object} input
* @param {Request|string} input.request The request or URL to be fetched.
* @return {Promise.<Response>} The network response.
*/
async fetch({request}) {
assert.atLeastOne({request});
const clonedRequest = this.pluginCallbacks.fetchDidFail ?
request.clone() : null;
if (this.pluginCallbacks.requestWillFetch) {
for (let callback of this.pluginCallbacks.requestWillFetch) {
const returnedPromise = callback({request});
assert.isInstance({returnedPromise}, Promise);
const returnedRequest = await returnedPromise;
assert.isInstance({returnedRequest}, Request);
request = returnedRequest;
}
}
try {
return await fetch(request, this.fetchOptions);
} catch (err) {
if (this.pluginCallbacks.fetchDidFail) {
for (let callback of this.pluginCallbacks.fetchDidFail) {
callback({request: clonedRequest.clone()});
}
}
throw err;
}
}
/**
* Combines both fetching and caching using the previously configured options
* and calling the appropriate plugins.
*
* By default, responses with a status of [2xx](https://fetch.spec.whatwg.org/#ok-status)
* will be considered valid and cacheable, but this could be overridden by
* configuring one or more plugins that implement the `cacheWillUpdate`
* lifecycle callback.
*
* @example
* requestWrapper.fetchAndCache({
* request: event.request
* })
* .then((response) => {
* ...
* })
* .catch((err) => {
* ...
* });
*
* @param {Object} input
* @param {Request} input.request The request to fetch.
* @param {boolean} [input.waitOnCache] `true` means the method should wait
* for the cache.put() to complete before returning. The default value
* of `false` means return without waiting. It this value is true
* and the response can't be cached, an error will be thrown.
* @param {Request} [input.cacheKey] Supply a cacheKey if you wish to cache
* the response against an alternative request to the `request`
* argument.
* @return {Promise.<Response>} The network response.
*/
async fetchAndCache({request, waitOnCache, cacheKey}) {
assert.atLeastOne({request});
let cachingComplete;
const response = await this.fetch({request});
// response.ok is true if the response status is 2xx.
// That's the default condition.
let cacheable = response.ok;
if (this.pluginCallbacks.cacheWillUpdate) {
cacheable = this.pluginCallbacks.cacheWillUpdate[0](
{request, response});
}
if (cacheable) {
const newResponse = response.clone();
// cacheDelay is a promise that may or may not be used to delay the
// completion of this method, depending on the value of `waitOnCache`.
cachingComplete = this.getCache().then(async (cache) => {
let oldResponse;
// Only bother getting the old response if the new response isn't opaque
// and there's at least one cacheDidUpdateCallbacks. Otherwise, we don't
// need it.
if (response.type !== 'opaque' &&
this.pluginCallbacks.cacheDidUpdate) {
oldResponse = await this.match({request});
}
// Regardless of whether or not we'll end up invoking
// cacheDidUpdateCallbacks, wait until the cache is updated.
const cacheRequest = cacheKey || request;
await cache.put(cacheRequest, newResponse);
for (let callback of (this.pluginCallbacks.cacheDidUpdate || [])) {
callback({
cacheName: this.cacheName,
oldResponse,
newResponse,
url: request.url,
});
}
});
} else if (!cacheable) {
logHelper.debug(`[RequestWrapper] The response for ${request.url}, with
a status of ${response.status}, wasn't cached. By default, only
responses with a status of 200 are cached. You can configure the
cacheableResponse plugin to change this default.`.replace(/\s+/g, ' '));
if (waitOnCache) {
// If the developer request to wait on the cache but the response
// isn't cacheable, throw an error.
throw ErrorFactory.createError('invalid-reponse-for-caching');
}
}
// Only conditionally await the caching completion, giving developers the
// option of returning early for, e.g., read-through-caching scenarios.
if (waitOnCache && cachingComplete) {
await cachingComplete;
}
return response;
}
} |
JavaScript | class AddTodos extends React.Component {
constructor(props, context){
super(props,context);
//Declaring component state
this.state = {
todo: {
text: '',
completed: false
},
};
/**
* Binding custom methods to this component
*/
this.addTodo = this.addTodo.bind(this);
this.updateTodoState = this.updateTodoState.bind(this);
this.handleEnter = this.handleEnter.bind(this);
}
/*****************
* REACT METHODS *
*****************/
/**
* Set focus on text input when component did mount
*/
componentDidMount(){
ReactDOM.findDOMNode(this.refs.todoText).focus();
}
/******************
* CUSTOM METHODS *
******************/
/**
* Change state when typing on input
*/
updateTodoState(e) {
const field = e.target.name;
let todo = this.state.todo;
todo[field] = e.target.value;
return this.setState({todo});
}
/**
* Add new todo calling a redux action
*/
addTodo() {
if(this.state.todo.text.length){
this.props.actions.addTodo(this.state.todo);
this.clearInputField();
}
}
/**
* Clear input field
*/
clearInputField() {
let todo = this.state.todo;
todo.text = '';
this.setState({todo});
}
/**
* Add new todo when hiting the enter key
*/
handleEnter(e){
if(e.key === 'Enter'){
this.addTodo();
}
}
render (){
return (
<div className="control is-grouped has-padding-vertical-1 is-marginless">
<p className="control is-expanded">
<input className="input is-large" placeholder="What you need to do?" type="text" ref="todoText" value={this.state.todo.text} name="text" onKeyPress={this.handleEnter} onChange={this.updateTodoState} />
</p>
<p className="control">
<button className="button is-primary is-large" onClick={this.addTodo}>Add Todo</button>
</p>
</div>
);
}
} |
JavaScript | class CleverOnboarding {
/**
* @param {OnboardOptions} options
*/
constructor(options) {
/**
* @private
* Options property exposing widget's options
*/
this._options = {};
this._options.fillColor = getOptionValue(options.fillColor, Defaults.FILL_COLOR);
this._options.fillOpacity = getOptionValue(options.fillOpacity, Defaults.FILL_OPACITY);
this._options.nextText = getOptionValue(options.nextText, Defaults.NEXT_TEXT);
this._options.windowClassName = getOptionValue(options.windowClassName, Defaults.WINDOW_CLASS_NAME);
this._options.animationDuration = getOptionValue(options.animationDuration, Defaults.ANIMATION_DURATION);
this._options.windowWidth = getOptionValue(options.windowWidth, Defaults.WINDOW_WIDTH);
this._options.steps = options.steps;
/**
* @private
* observable handler
*/
this._observable = new Observable([
/**
* Fires when onboarding starts.
*
* @event Onboard#start
* @memberof Onboard
* @type {Object}
* @property {Object} step
* @property {number} stepIndex
*/
"start",
/**
* Fires when onboarding step changes.
*
* @event Onboard#stop
* @memberof Onboard
* @type {Object}
* @property {Object} step
* @property {number} stepIndex
*/
"step",
/**
* Fires when user clicks on close button.
*
* @event Onboard#closeClick
* @memberof Onboard
*/
"closeClick",
/**
* Fires when onboarding finishes.
*
* @event Onboard#step
* @memberof Onboard
* @type {Object}
* @property {Object} step
* @property {number} stepIndex
*/
"stop"
]);
/**
* @private
* model
*/
this._model = new OnboardModel(this._options);
this._model.on("start", (step, index)=>{
this._observable.fire("start", {
step:step,
index:index
});
});
this._model.on("stop", (step, index)=>{
this._observable.fire("stop", {
step:step,
index:index
});
});
this._model.on("step", (step, index, lastStep, lastIndex)=>{
this._observable.fire("step", {
step,
index,
lastStep,
lastIndex
});
});
/**
* @private
* renderer
*/
this._onboardRenderer = new OnboardRenderer(this._options, this._model);
/**
* @private
* key handler
*/
this._onboardKeyHandler = new OnboardKeyHandler(this._options, this._model);
this._onboardRenderer.on("closeClick", (step, index)=>{
this._observable.fire("closeClick", {
step,
index,
});
});
this.render();
}
/**
* Binds widget event
* @param {string} eventName event name
* @param {Function} handler event handler
* @return {Onboard} returns this widget instance
*/
on(eventName, handler) {
this._observable.on(eventName, handler);
return this;
}
/**
* Unbinds widget event
* @param {string} eventName event name
* @param {Function} [handler] event handler
* @return {Onboard} returns this widget instance
*/
off(eventName, handler) {
this._observable.off(eventName, handler);
return this;
}
/**
* Destroys this widget
* @return {Onboard} returns this widget instance
*/
destroy() {
this._observable.destroy();
this._onboardRenderer.destroy();
this._options = null;
this._model.destroy();
this._onboardKeyHandler.destroy();
return this;
}
/**
* Renders this widget
* @param {string|HTMLElement} selector selector or DOM element
* @return {Onboard} returns this widget instance
*/
render(selector) {
this._onboardRenderer.render(selector);
return this;
}
/**
* Starts onboarding
* @param {StepOptions[]} steps
* @return {Onboard} returns this widget instance
*/
start(steps) {
this._model.start(steps);
return this;
}
/**
* Stops onboarding
* @return {Onboard} returns this widget instance
*/
stop() {
this._model.stop();
return this;
}
} |
JavaScript | class searchBar extends Component {
constructor(props) {
super(props);
//whenever we use state, we initialize it by creating a new object and assigning it to state
this.state = {term: ''}
}
render() {
// This is a special React Defined property=> onChange
return (
<div className="search-bar">
<input
value={this.state.term}
onChange={(event) => this.onInputChange(event.target.value)}
/>
</div>)
}
onInputChange(term) {
this.setState({term});
this.props.onSearchTermChange(term);
}
} |
JavaScript | class TokenSolver {
constructor() {
this.include = [];
this.symbols = [];
this.regexp = null;
this.priority = 1;
}
/**
* Used to build regexp from self properties
* @returns {*}
*/
build() {
return null;
}
} |
JavaScript | class Ratio extends AdjustFunction {
/**
* Constructor
*/
constructor() {
super();
this.setInput("input", SourceData.create("prop", "input"));
this.setInput("ratio", SourceData.create("prop", "ratio"));
this.setInput("outputName", "output");
}
/**
* Function that removes the used props
*
* @param aProps Object The props object that should be adjusted
*/
removeUsedProps(aProps) {
//METODO: change this to actual source cleanup
delete aProps["input"];
delete aProps["ratio"];
}
/**
* Creates the ratio
*
* @param aData * The data to adjust
* @param aManipulationObject WprrBaseObject The manipulation object that is performing the adjustment. Used to resolve sourcing.
*
* @return * The modified data
*/
adjust(aData, aManipulationObject) {
//console.log("wprr/manipulation/adjustfunctions/logic/Ratio::adjust");
let input = this.getInput("input", aData, aManipulationObject);
let ratio = this.getInput("ratio", aData, aManipulationObject);
let outputName = this.getInput("outputName", aData, aManipulationObject);
this.removeUsedProps(aData);
aData[outputName] = input*ratio;
return aData;
}
/**
* Creates a new instance of this class.
*
* @param aInput SourceData|Number The input value
* @param aRatio SourceData|Number The ratio to scale to
* @param aOutputName SourceData|String The output name to stroe the data in
*
* @return Ratio The new instance.
*/
static create(aInput = null, aRatio = null, aOutputName = null) {
let newRatio = new Ratio();
newRatio.setInputWithoutNull("input", aInput);
newRatio.setInputWithoutNull("ratio", aRatio);
newRatio.setInputWithoutNull("outputName", aOutputName);
return newRatio;
}
} |
JavaScript | class Core {
/**
* Registers shutdown listeners that will try to process whatever remaining events are still left.
*/
constructor() {
this._events = [];
this._loggers = {};
this._rules = {};
process.on('beforeExit', this.exit.bind(this));
}
/**
* Register an existing logger in the system so that it can receive configuration updates.
*
* @param {Logger} logger
*/
registerLogger(logger) {
if (this._loggers[logger.name]) {
throw new Error('Trying to create logger with existing name. Only one instance can exist with the same name');
}
this._loggers[logger.name] = logger;
for (let pattern in this._rules) {
if (logger.name.match(pattern)) {
logger.config = this._rules[pattern];
}
}
}
/**
* Loads the registered Configurators and applies the configs to all plugins and loggers.
*/
initialize() {
let config = {
appenders: {},
processors: {},
configurators: {}
};
// TODO The loading order needs to be determined so that 'Default' will be loaded last and 'Arguments' first.
for (let type in Plugins.registered.configurators) {
let configurator = this.configureConfigurator(type, config);
configurator.scan(config, updatedConfig => {
config = updatedConfig;
this.configure(updatedConfig);
});
Plugins.on('config', config => configurator.onChange(config, this.configure));
}
}
/**
* Allows to set the entire configuration at once.
*
* @param {Object} configuration
*/
configure(configuration) {
if (!_.isEqual(configuration, this._currentConfiguration)) {
for (let name in configuration.processors) {
this.configureProcessor(name, configuration.processors[name]);
}
for (let name in configuration.appenders) {
this.configureAppender(name, configuration.appenders[name]);
}
for (let name in configuration.configurators) {
this.configureConfigurator(name, configuration.configurators[name]);
}
for (let pattern in configuration.loggers) {
this.configureLogger(pattern, configuration.loggers[pattern]);
}
Plugins.emit('config', configuration);
}
}
/**
* Configure a processor using this method.
*
* @param {string} name
* @param {Object} configuration
* @returns {Processor}
* @throws Error when processor was not found or instance could not be created
*/
configureProcessor(name, configuration) {
try {
let processor = Plugins.getInstance(name, 'processor');
processor.configuration = configuration;
return processor;
} catch (e) {
return Plugins.createInstance(configuration.type, name, configuration);
}
}
/**
* Configure an appender using this method.
*
* @param {string} name
* @param {Object} [configuration]
* @returns {Appender}
* @throws Error when appender was not found or instance could not be created
*/
configureAppender(name, configuration) {
try{
let appender = Plugins.getInstance(name, 'appender');
if (configuration) {
if (configuration.type != appender.configuration.type) {
appender = Plugins.createInstance(configuration.type, name, configuration);
} else {
appender.configuration = configuration;
}
}
return appender;
} catch(e) {
return Plugins.createInstance(configuration.type, name, configuration);
}
}
/**
* Configure an configurator using this method.
*
* @param {string} type
* @param {Object} [configuration]
* @returns {Configurator}
* @throws Error when configurator was not found or instance could not be created
*/
configureConfigurator(type, configuration) {
try {
let configurator = Plugins.getInstance(type, 'configurator');
configurator.configuration = configuration;
return configurator;
} catch (e) {
return Plugins.createInstance(type, configuration);
}
}
/**
* Configure one or several loggers that match a given string or regex pattern.
*
* @param {String|RegExp} pattern
* @param {Object} config
*/
configureLogger(pattern, config) {
this._rules[pattern] = config;
for (let name in this._loggers) {
if (name.match(pattern)) {
this._loggers[name].config = config;
}
}
}
/**
* Returns the configuration for a specific logger or an empty object.
* @param {string} name
* @returns {Object}
*/
getLoggerConfig(name) {
let config = {};
for (let pattern in this._rules) {
if (name.match(pattern)) {
_.mergeWith(config, this._rules[pattern], (val1, val2) => {
if (_.isArray(val1)) {
return val1.concat(val2);
}
return [val1].concat(val2);
});
}
}
return this._rules[name] || {};
}
/**
* Queues an event up for processing on next tick. If this is the first event to be added then an on tick listener
* is registered.
*
* @param {Event} event
*/
queueEvent(event) {
if (!this._events.length) {
setImmediate(this.process.bind(this));
}
this._events.push(event);
}
/**
* This method is called at the end of the event loop and will process all queued up events.
*/
process() {
for (let event of this._events) {
for (let pattern in this._loggers) {
if (event.source.match(pattern)) {
for (let name of this._loggers[pattern].listAppenders()) {
//TODO this might be expensive, consider mapping events to appenders (via loggers) before instantiating them each time
let appender = Plugins.getInstance(name, 'appender');
let processors = [];
for (let processorName of appender.configuration.processors) {
processors.push(Plugins.getInstance(processorName, 'processor'));
}
processors.push(appender);
this._processChain([event], processors);
}
}
}
}
}
/**
* Internal method to process the processor chain recursively and call the appender in the end.
*
* @param {Event[]} events
* @param {Plugin[]} plugins
* @private
*/
_processChain(events, plugins) {
let plugin = plugins.unshift();
if (plugin instanceof Plugins.interfaces.Appender) {
plugin.append(events);
}
if (plugin instanceof Plugins.interfaces.Processor) {
plugin.process(events, events => {
this._processChain(events, plugins);
});
}
}
/**
* Removes all existing loggers and events.
*/
reset() {
this._events = [];
this._loggers = {};
this._rules = {};
delete this._currentConfiguration;
}
/**
* When called all messages that have been queued up are processed at the end of the tick and the program is exited
* afterwards. Note that any plugins that delay processing of messages such as the {@link Batcher} will keep
* messages from showing up in the logs. Anything that cannot be resolved in this tick will be lost.
*/
exit() {
this.process();
process.exit();
}
} |
JavaScript | class Home extends Component {
render() {
const { title, className } = this.props;
return (
<Template title={title} className={className}>
<main className={'main-content'} role="main">
<div className={'main-content-left'}>
<h1>Delicious Food</h1>
<p className={'mt-xs-20'}>
Only the pure of heart can make a superb burger.
</p>
<NavLink
to={'/categories'}
className={
'btn-primary-lg-pill mt-xs-20 mt-md-40 hide-xs-only'
}
>
Order Online
</NavLink>
</div>
<div className={'main-content-right'}>
<img src={'/assets/images/home-burger.png'} />
</div>
</main>
</Template>
);
}
} |
JavaScript | class DistributedWriteLock {
/**
* @constructor
* @param {Locker} locker - The `Locker` instance that created this `RWLock` .
* @param {String} key - The keys that are locked by this RWLock.
* @param {String} token - The token that is used for write lock key.
* @param {Mixed} distributedShard - null for a normal lock, shard number for a distributed read lock
* @param {Boolean} [isWriteLock=false] - If true, this lock is a write lock.
* @param {Number} [heartbeatInterval=1000] - Heartbeat interval in milliseconds, null or false to disable
* @param {Number} [heartbeatTimeout=5] - Heartbeat timeout in seconds
*/
constructor(rwlocks) {
this.rwlocks = rwlocks;
this.locker = rwlocks[0].locker;
this.key = rwlocks[0].key;
this.isWriteLock = rwlocks[0].isWriteLock;
this.isLocked = true;
this.token = rwlocks[0].token;
// Number of times this lock has been locked. Expect the same number of releases.
this.referenceCount = 1;
}
/**
* Forces releasing the lock immediately, regardless of reference counts. This does not
* decrement the reference count.
*
* @return {Promise} - Resolves when the lock is released.
*/
async forceRelease() {
if (!this.isLocked) return;
this.isLocked = false;
let promises = [];
for (let lock of this.rwlocks) {
promises.push(lock.forceRelease());
}
await Promise.all(promises);
}
/**
* Decrements the reference counter. If it is decremented to zero, the lock is released.
*
* @return {Promise} - Resolves when lock is released or reference counter is decremented.
*/
release() {
this.referenceCount--;
if (this.referenceCount < 0) {
this.referenceCount = 0;
console.warn('Lock on ' + this.key + ' released too many times');
}
if (this.referenceCount === 0) {
return this.forceRelease();
} else {
return Promise.resolve();
}
}
/**
* Increments the reference counter of this lock. Throws an error if the lock is already
* released.
*
* @method _relock
* @protected
* @throws {XError}
* @return {RWLock} - this
*/
_relock() {
if (!this.isLocked) {
throw new XError(XError.INTERNAL_ERROR, 'Cannot relock a lock after release');
}
this.referenceCount++;
return this;
}
} |
JavaScript | class App extends Component {
constructor(props){
super(props)
this.playerChoice = this.playerChoice.bind(this)
this.symbols = ["rock", "paper", "scissors", "lizard", "spock"]
this.state = {
endpoint: "localhost:8000",
playerRedDisplay: this.symbols[0],
playerBlueDisplay: this.symbols[0],
playerRed: '',
playerBlue: '',
round: 1,
scoreRed: 0,
scoreBlue: 0,
resultDisplay: "",
nextMove: false,
nextFight: false,
buttonsChoice: true,
nextRound: false,
animationPlayerOne: "p1-idle",
animationPlayerTwo: "p2-idle",
healthRyu: 100,
healthChun: 100,
playerOneHasPlayed: false,
playerTwoHasPlayed: false,
counterNextMove: 10,
}
this.socket = props.socket
}
componentDidMount(){
// reception des messages
this.socket.on('moves', (data) =>{
console.log('moves received: ', data);
//first two states don't work!!!!
this.setState({
playerRed: this.symbols[data.movePlayerOne.playerOneMove],
playerBlue: this.symbols[data.movePlayerTwo.playerTwoMove],
playerOneHasPlayed: data.playerOneHasPlayed,
playerTwoHasPlayed: data.playerTwoHasPlayed,
nextFight: true,
})
//console.log(this.state.playerRed);
//this.runGame();
});
this.play(soundMusic, true);
//this.decideWinner();
}
componentDidUpdate(){
/*this.socket.on('moves', (data) =>{
this.setState({
playerRed: this.symbols[data.movePlayerOne],
playerBlue: this.symbols[data.movePlayerTwo],
playerOneHasPlayed: data.playerOneHasPlayed,
playerTwoHasPlayed: data.playerTwoHasPlayed,
nextFight: true,
})
if (this.state.playerOneHasPlayed === true && this.state.playerTwoHasPlayed === true){
this.runGame();
}
});*/
}
play = (url, loop) => {
let stream = new Audio(url);
stream.preload = 'none';
stream.loop = loop;
stream.play();
}
stop = (url) => {
let stream = new Audio(url);
stream.pause(url);
stream.currentTime = 0;
}
/* function to make a move*/
playerChoice = (move) => {
if (this.props.playerNumberOne === true){
console.log("move playerOne");
this.socket.emit('move-playerone', {playerOneMove: move})
}
else {
console.log("move playerTwo");
this.socket.emit('move-playertwo', {playerTwoMove: move})
}
}
/* function to launch the next round */
runNextRound = () => {
this.setState((preState) => {return {round : preState.round + 1}});
this.setState({
playerRedDisplay: this.symbols[0],
playerBlueDisplay: this.symbols[0],
resultDisplay: "",
winner: "",
nextMove: false,
nextFight: false,
buttonsChoice: true,
nextRound: false,
animationPlayerOne: "p1-idle",
animationPlayerTwo: "p2-idle",
healthRyu: 100,
healthChun: 100,
//playerOneHasPlayed: false,
//playerTwoHasPlayed: false,
})
//this.play(soundMusic, true);
}
/* function to decide winner + if the round is finished */
decideWinner = () => {
const {playerBlue, playerRed} = this.state;
console.log("playerRed:" + this.state.playerRed);
console.log("playerBlue:" + this.state.playerBlue);
this.setState({
playerRedDisplay: this.state.playerRed,
playerBlueDisplay: this.state.playerBlue,
resultDisplay: this.state.playerRed + " versus " + this.state.playerBlue + " : ",
nextFight: false,
nextMove: true,
buttonsChoice: false,
nextRound: false,
})
if (playerRed === playerBlue){
this.play(soundChunKick, false);
this.play(soundRyuKick, false);
return " It's a draw !"
}
if (
(playerRed==="scissors" && playerBlue ==="paper")||
(playerRed==="paper" && playerBlue ==="rock")||
(playerRed==="rock" && playerBlue ==="lizard")||
(playerRed==="lizard" && playerBlue ==="spock")||
(playerRed==="spock" && playerBlue ==="scissors")||
(playerRed==="scissors" && playerBlue ==="lizard")||
(playerRed==="lizard" && playerBlue ==="paper")||
(playerRed==="paper" && playerBlue ==="spock")||
(playerRed==="spock" && playerBlue ==="rock")||
(playerRed==="rock" && playerBlue ==="scissors")
)
{
//Ryu strikes
if (this.state.healthChun !== 20){
this.setState((preState) => {return {scoreRed : preState.scoreRed + 1, healthChun : preState.healthChun -20, animationPlayerOne: "p1-won", animationPlayerTwo: "p2-lost"}});
this.play(soundRyuKick, false);
return this.props.playerOne + " strikes ! "
}
//Ryu wins
if (this.state.healthChun === 20){
this.setState((preState) => {return {scoreRed : preState.scoreRed + 1, healthChun : preState.healthChun -20, nextMove: false, nextFight: false, nextRound: true, animationPlayerOne: "p1-wonRound", animationPlayerTwo: "p2-looseRound"}});
this.stop(soundMusic);
this.play(soundChunKo, false);
this.play(soundEndRound, false);
return this.props.playerOne + " wins ! "
}
}
//Chun-li strikes
if (this.state.healthRyu !== 20){
this.setState((preState) => {return {scoreBlue : preState.scoreBlue + 1, healthRyu : preState.healthRyu -20, animationPlayerTwo: "p2-won", animationPlayerOne: "p1-lost"}});
this.play(soundChunKick, false);
return this.props.playerTwo + " strikes !"
}
//Chun-li wins
if (this.state.healthRyu === 20){
this.setState((preState) => {return {scoreBlue : preState.scoreBlue + 1, healthRyu : preState.healthRyu -20, nextMove: false, nextFight: false, nextRound: true, animationPlayerOne: "p1-looseRound", animationPlayerTwo: "p2-wonRound"}});
this.stop(soundMusic);
this.play(soundRyuKo, false);
this.play(soundEndRound, false);
return this.props.playerTwo + " wins !"
}
}
/* function to launch a game */
runGame = () => {
this.play(soundStrikes, false);
this.setState({nextFight: false, buttonsChoice: false})
this.setState({winner: this.decideWinner()})
}
/* function that reset some states after a move */
nextMove = () => {
this.setState({
playerRedDisplay: this.symbols[0],
playerBlueDisplay: this.symbols[0],
nextFight: false,
nextMove: false,
buttonsChoice: true,
resultDisplay: "",
winner: "",
animationPlayerOne: "p1-idle",
animationPlayerTwo: "p2-idle",
})
}
render(){
const nextMove = this.state.nextMove;
const nextFight = this.state.nextFight;
const nextRound = this.state.nextRound;
const buttonsChoice = this.state.buttonsChoice;
let buttonNextDisplay;
let buttonsChoiceDisplay;
let buttonNextRound;
if (nextMove) {
//buttonNextDisplay = <div className="hud"><button className="myButton" onClick={this.nextMove}>NEXT MOVE</button></div>
let counter =0;
buttonNextDisplay = <div className="hud">Ready for next move!</div>
let myInterval = setInterval(() => {
counter++;
//this.setState({counterNextMove: counter})
//counterDecrease--;
if(counter > 5){
clearInterval(myInterval)
this.nextMove();
}
},500)
}
if (nextFight) {
//buttonNextDisplay = <div className="hud"><button className="myButton" onClick={this.runGame}>FIGHT!</button></div>
this.runGame();
}
if (buttonsChoice) {
buttonsChoiceDisplay =
<div className="buttonsGroup" id="buttonsGroup">
<div className="hud">Choose your move:</div>
<input className = "buttonsPlay" alt = "button rock" onClick={() => this.playerChoice(0)} type = "image" src = "./img/rock.png" />
<input className = "buttonsPlay" alt = "button paper" onClick={() => this.playerChoice(1)} type = "image" src = "./img/paper.png" />
<input className = "buttonsPlay" alt = "button scissors" onClick={() => this.playerChoice(2)} type = "image" src = "./img/scissors.png" />
<input className = "buttonsPlay" alt = "button lizard" onClick={() => this.playerChoice(3)} type = "image" src = "./img/lizard.png" />
<input className = "buttonsPlay" alt = "button spock" onClick={() => this.playerChoice(4)} type = "image" src = "./img/spock.png" />
</div>
}
if (nextRound) {
buttonNextRound =
<div className="hud">
<button className="myButton" onClick={this.runNextRound}>PLAY NEXT ROUND</button>
</div>
}
return (
<div id="conteneur-flexbox">
<div className="title" id="title"><img src="img/socket-fighter.png" alt=""/></div>
<div className="hud" id="player-1">
<div>{this.props.playerOne}: {this.state.scoreRed}</div>
<div><progress id="health-ryu" className="health" value={`${this.state.healthRyu}`} max="100"></progress></div>
<PlayerSprite
character="ryu"
animation={this.state.animationPlayerOne}
/>
</div>{/*\div player-1*/}
<div className="App" id="App">
<div className="hud">ROUND: {this.state.round} </div>
<div id="cards" className="cards">
<PlayerCard
color="red"
symbol={this.state.playerRedDisplay}
/>
<PlayerCard
color="blue"
symbol={this.state.playerBlueDisplay}
/>
</div>
<div className="versus"><img src="img/versus.png" alt=""/></div>
<div className="hud">{/*this.state.resultDisplay*/} {this.state.winner}</div>
{buttonsChoiceDisplay}
{buttonNextDisplay}
{buttonNextRound}
</div>{/*\div app*/}
<div className="hud" id="player-2">
<div>{this.props.playerTwo}: {this.state.scoreBlue}</div>
<div><progress id="health-chun" className="health" value={`${this.state.healthChun}`} max="100"></progress></div>
<PlayerSprite
character="chun-li"
animation={this.state.animationPlayerTwo}
/>
</div>{/*\div player-2*/}
</div>//\conteneur-flexbox
);
}//\render
}//\class App |
JavaScript | class PolygraphException {
constructor(reason="", exceptionType="unkown") {
this.type = exceptionType;
var dateConf = new Date().toJSON();
this.datetime = dateConf.substring(0, 10);
this.dayOfWeek = dateConf.substring(10, 11);
this.time = dateConf.substring(12, 19);
this.date = dateConf.substring(0, 10);
this.reason = reason;
}
toConsoleString(enableFormating=false) {
if(enableFormating) return "%cPolygraph["+this.date+" "+this.time+"]> %c"+this.content; else return "Polygraph["+this.date+" "+this.time+"]> "+this.content;
}
} |
JavaScript | class FileBuilder {
constructor({ fileURL, mountEntry, outDir, config, }) {
this.output = {};
this.filesToResolve = {};
this.filesToProxy = [];
this.fileURL = fileURL;
this.mountEntry = mountEntry;
this.outDir = outDir;
this.config = config;
}
async buildFile() {
this.filesToResolve = {};
const isSSR = this.config.buildOptions.ssr;
const srcExt = path_1.default.extname(url_1.default.fileURLToPath(this.fileURL));
const fileOutput = this.mountEntry.static
? { [srcExt]: { code: await util_1.readFile(this.fileURL) } }
: await build_pipeline_1.buildFile(this.fileURL, {
config: this.config,
isDev: false,
isSSR,
isHmrEnabled: false,
});
for (const [fileExt, buildResult] of Object.entries(fileOutput)) {
let { code, map } = buildResult;
if (!code) {
continue;
}
let outFilename = path_1.default.basename(url_1.default.fileURLToPath(this.fileURL));
const extensionMatch = util_1.getExtensionMatch(this.fileURL.toString(), this.config._extensionMap);
if (extensionMatch) {
const [inputExt, outputExts] = extensionMatch;
if (outputExts.length > 1) {
outFilename = util_1.addExtension(path_1.default.basename(url_1.default.fileURLToPath(this.fileURL)), fileExt);
}
else {
outFilename = util_1.replaceExtension(path_1.default.basename(url_1.default.fileURLToPath(this.fileURL)), inputExt, fileExt);
}
}
const outLoc = path_1.default.join(this.outDir, outFilename);
const sourceMappingURL = outFilename + '.map';
if (this.mountEntry.resolve && typeof code === 'string') {
switch (fileExt) {
case '.css': {
if (map)
code = util_1.cssSourceMappingURL(code, sourceMappingURL);
this.filesToResolve[outLoc] = {
baseExt: fileExt,
root: this.config.root,
contents: code,
locOnDisk: url_1.default.fileURLToPath(this.fileURL),
};
break;
}
case '.js': {
if (fileOutput['.css']) {
// inject CSS if imported directly
code = `import './${util_1.replaceExtension(outFilename, '.js', '.css')}';\n` + code;
}
code = build_import_proxy_1.wrapImportMeta({ code, env: true, hmr: false, config: this.config });
if (map)
code = util_1.jsSourceMappingURL(code, sourceMappingURL);
this.filesToResolve[outLoc] = {
baseExt: fileExt,
root: this.config.root,
contents: code,
locOnDisk: url_1.default.fileURLToPath(this.fileURL),
};
break;
}
case '.html': {
code = build_import_proxy_1.wrapHtmlResponse({
code,
hmr: getIsHmrEnabled(this.config),
hmrPort: hmrEngine ? hmrEngine.port : undefined,
isDev: false,
config: this.config,
mode: 'production',
});
this.filesToResolve[outLoc] = {
baseExt: fileExt,
root: this.config.root,
contents: code,
locOnDisk: url_1.default.fileURLToPath(this.fileURL),
};
break;
}
}
}
this.output[outLoc] = code;
if (map) {
this.output[path_1.default.join(this.outDir, sourceMappingURL)] = map;
}
}
}
async resolveImports(importMap) {
let isSuccess = true;
this.filesToProxy = [];
for (const [outLoc, rawFile] of Object.entries(this.filesToResolve)) {
// don’t transform binary file contents
if (Buffer.isBuffer(rawFile.contents)) {
continue;
}
const file = rawFile;
const resolveImportSpecifier = import_resolver_1.createImportResolver({
fileLoc: file.locOnDisk,
config: this.config,
});
const resolvedCode = await rewrite_imports_1.transformFileImports(file, (spec) => {
var _a, _b;
// Try to resolve the specifier to a known URL in the project
let resolvedImportUrl = resolveImportSpecifier(spec);
// If not resolved, then this is a package. During build, dependencies are always
// installed locally via esinstall, so use localPackageSource here.
if (importMap.imports[spec]) {
resolvedImportUrl = local_1.default.resolvePackageImport(spec, importMap, this.config);
}
// If still not resolved, then this imported package somehow evaded detection
// when we scanned it in the previous step. If you find a bug here, report it!
if (!resolvedImportUrl) {
isSuccess = false;
logger_1.logger.error(`${file.locOnDisk} - Could not resolve unknown import "${spec}".`);
return spec;
}
// Ignore "http://*" imports
if (util_1.isRemoteUrl(resolvedImportUrl)) {
return resolvedImportUrl;
}
// Ignore packages marked as external
if ((_a = this.config.packageOptions.external) === null || _a === void 0 ? void 0 : _a.includes(resolvedImportUrl)) {
return resolvedImportUrl;
}
// Handle normal "./" & "../" import specifiers
const importExtName = path_1.default.extname(resolvedImportUrl);
const isBundling = !!((_b = this.config.optimize) === null || _b === void 0 ? void 0 : _b.bundle);
const isProxyImport = importExtName &&
importExtName !== '.js' &&
!path_1.default.posix.isAbsolute(spec) &&
// If using our built-in bundler, treat CSS as a first class citizen (no proxy file needed).
// TODO: Remove special `.module.css` handling by building css modules to native JS + CSS.
(!isBundling || !/(?<!module)\.css$/.test(resolvedImportUrl));
const isAbsoluteUrlPath = path_1.default.posix.isAbsolute(resolvedImportUrl);
let resolvedImportPath = util_1.removeLeadingSlash(path_1.default.normalize(resolvedImportUrl));
// We treat ".proxy.js" files special: we need to make sure that they exist on disk
// in the final build, so we mark them to be written to disk at the next step.
if (isProxyImport) {
if (isAbsoluteUrlPath) {
this.filesToProxy.push(path_1.default.resolve(this.config.buildOptions.out, resolvedImportPath));
}
else {
this.filesToProxy.push(path_1.default.resolve(path_1.default.dirname(outLoc), resolvedImportPath));
}
resolvedImportPath = resolvedImportPath + '.proxy.js';
resolvedImportUrl = resolvedImportUrl + '.proxy.js';
}
// When dealing with an absolute import path, we need to honor the baseUrl
if (isAbsoluteUrlPath) {
resolvedImportUrl = util_1.relativeURL(path_1.default.dirname(outLoc), path_1.default.resolve(this.config.buildOptions.out, resolvedImportPath));
}
// Make sure that a relative URL always starts with "./"
if (!resolvedImportUrl.startsWith('.') && !resolvedImportUrl.startsWith('/')) {
resolvedImportUrl = './' + resolvedImportUrl;
}
return resolvedImportUrl;
});
this.output[outLoc] = resolvedCode;
}
return isSuccess;
}
async writeToDisk() {
mkdirp_1.default.sync(this.outDir);
for (const [outLoc, code] of Object.entries(this.output)) {
const encoding = typeof code === 'string' ? 'utf8' : undefined;
await fs_1.promises.writeFile(outLoc, code, encoding);
}
}
async getProxy(originalFileLoc) {
const proxiedCode = this.output[originalFileLoc];
const proxiedUrl = originalFileLoc
.substr(this.config.buildOptions.out.length)
.replace(/\\/g, '/');
return build_import_proxy_1.wrapImportProxy({
url: proxiedUrl,
code: proxiedCode,
hmr: false,
config: this.config,
});
}
async writeProxyToDisk(originalFileLoc) {
const proxyCode = await this.getProxy(originalFileLoc);
const importProxyFileLoc = originalFileLoc + '.proxy.js';
await fs_1.promises.writeFile(importProxyFileLoc, proxyCode, 'utf8');
}
} |
JavaScript | class PostPage extends Component {
componentDidMount() {
this.props.showPost(this.props.match.params.postId);
}
render() {
if (this.props.post) {
return (
<div className="main">
<Card>
<Card.Img variant="top" src={this.props.post.image} />
</Card>
<Card className="text-center">
<Card.Header>Details</Card.Header>
<Card.Body>
<Card.Title>{this.props.post.title}</Card.Title>
<Card.Text>{this.props.post.description}</Card.Text>
<Card.Title>$ {this.props.post.price} per ticket</Card.Title>
<hr />
{this.props.post.winner ? (
<p>Winner is ticket number: {this.props.post.winner}</p>
) : (
<PostForm
answers={this.props.post.answers[0]}
question={this.props.post.question.content}
/>
)}
</Card.Body>
<Card.Footer>
Winner announced on: {this.props.post.date}
</Card.Footer>
</Card>
</div>
);
} else {
return <Loading />;
}
}
} |
JavaScript | class Rectangle extends Base {
/**
* Static config method. Object returned defines the default properties of the class. This
* also defines the properties that may be passed to the class constructor.
*
* @returns {{
* id: string,
* title: string,
* cssClass: string,
* stroke: string,
* strokeWidth: number,
* fill: string,
* opacity: string,
* height: number,
* width: number,
* x: number,
* y: number,
* cornerRadius: number,
* cursor: string,
* children: array,
* xmlns: string,
* onClick: function,
* onMouseOver: function,
* onMouseOut: function,
* onMouseDown: function
* }}
*/
static get config() {
return {
id: 'rect1',
title: 'rectangle',
cssClass: null,
stroke: null,
strokeWidth: null,
fill: null,
opacity: null,
height: null,
width: null,
x: null,
y: null,
cornerRadius: null,
cursor: null,
xmlns: Util.xmlNamespaces().xmlns,
children: [],
onClick: null,
onMouseOver: null,
onMouseOut: null,
onMouseDown: null,
};
}
static factory(config) {
return new Rectangle(config || this.config);
}
/**
* Class constructor.
*
* @param config (optional)
*/
constructor(config) {
super();
this.apply(this, config || this.config, this.config);
this.init();
}
/**
* Method called by the constructor to create and assign docElement based
* on the properties exposed by the class.
*
* Note - if the autoBind flag is true, then it ends by invoking bind method.
*/
init() {
let svg = '<rect';
if (this.id) {
svg += ' id="' + this.id + '"';
}
if (this.title) {
svg += ' title="' + this.title + '"';
}
if (this.cssClass) {
svg += ' class="' + this.cssClass + '"';
}
if (this.x) {
svg += ' x="' + this.x + '"';
}
if (this.y) {
svg += ' y="' + this.y + '"';
}
if (this.width) {
svg += ' width="' + this.width + '"';
}
if (this.height) {
svg += ' height="' + this.height + '"';
}
if (this.fill) {
svg += ' fill="' + this.fill + '"';
}
if (this.opacity) {
svg += ' opacity="' + this.opacity + '"';
}
if (this.stroke) {
svg += ' stroke="' + this.stroke + '"';
}
if (this.strokeWidth) {
svg += ' stroke-width="' + this.strokeWidth + '"';
}
if (this.onMouseOut) {
svg += ' onmouseout="' + this.onMouseOut + '"';
}
if (this.onMouseOver) {
svg += ' onmouseover="' + this.onMouseOver + '"';
}
if (this.onMouseDown) {
svg += ' onmousedown="' + this.onMouseDown + '"';
}
if (this.cursor) {
svg += ' style="cursor: ' + this.cursor + ';"';
}
if (this.cornerRadius) {
svg += ' rx="' + this.cornerRadius + '"';
svg += ' ry="' + this.cornerRadius + '"';
}
svg += '>';
if (this.children && this.children.length > 0) {
for (var i = 0; i < this.children.length; i++) {
var child = this.children[i];
if (child.innerHTML) {
svg += child.innerHTML;
}
}
}
svg += '</rect>';
this.innerHTML = svg;
}
} |
JavaScript | class MyExtension extends HouseExtension {
onPlayerEnterHouse(player, location) {
assert.equal(player, gunther);
assert.equal(location, currentLocation);
enteredHouse = true;
}
onPlayerLeaveHouse(player, location) {
assert.equal(player, gunther);
assert.equal(location, currentLocation);
leftHouse = true;
}
} |
JavaScript | class CleanOtherChannel extends TestCase {
/**
* Executes the test case
* @return {Promise} nothing (in case of failure - an exception will be thrown)
*/
async execute() {
super.execute();
const discordClient = this.processor.discordClient;
this.assertNotNull(discordClient);
const guild = discordClient.guilds.cache.get(this.processor.prefsManager.test_discord_guild_id);
this.assertNotNull(guild);
const channel1 = guild.channels.cache.get(this.processor.prefsManager.test_discord_text_channel_1_id);
this.assertNotNull(channel1);
const channel2 = guild.channels.cache.get(this.processor.prefsManager.test_discord_text_channel_2_id);
this.assertNotNull(channel2);
await this.sleep(5000);
await channel2.send('Delete me!');
await channel1.send('Dont delete me!');
channel1.send('!clean -c <#' + channel2.id + '> -t 5s');
const receivedMessage = await this.getReply(channel1);
const timeLimitMillis = new Date().getTime() - 5000;
this.assertNotNull(receivedMessage);
this.assertTrue(receivedMessage.content.startsWith('cleaned 1 '));
const messages1 = await channel1.messages.fetch({ limit: 4 });
this.assertNotNull(messages1);
const messagesArray1 = Array.from(messages1.values());
const recentMessages1 = [];
for (const message of messagesArray1) {
if (message.createdTimestamp > timeLimitMillis) {
recentMessages1.push(message);
}
}
const messages2 = await channel2.messages.fetch({ limit: 4 });
this.assertNotNull(messages2);
const messagesArray2 = Array.from(messages2.values());
const recentMessages2 = [];
for (const message of messagesArray2) {
if (message.createdTimestamp > timeLimitMillis) {
recentMessages2.push(message);
}
}
let deleteFound = false;
let dontDeleteFound = false;
let replyFound = false;
for (const message of recentMessages1) {
if (message.content === 'Dont delete me!') {
dontDeleteFound = true;
}
if (message.content.startsWith('cleaned 1 ')) {
replyFound = true;
}
}
for (const message of recentMessages2) {
if (message.content === 'Delete me!') {
deleteFound = true;
}
}
this.assertTrue(dontDeleteFound);
this.assertTrue(!deleteFound);
this.assertTrue(replyFound);
}
} |
JavaScript | @inject({ modules: ["Downloader", "Link"] })
class DownloadLink extends React.Component {
constructor(props) {
super(props);
this.state = {
showDialog: false
};
this.dialog = null;
this.getDialog = this.getDialog.bind(this);
}
componentWillReceiveProps() {
if (this.dialog) {
this.getDialog();
}
}
getDialog() {
const result = this.props.download({
download: this.downloader.download,
data: this.props.params || null
});
// At this point we do not want to import Modal component to perform the check so we assume it is a ModalDialog if it is not null
if (result) {
this.dialog = result;
this.setState({ showDialog: true });
}
}
render() {
if (this.props.render) {
return this.props.render.call(this);
}
const {
modules: { Downloader, Link },
...props
} = this.props;
const downloader = <Downloader onReady={downloader => (this.downloader = downloader)} />;
props.onClick = () => {
if (this.props.disabled) {
return;
}
if (_.isString(this.props.download)) {
this.downloader.download(this.props.method, this.props.download, this.props.params);
} else {
this.getDialog();
}
};
delete props["download"];
let dialog = null;
if (this.dialog) {
dialog = React.cloneElement(this.dialog, {
onHidden: () => {
this.dialog = null;
this.setState({ showDialog: false });
},
onComponentDidMount: dialog => {
if (this.state.showDialog) {
dialog.show();
}
}
});
}
return (
<Link {..._.omit(props, ["render"])}>
{this.props.children}
{downloader}
{dialog}
</Link>
);
}
} |
JavaScript | class Employee{
// Constructor
constructor(arg_name, arg_id, arg_email){
// Parameterized properties
this.name = arg_name;
this.id = arg_id;
this.email = arg_email;
// Implicit property
this.role = "Employee";
}
// Getter methods
getName(){ return this.name;}
getId(){ return this.id; }
getEmail(){ return this.email; }
getRole(){ return this.role; }
} |
JavaScript | class Uri extends Bag {
/**
* Constructor
*/
constructor(uri) {
super()
if (uri instanceof Bag) {
this.replace(uri.all())
} else if (typeof uri === 'object') {
this.replace(uri)
} else if (typeof uri === 'string') {
const url = new Url()
const info = url.parse(uri, true)
this.set(Uri.PROTOCOL, info.protocol)
this.set(Uri.HOST, info.hostname)
this.set(Uri.PORT, parseInt(info.port))
this.set(Uri.PATH, info.pathname)
this.set(Uri.HASH, info.hash)
this.set(Uri.HREF, info.href)
this.set(Uri.SEARCH, info.search)
this.set(Uri.QUERY, new Bag(info.query))
} else {
this.set(Uri.QUERY, new Bag())
}
}
/**
* Get request's query
* @returns {Bag}
*/
getQuery() {
return this.get(Uri.QUERY)
}
/**
* Set request's query
* @param {Bag|Object|string} query
*/
setQuery(query) {
if (query instanceof Bag) {
this.set(Uri.QUERY, query)
} else if (typeof query === 'object') {
this.set(Uri.QUERY, new Bag(query))
} else if (typeof query === 'string') {
const url = new Url()
this.set(Uri.QUERY, new Bag(url.parse(query, true).query))
} else {
throw new Error('The query of request must be either a string, an instance of Bag or an object.')
}
this.set(Uri.SEARCH, this.getQuery().toString())
}
/**
* Returns uri as a string
* @returns {string}
*/
toString() {
const url = new Url()
url.protocol = this.get(Uri.PROTOCOL)
url.hostname = this.get(Uri.HOST)
url.port = this.get(Uri.PORT)
url.pathname = this.get(Uri.PATH)
url.hash = this.get(Uri.HASH)
url.search = this.get(Uri.SEARCH)
return url.format()
}
} |
JavaScript | class QueryActions {
constructor() {
/**
* Selects a CPS for a query.
* @function cps
* @param {object} cps - The selected cps.
* @param {string} cps.name - The name of the cps.
* @param {string} cps.id - The id of the cps.
* @instance
* @memberOf module:VisualizationConfigurator.QueryActions
*/
/**
* Selects an entity type for a query.
* @function type
* @param {object} type - The selected type.
* @param {string} type.name - The name of the type.
* @param {string} type.id - The id of the type.
* @instance
* @memberOf module:VisualizationConfigurator.QueryActions
*/
/**
* Selects an entity for a query.
* @function entity
* @param {object} entity - The selected entity.
* @param {string} entity.name - The name of the entity.
* @param {string} entity.id - The id of the entity.
* @instance
* @memberOf module:VisualizationConfigurator.QueryActions
*/
/**
* Selects an attribute type for a query.
* @function attributeType
* @param {object} attributeType - The selected attribute type.
* @param {string} attributeType.name - The name of the attribute type.
* @param {string} attributeType.id - The id of the attribute type.
* @instance
* @memberOf module:VisualizationConfigurator.QueryActions
*/
/**
* Selects an attribute for a query.
* @function attribute
* @param {object} attribute - The selected attribute.
* @param {string} attribute.name - The name of the attribute.
* @param {string} attribute.id - The id of the attribute.
* @instance
* @memberOf module:VisualizationConfigurator.QueryActions
*/
/**
* Adds the selected QueryItems as a Query.
* @function add
* @param {string} label - Label of the query.
* @instance
* @memberOf module:VisualizationConfigurator.QueryActions
*/
/**
* Clears the saved queries.
* @function clear
* @instance
* @memberOf module:VisualizationConfigurator.QueryActions
*/
this.generateActions('cps', 'typeChange', 'entity',
'attribute', 'attributeType',
'add', 'clear');
}
} |
JavaScript | class EditorPageLayoutPlugin extends _prosemirrorState.Plugin {
constructor() {
super(SPEC);
}
} |
JavaScript | class BookList {
constructor(Books) {
this.bookListCollection = Books;
}
clear() {
localStorage.clear('library');
document.getElementById('list_container').innerHTML = '';
this.bookListCollection = [];
}
addBook(Book) {
this.bookListCollection.push(Book);
const TitleP = document.createElement('p');
const AuthorP = document.createElement('p');
const RButton = document.createElement('button');
RButton.addEventListener('click', () => { this.RemoveBook(Book.id); });
RButton.innerHTML = 'Remove';
RButton.setAttribute('id', Book.id);
RButton.setAttribute('class', 'rmv-btn');
const BookContainer = document.createElement('div');
BookContainer.setAttribute('id', Book.id);
TitleP.innerHTML = `Title: ${Book.title}`;
AuthorP.innerHTML = `Author: ${Book.author}`;
document.getElementById('list_container').appendChild(BookContainer).appendChild(TitleP);
document.getElementById('list_container').appendChild(BookContainer).appendChild(AuthorP);
document.getElementById('list_container').appendChild(BookContainer).appendChild(RButton);
}
RemoveBook(BookId) {
const BookContainer = document.getElementById(BookId);
BookContainer.parentNode.removeChild(BookContainer);
const BooksNew = [];
/* eslint-disable */
for (const i in this.bookListCollection) {
if (this.bookListCollection[i].id !== BookId) {
BooksNew.push(this.bookListCollection[i]);
}
}
/* eslint-enable */
this.bookListCollection = BooksNew;
localStorage.clear();
const BookList = JSON.stringify(BooksNew);
// eslint-disable-next-line no-unused-vars
localStorage.setItem('library', BookList);
}
AddToStorage() {
localStorage.setItem('library', JSON.stringify(this.bookListCollection));
}
/* eslint-disable */
ShowBooks() {
for (const i in this.bookListCollection) {
this.addBook(this.bookListCollection[i])
}
}
} |
JavaScript | class TreeNode extends EventTarget {
/**
* Constructor.
*/
constructor() {
super();
/**
* The node ID
* @type {string}
* @private
*/
this.id_ = '';
this.setId(nodeId.toString());
nodeId++;
/**
* The node label
* @type {?string}
* @private
*/
this.label_ = null;
/**
* The node's parent
* @type {?ITreeNode}
* @private
*/
this.parent_ = null;
/**
* The node's children
* @type {?Array<!ITreeNode>}
* @private
*/
this.children_ = null;
/**
* @type {Object<string, !ITreeNode>}
* @protected
*/
this.childIdMap = {};
}
/**
* @inheritDoc
*/
disposeInternal() {
// clean up listeners first so events aren't handled on disposed tree nodes
super.disposeInternal();
if (this.children_) {
for (var i = 0, n = this.children_.length; i < n; i++) {
var c = this.children_[i];
this.destroyChild(c);
c.dispose();
}
this.children_ = null;
}
}
/**
* @inheritDoc
*/
getId() {
return this.id_;
}
/**
* @inheritDoc
*/
setId(value) {
this.id_ = value;
}
/**
* @inheritDoc
*/
getLabel() {
return this.label_;
}
/**
* Sets the label
*
* @param {?string} value The new label
*/
setLabel(value) {
if (value !== this.label_) {
var old = this.label_;
this.label_ = value;
this.dispatchEvent(new PropertyChangeEvent('label', value, old));
}
}
/**
* @inheritDoc
*/
getChildren() {
return this.children_;
}
/**
* @inheritDoc
*/
setChildren(value, opt_skipaddparent) {
if (value !== this.children_) {
if (this.children_) {
var i = this.children_.length;
while (i--) {
this.removeChild(this.children_[i]);
}
}
if (value) {
for (var i = 0, n = value.length; i < n; i++) {
this.addChild(value[i], opt_skipaddparent);
}
}
this.dispatchEvent(new PropertyChangeEvent('children', value, null));
}
}
/**
* @inheritDoc
*/
getParent() {
return this.parent_;
}
/**
* @inheritDoc
*/
setParent(value, opt_nocheckparent) {
if (this.parent_ !== value) {
this.parent_ = value;
if (this.parent_ && !opt_nocheckparent) {
this.parent_.addChild(this, true, 0);
}
}
}
/**
* @inheritDoc
*/
getRoot() {
var node = this;
while (node.getParent()) {
node = node.getParent();
}
return node;
}
/**
* @inheritDoc
*/
addChild(child, opt_skipaddparent, opt_index) {
if (!this.children_) {
this.children_ = [];
}
if (!this.hasChild(child)) {
// insert at the specified index, or at the end if unspecified
var index = opt_index != null ? opt_index : this.children_.length;
this.children_.splice(index, 0, child);
this.initChild(child);
if (!opt_skipaddparent) {
child.setParent(this, true);
}
this.dispatchEvent(new PropertyChangeEvent('children', this.children_));
return child;
}
return null;
}
/**
* @inheritDoc
*/
addChildren(value, opt_skipaddparent) {
var added = [];
if (value) {
var changed = false;
for (var i = 0, n = value.length; i < n; i++) {
var child = this.addChild(value[i], opt_skipaddparent);
if (child) {
changed = true;
}
}
if (changed) {
this.dispatchEvent(new PropertyChangeEvent('children', this.children_));
}
}
return added;
}
/**
* @inheritDoc
*/
hasChild(child) {
return child.getId() in this.childIdMap;
}
/**
* @inheritDoc
*/
hasChildren() {
return this.children_ != null && this.children_.length > 0;
}
/**
* @param {!ITreeNode} child
* @protected
*/
index(child) {
this.childIdMap[child.getId()] = child;
}
/**
* @param {!ITreeNode} child
* @protected
*/
unindex(child) {
delete this.childIdMap[child.getId()];
}
/**
* @inheritDoc
*/
removeChild(child) {
if (this.children_) {
var index = this.children_.indexOf(child);
if (index > -1) {
return this.removeChildInternal(index);
}
}
return null;
}
/**
* @inheritDoc
*/
removeChildAt(index) {
if (this.children_ && this.children_.length > index) {
return this.removeChildInternal(index);
}
return null;
}
/**
* Removes a child from the node.
*
* @param {number} index The child index to remove
* @return {!ITreeNode} The removed child
* @protected
*/
removeChildInternal(index) {
var child = this.children_[index];
if (child.getParent() === this) {
child.setParent(null);
}
this.children_.splice(index, 1);
this.destroyChild(child);
if (this.children_.length === 0) {
this.children_ = null;
}
this.dispatchEvent(new PropertyChangeEvent('children', this.children_));
return child;
}
/**
* @inheritDoc
*/
find(field, value) {
if (field in this && this[field] == value) {
return this;
}
var ret = null;
if (this.children_) {
for (var i = 0, n = this.children_.length; i < n; i++) {
ret = this.children_[i].find(field, value);
if (ret) {
return ret;
}
}
}
return null;
}
/**
* Provides a hook for setup on a child node that is being added.
*
* @param {!ITreeNode} child The child node
* @protected
*/
initChild(child) {
this.index(child);
child.listen(GoogEventType.PROPERTYCHANGE, this.onChildChange, false, this);
}
/**
* Provides a hook for a child node that is being removed
*
* @param {!ITreeNode} child The child node
* @protected
*/
destroyChild(child) {
this.unindex(child);
child.unlisten(GoogEventType.PROPERTYCHANGE, this.onChildChange, false, this);
}
/**
* Handles changes to children
*
* @param {!PropertyChangeEvent} e The change event
* @protected
*/
onChildChange(e) {
var p = e.getProperty();
if (p == 'children' || p == 'label') {
// propagate this up the tree
this.dispatchEvent(new PropertyChangeEvent(p));
}
}
/**
* @inheritDoc
*/
getSearchText() {
return this.getLabel() || '';
}
/**
* @inheritDoc
*/
getTags() {
return null;
}
/**
* @inheritDoc
*/
clone() {
var other = new this.constructor();
other.updateFrom(this);
return other;
}
/**
* Updates this node from the set of properties in the other
*
* @param {!ITreeNode} other
* @protected
*/
updateFrom(other) {
this.setId(other.getId());
this.setLabel(other.getLabel());
}
/**
* Does this node have the passed in elder (parent, or parent's parent's parent's, etc)
*
* @param {!ITreeNode} elder
* @return {boolean} if node has elder
*/
hasElder(elder) {
var parent = /** @type {TreeNode} */ (this.getParent());
if (parent && parent == elder) {
return true;
} else if (!parent) {
return false;
} else {
// Climb up the parent tree
return parent.hasElder(elder);
}
}
} |
JavaScript | class CompactData {
get isBaseChanged () {
return this._isBaseChanged
}
set isBaseChanged (value) {
this._isBaseChanged = value
}
get compact () {
return this._compact
}
set compact (value) {
this._compact = value
}
get base () {
return this._base
}
set base (value) {
this._base = value
}
/**
* Create a new CompactData instance.
* @param {BigNumber} rate - the total rate
* @param {BigNumber} base - the base to generate compact data
*/
constructor (rate, base) {
// const compactData = buildCompactData(rate, base)
const minInt8 = -128
const maxInt8 = 127
rate = new BigNumber(rate)
base = new BigNumber(base)
let compact
if (base.isEqualTo(0)) {
base = rate
this.isBaseChanged = true
compact = new BigNumber(0)
} else {
compact = rate
.dividedBy(base)
.minus(new BigNumber(1))
.multipliedBy(1000.0)
.integerValue()
// compact data is fit in a byte
if (
compact.isGreaterThanOrEqualTo(minInt8) &&
compact.isLessThanOrEqualTo(maxInt8)
) {
// overflowed, convert from int8 to byte so
// * -1 --> 255
// * -128 --> 128
if (compact.isLessThan(0)) {
compact = new BigNumber(2 ** 8).plus(compact)
}
} else {
base = rate
this.isBaseChanged = true
compact = new BigNumber(0)
}
}
this._base = base
this._compact = compact
}
} |
JavaScript | class TokenControlInfo {
get maxTotalImbalance () {
return this._maxTotalImbalance
}
set maxTotalImbalance (value) {
this._maxTotalImbalance = value
}
get maxPerBlockImbalance () {
return this._maxPerBlockImbalance
}
set maxPerBlockImbalance (value) {
this._maxPerBlockImbalance = value
}
get minimalRecordResolution () {
return this._minimalRecordResolution
}
set minimalRecordResolution (value) {
this._minimalRecordResolution = value
}
/**
* Create a new TokenControlInfo instance.
* @param minimalRecordResolution {uint} - minimum denominator in token wei that can be changed
* @param maxPerBlockImbalance {uint} - maximum wei amount of net absolute (+/-) change for a token in an ethereum
* block
* @param maxTotalImbalance {uint} - wei amount of the maximum net token change allowable that happens between 2
* price updates
*/
constructor (
minimalRecordResolution,
maxPerBlockImbalance,
maxTotalImbalance
) {
this._minimalRecordResolution = minimalRecordResolution
this._maxPerBlockImbalance = maxPerBlockImbalance
this._maxTotalImbalance = maxTotalImbalance
}
} |
JavaScript | class StepFunctionDataPoint {
get y () {
return this._y
}
set y (value) {
this._y = value
}
get x () {
return this._x
}
set x (value) {
this._x = value
}
/**
* Create a new StepFunctionDataPoint.
* @param x {int} - buy step in wei amount
* @param y {int} - impact on buy rate in basis points (bps). 1 bps = 0.01%
*/
constructor (x, y) {
this._x = x
this._y = y
}
} |
JavaScript | class RateSetting {
get sell () {
return this._sell
}
set sell (value) {
this._sell = value
}
get buy () {
return this._buy
}
set buy (value) {
this._buy = value
}
get address () {
return this._address
}
set address (value) {
this._address = value
}
/**
* Create a new RateSetting instance.
* @param {string} address - ERC20 token address
* @param {number} buy - buy rate per ETH
* @param {number} sell - sell rate per ETH
*/
constructor (address, buy, sell) {
validateAddress(address)
this._address = address
this._buy = buy
this._sell = sell
// this._buy = Web3.utils.padLeft(Web3.utils.numberToHex(buy), 14)
// this._sell = Web3.utils.padLeft(Web3.utils.numberToHex(sell), 14)
}
} |
JavaScript | class CompactDataLocation {
get indexInBulk () {
return this._indexInBulk
}
set indexInBulk (value) {
this._indexInBulk = value
}
get bulkIndex () {
return this._bulkIndex
}
set bulkIndex (value) {
this._bulkIndex = value
}
constructor (bulkIndex, indexInBulk) {
this._bulkIndex = bulkIndex
this._indexInBulk = indexInBulk
}
} |
JavaScript | class ConversionRatesContract extends BaseContract {
/**
* Create new ConversionRatesContract instance.
* @param {object} provider - Web3 provider
* @param {string} address - address of smart contract.
*/
constructor (web3, address) {
super(web3, address)
this.web3 = web3
this.contract = new this.web3.eth.Contract(conversionRatesABI, address)
/**
* getTokenIndices returns the index of given Token to use in setCompact
* data call.
* @param {string} token - ERC 20 token address
* @return {number} - index ot compact data
*/
this.getTokenIndices = token => {
let tokenIndices = {}
return (async () => {
validateAddress(token)
if (token in tokenIndices) {
return tokenIndices[token]
}
let results
try {
results = await this.contract.methods.getCompactData(token).call()
} catch (err) {
console.log(
`failed to query token ${token} for compact data, error: ${err}`
)
return
}
tokenIndices[token] = new CompactDataLocation(results[0], results[1])
return tokenIndices[token]
})()
}
}
/**
* Add a ERC20 token and its pricing configurations to reserve contract and
* enable it for trading.
* @param {object} adminAccount - admin account address
* @param {string} token - ERC20 token address
* @param {TokenControlInfo} tokenControlInfo - https://developer.kyber.network/docs/VolumeImbalanceRecorder#settokencontrolinfo
* @param {number} gasPrice (optional) - the gasPrice desired for the tx
*/
async addToken (adminAccount, token, tokenControlInfo, gasPrice) {
validateAddress(token)
await assertAdmin(this, adminAccount)
let addTokenTx = this.contract.methods.addToken(token)
await addTokenTx.send({
from: adminAccount,
gas: await addTokenTx.estimateGas({ from: adminAccount }),
gasPrice: gasPrice
})
console.log("Token Added...")
var controlInfoTx = this.contract.methods.setTokenControlInfo(
token,
tokenControlInfo.minimalRecordResolution,
tokenControlInfo.maxPerBlockImbalance,
tokenControlInfo.maxTotalImbalance
)
await controlInfoTx.send({
from: adminAccount,
gas: await controlInfoTx.estimateGas({ from: adminAccount }),
gasPrice: gasPrice
})
console.log("Token Control Information Updated...")
var enableTokenTx = this.contract.methods.enableTokenTrade(token)
await enableTokenTx.send({
from: adminAccount,
gas: await enableTokenTx.estimateGas({ from: adminAccount }),
gasPrice: gasPrice
})
console.log("Token Enabled...")
return this.getTokenIndices(token)
}
/**
* Add a ERC20 token and its pricing configurations to reserve contract and
* enable it for trading.
* @param {object} adminAccount - admin account address
* @param {string} token - ERC20 token address
* @param {TokenControlInfo} tokenControlInfo - https://developer.kyber.network/docs/VolumeImbalanceRecorder#settokencontrolinfo
* @param {number} gasPrice (optional) - the gasPrice desired for the tx
*/
async updateTokenControlInfo (adminAccount, token, tokenControlInfo, gasPrice) {
validateAddress(token)
await assertAdmin(this, adminAccount)
var controlInfoTx = this.contract.methods.setTokenControlInfo(
token,
tokenControlInfo.minimalRecordResolution,
tokenControlInfo.maxPerBlockImbalance,
tokenControlInfo.maxTotalImbalance
)
await controlInfoTx.send({
from: adminAccount,
gas: await controlInfoTx.estimateGas({ from: adminAccount }),
gasPrice: gasPrice
})
console.log("Token Control Information Updated...")
return this.getTokenIndices(token)
}
/**
* Set adjustments for tokens' buy and sell rates depending on the net traded
* amounts. Only operator can invoke.
* @param {object} operatorAddress - address of the operator account
* @param {string} token - ERC20 token address
* @param {StepFunctionDataPoint[]} buy - array of buy step function configurations
* @param {StepFunctionDataPoint[]} sell - array of sell step function configurations
* @param {number} [gasPrice=undefined] - the gasPrice desired for the tx
*/
async setImbalanceStepFunction (
operatorAddress,
token,
buy,
sell,
gasPrice = undefined
) {
validateAddress(token)
await assertOperator(this, operatorAddress)
const xBuy = buy.map(val => val.x)
const yBuy = buy.map(val => val.y)
const xSell = sell.map(val => val.x)
const ySell = sell.map(val => val.y)
if (yBuy > 0) {
console.warn(
`yBuy ${yBuy} is positive, which is contradicted to the logic of setImbalanceStepFunction`
)
}
if (ySell > 0) {
console.warn(
`ySell ${ySell} is positive, which is contradicted to the logic of setImbalanceStepFunction`
)
}
let tx = this.contract.methods.setImbalanceStepFunction(
token,
xBuy,
yBuy,
xSell,
ySell
)
return tx.send({
from: operatorAddress,
gas: await tx.estimateGas({ from: operatorAddress }),
gasPrice: gasPrice
})
}
/**
* Set adjustments for tokens' buy and sell rates depending on the size of a
* buy / sell order. Only operator can invoke.
* @param {object} operatorAddress - address of the operator account
* @param {string} token - ERC20 token address
* @param {StepFunctionDataPoint[]} buy - array of buy step function configurations
* @param {StepFunctionDataPoint[]} sell - array of sell step function configurations
* @param {number} gasPrice (optional) - the gasPrice desired for the tx
*/
async setQtyStepFunction (operatorAddress, token, buy, sell, gasPrice) {
validateAddress(token)
await assertOperator(this, operatorAddress)
const xBuy = buy.map(val => val.x)
const yBuy = buy.map(val => val.y)
const xSell = sell.map(val => val.x)
const ySell = sell.map(val => val.y)
if (yBuy > 0) {
console.warn(
`yBuy ${yBuy} is positive, which is contradicted to the logic of setQtyStepFunction`
)
}
if (ySell > 0) {
console.warn(
`ySell ${ySell} is positive, which is contradicted to the logic of setQtyStepFunction`
)
}
let tx = this.contract.methods.setQtyStepFunction(
token,
xBuy,
yBuy,
xSell,
ySell
)
return tx.send({
from: operatorAddress,
gas: await tx.estimateGas({ from: operatorAddress }),
gasPrice: gasPrice
})
}
/**
* Return the buying ETH based rate. The rate might be vary with
* different quantity.
* @param {string} token - token address
* @param {number} qty - quantity of token
* @param {number} [currentBlockNumber=0] - current block number, default to
* use latest known block number.
* @return {number} - buy rate
*/
getBuyRates (token, qty, currentBlockNumber = 0) {
return this.contract.methods
.getRate(token, currentBlockNumber, true, qty)
.call()
}
/**
* Return the buying ETH based rate. The rate might be vary with
* different quantity.
* @param {string} token - token address
* @param {number} qty - quantity of token
* @param {number} [currentBlockNumber=0] - current block number
* known block number.
*/
getSellRates (token, qty, currentBlockNumber = 0) {
return this.contract.methods
.getRate(token, currentBlockNumber, false, qty)
.call()
}
/**
* Set the buying rate for given token.
* @param {object} operatorAddress - address of the operator account
* @param {RateSetting[]} rates - token address
* @param {number} [currentBlockNumber=0] - current block number
* @param {number} gasPrice (optional) - the gasPrice desired for the tx
*/
async setRate (operatorAddress, rates, currentBlockNumber = 0, gasPrice) {
await assertOperator(this, operatorAddress)
const indices = await rates.reduce(async (acc, val) => {
const accumulator = await acc.then()
accumulator[val.address] = await this.getTokenIndices(val.address)
return Promise.resolve(accumulator)
}, Promise.resolve({}))
const data = await rates.reduce(
async (acc, val) => {
const accumulator = await acc.then()
const currentBaseBuy = await this.contract.methods
.getBasicRate(val.address, true)
.call()
const buyCompactData = new CompactData(val.buy, currentBaseBuy)
const currentBaseSell = await this.contract.methods
.getBasicRate(val.address, false)
.call()
const sellCompactData = new CompactData(val.sell, currentBaseSell)
if (buyCompactData.isBaseChanged || sellCompactData.isBaseChanged) {
accumulator.tokens.push(val.address)
accumulator.baseBuys.push(buyCompactData.base.toString())
accumulator.baseSells.push(sellCompactData.base.toString())
}
const buyCompact = buyCompactData.compact.toString()
accumulator.compactBuys[val.address] = buyCompact
const sellCompact = sellCompactData.compact.toString()
accumulator.compactSells[val.address] = sellCompact
return Promise.resolve(accumulator)
},
Promise.resolve({
tokens: [],
baseBuys: [],
baseSells: [],
compactBuys: {},
compactSells: {}
})
)
let compactInputs = buildCompactBulk(
data.compactBuys,
data.compactSells,
indices
)
compactInputs.buyResults = compactInputs.buyResults.map(val =>
Web3.utils.padLeft(Web3.utils.bytesToHex(val), 14)
)
compactInputs.sellResults = compactInputs.sellResults.map(val =>
Web3.utils.padLeft(Web3.utils.bytesToHex(val), 14)
)
let tx
if (data.tokens.length === 0) {
tx = this.contract.methods.setCompactData(
compactInputs.buyResults,
compactInputs.sellResults,
currentBlockNumber,
compactInputs.indexResults
)
} else {
tx = this.contract.methods.setBaseRate(
data.tokens,
data.baseBuys,
data.baseSells,
compactInputs.buyResults,
compactInputs.sellResults,
currentBlockNumber,
compactInputs.indexResults
)
}
const gas = await tx.estimateGas({ from: operatorAddress })
return tx.send({
from: operatorAddress,
gas,
gasPrice: gasPrice
})
}
} |
JavaScript | class Section {
/**
* @param {string} name - Section name.
* @param {string} content - Text content.
* @param {number} type - Source formating.
*/
constructor(name, content, type) {
this.title = this.name = this.longname = name;
this.content = content;
this.type = type;
// default values
this.parent = null;
this.children = [];
}
/**
* Moves children from current parent to different one.
*
* @param {?Section} parent - New parent. If null, the section has no parent.
*/
setParent(parent) {
// removes node from old parent
if (this.parent) {
removeChild(this.parent, this);
}
this.parent = parent;
if (parent) {
addChild(parent, this);
}
}
/* eslint-disable class-methods-use-this */
/**
* Removes children from current node.
*
* @param {Section} child - Old child.
*/
removeChild(child) {
child.setParent(null);
}
/* eslint-enable class-methods-use-this */
/**
* Adds new children to current node.
*
* @param {Section} child - New child.
*/
addChild(child) {
child.setParent(this);
}
/**
* Prepares source.
*
* @return {string} HTML source.
*/
parse() {
switch (this.type) {
// nothing to do
case exports.TYPES.HTML:
return this.content;
// markdown
case exports.TYPES.MARKDOWN:
return markdown.getParser()(this.content);
// uhm... should we react somehow?
// if not then this case can be merged with TYPES.HTML
default:
return this.content;
}
}
} |
JavaScript | class RootSection extends Section {
constructor() {
super('', '', null);
this._sections = {};
}
/**
* Retrieve a section by name.
* @param {string} name - Section name.
* @return {module:jsdoc/section.Section} Section instance.
*/
getByName(name) {
return hasOwnProp.call(this._sections, name) && this._sections[name];
}
/**
* Add a child section to the root.
* @param {module:jsdoc/section.Section} child - Child section.
*/
_addSection(child) {
this._sections[child.name] = child;
}
} |
JavaScript | class AboutPage extends Component{
render(){
return(
<div style={{backgroundColor: '#282c34'}}>
<Typography variant="h3" component="h2" style={{ paddingTop:"5%", color: 'white'}} >
<hr width="70%"></hr>
<b>About Me</b>
<hr width="80%"></hr>
</Typography>
<Grid container justify = 'space-evenly' style={{paddingTop:"3%", paddingLeft:"15%",paddingRight:"15%", textAlign:"left"}}>
<Grid item md={5} style={{paddingLeft:"5%", paddingBottom:"10%"}}>
<Zoom timeout={2000}>
<Card style={{ backgroundColor: '#282c34'}}>
<CardMedia
style = {{
elevation:20,
paddingTop:"80%",
width:"330px",
}}
image={
require("../asuEngineering.jpeg")
}
/>
</Card>
<CardMedia></CardMedia>
</Zoom>
</Grid>
<Grid item md={7} style={{paddingLeft:"2%"}}>
<Typography variant="subtitle1" style={{fontSize:16 , textAlign:"left", color: '#cfd8dc',paddingBottom:"3%", paddingLeft:"5%"}}>
My name is <b style={{color:"white"}}>Matthew Pham</b>. I am a Software Engineer currently majoring in <i><b>Computer Science</b></i> at <b style={{color:"white"}}>Arizona State University</b>.
I enjoy building web apps in both backend and frontend.
My expertise covers these languages and frameworks.
</Typography>
<Grid container justify="center">
<Grid item xs style={{paddingLeft:"3%", paddingRight:"3%"}}>
<List>
<TechDescrip title="Node.JS"></TechDescrip>
<TechDescrip title="Java"></TechDescrip>
<TechDescrip title="C/C++"></TechDescrip>
</List>
</Grid>
<Grid item xs style={{paddingLeft:"3%"}}>
<List>
<TechDescrip title="React"></TechDescrip>
<TechDescrip title="Express"></TechDescrip>
<TechDescrip title="Lambda AWS"></TechDescrip>
</List>
</Grid>
<Grid item xs style={{paddingLeft:"3%"}}>
<List>
<TechDescrip title="HTML/CSS"></TechDescrip>
<TechDescrip title="JavaScript"></TechDescrip>
<TechDescrip title="Json/API"></TechDescrip>
</List>
</Grid>
</Grid>
</Grid>
</Grid>
</div>
)
}
} |
JavaScript | class Comet {
/**
* @param {string} token Comet API Token
*/
constructor(token) {
if(!token) throw new Error(`You need to enter your token, if you don't have it you can get it at https://c0met.xyz`);
let self = this;
self.url = "https://c0met.xyz";
this.options = {};
(async function() {
const res = await self._request(`temp`, {}, {
token: token
}).catch(e => false);
if(!res) {
/**
* Property to unallow send requests
* @type {Boolean}
* @private
*/
Object.defineProperty(self, 'dontHandle', { value: true });
throw new Error('The main request could not be made');
} else {
if(res.message) {
/**
* Property to unallow send requests
* @type {Boolean}
* @private
*/
Object.defineProperty(self, 'dontHandle', { value: true });
throw new Error(res.message);
}
/**
* @private
*/
Object.defineProperty(self.options, 'token', { value: res.token, writable: true });
/**
* @private
*/
Object.defineProperty(self.options, 'originalToken', { value: token });
self.startAutoCheck();
return true;
}
})();
}
/**
* A function to periodical token check for wrapper
* @private
* @returns {void}
*/
async startAutoCheck() {
let self = this;
try {
const res = await self._request(`temp`, {}, {
token: self.options.originalToken
}).catch(e => false);
if(res.message) {
/**
* @private
*/
Object.defineProperty(self, 'dontHandle', { value: true });
throw new Error(res.message);
}
if(res.token !== this.options.token) {
/**
* @private
*/
Object.defineProperty(self.options, 'token', { value: res.token, writable: true });
}
} catch(e) {
}
await wait(60 * 1000)
this.startAutoCheck()
}
/**
* A method for Wrapper to force temp token Update
* @private
* @returns {any}
*/
async forceCheck() {
let self = this;
try {
const res = await self._request('/temp', {}, {
token: self.options.originalToken
});
if(!res || typeof res != 'object' || res.message) {
/**
* @private
*/
Object.defineProperty(self, 'dontHandle', { value: true });
throw new Error(res.message);
}
if(res.token !== this.options.token) {
/**
* @private
*/
Object.defineProperty(self.options, 'token', { value: res.token, writable: true });
}
} catch(e) {
}
return;
}
/**
* Private request function for Wrapper
* @private
* @param {string} path Path to make request
* @param {object} query Query for request
* @param {object} headers Headers for request
* @returns {Promise<(object|string|Buffer)>}
*/
_request(path, query = {}, headers = {}) {
let self = this;
return new Promise(async (resolve, reject) => {
query = Object.entries(query).map((x, i) => `${i == 0 ? '?' : '&'}${x[0]}=${encodeURIComponent(x[1])}`).join('');
headers = Utils.fromDefault({
'User-Agent': `Comet-Wrapper v${pkg.version}`
}, headers)
let res = await fetch(`${self.url}${path.startsWith('/') ? '' : '/'}${path}${query}`, {
method: 'get',
headers: headers
}).catch(e => false);
if(!res) return resolve(false)
let body = res.headers.get('content-type').toLowerCase().startsWith('application/json') ? await res.json()
: res.headers.get('content-type').toLowerCase().startsWith('image') ? await res.buffer()
: res.headers.get('content-type').toLowerCase().startsWith('video') ? await res.buffer()
: await res.text();
return resolve(body)
})
}
/**
* Token function
* @description Generate a token (does not apply to the API)
* @example c.Rtñ=ky-FVhvSDbMuKÑDlcQwXkVCWbmAKKHPYwz_XOcdnGtñylqRg=ktjS
* @reject Token error
* @returns {Promise<string>}
*/
Token() {
let self = this;
return new Promise(async (resolve, reject) => {
do {
await wait(250);
} while(!self.options.token && !self.dontHandle);
if(!self.options || !self.options.token) return reject(new Error(`You need to enter your token, if you don't have it you can get it at https://c0met.xyz`));
let res = await this._request('generators/token', {}, {
token: this.options.token
});
if(!res) return reject(new Error('The request could not be made'));
if(res.message && res.message == 'You need a token to use this endpoint') {
await self.forceCheck();
resolve(await self.Token(...Object.values(arguments)));
}
if(res.message) return reject(new Error(res.message));
return resolve(res.token)
})
}
/**
* Beautiful Function
* @description Show Uncle Stan from Gravity Falls worshiping you
* @param {string} avatar The image that Uncle Stan will adore
* @reject Token error
* @returns {Promise<Buffer>}
*/
Beautiful(avatar) {
let self = this;
return new Promise(async (resolve, reject) => {
if(!avatar || typeof avatar !== 'string') return reject(new Error(`You need to put an avatar`));
do {
await wait(250);
} while(!self.options.token && !self.dontHandle);
if(!self.options || !self.options.token) return reject(new Error(`You need to enter your token, if you don't have it you can get it at https://c0met.xyz`));
let res = await this._request('imgedit/beautiful', {
avatar: avatar
}, {
token: self.options.token
});
if(!res) return reject(new Error('The request could not be made'));
if(res.message && res.message == 'You need a token to use this endpoint') {
await self.forceCheck();
resolve(await self.Beautiful(...Object.values(arguments)));
}
if(res.message) return reject(new Error(res.message));
return resolve(res)
})
}
/**
* Amiajoke Function
* @description Generate an image with a mansage saying "I'm a joke to you?"
* @param {string} avatar The image from the victim
* @reject Token error
* @returns {Promise<Buffer>}
*/
Amiajoke(avatar) {
let self = this;
return new Promise(async (resolve, reject) => {
if(!avatar || typeof avatar !== 'string') return reject(new Error(`You need to put an avatar`));
do {
await wait(250);
} while(!self.options.token && !self.dontHandle);
if(!self.options || !self.options.token) return reject(new Error(`You need to enter your token, if you don't have it you can get it at https://c0met.xyz`));
let res = await this._request('imgedit/amiajoke', {
avatar: avatar
}, {
token: self.options.token
});
if(!res) return reject(new Error('The request could not be made'));
if(res.message && res.message == 'You need a token to use this endpoint') {
await self.forceCheck();
resolve(await self.Beautiful(...Object.values(arguments)));
}
if(res.message) return reject(new Error(res.message));
return resolve(res)
})
}
/**
* Beautiful-2 Function
* @description Generates a meme-like image
* @param {string} avatar Image of the following cartoon
* @reject Token error
* @returns {Promise<Buffer>}
*/
Beautiful2(avatar) {
let self = this;
return new Promise(async (resolve, reject) => {
if(!avatar || typeof avatar !== 'string') return reject(new Error(`You need to put an avatar`));
do {
await wait(250);
} while(!self.options.token && !self.dontHandle);
if(!self.options || !self.options.token) return reject(new Error(`You need to enter your token, if you don't have it you can get it at https://c0met.xyz`));
let res = await this._request('imgedit/beautiful2', {
avatar: avatar
}, {
token: self.options.token
});
if(!res) return reject(new Error('The request could not be made'));
if(res.message && res.message == 'You need a token to use this endpoint') {
await self.forceCheck();
resolve(await self.Beautiful(...Object.values(arguments)));
}
if(res.message) return reject(new Error(res.message));
return resolve(res)
})
}
/**
* Challenger Function
* @description Generate an image from Challenger
* @param {string} avatar The image from the Challenger.
* @reject Token error
* @returns {Promise<Buffer>}
*/
Challenger(avatar) {
let self = this;
return new Promise(async (resolve, reject) => {
if(!avatar || typeof avatar !== 'string') return reject(new Error(`You need to put an avatar`));
do {
await wait(250);
} while(!self.options.token && !self.dontHandle);
if(!self.options || !self.options.token) return reject(new Error(`You need to enter your token, if you don't have it you can get it at https://c0met.xyz`));
let res = await this._request('imgedit/challenger', {
avatar: avatar
}, {
token: self.options.token
});
if(!res) return reject(new Error('The request could not be made'));
if(res.message && res.message == 'You need a token to use this endpoint') {
await self.forceCheck();
resolve(await self.Beautiful(...Object.values(arguments)));
}
if(res.message) return reject(new Error(res.message));
return resolve(res)
})
}
/**
* Blur Function
* @description Generate a blur type filter on your image.
* @param {string} avatar The image where the filter will be applied
* @param {number} count The degree of blur the image will have
* @reject Token error
* @returns {Promise<Buffer>}
*/
Blur(avatar, count) {
let self = this;
return new Promise(async (resolve, reject) => {
if(!avatar || typeof avatar !== 'string') return reject(new Error(`You need to put an avatar`));
if(!count) count = Math.floor(Math.random() * 99)+1;
if(isNaN(count)) return reject(new Error(`The value of count has to be a number`));
if(count < 1) return reject(new Error(`The value of count has to be a number greater than 0`));
if(count >= 210) return reject(new Error(`The value of count has to be a number less than 209`));
do {
await wait(250);
} while(!self.options.token && !self.dontHandle);
if(!self.options || !self.options.token) return reject(new Error(`You need to enter your token, if you don't have it you can get it at https://c0met.xyz`));
let res = await this._request('imgedit/blur', {
avatar: avatar,
count: count
}, {
token: self.options.token
});
if(!res) return reject(new Error('The request could not be made'));
if(res.message && res.message == 'You need a token to use this endpoint') {
await self.forceCheck();
resolve(await self.Blur(...Object.values(arguments)));
}
if(res.message) return reject(new Error(res.message));
return resolve(res)
})
}
/**
* Border Function
* @description Generate a image with a custom border.
* @param {string} avatar The image where the border will be applied
* @param {string} border The border background (can be an image or a list of hexadecimal numbers)
* @param {number} line The thickness of the border
* @reject Token error
* @returns {Promise<Buffer>}
*/
Border(avatar, border, line) {
let self = this;
return new Promise(async (resolve, reject) => {
if(!avatar || typeof avatar !== 'string') return reject(new Error(`You need to put an avatar`));
if(!border || typeof border !== 'string') return reject(new Error(`You need to put an border`));
if(!line) line = 5;
if(isNaN(line)) return reject(new Error(`The value of line has to be a number`));
if(line < 1) return reject(new Error(`The value of line has to be a number greater than 0`));
if(line >= 20) return reject(new Error(`The value of line has to be a number less than 20`));
do {
await wait(250);
} while(!self.options.token && !self.dontHandle);
if(!self.options || !self.options.token) return reject(new Error(`You need to enter your token, if you don't have it you can get it at https://c0met.xyz`));
let res = await this._request('imgedit/border', {
avatar: avatar,
border: border,
line: line
}, {
token: self.options.token
});
if(!res) return reject(new Error('The request could not be made'));
if(res.message && res.message == 'You need a token to use this endpoint') {
await self.forceCheck();
resolve(await self.Blur(...Object.values(arguments)));
}
if(res.message) return reject(new Error(res.message));
return resolve(res)
})
}
/**
* Concierge Function
* @description Based on two images, generate one of the concierge type
* @param {string} avatar1 The first avatar
* @param {string} avatar2 The second avatar
* @reject Token error
* @returns {Promise<Buffer>}
*/
Concierge(avatar, avatar1) {
let self = this;
return new Promise(async (resolve, reject) => {
if(!avatar || typeof avatar !== 'string') return reject(new Error(`You need to put an avatar1`));
if(!avatar1 || typeof avatar1 !== 'string') return reject(new Error(`You need to put an avatar2`));
do {
await wait(250);
} while(!self.options.token && !self.dontHandle);
if(!self.options || !self.options.token) return reject(new Error(`You need to enter your token, if you don't have it you can get it at https://c0met.xyz`));
let res = await this._request('imgedit/concierge', {
avatar1: avatar,
avatar2: avatar1
}, {
token: self.options.token
});
if(!res) return reject(new Error('The request could not be made'));
if(res.message && res.message == 'You need a token to use this endpoint') {
await self.forceCheck();
resolve(await self.Concierge(...Object.values(arguments)));
}
if(res.message) return reject(new Error(res.message));
return resolve(res)
})
}
/**
* Convolutional Function
* @description Apply a convolutional filter to the image (a 3x3 matrix of numbers)
* @param {string} avatar The image where the filter will be applied
* @param {string} filter The convolutional filter
* @reject Token error
* @returns {Promise<Buffer>}
*/
Convolutional(avatar, filter) {
let self = this;
return new Promise(async (resolve, reject) => {
if(!avatar || typeof avatar !== 'string') return reject(new Error(`You need to put an avatar`));
if(!filter || typeof filter !== 'string') return reject(new Error(`You need to put an filter`));
if(!filter.includes(',')) return reject(new Error(`The filter must have 9 numerical values separated by a comma`));
if(!filter.split(',').length > 8) return reject(new Error(`The filter must have 9 numerical values`));
do {
await wait(250);
} while(!self.options.token && !self.dontHandle);
if(!self.options || !self.options.token) return reject(new Error(`You need to enter your token, if you don't have it you can get it at https://c0met.xyz`));
let res = await this._request('imgedit/convolutional', {
avatar: avatar,
filter: filter
}, {
token: self.options.token
});
if(!res) return reject(new Error('The request could not be made'));
if(res.message && res.message == 'You need a token to use this endpoint') {
await self.forceCheck();
resolve(await self.Convolutional(...Object.values(arguments)));
}
if(res.message) return reject(new Error(res.message));
return resolve(res)
})
}
/**
* Darling Function
* @description Returns an image which he loves "Zero Two".
* @param {string} avatar Image loved by ZeroTwo.
* @reject Token error
* @returns {Promise<Buffer>}
*/
Darling(avatar) {
let self = this;
return new Promise(async (resolve, reject) => {
if(!avatar || typeof avatar !== 'string') return reject(new Error(`You need to put an avatar`));
do {
await wait(250);
} while(!self.options.token && !self.dontHandle);
if(!self.options || !self.options.token) return reject(new Error(`You need to enter your token, if you don't have it you can get it at https://c0met.xyz`));
let res = await this._request('imgedit/darling', {
avatar: avatar
}, {
token: self.options.token
});
if(!res) return reject(new Error('The request could not be made'));
if(res.message && res.message == 'You need a token to use this endpoint') {
await self.forceCheck();
resolve(await self.Darling(...Object.values(arguments)));
}
if(res.message) return reject(new Error(res.message));
return resolve(res)
})
}
/**
* Ed Function
* @description Based on two images, deliver one with ED type
* @param {string} avatar1 The first avatar
* @param {string} avatar2 The second avatar
* @reject Token error
* @returns {Promise<Buffer>}
*/
Ed(avatar, avatar1) {
let self = this;
return new Promise(async (resolve, reject) => {
if(!avatar || typeof avatar !== 'string') return reject(new Error(`You need to put an avatar1`));
if(!avatar1 || typeof avatar1 !== 'string') return reject(new Error(`You need to put an avatar2`));
do {
await wait(250);
} while(!self.options.token && !self.dontHandle);
if(!self.options || !self.options.token) return reject(new Error(`You need to enter your token, if you don't have it you can get it at https://c0met.xyz`));
let res = await this._request('imgedit/ed', {
avatar1: avatar,
avatar2: avatar1
}, {
token: self.options.token
});
if(!res) return reject(new Error('The request could not be made'));
if(res.message && res.message == 'You need a token to use this endpoint') {
await self.forceCheck();
resolve(await self.Ed(...Object.values(arguments)));
}
if(res.message) return reject(new Error(res.message));
return resolve(res)
})
}
/**
* Flip Function
* @description Returns the rotated image randomly
* @param {string} avatar The image to be modified
* @reject Token error
* @returns {Promise<Buffer>}
*/
Flip(avatar) {
let self = this;
return new Promise(async (resolve, reject) => {
if(!avatar || typeof avatar !== 'string') return reject(new Error(`You need to put an avatar`));
do {
await wait(250);
} while(!self.options.token && !self.dontHandle);
if(!self.options || !self.options.token) return reject(new Error(`You need to enter your token, if you don't have it you can get it at https://c0met.xyz`));
let res = await this._request('imgedit/flip', {
avatar: avatar
}, {
token: self.options.token
});
if(!res) return reject(new Error('The request could not be made'));
if(res.message && res.message == 'You need a token to use this endpoint') {
await self.forceCheck();
resolve(await self.Flip(...Object.values(arguments)));
}
if(res.message) return reject(new Error(res.message));
return resolve(res)
})
}
/**
* Glitch Function
* @description Generates an image with a Glitch filter.
* @param {string} avatar The image to be modified
* @reject Token error
* @returns {Promise<Buffer>}
*/
Glitch(avatar) {
let self = this;
return new Promise(async (resolve, reject) => {
if(!avatar || typeof avatar !== 'string') return reject(new Error(`You need to put an avatar`));
do {
await wait(250);
} while(!self.options.token && !self.dontHandle);
if(!self.options || !self.options.token) return reject(new Error(`You need to enter your token, if you don't have it you can get it at https://c0met.xyz`));
let res = await this._request('imgedit/glitch', {
avatar: avatar
}, {
token: self.options.token
});
if(!res) return reject(new Error('The request could not be made'));
if(res.message && res.message == 'You need a token to use this endpoint') {
await self.forceCheck();
resolve(await self.Glitch(...Object.values(arguments)));
}
if(res.message) return reject(new Error(res.message));
return resolve(res)
})
}
/**
* Grayscale Function
* @description Generates an image with a Grayscale filter.
* @param {string} avatar The image to be modified
* @reject Token error
* @returns {Promise<Buffer>}
*/
Grayscale(avatar) {
let self = this;
return new Promise(async (resolve, reject) => {
if(!avatar || typeof avatar !== 'string') return reject(new Error(`You need to put an avatar`));
do {
await wait(250);
} while(!self.options.token && !self.dontHandle);
if(!self.options || !self.options.token) return reject(new Error(`You need to enter your token, if you don't have it you can get it at https://c0met.xyz`));
let res = await this._request('imgedit/grayscale', {
avatar: avatar
}, {
token: self.options.token
});
if(!res) return reject(new Error('The request could not be made'));
if(res.message && res.message == 'You need a token to use this endpoint') {
await self.forceCheck();
resolve(await self.Grayscale(...Object.values(arguments)));
}
if(res.message) return reject(new Error(res.message));
return resolve(res)
})
}
/**
* Invert Grayscale Function
* @description Generates an image with a Invert Grayscale filter.
* @param {string} avatar The image to be modified
* @reject Token error
* @returns {Promise<Buffer>}
*/
Invert_Grayscale(avatar) {
let self = this;
return new Promise(async (resolve, reject) => {
if(!avatar || typeof avatar !== 'string') return reject(new Error(`You need to put an avatar`));
do {
await wait(250);
} while(!self.options.token && !self.dontHandle);
if(!self.options || !self.options.token) return reject(new Error(`You need to enter your token, if you don't have it you can get it at https://c0met.xyz`));
let res = await this._request('imgedit/invert_grayscale', {
avatar: avatar
}, {
token: self.options.token
});
if(!res) return reject(new Error('The request could not be made'));
if(res.message && res.message == 'You need a token to use this endpoint') {
await self.forceCheck();
resolve(await self.Invert_Grayscale(...Object.values(arguments)));
}
if(res.message) return reject(new Error(res.message));
return resolve(res)
})
}
/**
* Not Stonk Function
* @description Generates an image with a Not Stonk.
* @param {string} avatar The image to be modified
* @reject Token error
* @returns {Promise<Buffer>}
*/
Not_Stonk(avatar) {
let self = this;
return new Promise(async (resolve, reject) => {
if(!avatar || typeof avatar !== 'string') return reject(new Error(`You need to put an avatar`));
do {
await wait(250);
} while(!self.options.token && !self.dontHandle);
if(!self.options || !self.options.token) return reject(new Error(`You need to enter your token, if you don't have it you can get it at https://c0met.xyz`));
let res = await this._request('imgedit/nstonk', {
avatar: avatar
}, {
token: self.options.token
});
if(!res) return reject(new Error('The request could not be made'));
if(res.message && res.message == 'You need a token to use this endpoint') {
await self.forceCheck();
resolve(await self.Not_Stonk(...Object.values(arguments)));
}
if(res.message) return reject(new Error(res.message));
return resolve(res)
})
}
/**
* Invert Function
* @description Generates an image with a Invert filter.
* @param {string} avatar The image to be modified
* @reject Token error
* @returns {Promise<Buffer>}
*/
Invert(avatar) {
let self = this;
return new Promise(async (resolve, reject) => {
if(!avatar || typeof avatar !== 'string') return reject(new Error(`You need to put an avatar`));
do {
await wait(250);
} while(!self.options.token && !self.dontHandle);
if(!self.options || !self.options.token) return reject(new Error(`You need to enter your token, if you don't have it you can get it at https://c0met.xyz`));
let res = await this._request('imgedit/invert', {
avatar: avatar
}, {
token: self.options.token
});
if(!res) return reject(new Error('The request could not be made'));
if(res.message && res.message == 'You need a token to use this endpoint') {
await self.forceCheck();
resolve(await self.Invert(...Object.values(arguments)));
}
if(res.message) return reject(new Error(res.message));
return resolve(res)
})
}
/**
* Pencil Shading Function
* @description Generates an image with a Pencil Shading efect.
* @param {string} avatar The image to be modified
* @reject Token error
* @returns {Promise<Buffer>}
*/
Pencil_Shading(avatar) {
let self = this;
return new Promise(async (resolve, reject) => {
if(!avatar || typeof avatar !== 'string') return reject(new Error(`You need to put an avatar`));
do {
await wait(250);
} while(!self.options.token && !self.dontHandle);
if(!self.options || !self.options.token) return reject(new Error(`You need to enter your token, if you don't have it you can get it at https://c0met.xyz`));
let res = await this._request('imgedit/pencil_shading', {
avatar: avatar
}, {
token: self.options.token
});
if(!res) return reject(new Error('The request could not be made'));
if(res.message && res.message == 'You need a token to use this endpoint') {
await self.forceCheck();
resolve(await self.Pencil_Shading(...Object.values(arguments)));
}
if(res.message) return reject(new Error(res.message));
return resolve(res)
})
}
/**
* Peridot Function
* @description Generate an image of peridot looking at you.
* @param {string} avatar The image to be modified
* @reject Token error
* @returns {Promise<Buffer>}
*/
Peridot(avatar) {
let self = this;
return new Promise(async (resolve, reject) => {
if(!avatar || typeof avatar !== 'string') return reject(new Error(`You need to put an avatar`));
do {
await wait(250);
} while(!self.options.token && !self.dontHandle);
if(!self.options || !self.options.token) return reject(new Error(`You need to enter your token, if you don't have it you can get it at https://c0met.xyz`));
let res = await this._request('imgedit/peridot', {
avatar: avatar
}, {
token: self.options.token
});
if(!res) return reject(new Error('The request could not be made'));
if(res.message && res.message == 'You need a token to use this endpoint') {
await self.forceCheck();
resolve(await self.Peridot(...Object.values(arguments)));
}
if(res.message) return reject(new Error(res.message));
return resolve(res)
})
}
/**
* Pixel Function
* @description Generates an image with a Pixel effect.
* @param {string} avatar The image to be modified
* @reject Token error
* @returns {Promise<Buffer>}
*/
Pixel(avatar) {
let self = this;
return new Promise(async (resolve, reject) => {
if(!avatar || typeof avatar !== 'string') return reject(new Error(`You need to put an avatar`));
do {
await wait(250);
} while(!self.options.token && !self.dontHandle);
if(!self.options || !self.options.token) return reject(new Error(`You need to enter your token, if you don't have it you can get it at https://c0met.xyz`));
let res = await this._request('imgedit/pixel', {
avatar: avatar
}, {
token: self.options.token
});
if(!res) return reject(new Error('The request could not be made'));
if(res.message && res.message == 'You need a token to use this endpoint') {
await self.forceCheck();
resolve(await self.Pixel(...Object.values(arguments)));
}
if(res.message) return reject(new Error(res.message));
return resolve(res)
})
}
/**
* Rip Function
* @description Generates an Rip image.
* @param {string} avatar The image to be modified
* @param {string} name The name of the person has died
* @param {string} year The year he died
* @reject Token error
* @returns {Promise<Buffer>}
*/
Rip(avatar, name, year) {
let self = this;
return new Promise(async (resolve, reject) => {
if(!avatar || typeof avatar !== 'string') return reject(new Error(`You need to put an avatar`));
do {
await wait(250);
} while(!self.options.token && !self.dontHandle);
if(!self.options || !self.options.token) return reject(new Error(`You need to enter your token, if you don't have it you can get it at https://c0met.xyz`));
let q = {
avatar: avatar
}
if(name && typeof name == 'string') q.name = name;
if(year && typeof year == 'string') q.name = year;
let res = await this._request('imgedit/rip', q, {
token: self.options.token
});
if(!res) return reject(new Error('The request could not be made'));
if(res.message && res.message == 'You need a token to use this endpoint') {
await self.forceCheck();
resolve(await self.Rip(...Object.values(arguments)));
}
if(res.message) return reject(new Error(res.message));
return resolve(res)
})
}
/**
* Sepia Function
* @description Generates an image with a Sepia effect.
* @param {string} avatar The image to be modified
* @reject Token error
* @returns {Promise<Buffer>}
*/
Sepia(avatar) {
let self = this;
return new Promise(async (resolve, reject) => {
if(!avatar || typeof avatar !== 'string') return reject(new Error(`You need to put an avatar`));
do {
await wait(250);
} while(!self.options.token && !self.dontHandle);
if(!self.options || !self.options.token) return reject(new Error(`You need to enter your token, if you don't have it you can get it at https://c0met.xyz`));
let res = await this._request('imgedit/sepia', {
avatar: avatar
}, {
token: self.options.token
});
if(!res) return reject(new Error('The request could not be made'));
if(res.message && res.message == 'You need a token to use this endpoint') {
await self.forceCheck();
resolve(await self.Sepia(...Object.values(arguments)));
}
if(res.message) return reject(new Error(res.message));
return resolve(res)
})
}
/**
* Stonk Function
* @description Generates an image with a Stonk effect.
* @param {string} avatar The image to be modified
* @reject Token error
* @returns {Promise<Buffer>}
*/
Stonk(avatar) {
let self = this;
return new Promise(async (resolve, reject) => {
if(!avatar || typeof avatar !== 'string') return reject(new Error(`You need to put an avatar`));
do {
await wait(250);
} while(!self.options.token && !self.dontHandle);
if(!self.options || !self.options.token) return reject(new Error(`You need to enter your token, if you don't have it you can get it at https://c0met.xyz`));
let res = await this._request('imgedit/stonk', {
avatar: avatar
}, {
token: self.options.token
});
if(!res) return reject(new Error('The request could not be made'));
if(res.message && res.message == 'You need a token to use this endpoint') {
await self.forceCheck();
resolve(await self.Stonk(...Object.values(arguments)));
}
if(res.message) return reject(new Error(res.message));
return resolve(res)
})
}
/**
* Spin Function
* @description Generates a rotating image animation.
* @param {string} avatar Enter the image to be animated.
* @reject Token error
* @returns {Promise<Buffer>}
*/
Spin(avatar) {
let self = this;
return new Promise(async (resolve, reject) => {
if(!avatar || typeof avatar !== 'string') return reject(new Error(`You need to put an avatar`));
do {
await wait(250);
} while(!self.options.token && !self.dontHandle);
if(!self.options || !self.options.token) return reject(new Error(`You need to enter your token, if you don't have it you can get it at https://c0met.xyz`));
let res = await this._request('imgedit/spin', {
avatar: avatar
}, {
token: self.options.token
});
if(!res) return reject(new Error('The request could not be made'));
if(res.message && res.message == 'You need a token to use this endpoint') {
await self.forceCheck();
resolve(await self.Spin(...Object.values(arguments)));
}
if(res.message) return reject(new Error(res.message));
return resolve(res)
})
}
/**
* Tint Function
* @description Generates an image with a Tint effect.
* @param {string} avatar The image to be modified
* @param {string|number} color The color of tint
* @reject Token error
* @returns {Promise<Buffer>}
*/
Tint(avatar, color) {
let self = this;
return new Promise(async (resolve, reject) => {
if(!avatar || typeof avatar !== 'string') return reject(new Error(`You need to put an avatar`));
if(!color || !['string', 'number'].includes(typeof color)) return reject(new Error(`You need to put an color`));
if(typeof color == 'number') color = Number(color).toString('16');
color = color.replace('#', '');
if(color.startsWith('0x') && color.length > 7) color = color.slice(2);
if(!color.length > 2 && !color.length < 7) return reject(new Error(`You need to put an valid color`));
do {
await wait(250);
} while(!self.options.token && !self.dontHandle);
if(!self.options || !self.options.token) return reject(new Error(`You need to enter your token, if you don't have it you can get it at https://c0met.xyz`));
let res = await this._request('imgedit/tint', {
avatar: avatar,
color: '#' + color
}, {
token: self.options.token
});
if(!res) return reject(new Error('The request could not be made'));
if(res.message && res.message == 'You need a token to use this endpoint') {
await self.forceCheck();
resolve(await self.Tint(...Object.values(arguments)));
}
if(res.message) return reject(new Error(res.message));
return resolve(res)
})
}
/**
* Triggered Function
* @description Generates an image with a Triggered effect.
* @param {string} avatar The image to be modified
* @reject Token error
* @returns {Promise<Buffer>}
*/
Triggered(avatar) {
let self = this;
return new Promise(async (resolve, reject) => {
if(!avatar || typeof avatar !== 'string') return reject(new Error(`You need to put an avatar`));
do {
await wait(250);
} while(!self.options.token && !self.dontHandle);
if(!self.options || !self.options.token) return reject(new Error(`You need to enter your token, if you don't have it you can get it at https://c0met.xyz`));
let res = await this._request('imgedit/triggered', {
avatar: avatar
}, {
token: self.options.token
});
if(!res) return reject(new Error('The request could not be made'));
if(res.message && res.message == 'You need a token to use this endpoint') {
await self.forceCheck();
resolve(await self.Triggered(...Object.values(arguments)));
}
if(res.message) return reject(new Error(res.message));
return resolve(res)
})
}
/**
* Delet Function
* @description Generates an image with Windows screen "Deleting" a image.
* @param {string} avatar The image to be deleted.
* @reject Token error
* @returns {Promise<Buffer>}
*/
Delet(avatar) {
let self = this;
return new Promise(async (resolve, reject) => {
if(!avatar || typeof avatar !== 'string') return reject(new Error(`You need to put an avatar`));
do {
await wait(250);
} while(!self.options.token && !self.dontHandle);
if(!self.options || !self.options.token) return reject(new Error(`You need to enter your token, if you don't have it you can get it at https://c0met.xyz`));
let res = await this._request('imgedit/delet', {
avatar: avatar
}, {
token: self.options.token
});
if(!res) return reject(new Error('The request could not be made'));
if(res.message && res.message == 'You need a token to use this endpoint') {
await self.forceCheck();
resolve(await self.Delet(...Object.values(arguments)));
}
if(res.message) return reject(new Error(res.message));
return resolve(res)
})
}
/**
* @typedef {Object} ColorInfo
* @property {string} name The name of color
* @property {string} hex The hexadecimal code
* @property {string} rgb The RGB code
* @property {string} hsl The HSL Code
* @property {string} cymk The CYMK Code
* @property {Array<string>} similars Similars colors,
* @property {number} integer The integer of color,
* @property {string} negative The negative color,
* @property {Boolean} isLight If color is light
* @property {Boolean} isDark If color is dark
* @property {Buffer} example A example image of the color
*/
/**
* Color Function
* @description Returns information about a Hexadecimal color.
* @param {string|number} color The color of tint
* @reject Token error
* @returns {Promise<ColorInfo>}
*/
Color(color) {
let self = this;
return new Promise(async (resolve, reject) => {
if(!color || !['string', 'number'].includes(typeof color)) return reject(new Error(`You need to put an color`));
if(typeof color == 'number') color = Number(color).toString('16');
color = color.replace('#', '');
if(color.startsWith('0x') && color.length > 7) color = color.slice(2);
if(!color.length > 2 && !color.length < 7) return reject(new Error(`You need to put an valid color`));
do {
await wait(250);
} while(!self.options.token && !self.dontHandle);
if(!self.options || !self.options.token) return reject(new Error(`You need to enter your token, if you don't have it you can get it at https://c0met.xyz`));
let res = await this._request('information/color', {
color: '#' + color
}, {
token: self.options.token
});
if(!res) return reject(new Error('The request could not be made'));
if(res.message && res.message == 'You need a token to use this endpoint') {
await self.forceCheck();
resolve(await self.Color(...Object.values(arguments)));
}
if(res.message) return reject(new Error(res.message));
return resolve(res)
})
}
/**
* @typedef {Object} Lyrics
* @property {string} name Name of song
* @property {string} author The author of song
* @property {string} image The image of song
* @property {string} lyric The lyric of song
*/
/**
* Lyric Function
* @description Returns the information of a song.
* @param {string} song The song from which you want to obtain information
* @reject Token error
* @returns {Promise<Lyrics>}
*/
Lyric(song) {
let self = this;
return new Promise(async (resolve, reject) => {
if(!song || typeof song != 'string') return reject(new Error(`You need to put an song`));
do {
await wait(250);
} while(!self.options.token && !self.dontHandle);
if(!self.options || !self.options.token) return reject(new Error(`You need to enter your token, if you don't have it you can get it at https://c0met.xyz`));
let res = await this._request('information/lyrics', {
lyric: song
}, {
token: self.options.token
});
if(!res) return reject(new Error('The request could not be made'));
if(res.message && res.message == 'You need a token to use this endpoint') {
await self.forceCheck();
resolve(await self.Color(...Object.values(arguments)));
}
if(res.message) return reject(new Error(res.message));
return resolve(res)
})
}
/**
* @typedef {Object} DebugInfo
* @property {Boolean} ping
* @property {Boolean} query
* @property {Boolean} querymismatch
* @property {Boolean} ipinsrv
* @property {Boolean} cnameinsrv
* @property {Boolean} animatedmotd
* @property {number} cachetime
*/
/**
* @typedef {Object} Motd
* @property {Array<string>} raw
* @property {Array<string>} clean
* @property {Array<string>} html
*/
/**
* @typedef {Object} PlayersInfo
* @property {number} online
* @property {number} max
*/
/**
* @typedef {Object} McInfo
* @property {string} ip
* @property {number} port
* @property {DebugInfo} debug
* @property {Motd} motd
* @property {PlayersInfo} players
* @property {string|number} version
* @property {Boolean} online
* @property {number} protocol
* @property {string} hostname
* @property {string} icon
*/
/**
* McServer Function
* @description Returns the information of a minecraft server.
* @param {string} ip The minecraft server ip from which you want to obtain information
* @param {number} port
* @reject Token error
* @returns {Promise<McInfo>}
*/
McServer(ip, port) {
let self = this;
return new Promise(async (resolve, reject) => {
if(!ip || typeof ip != 'string') return reject(new Error(`You need to put an ip`));
do {
await wait(250);
} while(!self.options.token && !self.dontHandle);
if(!self.options || !self.options.token) return reject(new Error(`You need to enter your token, if you don't have it you can get it at https://c0met.xyz`));
let q = {
ip: ip
}
if(port && typeof port == 'number') q.port = port;
let res = await this._request('information/mcserver', q, {
token: self.options.token
});
if(!res) return reject(new Error('The request could not be made'));
if(res.message && res.message == 'You need a token to use this endpoint') {
await self.forceCheck();
resolve(await self.Color(...Object.values(arguments)));
}
if(res.message) return reject(new Error(res.message));
return resolve(res)
})
}
/**
* @typedef {Object} PreColorInfo
* @property {string} hex
*/
/**
* Pre Color Function
* @description Obtain the predominant color of an image
* @param {string} avatar The image to obtain color
* @reject Token error
* @returns {Promise<PreColorInfo>}
*/
PreColor(avatar) {
let self = this;
return new Promise(async (resolve, reject) => {
if(!avatar || typeof avatar !== 'string') return reject(new Error(`You need to put an avatar`));
do {
await wait(250);
} while(!self.options.token && !self.dontHandle);
if(!self.options || !self.options.token) return reject(new Error(`You need to enter your token, if you don't have it you can get it at https://c0met.xyz`));
let res = await this._request('information/precolor', {
image: avatar
}, {
token: self.options.token
});
if(!res) return reject(new Error('The request could not be made'));
if(res.message && res.message == 'You need a token to use this endpoint') {
await self.forceCheck();
resolve(await self.PreColor(...Object.values(arguments)));
}
if(res.message) return reject(new Error(res.message));
return resolve(res)
})
}
/**
* Screenshot Function
* @description Get the image of a page
* @param {string} url The url of a web
* @reject Token error
* @returns {Promise<Buffer>}
*/
Screenshot(url) {
let self = this;
return new Promise(async (resolve, reject) => {
if(!url || typeof url != 'string') return reject(new Error(`You need to put an url`));
do {
await wait(250);
} while(!self.options.token && !self.dontHandle);
if(!self.options || !self.options.token) return reject(new Error(`You need to enter your token, if you don't have it you can get it at https://c0met.xyz`));
let res = await this._request('information/screenshot', {
url: url
}, {
token: self.options.token
});
if(!res) return reject(new Error('The request could not be made'));
if(res.message && res.message == 'You need a token to use this endpoint') {
await self.forceCheck();
resolve(await self.Screenshot(...Object.values(arguments)));
}
if(res.message) return reject(new Error(res.message));
return resolve(res)
})
}
/**
* @typedef {Object} Duration
* @property {number} days
* @property {number} hours
* @property {number} minutes
* @property {number} seconds
* @property {number} milliseconds
* @property {number} microseconds
* @property {number} nanoseconds
*/
/**
* @typedef {Object} VideoInfo
* @property {string} title
* @property {string} description
* @property {string|number} views
* @property {Duration} duration
* @property {string} author
*/
/**
* YT Function
* @description Get information about a video
* @param {string} id The id of a youtube video
* @reject Token error
* @returns {Promise<VideoInfo>}
*/
YT(id) {
let self = this;
return new Promise(async (resolve, reject) => {
if(!id || typeof id != 'string') return reject(new Error(`You need to put an video id`));
do {
await wait(250);
} while(!self.options.token && !self.dontHandle);
if(!self.options || !self.options.token) return reject(new Error(`You need to enter your token, if you don't have it you can get it at https://c0met.xyz`));
let res = await this._request('information/yt', {
id: id
}, {
token: self.options.token
});
if(!res) return reject(new Error('The request could not be made'));
if(res.message && res.message == 'You need a token to use this endpoint') {
await self.forceCheck();
resolve(await self.YT(...Object.values(arguments)));
}
if(res.message) return reject(new Error(res.message));
return resolve(res)
})
}
/**
* @typedef {Object} AIResponse
* @property {string} text
*/
/**
* AI Function
* @description Talk to an artificial intelligence.
* @param {string} message The message you want to send to artificial intelligence
* @reject Token error
* @returns {Promise<AIResponse>}
*/
AI(message) {
let self = this;
return new Promise(async (resolve, reject) => {
if(!message || typeof message != 'string') return reject(new Error(`You need to put an message`));
do {
await wait(250);
} while(!self.options.token && !self.dontHandle);
if(!self.options || !self.options.token) return reject(new Error(`You need to enter your token, if you don't have it you can get it at https://c0met.xyz`));
let res = await this._request('misc/ai', {
message: message
}, {
token: self.options.token
});
if(!res) return reject(new Error('The request could not be made'));
if(res.message && res.message == 'You need a token to use this endpoint') {
await self.forceCheck();
resolve(await self.AI(...Object.values(arguments)));
}
if(res.message) return reject(new Error(res.message));
return resolve(res)
})
}
/**
* @typedef {Object} B64Response
* @property {string} response
*/
/**
* Base64 Function
* @description Convert or decode to base64.
* @param {string} message The message you want to encode or decode in base64
* @param {Boolean} decode Determines whether to encode or decode the
* @reject Token error
* @returns {Promise<B64Response>}
*/
Base64(message, decode = false) {
let self = this;
return new Promise(async (resolve, reject) => {
if(!message || typeof message != 'string') return reject(new Error(`You need to put an message`));
if(typeof decode !== 'boolean') return reject(new Error(`You need to put a boolean`));
do {
await wait(250);
} while(!self.options.token && !self.dontHandle);
if(!self.options || !self.options.token) return reject(new Error(`You need to enter your token, if you don't have it you can get it at https://c0met.xyz`));
let res = await this._request('misc/base64', {
text: message,
method: decode ? 'decode' : 'convert'
}, {
token: self.options.token
});
if(!res) return reject(new Error('The request could not be made'));
if(res.message && res.message == 'You need a token to use this endpoint') {
await self.forceCheck();
resolve(await self.Base64(...Object.values(arguments)));
}
if(res.message) return reject(new Error(res.message));
return resolve(res)
})
}
/**
* @typedef {Object} BinaryResponse
* @property {string} response
*/
/**
* Binary Function
* @description Convert or decode to binary.
* @param {string} message The message you want to encode or decode in Binary
* @param {Boolean} decode Determines whether to encode or decode the
* @reject Token error
* @returns {Promise<BinaryResponse>}
*/
Binary(message, decode = false) {
let self = this;
return new Promise(async (resolve, reject) => {
if(!message || typeof message != 'string') return reject(new Error(`You need to put an message`));
if(typeof decode !== 'boolean') return reject(new Error(`You need to put a boolean`));
do {
await wait(250);
} while(!self.options.token && !self.dontHandle);
if(!self.options || !self.options.token) return reject(new Error(`You need to enter your token, if you don't have it you can get it at https://c0met.xyz`));
let res = await this._request('misc/binary', {
text: message,
method: decode ? 'decode' : 'convert'
}, {
token: self.options.token
});
if(!res) return reject(new Error('The request could not be made'));
if(res.message && res.message == 'You need a token to use this endpoint') {
await self.forceCheck();
resolve(await self.Binary(...Object.values(arguments)));
}
if(res.message) return reject(new Error(res.message));
return resolve(res)
})
}
/**
* @typedef {Object} SWResponse
* @property {string} orginal
* @property {Array<string>} found
* @property {number} count
* @property {number} percent
*/
/**
* Swear word Function
* @description Detect swear word in text
* @param {string} message The text you want to check
* @reject Token error
* @returns {Promise<SWResponse>}
*/
SW(message) {
let self = this;
return new Promise(async (resolve, reject) => {
if(!message || typeof message != 'string') return reject(new Error(`You need to put an message`));
do {
await wait(250);
} while(!self.options.token && !self.dontHandle);
if(!self.options || !self.options.token) return reject(new Error(`You need to enter your token, if you don't have it you can get it at https://c0met.xyz`));
let res = await this._request('moderation/sw', {
text: message
}, {
token: self.options.token
});
if(!res) return reject(new Error('The request could not be made'));
if(res.message && res.message == 'You need a token to use this endpoint') {
await self.forceCheck();
resolve(await self.Zalgo(...Object.values(arguments)));
}
if(res.message) return reject(new Error(res.message));
return resolve(res)
})
}
/**
* @typedef {Object} ZalgoResponse
* @property {string} orginal
* @property {string} clearned
* @property {string} converted
*/
/**
* Zalgo Function
* @description Converts normal text to zalgo.
* @param {string} message The message you want to conver into zalgo
* @reject Token error
* @returns {Promise<ZalgoResponse>}
*/
Zalgo(message) {
let self = this;
return new Promise(async (resolve, reject) => {
if(!message || typeof message != 'string') return reject(new Error(`You need to put an message`));
do {
await wait(250);
} while(!self.options.token && !self.dontHandle);
if(!self.options || !self.options.token) return reject(new Error(`You need to enter your token, if you don't have it you can get it at https://c0met.xyz`));
let res = await this._request('moderation/zalgo', {
text: message
}, {
token: self.options.token
});
if(!res) return reject(new Error('The request could not be made'));
if(res.message && res.message == 'You need a token to use this endpoint') {
await self.forceCheck();
resolve(await self.Zalgo(...Object.values(arguments)));
}
if(res.message) return reject(new Error(res.message));
return resolve(res)
})
}
} |
JavaScript | class SceneManager {
constructor() {
/**
* Store all registered scenes.
* @access private
*/
this.availableScenes = []
/**
* Store all loaded scenes.
* @access private
*/
this.activeScenes = []
}
/**
* Register a scene.
* @param {string} name name of scene
* @param {Scene} Class subclass of {@link Scene}
*/
register(name, Class) {
this.availableScenes.push({
name,
Class,
})
}
/**
* Load scene which is already registered. This method will remove all scenes
* which aren't sticky.
*
* @param {string} name name of scene
* @param {Object} [options]
* @param {boolean} [options.sticky=false] scene will not be removed unless
* you unload it explicitly
* @param {boolean} [options.transition=true] enable transition when switching
* scene
* @param {number} [options.transitionTime=1] transition's duration, unit in
* seconds
* @return {boolean} load is done or not
*/
load(name, { sticky = false, transition = true, transitionTime = 1 } = {}) {
this.cleanup()
const scene = this.availableScenes.find(s => s.name === name)
if (!scene) {
if (name) {
// eslint-disable-next-line
console.error(
`[${classname(this)}] failed to load unregistered scene - ${name}`
)
}
return false
}
const { Class, name: $name } = scene
const activeScene = new Class($name)
activeScene.sticky = sticky
this.activeScenes.push(activeScene)
if (transition) {
// a simple transition
activeScene.alpha = 0
activeScene.add(new Tween({ alpha: 1 }, transitionTime))
}
Black.stage.addChild(activeScene)
return true
}
/**
* Load scene according `scene` field in querystring
*/
qsload() {
const qo = queryObject()
const { scene: name } = qo
return this.load(name)
}
/**
* Cleanup useless actived scenes
* @access private
*/
cleanup() {
this.activeScenes = this.activeScenes.filter(scene => {
if (scene.sticky) {
return true
} else {
Black.stage.removeChild(scene)
return false
}
})
}
/**
* Unload a scene by name explicitly.
* @param {string} name name of scene
*/
unload(name) {
const index = this.activeScenes.findIndex(s => s.name === name)
if (index >= 0) {
const scene = this.activeScenes[index]
Black.stage.removeChild(scene)
this.activeScenes.splice(index, 1)
}
}
/**
* Find a loaded scene by name.
* @param {string} name name of a loaded scene
*/
find(name) {
const scene = this.activeScenes.find(s => s.name === name)
return scene
}
} |
JavaScript | class Shape {
/**
* Create a new Shape.
*
* @param position The x and y position of the shape
* @param settings Various settings for drawing the shape {color, filled, width, font}
*/
constructor(position, settings) {
this.position = position;
this.settings = settings;
}
/**
* Draw the shape.
*
* @param ctx A 2d context for the canvas to which the Shape should be drawn to
*/
render(ctx) {
ctx.fillStyle = this.settings.color;
ctx.strokeStyle = this.settings.color;
ctx.lineWidth = this.settings.width;
ctx.font = this.settings.font;
}
/**
* Move the shape's position by a provided new one.
*
* @param position A 2d position
*/
move(position) {
this.position = position;
}
/**
* Resize the object, from its position to the new one
*
* @param x Horizontal coordinate
* @param y Vertical coordinate
*/
resize(x, y) {
}
} |
JavaScript | class Rectangle extends Shape {
/**
* Create a new rectangle.
*
* @param position The x and y position of the shape
* @param settings Various settings for drawing the shape {color, filled, width, font}
* @param width Horizontal length of rectangle
* @param height Vertical length of rectangle
*/
constructor(position, settings, width, height) {
super(position, settings);
this.width = width;
this.height = height;
}
/** @inheritDoc */
render(ctx) {
super.render(ctx);
if (this.settings.filled) {
ctx.fillRect(this.position.x, this.position.y, this.width, this.height);
} else {
ctx.strokeRect(this.position.x, this.position.y, this.width, this.height);
}
}
/** @inheritDoc */
resize(x, y) {
this.width = x - this.position.x;
this.height = y - this.position.y;
}
} |
JavaScript | class Oval extends Shape {
/**
* Create a new Oval.
*
* @param position The x and y position of the shape
* @param settings Various settings for drawing the shape {color, filled, width, font}
* @param xRadius The horizontal half width of the oval
* @param yRadius The vertical half width of the oval
*/
constructor(position, settings, xRadius, yRadius) {
super(position, settings);
this.xRadius = xRadius;
this.yRadius = yRadius;
// The width and height of the oval is determined by
// the distance from position to (x,y). The center
// of the oval is their mid point.
this.x = position.x;
this.y = position.y;
}
/** @inheritDoc */
render(ctx) {
super.render(ctx);
ctx.beginPath();
let c_x = (this.position.x + this.x) / 2;
let c_y = (this.position.y + this.y) / 2;
ctx.ellipse(c_x, c_y, this.xRadius, this.yRadius, 0, 0, 2 * Math.PI);
if (this.settings.filled) {
ctx.fill();
} else {
ctx.stroke();
ctx.closePath();
}
}
/** @inheritDoc */
resize(x, y) {
this.x = x;
this.y = y;
this.xRadius = Math.abs(x - this.position.x) / 2;
this.yRadius = Math.abs(y - this.position.y) / 2;
}
} |
JavaScript | class Circle extends Oval {
/**
* Create a new Circle.
*
* @param position The x and y position of the shape
* @param settings Various settings for drawing the shape {color, filled, width, font}
* @param radius The half width of the circle
*/
constructor(position, settings, radius) {
super(position, settings, radius, radius);
}
/** @inheritDoc */
resize(x, y) {
this.x = x;
this.y = y;
let radius = Math.max(Math.abs(x - this.position.x), Math.abs(y - this.position.y)) / 2;
this.xRadius = radius;
this.yRadius = radius;
}
} |
JavaScript | class Line extends Shape {
/**
* Create a new Line.
*
* @param startPosition The x and y position of the shape
* @param settings Various settings for drawing the shape {color, filled, width, font}
* @param endPosition The end point of the line segment
*/
constructor(startPosition, settings, endPosition) {
super(startPosition, settings);
this.endPosition = {x: endPosition.x, y: endPosition.y};
}
/** @inheritDoc */
render(ctx) {
super.render(ctx);
ctx.beginPath();
ctx.moveTo(this.position.x, this.position.y);
ctx.lineTo(this.endPosition.x, this.endPosition.y);
ctx.stroke();
ctx.closePath();
}
/** @inheritDoc */
resize(x, y) {
this.endPosition.x = x;
this.endPosition.y = y;
}
} |
JavaScript | class LineList extends Shape {
/**
* Create a new LineList.
*
* @param position The x and y position of the shape
* @param settings Various settings for drawing the shape {color, filled, width, font}
*/
constructor(position, settings) {
super(position, settings);
// All coordinates are kept in two separated arrays
this.xList = [];
this.yList = [];
}
/** @inheritDoc */
render(ctx) {
super.render(ctx);
ctx.beginPath();
ctx.moveTo(this.position.x, this.position.y);
// Segments are smoothed using quadratic curves
for (let i = 0; ; i++) {
if (i > this.xList.length - 1) {
ctx.quadraticCurveTo(this.xList[i], this.yList[i], this.xList[i+1], this.yList[i+1]);
break;
}
let center = {x: (this.xList[i] + this.xList[i + 1]) / 2, y: (this.yList[i] + this.yList[i + 1]) / 2};
ctx.quadraticCurveTo(this.xList[i], this.yList[i], center.x, center.y);
}
ctx.stroke();
ctx.closePath();
}
/** @inheritDoc */
resize(x, y) {
this.xList.push(x);
this.yList.push(y);
}
} |
JavaScript | class DrawnText extends Shape {
/**
* Create a new DrawnText.
*
* @param position The x and y position of the shape
* @param settings Various settings for drawing the shape {color, filled, width, font}
*/
constructor(position, settings) {
super(position, settings);
// Letters are stored as internal char array.
this.chars = [];
}
/** @inheritDoc */
render(ctx) {
super.render(ctx);
if (this.settings.filled) {
ctx.fillText(this.chars.join(''), this.position.x, this.position.y);
} else {
ctx.strokeText(this.chars.join(''), this.position.x, this.position.y);
}
}
/**
* @inheritDoc
*
* @param key The button which was pressed to add to the text
*/
resize(key) {
// Delete last character if backspace
if (key === 'Backspace') {
if (this.chars.length > 0) {
this.chars.pop();
}
return;
}
// Discard all non-single-character-keys
if (key.length === 1) {
this.chars.push(key);
}
}
} |
JavaScript | class Err {
/*::
value: mixed;
validation: ValidationErr;
*/
constructor(value /*: mixed */, validation /*: ValidationErr */) {
this.value = value;
this.validation = validation;
}
} |
JavaScript | class StoreComponent extends React.PureComponent {
constructor() {
super();
this.handleStoreUpdate = this.handleStoreUpdate.bind(this);
}
componentWillMount() {
this.reduxWatcher = store.subscribe(this.handleStoreUpdate);
const storeState = store.getState();
const state = {};
this.props.watchInStore.forEach(key => {
state[key] = storeState[key];
})
this.setState(state);
}
componentWillUnmount() {
this.reduxWatcher();
}
handleStoreUpdate() {
const storeState = store.getState();
const update = {};
this.props.watchInStore.forEach(key => {
if (storeState[key] !== this.state[key]) {
update[key] = storeState[key];
}
});
if (Object.keys(update).length) {
this.setState({
...this.state,
...update
});
}
}
render() {
const props = { ...this.props };
delete props.children;
return React.cloneElement(this.props.children, {...props, ...this.state});
}
} |
JavaScript | class GiphySerice {
constructor( api_key ) {
this.API_KEY = api_key
this.URL = `https://api.giphy.com/v1/gifs/CRITERIA?api_key=${ this.API_KEY }`
}
/**
* Get the promise of fetching from giphy
* @param {string} from criteria: trending, search
* @param {object} params query params
* @return {promise}
*/
getGifs( from, params ) {
const queryString = params ? this._getQueryString( params ) : ''
const url = this.URL.replace( /CRITERIA/gi, from ) + queryString
return fetch( url ).then( res => res.json() )
}
/**
* Simple wrapper for shorthands lazyness
* @param {string} text
* @return {promise}
*/
searchGifs( text ) {
return this.getGifs( 'search', { q: text });
}
/**
* Simple wrapper for trending gifs
* @param {int} limit
* @return {promise}
*/
getTrendindGifs( limit = 7 ) {
return this.getGifs( 'trending', { limit: limit });
}
/**
* Helper function for query strings
* @param {obj} object
* @return {string}
*/
_getQueryString( object ) {
return '&' + Object.keys( object ).map( key => key + '=' + object[ key ] ).join('&');
}
} |
JavaScript | class ComparePage extends React.Component {
/*
loading: whether the page is still asking for data from the server or not
redirect_home: whether the page should prepare to redirect to the home page
redirect_main: whether the page should prepare to redirect to the main page
actual_song: the note data on the song generated by the site
corrected_song: the note data on the user input corrected
*/
state = {
loading: true,
redirect_home: false,
redirect_main: false, // TODO: can be refactored out
actual_song: [],
corrected_song: []
};
componentDidMount() {
//Sends in the data to check if the user input is correct
if (!this.props.hasPost()) {
this.setState({
redirect_home: true
});
} else {
axios
.post("/api/compare", this.props.popPost())
.then(response => JSON.parse(response.data))
.then(json => {
this.setState({
actual_song: json.actual,
corrected_song: json.corrected,
loading: false
});
console.log(json);
})
.catch(function(error) {
console.log(error);
});
}
}
// -- REDIRECT HANDLERS --
// Redirects to main
handlePlayAgain = () => {
Tone.Transport.stop();
this.setState({
redirect_main: true
});
};
// Redirects home
handleBackToStart = () => {
Tone.Transport.stop();
this.setState({
redirect_home: true
});
};
// -- VIEW HELPERS --
// Returns the amount of notes correct that the user inputted
getAmtCorrect = () => {
return this.state.corrected_song.filter(note => note.correct).length;
};
// Returns the total number of notes
getTotal = () => {
return this.state.actual_song.length;
};
// Calculates the percentage of notes correct in the user's transcription
getPct = () => {
return Math.floor((this.getAmtCorrect() / this.getTotal()) * 100);
};
render() {
if (this.state.redirect_home) {
return <Redirect to="/" />;
}
if (this.state.redirect_main) {
return <Redirect to="/main" />;
}
if (this.state.loading) {
return null;
}
return (
<div className="h-100 row align-items-center">
<div className="col">
<div className="d-flex flex-row align-items-center justify-content-between my-2">
<h3 className="m-0 font-weight-bold">Actual Transcription</h3>
<EmitPlayButton music={this.state.actual_song} />
</div>
<SheetMusic
keyId={1}
width={window.innerWidth - 10 * 2}
height={window.innerHeight / 3}
notes={this.state.actual_song}
editable={false}
/>
<div className="d-flex flex-row align-items-center justify-content-between my-2">
<h3 className="m-0 font-weight-bold">
Your Transcription ({this.getPct()}% correct)
</h3>
<EmitPlayButton music={this.state.corrected_song} />
</div>
<SheetMusic
keyId={2}
width={window.innerWidth - 10 * 2}
height={window.innerHeight / 3}
notes={this.state.corrected_song}
editable={false}
comparison={true}
/>
<div className="d-flex flex-row align-items-center justify-content-center my-2">
<button className="medium" onClick={this.handleBackToStart}>
Quit
</button>
<button className="medium red" onClick={this.handlePlayAgain}>
Try again
</button>
</div>
</div>
</div>
);
}
} |
JavaScript | class Plant {
/**
* Creates a Plant.
* @param {Env} env Parent ecosystem.
* @param {number} [x] X-value of position within the ecosystem.
* @param {number} [y] Y-value of position within the ecosystem.
* @param {number} [energy] Energy level.
* @param {number} [life] Amount of time (in frames) before certain death.
*/
constructor(env, x = random(width), y = random(height), energy = random(5, 10), life = random(5, 10) * 60){
this.env = env
this.pos = createVector(x, y)
this.energy = energy
this.life = life
this.constrain()
}
/** Limits position to the bounds of the ecosystem. */
constrain(){
this.pos.x = constrain(this.pos.x, 10, width - 10)
this.pos.y = constrain(this.pos.y, 10, height - 10)
}
/** Moves the organism one moment forward. */
act(){
// Generate energy
if(this.energy < 10) this.energy += .5
// Reproduce
// TODO: evolution? (e.g. mutation + genetic mixing)
while(this.env.plants.length < this.env.max[0] && this.energy >= 5){
this.env.plants.unshift(new Plant(
this.env,
this.pos.x + Env.randsign() * (10 + random(-100, 100)),
this.pos.y + Env.randsign() * (10 + random(-100, 100)),
1))
this.energy -= 1
}
this.life--
}
/** Draws the organism. */
draw(){
noStroke()
fill(COLORS.plant)
circle(this.pos.x, this.pos.y, map(this.energy, 0, 10, 2, 20))
}
} |
JavaScript | class Replace {
/**
* before and after must be valid Value types (that implement apply()).
*
* @param {Value} before - the value as it was before.
* @param {Value} after - the value as it is after.
*/
constructor(before, after) {
this.before = before;
this.after = after;
}
/** @returns {Replace} - the inverse of the replace */
revert() {
return new Replace(this.after, this.before);
}
_isDelete() {
return this.after.constructor.typeName() == "changes.empty";
}
/**
* Merge another change and return modified version of
* the other and current change.
*
* current + returned[0] and other + returned[1] are guaranteed
* to result in the same state.
*
* @returns {Change[]}
*/
merge(other) {
if (other == null) {
return [null, this];
}
if (other instanceof Replace) {
return this._mergeReplace(other);
}
const [left, right] = other.reverseMerge(this);
return [right, left];
}
_mergeReplace(other) {
if (this._isDelete() && other._isDelete()) {
return [null, null];
}
return [new Replace(this.after, other.after), null];
}
toJSON() {
return Encoder.encodeArrayValue([this.before, this.after]);
}
static typeName() {
return "changes.Replace";
}
static fromJSON(decoder, json) {
const before = decoder.decodeValue(json[0]);
const after = decoder.decodeValue(json[1]);
return new Replace(before, after);
}
} |
JavaScript | class Stream {
constructor() {
this.next = null;
}
/* push commits any changes upstream */
push() {
return null;
}
/* pull fetches any upstream changes which will be avilable via next */
pull() {
return null;
}
/* undo reverts the last change on the underlying stream which could
* be a parent stream. The last change may not really affect the
* current stream directly.
*
* Normal streams do not support undo but a stream created via
*`undoable` (and all its descendant streams/sub-streams) support
* undo.
*/
undo() {
return null;
}
/* redo reapplies the last change that got reverted by undo */
redo() {
return null;
}
/* append adds a local change */
append(c) {
return {change: c, version: this._appendChange(c, false)};
}
/* reverseAppend adds an *upstream* change; meant to be used by nw
* synchronizers */
reverseAppend(c) {
return {change: c, version: this._appendChange(c, true)};
}
_appendChange(c, reverse) {
const result = new Stream();
let s = this;
let nexts = result;
while (s.next !== null) {
let { change, version } = s.next;
s = version;
[c, change] = this._merge(change, c, reverse);
nexts.next = { change, version: new Stream() };
nexts = nexts.next.version;
}
s.next = { change: c, version: nexts };
return result;
}
_merge(left, right, reverse) {
if (left === null || right === null) {
return [right, left];
}
if (!reverse) {
return left.merge(right);
}
[right, left] = right.merge(left);
return [left, right];
}
} |
JavaScript | class DerivedStream {
constructor(parent) {
this.parent = parent;
this._next = null;
}
append() {
return null;
}
reverseAppend() {
return null;
}
push() {
return this.parent && this.parent.push();
}
pull() {
return this.parent && this.parent.pull();
}
undo() {
return this.parent && this.parent.undo();
}
redo() {
return this.parent && this.parent.redo();
}
get next() {
if (this._next) {
return this._next;
}
const next = this._getNext();
if (next) {
this._next = next;
}
return next;
}
} |
JavaScript | class Value {
constructor() {
this.stream = null;
this._next = null;
}
/** setStream mutates the current value and updates it stream **/
setStream(s) {
this.stream = s;
return this;
}
/**
* replace substitutes this with another value
* @returns {Value} r - r has same stream as this
**/
replace(replacement) {
return this.appendChange(new Replace(this.clone(), replacement.clone())).version;
}
/**
* appendChange applies a change to the value and the underlying stream
* It returns a {change, version} tuple much like next does.
*/
appendChange(c) {
if (!this.stream) {
return this.apply(c).clone();
}
const n = this.stream.append(c);
if (!n) {
return this;
}
return this._nextf(n.change, n.version);
}
/** @type {Object} null or {change, version} */
get next() {
if (this._next !== null || !this.stream) {
return this._next;
}
let n = this.stream.next;
for (; n && !n.change; n = n.version.next) {
// the following *mutation* is not strictly needed but improves
// performance when an value is referred to by multiple derived
// computations. it also helps better garbage collection of streams
this.stream = n.version;
}
if (!n) return null;
this._next = this._nextf(n.change, n.version);
return this._next;
}
/** latest returns the latest version */
latest() {
let result = this;
for (let n = this.next; n; n = result.next) {
result = n.version;
}
return result;
}
_nextf(change, version) {
return {
change,
version: this.apply(change)
.clone()
.setStream(version)
};
}
/** default apply only supports Replace */
apply(c) {
if (!c) {
return this.clone();
}
if (c instanceof Replace) {
return c.after;
}
return c.applyTo(this);
}
/** branch returns a value that is on its own branch with push/pull support **/
branch() {
return this.clone().setStream(branch(this.stream));
}
/** push pushes the changes up to the parent */
push() {
return this.stream && this.stream.push();
}
/** pull pulls changes from the parent */
pull() {
return this.stream && this.stream.pull();
}
/** undoes the last change on this branch */
undo() {
return this.stream && this.stream.undo();
}
/** redoes the last undo on this branch */
redo() {
return this.stream && this.stream.redo();
}
} |
JavaScript | class Bool extends Value {
constructor(b) {
super();
this.b = Boolean(b);
}
valueOf() {
return this.b;
}
/** clone makes a copy but with stream set to null */
clone() {
return new Bool(this.b);
}
toJSON() {
return this.b;
}
static typeName() {
return "dotdb.Bool";
}
static fromJSON(decoder, json) {
return new Bool(json);
}
} |
JavaScript | class Changes {
/** @param {...Change|Change[]} changes - sequentially combine changes */
constructor(...changes) {
this._all = [];
for (let cx of changes) {
if (cx instanceof Changes) {
cx = cx._all;
}
if (!Array.isArray(cx)) {
cx = [cx];
}
for (let c of cx) {
this._all.push(c);
}
}
}
/** @returns {Changes} - the inverse of the collection */
revert() {
let result = [];
for (let kk = this._all.length - 1; kk >= 0; kk--) {
const c = this._all[kk] && this._all[kk].revert();
if (c) {
result.push(c);
}
}
return Changes.create(result);
}
/**
* Merge another change and return modified version of
* the other and current change.
*
* current + returned[0] and other + returned[1] are guaranteed
* to result in the same state.
*
* @returns {Change[]}
*/
merge(other) {
if (other == null) {
return [null, this];
}
let result = [];
for (let c of this._all) {
if (c !== null) {
[other, c] = c.merge(other);
}
if (c !== null) {
result.push(c);
}
}
return [other, Changes.create(result)];
}
reverseMerge(other) {
if (other == null) {
return [null, this];
}
let result = [];
for (let c of this._all) {
if (other != null) {
[c, other] = other.merge(c);
}
if (c !== null) {
result.push(c);
}
}
return [other, Changes.create(result)];
}
applyTo(value) {
for (let c of this._all) {
value = value.apply(c);
}
return value;
}
*[Symbol.iterator]() {
for (let c of this._all) {
yield c;
}
}
toJSON() {
return Encoder.encodeArrayValue(this._all);
}
static typeName() {
return "changes.ChangeSet";
}
static fromJSON(decoder, json) {
if (!json || !json.length) {
return null;
}
return new Changes(json.map(elt => decoder.decodeChange(elt)));
}
static create(elts) {
if (elts && elts.length === 1) {
return elts[0];
}
return (elts && elts.length && new Changes(elts)) || null;
}
} |
JavaScript | class Operation {
/**
* @param {string} [id] - the id is typically auto-generated.
* @param {string} [parentId] - the id of the previous unacknowledged local op.
* @param {int} [version] - the zero-based index is updated by the server.
* @param {int} basis -- the version of the last applied acknowledged op.
* @param {Change} changes -- the actual change being sent to the server.
*/
constructor(id, parentId, version, basis, changes) {
this.id = id || Operation.newId();
this.parentId = parentId;
this.version = version;
this.basis = basis;
this.changes = changes;
}
toJSON() {
const unencoded = [this.id, this.parentId, this.changes];
const [id, parentId, c] = Encoder.encodeArrayValue(unencoded);
return [id, parentId, this.version, this.basis, c];
}
merge(otherOp) {
if (!this.changes) {
return [otherOp, this];
}
const [l, r] = this.changes.merge(otherOp.changes);
return [otherOp.withChanges(l), this.withChanges(r)];
}
withChanges(c) {
return new Operation(this.id, this.parentId, this.version, this.basis, c);
}
static typeName() {
return "ops.Operation";
}
static fromJSON(decoder, json) {
const [id, parentId, version, basis, changes] = json;
return new Operation(
decoder.decode(id),
decoder.decode(parentId),
version,
basis,
decoder.decodeChange(changes)
);
}
static newId() {
const bytes = new Uint8Array(16);
getRandomValues(bytes);
const toHex = x => ("00" + x.toString(16)).slice(-2);
return Array.prototype.map.call(bytes, toHex).join("");
}
/*
* useCrypto should be used to provide the polyfill for crypto
* @param [Object] crypto - the crypto module
* @param [function] cyrpto.randomFillSync -- this is only function used here
*/
static useCrypto(crypto) {
getRandomValues = crypto.randomFillSync;
}
} |
JavaScript | class Conn {
/**
* @param {string} url - url to post requests to
* @param {function} fetch - window.fetch implementation or polyfill
*/
constructor(url, fetch) {
this._request = Conn._request.bind(null, url, fetch);
this._limit = 1000;
this._duration = 30 * 1000 * 1000 * 1000;
}
/** withPollMilliseconds specifies poll interval to pass on to server */
withPollMilliseconds(ms) {
this._duration = ms * 1000 * 1000;
return this;
}
/**
* write ops using fetch
* @param [Operation[]] ops - ops to write
* @returns {Promise}
*/
write(ops) {
return this._request(new AppendRequest(ops));
}
/**
* read ops using fetch
* @param [int] version - version of op to start fetching from
* @param [limit] limit - max number of ops to fetch
* @param [duration] duration - max long poll interval to pass to server
* @returns {Promise}
*/
read(version, limit, duration) {
duration = duration || this._duration;
return this._request(new GetSinceRequest(version, limit, duration));
}
static async _request(url, fetch, req) {
const headers = { "Content-Type": " application/x-sjson" };
const body = JSON.stringify(Encoder.encode(req));
const res = await fetch(url, { method: "POST", body, headers });
if (!res.ok) {
return Promise.reject(new Error(res.status + " " + res.statusText));
}
const json = await res.json();
const r = Response.fromJSON(new Decoder(), json[Response.typeName()]);
if (r.err) {
return Promise.reject(r.err);
}
return (r.ops && r.ops.length && r.ops) || null;
}
} |
JavaScript | class PathChange {
/**
* The path is a sequence of index or key name to refer to the embeded value.
*
* Example: root.rows[3] will have path ["rows", 3].
*
* @param {Any[]} path - path to inner value.
* @param {Change} change - any change applied to inner value at path.
*/
constructor(path, change) {
if (path == undefined) {
path = null;
}
if (change === undefined) {
change = null;
}
this.path = path;
this.change = change;
}
/** @returns {Change} - the inverse of this change */
revert() {
if (this.change == null) {
return null;
}
return PathChange.create(this.path, this.change.revert());
}
reverseMerge(other) {
if (this.path === null || this.path.length === 0) {
const [left, right] = other.merge(this.change);
return [right, left];
}
if (other instanceof Replace) {
const before = other.before.apply(this);
return [new Replace(before, other.after), null];
}
throw new Error("unexpected PathChange.reverseMerge");
}
/**
* Merge another change and return modified version of
* the other and current change.
*
* current + returned[0] and other + returned[1] are guaranteed
* to result in the same state.
*
* @returns {Change[]}
*/
merge(other) {
if (other == null) {
return [null, this];
}
if (this.change == null) {
return [other, null];
}
if (this.path == null) {
return this.change.merge(other);
}
if (!(other instanceof PathChange)) {
other = new PathChange(null, other);
}
const len = PathChange.commonPrefixLen(this.path, other.path);
const ownLen = (this.path && this.path.length) || 0;
const otherLen = (other.path && other.path.length) || 0;
if (len != ownLen && len != otherLen) {
return [other, this];
}
if (len == ownLen && len == otherLen) {
const [left, right] = this.change.merge(other.change);
return [
PathChange.create(other.path, left),
PathChange.create(this.path, right)
];
}
if (len == ownLen) {
const [left, right] = this.change.merge(
PathChange.create(other.path.slice(len), other.change)
);
return [
PathChange.create(this.path, left),
PathChange.create(this.path, right)
];
}
const [left, right] = other.merge(this);
return [right, left];
}
applyTo(value) {
if (this.path === null || this.path.length === 0) {
return value.apply(this.change);
}
throw new Error("Unexpected use of PathChange.applyTo");
}
toJSON() {
const path = Encoder.encodeArrayValue(this.path);
return [path, Encoder.encode(this.change)];
}
static typeName() {
return "changes.PathChange";
}
static fromJSON(decoder, json) {
let path = json[0];
if (path !== null) {
path = path.map(x => decoder.decode(x));
}
const change = decoder.decodeChange(json[1]);
return new PathChange(path, change);
}
static commonPrefixLen(p1, p2) {
if (p1 == null || p2 == null) {
return 0;
}
let len = 0;
for (; len < p1.length && len < p2.length; len++) {
const encode = x => Encoder.encode(x);
if (JSON.stringify(encode(p1[len])) != JSON.stringify(encode(p2[len]))) {
return len;
}
}
return len;
}
static create(path, change) {
if (path == null || path.length == 0) {
return change;
}
if (change == null) {
return null;
}
if (change instanceof PathChange) {
const otherPath = change.path || [];
return this.create(path.concat(otherPath), change.change);
}
return new PathChange(path, change);
}
} |
JavaScript | class Splice {
/**
* @param {Number} offset -- where the sub-sequence starts.
* @param {Value} before -- the subsequnce as it was before.
* @param {Value} value - the subsequence as it is after.
*/
constructor(offset, before, after) {
this.offset = offset;
this.before = before;
this.after = after;
}
revert() {
return new Splice(this.offset, this.after, this.before);
}
reverseMerge(other) {
if (other == null) {
return [null, this];
}
if (other instanceof Replace) {
return this._mergeReplace(other);
}
if (other instanceof Splice) {
const [left, right] = other._mergeSplice(this);
return [right, left];
}
if (other instanceof PathChange) {
return this._mergePath(other, true);
}
const [self, otherx] = other.reverseMerge(this);
return [otherx, self];
}
merge(other) {
if (other == null) {
return [null, this];
}
if (other instanceof Replace) {
return this._mergeReplace(other);
}
if (other instanceof Splice) {
return this._mergeSplice(other);
}
if (other instanceof PathChange) {
return this._mergePath(other, false);
}
const [left, right] = other.reverseMerge(this);
return [right, left];
}
_mergePath(o, reverse) {
if (o.path == null || o.path.length === 0) {
if (reverse) {
return this.reverseMerge(o.change);
}
return this.merge(o.change);
}
const newPath = this.mapPath(o.path);
if (newPath == null) {
const p = [o.path[0] - this.offset].concat(o.path.slice(1));
const before = this.before.apply(new PathChange(p, o.change));
return [null, new Splice(this.offset, before, this.after)];
}
return [new PathChange(newPath, o.change), this];
}
mapPath(path) {
const idx = path[0];
if (idx < this.offset) {
return path;
}
if (idx >= this.offset + this.before.length) {
const idx2 = idx + this.after.length - this.before.length;
return [idx2].concat(path.slice(1));
}
// path obliterated
return null;
}
_mergeSplice(o) {
if (Splice._end(this) <= o.offset) {
// [ ] < >
const offset = o.offset + Splice._diff(this);
const other = new Splice(offset, o.before, o.after);
return [other, this];
}
if (Splice._end(o) <= this.offset) {
// < > [ ]
const offset = this.offset + Splice._diff(o);
const updated = new Splice(offset, this.before, this.after);
return [o, updated];
}
if (this.offset < o.offset && Splice._end(this) < Splice._end(o)) {
// [ < ] >
const oOffset = this.offset + this.after.length;
const end = Splice._end(this);
const oBefore = o.before.slice(end - o.offset, o.before.length);
const before = this.before.slice(0, o.offset - this.offset);
return [
new Splice(oOffset, oBefore, o.after),
new Splice(this.offset, before, this.after)
];
}
if (this.offset == o.offset && this.before.length < o.before.length) {
// <[ ] >
const oBefore = o.before.slice(this.before.length, o.before.length);
const oOffset = o.offset + this.after.length;
const other = new Splice(oOffset, oBefore, o.after);
return [
other,
new Splice(this.offset, this.before.slice(0, 0), this.after)
];
// golang behavior is below
// const oBefore = o.before.apply(new Splice(0, this.before, this.after));
// return [new Splice(o.offset, oBefore, o.after), null];
}
if (this.offset <= o.offset && Splice._end(this) >= Splice._end(o)) {
// [ < > ]
const diff = o.offset - this.offset;
const slice = this.before.slice(diff, diff + o.before.length);
const before = this.before.apply(new Splice(diff, slice, o.after));
return [null, new Splice(this.offset, before, this.after)];
}
if (this.offset > o.offset && Splice._end(this) <= Splice._end(o)) {
// < [ ]>
const diff = this.offset - o.offset;
const slice = o.before.slice(diff, diff + this.before.length);
const oBefore = o.before.apply(
new Splice(this.offset - o.offset, slice, this.after)
);
return [new Splice(o.offset, oBefore, o.after), null];
}
// < [ > ]
const oBefore = o.before.slice(0, this.offset - o.offset);
const offset = o.offset + o.after.length;
const before = this.before.slice(
Splice._end(o) - this.offset,
this.before.length
);
return [
new Splice(o.offset, oBefore, o.after),
new Splice(offset, before, this.after)
];
}
_mergeReplace(other) {
const after = other.before.apply(this);
return [new Replace(after, other.after), null];
}
toJSON() {
return [
this.offset,
Encoder.encode(this.before),
Encoder.encode(this.after)
];
}
static typeName() {
return "changes.Splice";
}
static fromJSON(decoder, json) {
const before = decoder.decodeValue(json[1]);
const after = decoder.decodeValue(json[2]);
return new Splice(json[0], before, after);
}
static _end(s) {
return s.offset + s.before.length;
}
static _diff(s) {
return s.after.length - s.before.length;
}
} |
JavaScript | class Move {
/**
* Example: new Move(1, 2, -1) represents removing the slice
* value.slice(1, 3) and re-inserting it at index 0.
*
* @param {Number} offset - index of first element to shift.
* @param {Number} count - number of elements to shift.
* @param {Number} distance - how many elements to skip over.
*
*/
constructor(offset, count, distance) {
this.offset = offset;
this.count = count;
this.distance = distance;
}
/** @returns {Move} - the inverse of the move */
revert() {
return new Move(this.offset + this.distance, this.count, -this.distance);
}
reverseMerge(c) {
if (!c) {
return [null, this];
}
if (c instanceof Replace) {
return this._mergeReplace(c);
}
if (c instanceof PathChange) {
return this._mergePath(c, true);
}
if (c instanceof Splice) {
return this._mergeSplice(c);
}
const [left, right] = c.merge(this);
return [right, left];
}
/**
* Merge another change and return modified version of
* the other and current change.
*
* current + returned[0] and other + returned[1] are guaranteed
* to result in the same state.
*
* @returns {Change[]}
*/
merge(c) {
if (!c) {
return [null, this];
}
if (c instanceof Replace) {
return this._mergeReplace(c);
}
if (c instanceof PathChange) {
return this._mergePath(c, false);
}
if (c instanceof Splice) {
return this._mergeSplice(c);
}
if (c instanceof Move) {
return this._mergeMove(c);
}
const [self, cx] = c.reverseMerge(this);
return [cx, self];
}
_mergeReplace(other) {
const after = other.before.apply(this);
return [new Replace(after, other.after), null];
}
_mergePath(o, reverse) {
if (o.path == null || o.path.length === 0) {
if (reverse) {
return this.reverseMerge(o.change);
}
return this.merge(o.change);
}
const newPath = this.mapPath(o.path);
return [new PathChange(newPath, o.change), this];
}
_mergeMove(o) {
if (
o.offset === this.offset &&
o.distance === this.distance &&
o.count === this.count
) {
return [null, null];
}
if (
this.distance === 0 ||
this.count === 0 ||
o.distance === 0 ||
o.count === 0
) {
return [o, this];
}
if (
this.offset >= o.offset + o.count ||
o.offset >= this.offset + this.count
) {
return this._mergeMoveNoOverlap(o);
}
if (
this.offset <= o.offset &&
this.offset + this.count >= o.offset + o.count
) {
return this._mergeMoveContained(o);
}
if (
this.offset >= o.offset &&
this.offset + this.count <= o.offset + o.count
) {
return this.reverseMerge(o);
}
if (this.offset < o.offset) {
return this._mergeMoveRightOverlap(o);
}
return this.reverseMerge(o);
}
_mergeMoveNoOverlap(o) {
const dest = this._dest();
const odest = o._dest();
if (!this._contains(odest) && !o._contains(dest)) {
return this._mergeMoveNoOverlapNoDestMixups(o);
}
if (this._contains(odest) && o._contains(dest)) {
return this._mergeMoveNoOverlapMixedDests(o);
}
if (o._contains(dest)) {
return this.reverseMerge(o);
}
return this._mergeMoveNoOverlapContainedDest(o);
}
_mergeMoveNoOverlapContainedDest(o) {
const dest = this._dest();
let odest = o._dest();
let destx = dest;
if (dest >= odest && dest <= o.offset) {
destx += o.count;
} else if (dest > o.offset && dest <= odest) {
destx -= o.count;
}
const m1 = new Move(this.offset, this.count + o.count, this.distance);
if (o.offset <= this.offset) {
m1.offset -= o.count;
}
if (destx <= m1.offset) {
m1.distance = destx - m1.offset;
} else {
m1.distance = destx - m1.offset - m1.count;
}
const o1 = new Move(o.offset, o.count, o.distance);
if (o.offset > this.offset && o.offset < dest) {
o1.offset -= this.count;
} else if (o.offset >= dest && o.offset < this.offset) {
o1.offset += this.count;
}
odest += this.distance;
if (odest <= o1.offset) {
o1.distance = odest - o1.offset;
} else {
o1.distance = odest - o1.offset - o1.count;
}
return [o1, m1];
}
_mergeMoveNoOverlapNoDestMixups(o) {
const dest = this._dest();
const odest = o._dest();
const o1dest =
odest == dest ? this.offset + this.distance : this._mapPoint(odest);
const o1 = Move._withDest(this._mapPoint(o.offset), o.count, o1dest);
const m1dest = o._mapPoint(dest);
const m1 = Move._withDest(o._mapPoint(this.offset), this.count, m1dest);
return [o1, m1];
}
_mergeMoveNoOverlapMixedDests(o) {
const dest = this._dest();
const odest = o._dest();
const lcount = dest - o.offset;
const rcount = o.count - lcount;
const loffset = this.offset + this.distance - lcount;
const roffset = this.offset + this.distance + this.count;
const ldistance = odest - this.offset;
const rdistance = odest - this.offset - this.count;
const ox = new Changes(
new Move(loffset, lcount, ldistance),
new Move(roffset, rcount, rdistance)
);
let distance = o.offset - this.offset - this.count;
if (distance < 0) {
distance = -(this.offset - o.offset - o.count);
}
const offset = o.offset + o.distance - (odest - this.offset);
const count = this.count + o.count;
return [ox, new Move(offset, count, distance)];
}
_mergeMoveRightOverlap(o) {
const overlapSize = this.offset + this.count - o.offset;
const overlapUndo = new Move(o.offset + o.distance, overlapSize, 0);
const non = new Move(o.offset + overlapSize, o.count - overlapSize, 0);
if (o.distance > 0) {
overlapUndo.distance = -o.distance;
non.distance = o.distance;
} else {
overlapUndo.distance = o.count - overlapSize - o.distance;
non.distance = o.distance - overlapSize;
}
const [l, r] = this._mergeMoveNoOverlap(non);
return [l, new Changes(overlapUndo, r)];
}
_mergeMoveContained(o) {
const odest = o._dest();
let ox = new Move(o.offset + this.distance, o.count, o.distance);
if (this.offset <= odest && odest <= this.offset + this.count) {
return [ox, this];
}
if (odest == this._dest()) {
ox = Move._withDest(ox.offset, ox.count, this.offset + this.distance);
let offset = this.offset;
if (o.distance < 0) {
offset += o.count;
}
const distance = o.offset + o.count + o.distance;
return [ox, Move._withDest(offset, this.count - o.count, distance)];
}
ox = Move._withDest(ox.offset, ox.count, this._mapPoint(odest));
const offset = o._mapPoint(this.offset);
const distance = o._mapPoint(this._dest());
return [ox, Move._withDest(offset, this.count - o.count, distance)];
}
_mapPoint(idx) {
if (idx >= this.offset + this.distance && idx <= this.offset) {
return idx + this.count;
}
if (
idx >= this.offset + this.count &&
idx < this.offset + this.count + this.distance
) {
return idx - this.count;
}
return idx;
}
_dest() {
if (this.distance < 0) {
return this.offset + this.distance;
}
return this.offset + this.distance + this.count;
}
_contains(p) {
return p > this.offset && p < this.offset + this.count;
}
_mergeSplice(o) {
if (
this.offset >= o.offset &&
this.offset + this.count <= o.offset + o.before.length
) {
return this._mergeMoveWithinSpliceBefore(o);
}
if (
this.offset <= o.offset &&
this.offset + this.count >= o.offset + o.before.length
) {
// splice is fully within move sub-sequence
const ox = new Splice(o.offset + this.distance, o.before, o.after);
const thisx = new Move(
this.offset,
this.count + o.after.length - o.before.length,
this.distance
);
return [ox, thisx];
}
if (
this.offset >= o.offset + o.before.length ||
o.offset >= this.offset + this.count
) {
return this._mergeMoveOutsideSpliceBefore(o);
}
// first undo the intersection and then merge as before
const rest = new Move(this.offset, this.count, this.distance);
const undo = new Move(this.offset + this.distance, 0, 0);
if (this.offset > o.offset) {
const left = o.offset + o.before.length - this.offset;
rest.offset += left;
rest.count -= left;
undo.count = left;
if (this.distance < 0) {
rest.distance -= left;
undo.distance = this.count - this.distance - left;
} else {
undo.distance = -this.distance;
}
} else {
const right = this.offset + this.count - o.offset;
rest.count -= right;
undo.count = right;
undo.offset += rest.count;
if (this.distance < 0) {
undo.distance = -this.distance;
} else {
rest.distance += right;
undo.distance = right - this.distance - this.count;
}
}
// distance seems to become -0 in some cases which causes
// tests to fail
undo.distance = undo.distance || 0;
rest.distance = rest.distance || 0;
const [ox, restx] = rest._mergeMoveOutsideSpliceBefore(o);
return [new Changes(undo, ox), restx];
}
_mergeMoveOutsideSpliceBefore(o) {
const diff = o.after.length - o.before.length;
const dest =
this.distance < 0
? this.offset + this.distance
: this.offset + this.distance + this.count;
if (dest > o.offset && dest < o.offset + o.before.length) {
const right = o.offset + o.before.length - dest;
const oBefore1 = o.before.slice(0, dest - o.offset);
const oBefore2 = o.before.slice(dest - o.offset, dest - o.offset + right);
const empty = o.before.slice(0, 0);
const splice1 = new Splice(o.offset, oBefore1, o.after);
const splice2 = new Splice(
this.offset + this.count + this.distance,
oBefore2,
empty
);
const move = new Move(this.offset, this.count, this.distance);
if (this.offset < o.offset) {
splice1.offset -= this.count;
move.distance += right + diff;
} else {
move.distance += right;
move.offset += diff;
}
return [new Changes([splice2, splice1]), move];
}
if (dest <= o.offset) {
if (this.offset > o.offset) {
const s = new Splice(o.offset + this.count, o.before, o.after);
const m = new Move(
this.offset + diff,
this.count,
this.distance - diff
);
return [s, m];
}
} else if (dest >= o.offset + o.before.length) {
if (this.offset > o.offset) {
const m = new Move(this.offset + diff, this.count, this.distance);
return [o, m];
}
const s = new Splice(o.offset - this.count, o.before, o.after);
const m = new Move(this.offset, this.count, this.distance + diff);
return [s, m];
}
return [o, this];
}
_mergeMoveWithinSpliceBefore(o) {
const dest =
this.distance > 0
? this.offset + this.count + this.distance
: this.offset + this.distance;
if (dest >= o.offset && dest <= o.offset + o.before.length) {
const oBefore = o.before.apply(
new Move(this.offset - o.offset, this.count, this.distance)
);
return [new Splice(o.offset, oBefore, o.after), null];
}
const empty = o.before.slice(0, 0);
const slice = o.before.slice(
this.offset - o.offset,
this.offset - o.offset + this.count
);
const spliced = o.before.apply(
new Splice(this.offset - o.offset, slice, empty)
);
if (this.distance < 0) {
const other = new Splice(dest, empty, slice);
const self = new Splice(o.offset + this.count, spliced, o.after);
return [self, other];
}
const other = new Splice(
dest + o.after.length - o.before.length,
empty,
slice
);
const self = new Splice(o.offset, spliced, o.after);
return [self, other];
}
mapPath(path) {
const idx = path[0];
if (idx >= this.offset && idx < this.offset + this.count) {
return [idx + this.distance].concat(path.slice(1));
}
if (this.distance > 0) {
const e = this.offset + this.count + this.distance;
if (idx >= this.offset + this.count && idx < e) {
return [idx - this.count].concat(path.slice(1));
}
} else if (idx >= this.offset + this.distance && idx < this.offset) {
return [idx + this.count].concat(path.slice(1));
}
return path;
}
toJSON() {
return [this.offset, this.count, this.distance];
}
static typeName() {
return "changes.Move";
}
static fromJSON(decoder, json) {
return new Move(json[0], json[1], json[2]);
}
static _withDest(offset, count, dest) {
let distance = dest - offset - count;
if (distance < 0) {
distance = dest - offset;
}
return new Move(offset, count, distance);
}
} |
JavaScript | class Substream extends DerivedStream {
constructor(parent, key) {
super(parent);
this.key = key;
}
append(c) {
const cx = new PathChange([this.key], c);
return this._nextf(this.parent && this.parent.append(cx));
}
reverseAppend(c) {
const cx = new PathChange([this.key], c);
return this._nextf(this.parent && this.parent.reverseAppend(cx));
}
_nextf(n) {
if (!n) {
return null;
}
const { xform, key, ok } = transform(n.change, this.key);
if (!ok) {
// TODO: this should not be null for append case?
return null;
}
return { change: xform, version: new Substream(n.version, key) };
}
_getNext() {
return this._nextf(this.parent && this.parent.next);
}
} |
JavaScript | class Null extends Value {
/** clone makes a copy but with stream set to null */
clone() {
return new Null();
}
toJSON() {
return [];
}
static typeName() {
return "changes.empty";
}
static fromJSON() {
return new Null();
}
} |
JavaScript | class Dict extends Value {
constructor(initial, defaultFn) {
super();
this.map = initial || {};
this._defaultFn = defaultFn || (() => new Null());
}
setDefaultFn(defaultFn) {
this._defaultFn = defaultFn || (() => new Null());
}
/** get looks up a key and returns the value (or a default value) */
get(key) {
const s = new Substream(this.stream, key);
return (this.map[key] || this._defaultFn()).clone().setStream(s);
}
/** check if key exists */
keyExists(key) {
return !!this.map[key];
}
/** clone makes a copy but with stream set to null */
clone() {
return new this.constructor(this.map, this._defaultFn);
}
apply(c) {
if (!c) {
return this.clone();
}
if (c instanceof Replace) {
return c.after;
}
if (c instanceof PathChange) {
if (c.path === null || c.path.length === 0) {
return this.apply(c.change);
}
return this._applyPath(c.path, c.change);
}
return c.applyTo(this);
}
_applyPath(path, c) {
let val = this.map[path[0]] || this._defaultFn();
val = val.apply(new PathChange(path.slice(1), c));
const clone = {};
for (let key in this.map) {
clone[key] = this.map[key];
}
if (val instanceof Null) {
delete clone[path[0]];
} else {
clone[path[0]] = val;
}
return new this.constructor(clone, this._defaultFn);
}
*[MapIterator]() {
for (let key in this.map) {
yield [key, this.get(key)];
}
}
toJSON() {
let all = [];
for (let key in this.map) {
all.push(key, Encoder.encode(this.map[key]));
}
return all;
}
static typeName() {
return "dotdb.Dict";
}
static fromJSON(decoder, json) {
json = json || [];
const map = {};
for (let kk = 0; kk < json.length; kk += 2) {
map[json[kk]] = decoder.decodeValue(json[kk + 1]);
}
return new this(map);
}
} |
JavaScript | class Text extends Value {
constructor(text) {
super();
this.text = (text || "").toString();
}
slice(start, end) {
return new Text(this.text.slice(start, end));
}
get length() {
return this.text.length;
}
/**
* splice splices a replacement string (or Text)
*
* @param {Number} offset - where the replacement starts
* @param {Number} count - number of characters to remove
* @param {Text|String} replacement - what to replace with
*
* @return {Text}
*/
splice(offset, count, replacement) {
if (!(replacement instanceof Text)) {
replacement = new Text(replacement);
}
const before = this.slice(offset, offset + count);
return this.appendChange(new Splice(offset, before, replacement)).version;
}
/**
* move shifts the sub-sequence by the specified distance.
* If distance is positive, the sub-sequence shifts over to the
* right by as many characters as specified in distance. Negative
* distance shifts left.
*
* @param {Number} offset - start of sub-sequence to shift
* @param {Number} count - size of sub-sequence to shift
* @param {Number} distance - distance to shift
*
* @return {Text}
*/
move(offset, count, distance) {
return this.appendChange(new Move(offset, count, distance)).version;
}
/** clone makes a copy but with stream set to null */
clone() {
return new Text(this.text);
}
/**
* Apply any change immutably.
* @param {Change} c -- any change; can be null.
* @returns {Value}
*/
apply(c) {
if (!c) {
return this.clone();
}
if (c instanceof Replace) {
return c.after;
}
if (c instanceof Splice) {
const left = this.text.slice(0, c.offset);
const right = this.text.slice(c.offset + c.before.length);
return new Text(left + c.after.text + right);
}
if (c instanceof Move) {
let { offset: o, distance: d, count: cx } = c;
if (d < 0) {
[o, cx, d] = [o + d, -d, cx];
}
const s1 = this.text.slice(0, o);
const s2 = this.text.slice(o, o + cx);
const s3 = this.text.slice(o + cx, o + cx + d);
const s4 = this.text.slice(o + cx + d);
return new Text(s1 + s3 + s2 + s4);
}
return c.applyTo(this);
}
toJSON() {
return this.text;
}
static typeName() {
return "dotdb.Text";
}
static fromJSON(decoder, json) {
return new Text(json);
}
} |