language
stringclasses 5
values | text
stringlengths 15
988k
|
---|---|
JavaScript | class AxesLayer extends Layer {
initializeState() {
const {gl} = this.context;
const {attributeManager} = this.state;
attributeManager.addInstanced({
instancePositions: {size: 2, update: this.calculateInstancePositions, noAlloc: true},
instanceNormals: {size: 3, update: this.calculateInstanceNormals, noAlloc: true}
});
this.setState({
models: this._getModels(gl),
numInstances: 0,
labels: null,
center: [0, 0, 0],
dim: [1, 1, 1]
});
}
updateState({oldProps, props, changeFlags}) {
const {attributeManager} = this.state;
if (changeFlags.dataChanged || oldProps.ticksCount !== props.ticksCount) {
const {data, ticksCount} = props;
const ticks = this.calculateTicks(data, ticksCount);
this.setState({
ticks,
labelTexture: this.renderLabelTexture(ticks),
center: data.map(b => (b[0] + b[1]) / 2),
dim: data.map(b => b[1] - b[0])
});
attributeManager.invalidateAll();
}
}
updateAttributes(props) {
super.updateAttributes(props);
const {attributeManager, models, numInstances} = this.state;
const changedAttributes = attributeManager.getChangedAttributes({clearChangedFlags: true});
models.grids.setInstanceCount(numInstances);
models.grids.setAttributes(changedAttributes);
models.labels.setInstanceCount(numInstances);
models.labels.setAttributes(changedAttributes);
}
draw({uniforms}) {
const {center, dim, models, labelTexture} = this.state;
const {fontSize, axesColor, axesOffset} = this.props;
if (labelTexture) {
const baseUniforms = {
fontSize,
modelCenter: center,
modelDim: dim,
gridOffset: axesOffset,
strokeColor: axesColor
};
models.grids.render(Object.assign({}, uniforms, baseUniforms));
models.labels.render(Object.assign({}, uniforms, baseUniforms, labelTexture));
}
}
_getModels(gl) {
/* grids:
* for each x tick, draw rectangle on yz plane around the bounding box.
* for each y tick, draw rectangle on zx plane around the bounding box.
* for each z tick, draw rectangle on xy plane around the bounding box.
* show/hide is toggled by the vertex shader
*/
const gridShaders = assembleShaders(gl, {
vs: gridVertex,
fs: fragmentShader
});
/*
* rectangles are defined in 2d and rotated in the vertex shader
*
* (-1,1) (1,1)
* +-----------+
* | |
* | |
* | |
* | |
* +-----------+
* (-1,-1) (1,-1)
*/
// offset of each corner
const gridPositions = [
// left edge
-1, -1, 0, -1, 1, 0,
// top edge
-1, 1, 0, 1, 1, 0,
// right edge
1, 1, 0, 1, -1, 0,
// bottom edge
1, -1, 0, -1, -1, 0
];
// normal of each edge
const gridNormals = [
// left edge
-1, 0, 0, -1, 0, 0,
// top edge
0, 1, 0, 0, 1, 0,
// right edge
1, 0, 0, 1, 0, 0,
// bottom edge
0, -1, 0, 0, -1, 0
];
const grids = new Model({
gl,
id: `${this.props.id}-grids`,
vs: gridShaders.vs,
fs: gridShaders.fs,
geometry: new Geometry({
drawMode: GL.LINES,
positions: new Float32Array(gridPositions),
normals: new Float32Array(gridNormals)
}),
isInstanced: true
});
/* labels
* one label is placed at each end of every grid line
* show/hide is toggled by the vertex shader
*/
const labelShaders = assembleShaders(gl, {
vs: labelVertex,
fs: labelFragment
});
let labelTexCoords = [];
let labelPositions = [];
let labelNormals = [];
let labelIndices = [];
for (let i = 0; i < 8; i++) {
/*
* each label is rendered as a rectangle
* 0 2
* +--.+
* | / |
* +'--+
* 1 3
*/
labelTexCoords = labelTexCoords.concat([0, 0, 0, 1, 1, 0, 1, 1]);
labelIndices = labelIndices.concat([
i * 4 + 0, i * 4 + 1, i * 4 + 2,
i * 4 + 2, i * 4 + 1, i * 4 + 3
]);
// all four vertices of this label's rectangle is anchored at the same grid endpoint
for (let j = 0; j < 4; j++) {
labelPositions = labelPositions.concat(gridPositions.slice(i * 3, i * 3 + 3));
labelNormals = labelNormals.concat(gridNormals.slice(i * 3, i * 3 + 3));
}
}
const labels = new Model({
gl,
id: `${this.props.id}-labels`,
vs: labelShaders.vs,
fs: labelShaders.fs,
geometry: new Geometry({
drawMode: GL.TRIANGLES,
indices: new Uint16Array(labelIndices),
positions: new Float32Array(labelPositions),
texCoords: {size: 2, value: new Float32Array(labelTexCoords)},
normals: new Float32Array(labelNormals)
}),
isInstanced: true
});
return {grids, labels};
}
calculateInstancePositions(attribute) {
const {ticks} = this.state;
const positions = ticks.map(axisTicks =>
axisTicks.map((t, i) => [t, i])
);
const value = new Float32Array(flatten(positions));
attribute.value = value;
this.setState({numInstances: value.length / attribute.size});
}
calculateInstanceNormals(attribute) {
const {ticks: [xTicks, yTicks, zTicks]} = this.state;
const normals = [
xTicks.map(t => [1, 0, 0]),
yTicks.map(t => [0, 1, 0]),
zTicks.map(t => [0, 0, 1])
];
attribute.value = new Float32Array(flatten(normals));
}
// updates the instancePositions and instanceNormals attributes
calculateTicks(bounds, ticksCount) {
const xTicks = getTicks(bounds[0], ticksCount);
const yTicks = getTicks(bounds[1], ticksCount);
const zTicks = getTicks(bounds[2], ticksCount);
return [xTicks, yTicks, zTicks];
}
renderLabelTexture(ticks) {
if (this.state.labels) {
this.state.labels.labelTexture.delete();
}
// attach a 2d texture of all the label texts
const textureInfo = textMatrixToTexture(this.context.gl, ticks, FONT_SIZE);
if (textureInfo) {
// success
const {columnWidths, texture} = textureInfo;
return {
labelHeight: FONT_SIZE,
labelWidths: columnWidths,
labelTextureDim: [texture.width, texture.height],
labelTexture: texture
};
}
return null;
}
} |
JavaScript | class CreationFeedback extends Component {
constructor(props) {
super(props);
this.state = {
closed: false
};
}
close = () => {
this.setState({ closed: true });
};
render() {
const { closed } = this.state;
const { title, message, classes } = this.props;
if (closed) return null;
return (
<div className={classes.container}>
<button className={classes.closeElement} onClick={this.close}>
<Icon type="close" />
</button>
<div className={classes.iconContainer}>
<Icon type="check-circle" theme="filled" className={classes.icon}/>
</div>
<h6 className={classes.title}>{title}</h6>
{message && <div className={classes.message}>{message}</div>}
</div>
);
}
} |
JavaScript | class RouterElement extends HTMLElement {
/**
* Dispatch a 'router.route' element which will be picked up by any higher <router-element>
* @param {HTMLElement} element
* @param {String} url
*/
static route(element, url){
element.dispatchEvent(new CustomEvent('router.route', {
detail: url,
bubbles: true
}))
}
/**
* Constructor
*/
constructor() {
super();
/**
* Whether history saving is available.
* This doesn't work on file: routes.
* @type {Boolean}
*/
this.history_allowed = window.location.protocol !== 'file:';
/**
* Map of routes
* @type {Map<String, RouteElement>}
*/
this.routes = new Map();
/**
* The associated, optional nav controls
* @type {Map<String, Array<HTMLElement>>}
*/
this.navs = new Map();
/**
* The currently displayed route url
* @type {String}
*/
this.current_url = null;
// Add a mutation observer to watch for removed route-elements
const observer = new MutationObserver((mutations) => {
mutations.forEach(mutation => {
switch(mutation.type){
case 'childList':
if(mutation.removedNodes.length){
this.handleRemovedChildNode(mutation.removedNodes);
}
break;
}
});
});
observer.observe(this, {childList: true});
// Add an event listener to listen for bubbled route requests via events
this.addEventListener('router.route', event => {
this.route(event.detail);
});
}
/**
* On connection, find all routes and attach the window popstate handler.
*/
connectedCallback(){
if(this.getAttribute('back') !== 'false'){
window.addEventListener('popstate', () => {
this.route(window.location.pathname, {add_to_history: false});
});
}
this.findRoutes();
this.findNavs();
if(this.getAttribute('auto') !== 'false'){
this.initialize();
}
}
/**
* Initialize by routing the location pathname.
*/
initialize(){
this.route(window.location.pathname, {add_to_history: false});
}
/**
* Handle a removed route-element.
* @param {Array<Node>} nodes
*/
handleRemovedChildNode(nodes){
for(let i = 0; i < nodes.length; i++){
if(this.current_url === nodes[i].getAttribute('url')){
this.current_url = null;
this.dispatchEvent(new Event('router.removed', {bubbles: true}));
break;
}
}
}
/**
* Find any optional nav elements.
* These must be identified by class route-element-nav
*/
findNavs(){
this.navs.clear();
const nav_selector = this.getAttribute('nav');
if(!nav_selector){
return
}
const nav_elements = document.querySelectorAll(nav_selector);
if(!nav_elements.length){
return;
}
nav_elements.forEach(nav_element => {
const navs = nav_element.querySelectorAll('.route-element-nav');
navs.forEach(nav => {
// Get either the href or url attribute
const href = nav.getAttribute('href');
const url = nav.getAttribute('url');
const value = href || url;
if(!value){
console.warn('route-element-nav is missing an href/url attribute');
return;
}
nav.addEventListener('click', event => {
event.preventDefault();
this.route(value);
});
const navs = this.navs.get(value) || [];
navs.push(nav);
this.navs.set(value, navs);
});
});
}
/**
* Set the active nav
* @param {String} url
*/
setNav(url){
// Remove active class from currrent nav(s)
const current_navs = this.navs.get(this.current_url);
if(current_navs && current_navs.length){
current_navs.forEach(nav => {
nav.classList.remove('route-element-nav-active');
});
}
// Add active class to matching nav(s)
const navs = this.navs.get(url);
if(navs && navs.length){
navs.forEach(nav => {
nav.classList.toggle('route-element-nav-active', true);
});
}
}
/**
* Clear the route map and then find all immediate child route-elements.
* Attach handlers to see if their URLs ever change.
*/
findRoutes() {
this.routes.clear();
for (let i = 0; i < this.children.length; i++) {
const element = this.children[i];
if (element instanceof RouteElement) {
this.routes.set(element.getAttribute('url'), element);
// When the url changes, and it was the current route, set current_url to null
element.addEventListener('route.urlchanged', ({detail}) => {
if(this.current_url === detail){
this.current_url = null;
}
});
}
}
}
/**
* Display a route-element based on the provided URL.
* Add the url to the window history.
* If nothing close can be found, emits "notfound" event
* @param {String} url
* @param {Object} [options={}]
* @param {Boolean} [options.add_to_history=true] - Whether to add the route to window history
*/
route(url, {add_to_history = true} = {}) {
// Validate url
if(typeof url !== 'string'){
console.warn('Invalid URL passed to route()');
return;
}
// URL after passing through some modifications
let processed_url = url;
// Strip query params
const params_index = processed_url.indexOf('?');
if(params_index > -1){
processed_url = processed_url.slice(0, params_index);
}
// Emit event in case someone wants to block this
// They can set cancel to true
const detail = {url, cancel: false};
this.dispatchEvent(new CustomEvent('router.beforeroute', {
detail: detail,
bubbles: true
}));
if(detail.cancel){
return;
}
// Add to history, use original URL
if (add_to_history && this.history_allowed && this.getAttribute('history') !== 'false'){
window.history.pushState(null, null, url);
}
const found_url = this.setRoute(processed_url)
const event_name = found_url ? 'router.routed' : 'router.notfound';
this.dispatchEvent(new CustomEvent(event_name, {
detail: found_url ? found_url : processed_url,
bubbles: true
}));
}
/**
* Reveal a route-element based on the provided url.
* If the exact route is not found, tries to find the one that matches the most.
* Hide the previously revealed route.
* Call the route's init() function which will call its initialize()
* @param {String} url
* @returns {String} Found URL if found, blank if not found
*/
setRoute(url){
let route = this.routes.get(url);
if (!route) {
if(this.getAttribute('partial') !== 'false'){
// Find the best match possible
let best = '';
this.routes.forEach((route_element, route_url) => {
if(url.startsWith(route_url)){
if(route_url.length > best.length){
best = route_url;
}
}
});
if(best){
url = best;
route = this.routes.get(url);
}
}
}
if(!route){
return "";
}
// Hide the current route
if (this.current_url !== null) {
const current_route = this.routes.get(this.current_url);
if(current_route){
current_route.toggle(false);
}
}
this.setNav(url);
route.toggle(true);
route.init();
this.current_url = url;
return this.current_url;
}
} |
JavaScript | class CWCIconMaterialAv extends CustomHTMLElement {
/**
* @public @static @name template
* @description Template function to return web component UI
* @return {TemplateResult} HTML template result
*/
static template() {
return html`
<style>
:host {
display: inline-block;
width: 30px;
height: 30px;
padding: 5px;
box-sizing: border-box;
vertical-align: middle;
}
svg { float: left; }
</style>
${ICONS[this.getAttribute('name')]}
`;
}
/**
* @public @static @get @name observedAttributes
* @description Provide attributes to watch for changes
* @return {Array} Array of attribute names as strings
*/
static get observedAttributes() { return ['name'] }
/**
* @public @name attributeChanged
* @description Callback run when a custom elements attributes change
* @param {String} attribute The attribute name
* @param {Mixed} oldValue The old value
* @param {Mixed} newValue The new value
*/
attributeChanged(attribute, oldValue, newValue) { this.updateTemplate() }
} |
JavaScript | class App extends Component {
componentWillMount() {
firebase.initializeApp({
apiKey: 'AIzaSyBtxMY4K6uHxv_2e3GD-FWAD2ACX6lPVRE',
authDomain: 'authentication-70a18.firebaseapp.com',
databaseURL: 'https://authentication-70a18.firebaseio.com',
storageBucket: 'authentication-70a18.appspot.com',
messagingSenderId: '682333809338'
});
}
render() {
return (
<View style={{ flex: 1 }}>
<Header headerText="Authentication" />
<LoginForm />
</View>
);
}
} |
JavaScript | class FVBoxGeometry extends AbstractBoxGeometry {
constructor() {
super();
const { faceList, vertexMap } = this.cloneData();
this.faceList = faceList;
this.vertexMap = vertexMap;
}
/**
* Populate a faceList and a vertex map
*/
cloneData() {
//vertices
const v0 = new Vertex(0,0,0, 'v0');
const v1 = new Vertex(1,0,0, 'v1');
const v2 = new Vertex(1,1,0, 'v2');
const v3 = new Vertex(0,1,0, 'v3');
const v4 = new Vertex(0,0,1, 'v4');
const v5 = new Vertex(1,0,1, 'v5');
const v6 = new Vertex(1,1,1, 'v6');
const v7 = new Vertex(0,1,1, 'v7');
const v8 = new Vertex(.5,.5,1, 'v8');
const v9 = new Vertex(.5,.5,0, 'v9');
// faces
const f0 = [ v0, v4, v5 ];
const f1 = [ v0, v5, v1 ];
const f2 = [ v1, v5, v6 ];
const f3 = [ v1, v6, v2 ];
const f4 = [ v2, v6, v7 ];
const f5 = [ v2, v7, v3 ];
const f6 = [ v3, v7, v4 ];
const f7 = [ v3, v4, v0 ];
const f8 = [ v8, v5, v4 ];
const f9 = [ v8, v6, v5 ];
const f10 = [ v8, v7, v6 ];
const f11 = [ v8, v4, v7 ];
const f12 = [ v9, v1, v0 ];
const f13 = [ v9, v2, v1 ];
const f14 = [ v9, v3, v2 ];
const f15 = [ v9, v0, v3 ];
// faceList
const faceList = [];
faceList.push(f0);
faceList.push(f1);
faceList.push(f2);
faceList.push(f3);
faceList.push(f4);
faceList.push(f5);
faceList.push(f6);
faceList.push(f7);
faceList.push(f8);
faceList.push(f9);
faceList.push(f10);
faceList.push(f11);
faceList.push(f12);
faceList.push(f13);
faceList.push(f14);
faceList.push(f15);
//vertexMap
const vertexMap = new Map();
vertexMap.set(v0, [ f0, f1, f7, f12, f15 ]);
vertexMap.set(v1, [ f1, f2, f3, f12, f13 ]);
vertexMap.set(v2, [ f3, f4, f5, f13, f14 ]);
vertexMap.set(v3, [ f5, f6, f7, f14, f15 ]);
vertexMap.set(v4, [ f0, f6, f7, f8, f11 ]);
vertexMap.set(v5, [ f0, f1, f2, f8, f9 ]);
vertexMap.set(v6, [ f2, f3, f4, f9, f10 ]);
vertexMap.set(v7, [ f4, f5, f6, f10, f11 ]);
vertexMap.set(v8, [ f8, f9, f10, f11 ]);
vertexMap.set(v9, [ f12, f13, f14, f15 ]);
return {
faceList,
vertexMap,
}
}
} |
JavaScript | class PushNotificationGateway extends Disposable {
constructor(protocol, host, port, environment) {
super();
this._environment = environment;
this._jwtProvider = null;
this._started = false;
this._startPromise = null;
const requestInterceptor = RequestInterceptor.fromDelegate((options, endpoint) => {
return Promise.resolve()
.then(() => {
return this._jwtProvider.getToken()
.then((token) => {
options.headers = options.headers || {};
options.headers.Authorization = `Bearer ${token}`;
return options;
});
}).catch((e) => {
const failure = FailureReason.forRequest({ endpoint: endpoint })
.addItem(FailureType.REQUEST_IDENTITY_FAILURE)
.format();
return Promise.reject(failure);
});
});
const responseInterceptor = ResponseInterceptor.fromDelegate((response, ignored) => {
return response.data;
});
const protocolType = Enum.fromCode(ProtocolType, protocol.toUpperCase());
this._registerEndpoint = EndpointBuilder.for('register-device', 'register your device')
.withVerb(VerbType.POST)
.withProtocol(protocolType)
.withHost(host)
.withPort(port)
.withPathBuilder((pb) =>
pb.withLiteralParameter('version', 'v2')
.withLiteralParameter('register', 'register')
)
.withBody()
.withRequestInterceptor(requestInterceptor)
.withResponseInterceptor(responseInterceptor)
.withErrorInterceptor(ErrorInterceptor.GENERAL)
.endpoint;
this._unregisterEndpoint = EndpointBuilder.for('unregister-device', 'unregister your device')
.withVerb(VerbType.POST)
.withProtocol(protocolType)
.withHost(host)
.withPort(port)
.withPathBuilder((pb) =>
pb.withLiteralParameter('version', 'v2')
.withLiteralParameter('unregister', 'unregister')
)
.withBody()
.withRequestInterceptor(requestInterceptor)
.withResponseInterceptor(responseInterceptor)
.withErrorInterceptor(ErrorInterceptor.GENERAL)
.endpoint;
}
/**
* A description of the environment (e.g. development, production, etc).
*
* @public
* @return {String}
*/
get environment() {
return this._environment;
}
/**
* Attempts to establish a connection to the backend. This function should be invoked
* immediately following instantiation. Once the resulting promise resolves, a
* connection has been established and other instance methods can be used.
*
* @public
* @param {JwtProvider} jwtProvider
* @returns {Promise<PushNotificationGateway>}
*/
connect(jwtProvider) {
return Promise.resolve()
.then(() => {
assert.argumentIsRequired(jwtProvider, 'jwtProvider', JwtProvider, 'JwtProvider');
if (this._startPromise === null) {
this._startPromise = Promise.resolve()
.then(() => {
this._started = true;
this._jwtProvider = jwtProvider;
return this;
}).catch((e) => {
this._started = false;
this._startPromise = null;
this._jwtProvider = null;
throw e;
});
}
return this._startPromise;
});
}
/**
* Registers an iOS or Android device to receive push notifications.
*
* @public
* @param {Schema.Device} device - User information for registering device to receive push notifications.
* @returns {Promise<Schema.Device>}
*/
registerDevice(device) {
return Promise.resolve()
.then(() => {
checkStart.call(this);
assert.argumentIsRequired(device, 'device', Object);
assert.argumentIsRequired(device.user, 'device.user', Object);
assert.argumentIsRequired(device.user.id, 'device.user.id', String);
assert.argumentIsRequired(device.user.context, 'device.user.context', String);
assert.argumentIsRequired(device.provider, 'device.provider', String);
if (!device.apns && !device.fcm) {
throw new Error('Either [ device.apns ] or [ device.fcm ] must be provided');
}
if (device.apns) {
assert.argumentIsRequired(device.apns, 'device.apns', Object);
assert.argumentIsRequired(device.apns.device, 'device.apns.device', String);
assert.argumentIsRequired(device.apns.bundle, 'device.apns.bundle', String);
}
if (device.fcm) {
assert.argumentIsRequired(device.fcm, 'device.fcm', Object);
assert.argumentIsRequired(device.fcm.iid, 'device.fcm.iid', String);
assert.argumentIsRequired(device.fcm.package, 'device.fcm.package', String);
assert.argumentIsRequired(device.fcm.token, 'device.fcm.token', String);
}
return Gateway.invoke(this._registerEndpoint, device);
});
}
/**
* Unregisters an iOS or Android device.
*
* @public
* @param {Schema.UnregisterRequest} data - User information for unregistering the device.
* @returns {Promise<Object>}
*/
unregisterDevice(data) {
return Promise.resolve()
.then(() => {
checkStart.call(this);
assert.argumentIsRequired(data, 'data', Object);
assert.argumentIsRequired(data.user, 'data.user', Object);
assert.argumentIsRequired(data.user.id, 'data.user.id', String);
assert.argumentIsRequired(data.user.context, 'data.user.context', String);
assert.argumentIsRequired(data.device, 'data.device', Object);
assert.argumentIsRequired(data.device.device, 'data.device.device', String);
assert.argumentIsRequired(data.device.bundle, 'data.device.bundle', String);
return Gateway.invoke(this._unregisterEndpoint, {
user: data.user.id,
context: data.user.context,
device: data.device.device,
bundle: data.device.bundle
});
});
}
/**
* Creates and starts a new {@link PushNotificationGateway} for use in the private staging environment.
*
* @public
* @static
* @param {JwtProvider} jwtProvider
* @returns {Promise<PushNotificationGateway>}
*/
static forStaging(jwtProvider) {
return Promise.resolve()
.then(() => {
assert.argumentIsRequired(jwtProvider, 'jwtProvider', JwtProvider, 'JwtProvider');
return start(new PushNotificationGateway(REST_API_SECURE_PROTOCOL, Configuration.stagingHost, REST_API_SECURE_PORT, 'staging'), jwtProvider);
});
}
/**
* Creates and starts a new {@link PushNotificationGateway} for use in the public production environment.
*
* @public
* @static
* @param {JwtProvider} jwtProvider
* @returns {Promise<PushNotificationGateway>}
*/
static forProduction(jwtProvider) {
return Promise.resolve()
.then(() => {
assert.argumentIsRequired(jwtProvider, 'jwtProvider', JwtProvider, 'JwtProvider');
return start(new PushNotificationGateway(REST_API_SECURE_PROTOCOL, Configuration.productionHost, REST_API_SECURE_PORT, 'production'), jwtProvider);
});
}
_onDispose() {
}
toString() {
return '[PushNotificationGateway]';
}
} |
JavaScript | class AlexaResponseVO {
static getResponse (alexaRequest, sessionData = null) {
let {answer, shouldEndSession, card, description, videoURL, pictureURL } = alexaRequest
let directives = []
if(videoURL == null && description == null){
directives.push(
{
type: 'Display.RenderTemplate',
template: {
type: 'BodyTemplate2',
token: 'WelcomeScreen',
title: '',
backgroundImage: {
contentDescription: '',
sources: [{url: pictureURL }],
},
textContent: {
primaryText: {
type: 'PlainText',
text: description
}
}
}
})
}
else {
shouldEndSession = undefined;
directives.push({
type: "VideoApp.Launch",
videoItem: {
source: videoURL
}
})
}
let res =
{
version: '1.0',
sessionAttributes: {},
response: {
outputSpeech: {
type: 'SSML',
ssml: `<speak>${answer}</speak>`
},
shouldEndSession: shouldEndSession,
directives : directives,
description : description,
videoURL : videoURL
}
}
if (card) {
res.response.card = card
}
// add Session Attributes
res.sessionAttributes = sessionData
return res
}
} |
JavaScript | class FreeCameraControls extends GameModesBase
{
constructor(previousGameMode = undefined)
{
super();
// Remember previous game mode to return to when pressing shift + C
this.previousGameMode = previousGameMode;
this.movementSpeed = 0.06;
// Keymap
this.keymap = {
'87': { action: 'forward' },
'83': { action: 'back' },
'65': { action: 'left' },
'68': { action: 'right' },
'69': { action: 'up' },
'81': { action: 'down' },
'16': { action: 'fast' }
};
this.controls = {
forward: new Controls.LerpControl(),
left: new Controls.LerpControl(),
right: new Controls.LerpControl(),
up: new Controls.LerpControl(),
back: new Controls.LerpControl(),
down: new Controls.LerpControl(),
fast: new Controls.LerpControl()
};
}
init()
{
this.checkIfWorldIsSet();
this.world.cameraController.target.copy(this.world.camera.position);
this.world.cameraController.setRadius(0);
this.world.cameraDistanceTarget = 0.001;
this.world.dirLight.target = this.world.camera;
}
/**
* Handles game keys based on supplied inputs.
* @param {*} event Keyboard or mouse event
* @param {char} key Key or button pressed
* @param {boolean} value Value to be assigned to action
*/
handleAction(event, key, value)
{
super.handleAction(event, key, value);
// Shift modifier fix
key = event.keyCode;
if(key == '70' && value == true)
{
let forward = new THREE.Vector3(0, 0, -1).applyQuaternion(this.world.camera.quaternion);
let ball = new Object();
ball.setPhysics(new ObjectPhysics.Sphere({
mass: 1,
radius: 0.3,
position: new CANNON.Vec3().copy(this.world.camera.position).vadd(forward)
}));
ball.setModelFromPhysicsShape();
this.world.add(ball);
this.world.balls.push(ball);
if(this.world.balls.length > 10)
{
this.world.remove(this.world.balls[0]);
_.pull(this.world.balls, this.world.balls[0]);
}
}
// Turn off free cam
if (this.previousGameMode !== undefined && key == '67' && value == true && event.shiftKey == true)
{
this.world.gameMode = this.previousGameMode;
this.world.gameMode.init();
}
// Is key bound to action
else if (key in this.keymap)
{
// Get control and set it's parameters
let control = this.controls[this.keymap[key].action];
control.value = value;
}
}
handleScroll(event, value)
{
this.scrollTheTimeScale(value);
}
handleMouseMove(event, deltaX, deltaY)
{
this.world.cameraController.move(deltaX, deltaY);
}
update()
{
// Make light follow camera (for shadows)
this.world.dirLight.position.set(
this.world.camera.position.x + this.world.sun.x * 15,
this.world.camera.position.y + this.world.sun.y * 15,
this.world.camera.position.z + this.world.sun.z * 15
);
// Lerp all controls
for (let key in this.controls)
{
let ctrl = this.controls[key];
ctrl.floatValue = THREE.Math.lerp(ctrl.floatValue, +ctrl.value, 0.3);
}
// Set fly speed
let speed = this.movementSpeed * (this.controls.fast.value ? 5 : 1);
let up = new THREE.Vector3(0, 1, 0);
let forward = new THREE.Vector3(0, 0, -1).applyQuaternion(this.world.camera.quaternion);
let right = new THREE.Vector3(1, 0, 0).applyQuaternion(this.world.camera.quaternion);
this.world.cameraController.target.add(forward.multiplyScalar(speed * (this.controls.forward.floatValue - this.controls.back.floatValue)));
this.world.cameraController.target.add(right.multiplyScalar(speed * (this.controls.right.floatValue - this.controls.left.floatValue)));
this.world.cameraController.target.add(up.multiplyScalar(speed * (this.controls.up.floatValue - this.controls.down.floatValue)));
}
} |
JavaScript | class ParsedPath {
constructor(pth) {
Object.assign(this, upath.parse(pth));
this.full = pth;
}
toString() { return this.full; }
} |
JavaScript | class Resources {
constructor() {
this.resources = []
}
addFromFile(filename) {
const loadedResources = JSON.parse(fs.readFileSync(filename, 'utf8'));
loadedResources.map((loadedResource) => {
const aResource = new Resource()
aResource.initFromObject(loadedResource)
this.resources.push(aResource)
})
}
loadFromFile(filename) {
this.resources = []
this.addFromFile(filename)
}
byId(resId) {
return _.find(this.resources, ['resourceId', resId])
}
getOrders() {
const anOrder = []
this.resources.map((resource) => {
if (resource.orders) {
resource.orders.map((order) => {
anOrder.push({
date: order.date,
qnt: order.qnt,
resource: order.resource,
reqQnt: order.reqQnt,
price: order.resource.defPrice,
value: Math.round(order.qnt * order.resource.defPrice),
})
})
}
})
return anOrder
}
} |
JavaScript | class Node {
constructor(value) {
this.value = value;
this.next = null;
}
} |
JavaScript | class Stack {
constructor() {
this.top = null;
this.bottom = null;
this.length = 0;
}
// Returns the node at the top of the stack.
peek() {
return this.top;
}
// Add a node with the provided value to the top of the stack.
push(value) {
const newNode = new Node(value);
if (!this.bottom) {
this.bottom = newNode;
}
newNode.next = this.top;
this.top = newNode;
this.length++;
}
// Removes a node from the top of a stack and returns it.
pop() {
if (!this.top) {
return null;
}
if (!this.top.next) {
this.bottom = null;
}
const removedNode = this.top;
this.top = this.top.next;
this.length--;
return removedNode;
}
} |
JavaScript | class Tile {
/**
* @param {Tile|object} spec optional Tile to copy or spec of tile
* @param {string} spec.letter character(s) represented by this tile
* @param {boolean} spec.isBlank true if this tile is a blank (irresepective of letter)
* @param {number} spec.score value of this tile
* @param {number} spec.col optional column where the tile is placed
* @param {number} spec.row optional row where the tile is placed
*/
constructor(spec) {
// Caution; during gameplay, .letter for a blank will be cast
// to a letter chosen by the player. When the tile is returned
// to the rack, the letter will be reset to ' ' as isBlank is true.
// However the letter will stick to the Tile when it is sent to
// the server as part of the move. Henceforward that Tile will
// be locked to the chosen letter.
/**
* character(s) represented by this tile
* @member {string}
*/
this.letter = ' ';
/**
* value of this tile
* @member {number}
*/
this.score = 0;
/**
* true if this tile is a blank (irresepective of letter)
* @member {boolean}
*/
this.isBlank = false;
/**
* Column where the tile is placed
* @member {number}
*/
this.col = undefined;
/**
* Row where the tile is placed
* @member {number}
*/
this.row = undefined;
if (spec)
Object.getOwnPropertyNames(spec).forEach(
p => this[p] = spec[p]);
}
toString(place) {
const pl = place ? `@${this.col},${this.row}` : '';
return `|${this.letter}${pl}(${this.score})|`;
}
} |
JavaScript | class ApiService
{
/**
* Set the host of the api, takes
* the current host if not set
* @type {undefined | string}
*/
static HOST = undefined;
/**
* Set the port of the api, takes the
* current port if not set
* @type {undefined | number }
*/
static PORT = undefined;
/**
* The base url for each request
* @type {string}
*/
static BASE_URL = "/api/v1";
/**
* The header name for the authentication token
* added to each request
* @type {string}
*/
static AUTH_TOKEN_HEADER_NAME = "Authorization";
/**
* Angular $http service
* @type { { get:function, post:function, put:function, delete:function, defaults : {} } }
*/
@Inject $http;
/**
* Angular location service used to build the correct url
* @type {*}
*/
@Inject $location;
/**
* Does a GET Request and returns the data of the
* response
* @param {string} url
* @param { * } [config]
*/
get(url, config)
{
return this.$http.get(this.apiURL(url), config).then(r => r.data);
}
/**
* Does a POST Request and returns the data of the
* response
* @param {string} url
* @param {object} [data]
* @param { * } [config]
*/
post(url, data, config)
{
return this.$http.post(this.apiURL(url), data, config).then(r => r.data);
}
/**
* Does a PUT Request and returns the data of the
* response
* @param {string} url
* @param {object} data
* @param { * } [config]
*/
put(url, data, config)
{
return this.$http.put(this.apiURL(url), data, config).then(r => r.data);
}
/**
* Does a DELETE Request and returns the data of the
* response
* @param {string} url
* @param { * } [config]
*/
delete(url, config)
{
return this.$http.delete(this.apiURL(url), config).then(r => r.data);
}
/**
* Returns an url with injected ApiService.HOST and ApiService.BASE_URL
* @param {string} url
* @return {string}
*/
apiURL(url)
{
let host = ApiService.HOST || this.$location.host();
let port = ApiService.PORT || this.$location.port();
return this.$location.protocol() + "://" + host + ":" + port + ApiService.BASE_URL + url;
}
/**
* Instructs the ApiService to authenticate itself with the given token
* on each request
* @param {string} token
*/
authenticateWith(token)
{
this.$http.defaults.headers.common[ApiService.AUTH_TOKEN_HEADER_NAME] = "Bearer " + token;
}
/**
* Instruct the ApiService to stop authenticating itself
*/
dontAuthenticate()
{
delete this.$http.defaults.headers.common[ApiService.AUTH_TOKEN_HEADER_NAME];
}
} |
JavaScript | class classTest {
constructor() {
const { HttpService, RouterService } = $injector.inject('HttpService', 'RouterService');
this.http = HttpService;
this.router = RouterService;
}
} |
JavaScript | class FileSystem {
constructor(rest, opts) {
this.rest = rest;
// User can set cache level, defaults to 1.
this.cacheLevel = (opts && typeof opts.cacheLevel === 'number') ? opts.cacheLevel : 1;
this.fds = [];
this.statCache = {};
}
_delCache(path, ...levels) {
if (levels.indexOf(this.cacheLevel) === -1) {
return [];
}
let recurse = true;
const obj = this.statCache[path];
const removed = [obj];
if (obj && obj.isfile) {
recurse = false;
}
logger.silly(`Removing path "${path}" from cache.`);
delete this.statCache[path];
if (recurse) {
logger.debug(`Recursively removing path "${path}" from cache.`);
// eslint-disable-next-line no-param-reassign
path = (path.endsWith('/')) ? path : `${path}/`;
Object.keys(this.statCache).forEach((key) => {
if (key.startsWith(path)) {
removed.push(this.statCache[key]);
delete this.statCache[key];
}
});
}
return removed;
}
_addCache(path, obj, ...levels) {
if (levels.indexOf(this.cacheLevel) === -1) {
return;
}
if (!obj) {
return;
}
logger.silly(`Adding "${path}" to cache.`);
this.statCache[path] = obj;
}
_clearCache(...levels) {
if (levels.indexOf(this.cacheLevel) === -1) {
return;
}
logger.debug('Clearing cache');
this.statCache = {};
}
stat(path, callback) {
// Listing a directory fills this cache to speed up the all but certain
// stat() calls to follow.
const info = this.statCache[path];
if (info) {
logger.debug(`Cache HIT for "${path}"`);
CACHE_HIT.inc();
this._delCache(path, 0, 1);
if (info instanceof Error) {
// Negative cache
callback(info);
} else {
callback(null, info);
}
return;
}
logger.debug(`Cache MISS for "${path}"`);
CACHE_MISS.inc();
operationWrapper(this.rest, 'info', [path], (e, json) => {
if (e) {
if (e.statusCode === 404) {
// Negative cache, don't use the original (heavyweight) error instance.
const newError = new Error('File not found');
newError.statusCode = e.statusCode;
newError.message = e.message;
this._addCache(path, newError, 2);
}
callback(e);
return;
}
this._addCache(json.path, json, 2);
callback(null, json);
});
}
lstat(...args) {
return this.stat(...args);
}
rmdir(path, callback) {
return operationWrapper(this.rest, 'delete', [path], (e, json) => {
if (e && e.statusCode === 404
&& e.request.path === '/api/2/path/oper/remove/') {
this._delCache(path, 0, 1, 2);
// Mask out the error, and forge a fake response.
callback(null, {
result: {
status: 'SUCCESS',
},
});
} else {
if (!e) {
this._delCache(path, 0, 1, 2);
}
callback(e, json);
}
});
}
unlink(path, callback) {
return operationWrapper(this.rest, 'deleteFile', [path], (e, json) => {
if (e && e.statusCode === 404) {
this._delCache(path, 0, 1, 2);
// Mask out the error, and forge a fake response.
callback(null, {
result: {
status: 'SUCCESS',
},
});
} else {
if (!e) {
this._delCache(path, 0, 1, 2);
}
callback(e, json);
}
});
}
mkdir(path, callback) {
return operationWrapper(this.rest, 'mkdir', [path], (e, json) => {
if (!e) {
this._addCache(json.path, json, 2);
}
callback(e, json);
});
}
copy(src, dst, callback) {
// Because this is an operation, the JSON indicates the status of
// the operation, but does not return the dst object. Therefore
// we cannot "prime" the cache.
// However, we can evict the destination. I think it is safe to assume
// that dst is a directory (not the full path including file name).
const dstPath = pathlib.join(dst, pathlib.basename(src));
this._delCache(dstPath, 0, 1, 2);
return operationWrapper(this.rest, 'copy', [src, dst], callback);
}
copyFile(...args) {
return this.copy(...args);
}
copyDir(...args) {
return this.copy(...args);
}
move(src, dst, callback) {
// Because this is an operation, the JSON indicates the status of
// the operation, but does not return the dst object. Therefore
// we cannot "prime" the cache.
// However, we can evict the destination. I think it is safe to assume
// that dst is a directory (not the full path including file name).
const dstPath = pathlib.join(dst, pathlib.basename(src));
this._delCache(dstPath, 0, 1, 2);
return operationWrapper(this.rest, 'move', [src, dst], callback);
}
rename(src, dst, callback) {
return operationWrapper(this.rest, 'rename', [src, dst], (e, json) => {
if (e) {
callback(e);
return;
}
// Cache the item at cache level 2.
this._addCache(json.path, json, 2);
this._delCache(src, 0, 1, 2);
callback(null, json);
});
}
exists(path, callback) {
this.stat(path, (e) => {
if (e && e.statusCode === 404) {
// Does not exist.
callback(null, false);
} else if (e) {
// Some other error.
callback(e);
} else {
// Does exist.
callback(null, true);
}
});
}
createReadStream(path, _options, _callback) {
// https://nodejs.org/api/fs.html#fs_fs_createreadstream_path_options
// NOTE: I have to deviate from the fs module here and use a callback.
let options;
let callback;
if (typeof _options === 'function') {
// options omitted, shift.
callback = _options;
options = {};
} else {
callback = _callback;
options = _options;
}
if (typeof callback !== 'function') {
throw new Error('Return value of createReadStream() is not a stream, use callback!');
}
if (options && options.offset) {
// transform fs-style options to HTTP options.
options.headers = { Range: `bytes=${options.offset}-` };
delete options.offset;
}
const end = OPERATION.startTimer({ opName: 'createReadStream' });
return this.rest.download(path, (e, res) => {
if (e) {
end({ status: 'error' });
} else {
res.once('end', () => end({ status: 'success' }));
}
callback(e, res);
}, options);
}
createWriteStream(path, _options, _callback) {
// https://nodejs.org/api/fs.html#fs_fs_createwritestream_path_options
let options;
let callback;
if (typeof _options === 'function') {
callback = _options;
options = {};
} else {
callback = _callback;
options = _options;
}
if (options && options.offset) {
options.headers = { Range: `bytes=${options.offset}-` };
delete options.offset;
if (options.timestamp) {
const ts = moment.unix(options.timestamp);
options.headers['If-Unmodified-Since'] = ts.format('ddd, d M YYYY HH:mm:ss GMT');
delete options.timestamp;
}
}
const end = OPERATION.startTimer({ opName: 'createWriteStream' });
return this.rest.upload(path, (e, json) => {
end({ status: (e) ? 'error' : 'success' });
if (!e && json) {
this._addCache(json.path, json, 2);
}
if (callback) {
callback(e, json);
}
}, options);
}
open(path, _flags, _mode, _callback) {
// https://nodejs.org/api/fs.html#fs_fs_open_path_flags_mode_callback
let file = null;
let callback;
const end = OPERATION.startTimer({ opName: 'open' });
// Shift arguments.
if (typeof _mode === 'function') {
callback = _mode;
} else {
callback = _callback;
}
const flags = _flags || 'r';
const accessType = ACCESS_FLAGS[flags];
try {
switch (accessType) {
/*
Not currently any special handling for read or write.
case ACCESS_READ:
file = new FileReader(this, path, flags, callback);
break;
case ACCESS_WRITE:
file = new FileWriter(this, path, flags, callback);
break;
*/
case ACCESS_READ:
case ACCESS_WRITE:
case ACCESS_ALLOWED:
file = new FileProxy(this, path, flags, accessType, callback);
break;
default:
throw new Error(`invalid flags: ${flags} (${accessType})`);
}
} catch (e) {
callback(e);
end({ status: 'error' });
return null;
}
end({ status: 'success' });
return file;
}
close(fd, callback) {
const file = this.fds[fd];
const end = OPERATION.startTimer({ opName: 'close' });
if (!file) {
callback(new Error(`invalid fd ${fd}`));
end({ status: 'error' });
return;
}
file.close((e, json) => {
if (!e) {
this._addCache(json.path, json, 2);
}
callback(e, json);
});
end({ status: 'success' });
}
fstat(fd, callback) {
const file = this.fds[fd];
if (!file) {
callback(new Error(`invalid fd ${fd}`));
return;
}
this.stat(file.path, callback);
}
read(fd, buffer, offset, length, position, callback) {
// https://nodejs.org/api/fs.html#fs_fs_read_fd_buffer_offset_length_position_callback
const file = this.fds[fd];
const end = OPERATION.startTimer({ opName: 'read' });
if (!file) {
callback(new Error(`invalid fd ${fd}`));
end({ status: 'error' });
return;
}
file.read(buffer, offset, length, position, callback);
end({ status: 'success' });
}
readFile(path, _options, _callback) {
// https://nodejs.org/api/fs.html#fs_fs_readfile_path_options_callback
let buffer = Buffer.alloc(0);
let pos = 0;
let callback;
const end = OPERATION.startTimer({ opName: 'readFile' });
// Shift arguments.
if (typeof _options === 'function') {
callback = _options;
} else {
callback = _callback;
}
this.open(path, 'r', null, (openError, fd) => {
if (openError) {
callback(openError);
end({ status: 'error' });
return;
}
const readChunk = () => {
const chunk = Buffer.alloc(16384);
this.read(fd, chunk, 0, 16384, pos, (readError, bytesRead) => {
if (readError) {
end({ status: 'error' });
callback(readError);
return;
}
if (bytesRead === 0) {
end({ status: 'success' });
callback(null, buffer.subarray(0, pos));
return;
}
pos += bytesRead;
buffer = Buffer.concat([buffer, chunk]);
process.nextTick(readChunk);
});
};
process.nextTick(readChunk);
});
}
write(fd, buffer, offset, length, position, callback) {
// https://nodejs.org/api/fs.html#fs_fs_write_fd_buffer_offset_length_position_callback
// https://nodejs.org/api/fs.html#fs_fs_write_fd_string_position_encoding_callback
const file = this.fds[fd];
const end = OPERATION.startTimer({ opName: 'write' });
if (!file) {
callback(new Error(`invalid fd ${fd}`));
end({ status: 'error' });
return;
}
file.write(buffer, offset, length, position, callback);
end({ status: 'success' });
}
writeFile(path, buffer, _options, _callback) {
// https://nodejs.org/api/fs.html#fs_fs_writefile_file_data_options_callback
let pos = 0;
let callback;
const end = OPERATION.startTimer({ opName: 'writeFile' });
// Shift arguments.
if (typeof _options === 'function') {
callback = _options;
} else {
callback = _callback;
}
this.open(path, 'w', null, (openError, fd) => {
if (openError) {
callback(openError);
end({ status: 'error' });
return;
}
const writeChunk = () => {
this.write(fd, buffer, pos, buffer.byteLength, pos, (writeError, bytesWritten) => {
if (writeError) {
callback(writeError);
end({ status: 'error' });
return;
}
pos += bytesWritten;
if (pos === buffer.byteLength) {
this.close(fd, (closeError, json) => {
end({ status: 'success' });
this._addCache(json.path, json, 2);
callback(closeError, json);
});
return;
}
process.nextTick(writeChunk);
});
};
process.nextTick(writeChunk);
});
}
readdir(path, callback, opts) {
const reqOptions = {
...{
incremental: false,
qs: {
children: true,
limit: (opts && opts.limit) || 100,
},
},
...opts,
};
// https://nodejs.org/api/fs.html#fs_fs_readdir_path_options_callback
this.readdirstats(path, (e, infos) => {
if (e) {
callback(e);
return;
}
const names = [];
if (infos) {
for (let i = 0; i < infos.length; i++) {
names[i] = infos[i].name;
}
}
callback(null, names);
}, reqOptions);
}
readdirstats(path, callback, opts) {
const end = OPERATION.startTimer({ opName: 'readdirstats' });
const reqOptions = {
...{
incremental: (opts && opts.incremental) || false,
qs: {
children: true,
limit: (opts && opts.limit) || 100,
...(opts.fields && { fields: opts.fields }),
},
},
};
// Buffer when not incremental.
const infos = reqOptions.incremental ? null : [];
this._clearCache(0, 1);
// Make API call.
this.rest.info(path, (e, page, json) => {
if (e) {
callback(e);
end({ status: 'error' });
return;
}
if (json) {
// Don't modify the original.
const jsonClone = JSON.parse(JSON.stringify(json));
// Remove some stuff that we don't want in cache.
['children', 'total', 'pages', 'page', 'per_page'].forEach((key) => {
// eslint-disable-next-line no-param-reassign
delete jsonClone[key];
});
this._addCache(jsonClone.path, jsonClone, 1, 2);
}
// Last page, call callback.
if (page === null) {
// Note that infos is null when incremental.
end({ status: 'success' });
callback(null, infos);
return;
}
// Cache page of results.
for (let i = 0; i < page.length; i++) {
if (!reqOptions.incremental) {
infos.push(page[i]);
}
this._addCache(page[i].path, page[i], 1, 2);
}
if (reqOptions.incremental) {
callback(null, page);
}
}, reqOptions);
}
} |
JavaScript | class LinkLayer extends Duplex {
/**
* Create a new object LinkLayer
* @throws {error}
* @param {object} opts
* @param {stream} opts.stream
* @param {number} opts.timeOut
* @param {number} opts.retryTimes
* @param {boolean} opts.rawData
* @param {boolean} opts.disableMidParsing
*/
constructor(opts) {
opts = opts || {};
opts.readableObjectMode = true;
opts.writableObjectMode = true;
super(opts);
if (opts.stream === undefined) {
throw new Error("[LinkLayer] Socket is undefined");
}
//Create instances of manipulators
this.opParser = new OpenProtocolParser({
rawData: opts.rawData
});
this.opSerializer = new OpenProtocolSerializer();
this.midParser = new MIDParser();
this.midSerializer = new MIDSerializer();
//Create instances of manipulators
this.stream = opts.stream;
this.timeOut = opts.timeOut || 3000;
this.retryTimes = opts.retryTimes || 3;
//Raw Data
this.rawData = opts.rawData || false;
//Disable MID Parsing
this.disableMidParsing = opts.disableMidParsing || {};
this.linkLayerActive = false;
this.partsOfMessage = [];
this.receiverMessageInParts = 0;
this.numberMessageReceived = 1;
this.lastMessageReceived = {
mid: 0,
sequenceNumber: 0
};
this.stream.pause();
//Errors
this.midSerializer.on("error", (err) => this._onErrorSerializer(err));
this.opSerializer.on("error", (err) => this._onErrorSerializer(err));
//TODO
//Verificar outra tratativa
this.opParser.on("error", (err) => this._onErrorParser(err));
this.midParser.on("error", (err) => this._onErrorParser(err));
//Errors
//SEND DATA
this.midSerializer.on("data", (data) => this._onDataMidSerializer(data));
this.opSerializer.on("data", (data) => this._onDataOpSerializer(data));
//SEND DATA
//RECEIVER DATA
this.stream.on("data", (data) => this._onDataStream(data));
this.opParser.on("data", (data) => this._onDataOpParser(data));
this.midParser.on("data", (data) => this._onDataMidParser(data));
//RECEIVER DATA
}
_onErrorSerializer(err) {
if (this.linkLayerActive) {
this.sequenceNumber--;
}
if (this.callbackWrite) {
function doCallback(cb) {
process.nextTick(() => cb());
}
doCallback(this.callbackWrite);
this.callbackWrite = undefined;
}
this.emit("errorSerializer", err);
return;
}
_onErrorParser(err) {
this.emit("error", err);
return;
}
_onDataMidSerializer(data) {
if (data.mid !== NEGATIVE_ACK && data.mid !== POSITIVE_ACK && !data.isAck) {
clearTimeout(this.timer);
this.timer = setTimeout(() => this._resendMid(), this.timeOut);
}
this.messageParts = 0;
let length = data.payload.length;
//Multi Parts
if (length > 9979) {
let msgPart = 1;
let parts = length / 9979;
parts = Math.ceil(parts);
data.messageParts = parts;
this.messageParts = parts;
if (parts > 9) {
this.emit("error", new Error(`[LinkLayer] number of messages > 9, MID[${data.mid}], length buffer [${length}]`));
return;
}
let fullPayload = data.payload;
while (fullPayload.length > 0) {
if (fullPayload.length > 9979) {
data.payload = fullPayload.slice(0, 9979);
fullPayload = fullPayload.slice(9979);
} else {
data.payload = fullPayload;
fullPayload = Buffer.from("");
}
data.messageNumber = msgPart;
msgPart += 1;
this.message = data;
this.opSerializer.write(data);
}
return;
}
if (data.mid !== POSITIVE_ACK && data.mid !== NEGATIVE_ACK && !data.isAck) {
this.message = data;
}
this.opSerializer.write(data);
}
_onDataOpSerializer(data) {
this.stream.write(data);
}
_onDataStream(data) {
this.opParser.write(data);
}
_onDataOpParser(data) {
let duplicateMsg = false;
if (this.linkLayerActive) {
if (this.lastMessageReceived.mid === data.mid && this.lastMessageReceived.sequenceNumber === data.sequenceNumber) {
duplicateMsg = true;
this.sequenceNumberPartner -= 1;
}
}
if (data.messageParts !== 0 || this.receiverMessageInParts !== 0) {
this.receiverMessageInParts = data.messageParts;
if (data.messageNumber !== this.numberMessageReceived) {
if (this.linkLayerActive) {
this._sendLinkLayer(NEGATIVE_ACK, data.sequenceNumber, {
midNumber: data.mid,
errorCode: constants.ERROR_LINKLAYER.INCONSISTENCY_MESSAGE_NUMBER
});
}
this.emit("error", new Error(`[LinkLayer] inconsistency message number, MID[${data.mid}]`));
return;
}
this.partsOfMessage.push(data.payload);
if (this.receiverMessageInParts === this.numberMessageReceived) {
data.payload = Buffer.concat(this.partsOfMessage);
this.receiverMessageInParts = 0;
this.numberMessageReceived = 1;
this.lastMessageReceived = data;
if (!duplicateMsg) {
if (this.disableMidParsing[data.mid] && (data.mid !== POSITIVE_ACK && data.mid !== NEGATIVE_ACK)) {
if (!this.push(data)) {
this.stream.pause();
return;
}
} else {
this.midParser.write(data);
}
}
return;
}
this.numberMessageReceived += 1;
return;
}
if (this.linkLayerActive) {
if (data.sequenceNumber !== 0) {
if (data.mid === POSITIVE_ACK || data.mid === NEGATIVE_ACK) {
if (data.sequenceNumber !== (this.sequenceNumber)) {
this.emit("error", new Error(`[LinkLayer] sequence number invalid, MID[${data.mid}], received[${data.sequenceNumber}], expected[${this.sequenceNumber}]`));
return;
}
} else {
if (this.sequenceNumberPartner) {
if (this.sequenceNumberPartner === 99) {
this.sequenceNumberPartner = 0;
}
if (data.sequenceNumber !== (this.sequenceNumberPartner + 1)) {
this._sendLinkLayer(NEGATIVE_ACK, data.sequenceNumber, {
midNumber: data.mid,
errorCode: constants.ERROR_LINKLAYER.INVALID_SEQUENCE_NUMBER
});
this.emit("error", new Error(`[LinkLayer] sequence number invalid, MID[${data.mid}]`));
return;
}
}
this.sequenceNumberPartner = data.sequenceNumber;
this._sendLinkLayer(POSITIVE_ACK, data.sequenceNumber, {
midNumber: data.mid
});
}
}
}
this.lastMessageReceived = data;
if (!duplicateMsg) {
if (this.disableMidParsing[data.mid] && (data.mid !== POSITIVE_ACK && data.mid !== NEGATIVE_ACK)) {
if (!this.push(data)) {
this.stream.pause();
return;
}
} else {
this.midParser.write(data);
}
}
}
_onDataMidParser(data) {
clearTimeout(this.timer);
if (data.mid === POSITIVE_ACK || data.mid === NEGATIVE_ACK) {
this._receiverLinkLayer(data);
return;
}
if (!this.push(data)) {
this.stream.pause();
return;
}
}
_write(msg, encoding, callback) {
this.callbackWrite = callback;
this.resentTimes = 0;
if (this.linkLayerActive) {
msg.sequenceNumber = this.sequenceNumber;
this.sequenceNumber += 1;
if (this.sequenceNumber > 99) {
this.sequenceNumber = 1;
}
}
// if this is an ack, callback immediately
if (msg.isAck) {
clearTimeout(this.timer);
process.nextTick(() => {
this.callbackWrite = null;
callback();
});
}
this.midSerializer.write(msg);
}
_read(size) {
if (this.stream.isPaused()) {
this.stream.resume();
}
}
_destroy() {
clearTimeout(this.timer);
function destroyStream(stream){
// handles Node versions older than 8.x
if (typeof stream.destroy === 'function') {
stream.destroy();
} else {
stream._destroy();
}
}
destroyStream(this.opParser);
destroyStream(this.opSerializer);
destroyStream(this.midParser);
destroyStream(this.midSerializer);
}
finishCycle(err) {
if (this.callbackWrite) {
this.callbackWrite(err);
this.callbackWrite = undefined;
}
}
/**
* Enable LinkLayer
*/
activateLinkLayer() {
this.linkLayerActive = true;
this.sequenceNumber = 1;
}
/**
* Disable LinkLayer
*/
deactivateLinkLayer() {
this.linkLayerActive = false;
clearTimeout(this.timer);
}
/**
* @private
* @param {*} data
*/
_receiverLinkLayer(data) {
clearTimeout(this.timer);
if (data.mid === NEGATIVE_ACK || data.payload.midNumber !== this.message.mid || data.sequenceNumber !== this.sequenceNumber) {
let err = new Error(`incorrect fields of MID, MID[${data.payload.midNumber}] - Error code [${data.payload.errorCode}] -` +
` Expect MID[${this.message.mid}] - Expect SequenceNumber [${this.sequenceNumber}] - Current SequenceNumber [${data.sequenceNumber}]`);
if (this.callbackWrite) {
function doCallback(cb, err) {
process.nextTick(() => cb(err));
}
doCallback(this.callbackWrite, err);
this.callbackWrite = undefined;
} else {
this.emit("error", err);
}
return;
}
this.message = {};
if (this.callbackWrite) {
function doCallback(cb) {
process.nextTick(() => cb());
}
doCallback(this.callbackWrite);
this.callbackWrite = undefined;
}
}
/**
* @private
* @param {*} mid
* @param {*} sequenceNumber
* @param {*} payload
*/
_sendLinkLayer(mid, sequenceNumber, payload) {
if (sequenceNumber === 99) {
sequenceNumber = 0;
}
let msg = {
mid: mid,
sequenceNumber: (sequenceNumber + 1),
payload
};
this.midSerializer.write(msg);
}
/**
* @private
*/
_resendMid() {
clearTimeout(this.timer);
if (this.resentTimes < this.retryTimes) {
this.timer = setTimeout(() => this._resendMid(), this.timeOut);
this.opSerializer.write(this.message);
this.resentTimes += 1;
} else {
let err = new Error(`[LinkLayer] timeout send MID[${this.message.mid}]`);
this.resentTimes = 0;
if (this.callbackWrite) {
function doCallback(cb, err) {
process.nextTick(() => cb(err));
}
doCallback(this.callbackWrite, err);
this.callbackWrite = undefined;
} else {
this.emit("error", err);
}
}
}
} |
JavaScript | class FervieSitSprite {
constructor(animationLoader, size) {
this.animationLoader = animationLoader;
this.size = size;
this.animationFrame = 1;
this.isVisible = true;
}
static UNSCALED_IMAGE_WIDTH = 543;
static UNSCALED_IMAGE_HEIGHT = 443;
/**
* Preload the fervie sit image colored with the configured fervie colors
* @param p5
*/
preload(p5) {
this.animationLoader.getAnimationImageWithManualFrame(p5, AnimationId.Animation.FervieWalkUp, 1, this.size);
}
/**
* Draw the sitting fervie sprite on the screen based on the properties
* @param p5
* @param x
* @param y
* @param scale
*/
draw(p5, x, y, scale) {
let image = this.animationLoader.getAnimationImageWithManualFrame(p5, AnimationId.Animation.FervieWalkUp, 1, this.size);
p5.push();
p5.translate(x + Math.round((this.size/2) * (1 - scale)), y + (120 * scale));
p5.scale(scale, scale);
p5.image(image, 0, 0);
p5.pop();
}
/**
* Update the fervie
*/
update(p5, environment) {
}
} |
JavaScript | class EmptyCart extends PureComponent {
/**
* @param {HTMLElement} root The root element for which the component will be rendered.
*/
constructor(root) {
super(root);
super.render(EmptyCartTemplate());
}
} |
JavaScript | class Node {
constructor(data) {
this.data = data;
this.left = null;
this.right = null;
}
} |
JavaScript | class AreObjectIdsEqual extends AsyncObject {
constructor(objectId, otherId) {
super(objectId, otherId);
}
definedSyncCall() {
return (objectId, otherId) => {
return objectId.equals(otherId);
}
}
} |
JavaScript | class CallList extends Component {
setVisible = () => {
this.props.setMainVisible();
};
render() {
return (
<aside className="sidebar">
<div className="tab-content">
<div className="tab-pane active" id="calls-content">
<div className="d-flex flex-column h-100">
<div className="hide-scrollbar h-100" id="callContactsList">
<div className="sidebar-header sticky-top p-2">
<div className="d-flex justify-content-between align-items-center">
<h5 className="font-weight-semibold mb-0">Calls</h5>
<ChatAction />
</div>
<ChatFilter />
</div>
<ul className="contacts-list" id="callLogTab" data-call-list="">
<li className="contacts-item incoming active">
<Link
to="#"
className="media-link"
onClick={this.setVisible}
></Link>
<div className="contacts-link">
<div className="avatar">
<img src={avatar2} alt=""></img>
</div>
<div className="contacts-content">
<div className="contacts-info">
<h6 className="chat-name text-truncate">
Catherine Richardson
</h6>
</div>
<div className="contacts-texts">
<MissedCallSvg className="hw-16 text-muted mr-1" />
<p className="text-muted mb-0">Just now</p>
</div>
</div>
<div className="contacts-action">
<button
className="btn btn-secondary btn-icon btn-minimal btn-sm text-muted"
type="button"
>
<CallsSvg className="hw-20" />
</button>
</div>
</div>
</li>
<li className="contacts-item outgoing">
<Link to="#" className="media-link"></Link>
<div className="contacts-link outgoing">
<div className="avatar bg-info text-light">
<span>EW</span>
</div>
<div className="contacts-content">
<div className="contacts-info">
<h6 className="chat-name text-truncate">
Eva Walker
</h6>
</div>
<div className="contacts-texts">
<PhoneOutgoingSvg className="hw-16 text-muted mr-1" />
<p className="text-muted mb-0">5 mins ago</p>
</div>
</div>
<div className="contacts-action">
<button
className="btn btn-secondary btn-icon btn-minimal btn-sm text-muted"
type="button"
>
<CallNowSvg />
</button>
</div>
</div>
</li>
<li className="contacts-item missed">
<Link to="#" className="media-link"></Link>
<div className="contacts-link missed">
<div className="avatar">
<img src={avatar3} alt=""></img>
</div>
<div className="contacts-content">
<div className="contacts-info">
<h6 className="chat-name text-truncate">
Christopher Garcia
</h6>
</div>
<div className="contacts-texts">
<MissedCallSvg className="hw-16 text-danger mr-1" />
<p className="text-danger mb-0">20 mins ago</p>
</div>
</div>
<div className="contacts-action">
<button
className="btn btn-secondary btn-icon btn-minimal btn-sm text-muted"
type="button"
>
<CallNowSvg />
</button>
</div>
</div>
</li>
<li className="contacts-item outgoing">
<Link to="#" className="media-link"></Link>
<div className="contacts-link outgoing">
<div className="avatar">
<img src={avatar4} alt=""></img>
</div>
<div className="contacts-content">
<div className="contacts-info">
<h6 className="chat-name text-truncate">
Christina Turner
</h6>
</div>
<div className="contacts-texts">
<PhoneOutgoingSvg className="hw-16 text-muted mr-1" />
<p className="text-muted mb-0">4 hour ago</p>
</div>
</div>
<div className="contacts-action">
<button
className="btn btn-secondary btn-icon btn-minimal btn-sm text-muted"
type="button"
>
<CallNowSvg />
</button>
</div>
</div>
</li>
<li className="contacts-item incoming">
<Link to="#" className="media-link"></Link>
<div className="contacts-link incoming">
<div className="avatar">
<img src={avatar5} alt=""></img>
</div>
<div className="contacts-content">
<div className="contacts-info">
<h6 className="chat-name text-truncate">
Tammy Martinez
</h6>
</div>
<div className="contacts-texts">
<PhoneIncomingSvg />
<p className="text-muted mb-0">Yesterday</p>
</div>
</div>
<div className="contacts-action">
<button
className="btn btn-secondary btn-icon btn-minimal btn-sm text-muted"
type="button"
>
<CallNowSvg />
</button>
</div>
</div>
</li>
<li className="contacts-item incoming">
<Link to="#" className="media-link"></Link>
<div className="contacts-link incoming">
<div className="avatar">
<img src={avatar6} alt=""></img>
</div>
<div className="contacts-content">
<div className="contacts-info">
<h6 className="chat-name text-truncate">
Bonnie Torres
</h6>
</div>
<div className="contacts-texts">
<PhoneIncomingSvg />
<p className="text-muted mb-0">12/06/2020</p>
</div>
</div>
<div className="contacts-action">
<button
className="btn btn-secondary btn-icon btn-minimal btn-sm text-muted"
type="button"
>
<CallNowSvg />
</button>
</div>
</div>
</li>
<li className="contacts-item outgoing">
<Link to="#" className="media-link"></Link>
<div className="contacts-link outgoing">
<div className="avatar">
<img src={avatar7} alt=""></img>
</div>
<div className="contacts-content">
<div className="contacts-info">
<h6 className="chat-name text-truncate">
Jacqueline James
</h6>
</div>
<div className="contacts-texts">
<PhoneOutgoingSvg />
<p className="text-muted mb-0">16/05/2020</p>
</div>
</div>
<div className="contacts-action">
<button
className="btn btn-secondary btn-icon btn-minimal btn-sm text-muted"
type="button"
>
<CallNowSvg />
</button>
</div>
</div>
</li>
</ul>
</div>
</div>
</div>
</div>
</aside>
);
}
} |
JavaScript | class FieldValidation extends React.Component {
constructor(props) {
super(props);
}
componentDidMount() {
if (!this.props.validation || !this.props.name) return;
this.subscription = this.props.validation.on(this.props.name).subscribe(() => {
if (this._componentUnmounted) return;
this.forceUpdate();
});
}
componentWillUnmount() {
this._componentUnmounted = true;
if (this.subscription)
this.subscription.unsubscribe();
}
render() {
let { validation, always, rule, rules, dirty, children, ...rest } = this.props;
if (!this.props.name || !validation || (!always && !validation.dirty)) return null;
let hasError = false;
if (rule || !rules) {
hasError = validation.hasError(this.props.name, rule, dirty);
}
else if (rules && rules.length) {
for (let ruleName of rules) {
rule = ruleName;
hasError = validation.hasError(this.props.name, rule, dirty);
if (hasError) break;
}
}
if (!hasError) return null;
let message = (children && React.Children.count(children) > 0) ? children : null;
if (!message) {
let state = validation.getState(this.props.name);
if (state.errors) {
if (rule && state.errors[rule]) {
message = state.errors[rule].message || '';
}
else if (rules && rules.length) {
for (let ruleName of rules) {
if (state.errors[ruleName]) {
message = state.errors[ruleName].message || '';
break;
}
}
}
if (!message) {
for (let ruleName in state.errors) {
message = state.errors[ruleName].message || '';
break;
}
}
}
}
if (typeof message === "function") message = message();
return React.createElement('div', rest, message);
}
} |
JavaScript | class Release {
constructor() {
/**
* @inheritDoc
*/
this.name = Release.id;
}
/**
* @inheritDoc
*/
setupOnce() {
addGlobalEventProcessor((event) => __awaiter(this, void 0, void 0, function* () {
var _a, _b, _c;
const self = getCurrentHub().getIntegration(Release);
if (!self) {
return event;
}
const options = (_a = getCurrentHub().getClient()) === null || _a === void 0 ? void 0 : _a.getOptions();
/*
__sentry_release and __sentry_dist is set by the user with setRelease and setDist. If this is used then this is the strongest.
Otherwise we check for the release and dist in the options passed on init, as this is stronger than the release/dist from the native build.
*/
if (typeof ((_b = event.extra) === null || _b === void 0 ? void 0 : _b.__sentry_release) === "string") {
event.release = `${event.extra.__sentry_release}`;
}
else if (typeof (options === null || options === void 0 ? void 0 : options.release) === "string") {
event.release = options.release;
}
if (typeof ((_c = event.extra) === null || _c === void 0 ? void 0 : _c.__sentry_dist) === "string") {
event.dist = `${event.extra.__sentry_dist}`;
}
else if (typeof (options === null || options === void 0 ? void 0 : options.dist) === "string") {
event.dist = options.dist;
}
if (event.release && event.dist) {
return event;
}
try {
const release = yield NATIVE.fetchRelease();
if (release) {
event.release = `${release.id}@${release.version}+${release.build}`;
event.dist = `${release.build}`;
}
}
catch (_Oo) {
// Something went wrong, we just continue
}
return event;
}));
}
} |
JavaScript | class OrchestraBBcodePlugin
{
/**
* Init plugin
* @param {Editor} editor
*/
init(editor) {
editor.on('submit', (e) => {
editor.setContent(this.html2bbcode(e.getContent()));
editor.save();
});
}
/**
* Information plugin
*/
getInfo(){
return {
longname: 'Orchestra BBCode Plugin',
author: 'open orchestra',
infourl: 'www.open-orchestra.com'
};
}
/**
* Convert Html to BBcode
* @param {String} string
*/
html2bbcode(string){
let transformerList = BBcodeTransformerManager.getHtmlToBbcodeTransformer();
string = tinymce.trim(string);
$.each(transformerList, (regex, stringReplace) => {
string = string.replace(new RegExp(regex,'gi'), stringReplace);
});
return string;
}
} |
JavaScript | class ContentEditable extends Component {
@service() features;
/**
* latest cursor position in the contenteditable, it is aliased to the rawEditor.currentSelection
*
* @property currentSelection
* @type Array
*
* @private
*/
@alias('rawEditor.currentSelection')
currentSelection;
/**
* latest text content in the contenteditable, it is aliased to the rawEditor.currentTextContent
*
*
* @property currentTextContent
* @type String
*
* @private
*/
@alias('rawEditor.currentTextContent')
currentTextContent;
/**
* element of the component, it is aliased to the rawEditor.rootNode
*
* @property element
* @type DOMElement
*
* @private
*/
rootNode = null;
/**
* string representation of editable
*
* @property isEditable
* @type string
* @private
*/
@computed('editable')
get isEditable() {
return this.get('editable').toString();
}
/**
* richNode is the rich representation of the component element,
* it is aliased to the rawEditor.richNode
*
* @property richNode
* @type RichNode
* @private
*/
@alias('rawEditor.richNode')
richNode;
/**
*
* @property rawEditor
* @type RawEditor
*/
rawEditor = null;
/**
* components present in the editor
* @property components
* @type {Object}
* @public
*/
@alias('rawEditor.components')
components;
/**
* ordered set of input handlers
* @property eventHandlers
* @type Array
* @public
*/
@union('externalHandlers', 'defaultHandlers')
inputHandlers;
/**
* default input handlers
* @property defaultHandlers
* @type Array
* @private
*/
defaultHandlers = null;
/**
* external input handlersg
* @property externalHandlers
* @type Array
* @private
*/
externalHandlers = null;
/**
* @constructor
*/
init() {
super.init(...arguments);
const rawEditor = RawEditor.create({
handleFullContentUpdate: this.get('handleFullContentUpdate'),
textInsert: this.get('textInsert'),
textRemove: this.get('textRemove'),
selectionUpdate: this.get('selectionUpdate'),
elementUpdate: this.get('elementUpdate')
});
this.set('rawEditor', rawEditor);
const defaultInputHandlers = [ ArrowHandler.create({rawEditor}),
HeaderMarkdownHandler.create({rawEditor}),
// EmphasisMarkdownHandler.create({rawEditor}),
// ListInsertionMarkdownHandler.create({rawEditor}),
ClickHandler.create({rawEditor}),
EnterHandler.create({rawEditor}),
BackspaceHandler.create({rawEditor}),
TextInputHandler.create({rawEditor}),
TabHandler.create({rawEditor}),
IgnoreModifiersHandler.create({rawEditor})];
this.set('currentTextContent', '');
this.set('currentSelection', [0,0]);
this.set('defaultHandlers', defaultInputHandlers);
this.set('capturedEvents', A());
if( ! this.externalHandlers ) {
this.set('externalHandlers', []);
}
}
didUpdateAttrs() {
this.rawEditor.set('textInsert',this.textInsert);
this.rawEditor.set('textRemove',this.textRemove);
this.rawEditor.set('handleFullContentUpdate',this.handleFullContentUpdate);
this.rawEditor.set('selectionUpdate',this.selectionUpdate);
this.rawEditor.set('elementUpdate',this.elementUpdate);
this.rawEditor.set('handleFullContentUpdate',this.handleFullContentUpdate);
}
/**
* specify whether the editor should autofocus the contenteditable field
*
* @property focused
* @type boolean
* @default false
*
* @public
*/
focused = false;
/**
* specify whether the editor should be contenteditable
*
* @property editable
* @type boolean
* @default true
*
* @public
*/
editable = true;
/**
* specify whether yielded value should escape html syntax
*
* @property yieldHTML
* @type boolean
* @default true
*
* @public
*/
yieldHTML = true;
/**
* didRender hook, makes sure the element is focused
* and calls the rootNodeUpdated action
*
* @method didRender
*/
didInsertElement() {
super.didInsertElement(...arguments);
this.set('rawEditor.rootNode', this.get('element'));
let el = this.get('element');
// TODO: mapping using customEvents currently doesn't work, remove when it does
el.onpaste = (event) => this.paste(event);
if (this.get('focused'))
el.focus();
this.set('rawEditor.currentNode', this.rawEditor.rootNode);
forgivingAction('rawEditorInit', this)(this.get('rawEditor'));
next( () => {
forgivingAction('elementUpdate', this)();
this.get('rawEditor').generateDiffEvents.perform();
this.extractAndInsertComponents();
this.get('rawEditor').updateRichNode();
});
}
/**
* willDestroyElement, calls the rootNodeUpdated action
*
* @method willDestroyElement
*
*/
willDestroyElement() {
this.set('richNode', null);
this.set('rawEditor.rootNode', null);
forgivingAction('elementUpdate', this)();
}
/**
* keyDown events are handled for simple input we take over from
* browser input.
*/
keyDown(event) {
event = normalizeEvent(event);
if (this.isHandledInputEvent(event)) {
if (this.isCtrlZ(event)) {
event.preventDefault();
this.get('rawEditor').undo();
}
else {
let handlers = this.get('inputHandlers').filter(h => h.isHandlerFor(event));
try {
handlers.some( handler => {
let response = handler.handleEvent(event);
if (!response.get('allowBrowserDefault'))
event.preventDefault();
if (!response.get('allowPropagation'))
return true;
return false;
});
}
catch(e) {
warn(`handler failure`, {id: 'contenteditable.keydown.handler'});
warn(e, {id: 'contenteditable.keydown.handler'});
}
}
this.get('rawEditor').updateRichNode();
this.get('rawEditor').generateDiffEvents.perform();
this.capturedEvents.pushObject(event); // TODO: figure this out again
}
else {
runInDebug( () => {
console.warn('unhandled keydown', event); //eslint-disable-line no-console
});
}
this.lastKeyDown = event;
}
/**
* currently we disable paste
*/
paste(event) {
// see https://www.w3.org/TR/clipboard-apis/#paste-action for more info
if (this.features.isEnabled('editor-html-paste')) {
try {
const inputParser = new HTMLInputParser({});
const htmlPaste = (event.clipboardData || window.clipboardData).getData('text/html');
const cleanHTML = inputParser.cleanupHTML(htmlPaste);
const sel = this.rawEditor.selectHighlight(this.rawEditor.currentSelection);
this.rawEditor.update(sel, {set: { innerHTML: cleanHTML}});
}
catch(e) {
// fall back to text pasting
console.warn(e);
const text = (event.clipboardData || window.clipboardData).getData('text');
const sel = this.rawEditor.selectHighlight(this.rawEditor.currentSelection);
this.rawEditor.update(sel, {set: { innerHTML: text}});
}
}
else {
const text = (event.clipboardData || window.clipboardData).getData('text');
const sel = this.rawEditor.selectHighlight(this.rawEditor.currentSelection);
this.rawEditor.update(sel, {set: { innerHTML: text}});
}
event.preventDefault();
return false;
}
/**
* keyUp events are parsed for complex input, for uncaptured events we update
* the internal state to be inline with reality
*/
keyUp(event) {
this.handleUncapturedEvent(event);
}
/**
* compositionEnd events are parsed for complex input, for uncaptured events we update
* the internal state to be inline with reality
*/
compositionEnd(event) {
this.handleUncapturedEvent(event);
}
mouseUp(event) {
this.get('rawEditor').updateRichNode();
this.get('rawEditor').updateSelectionAfterComplexInput(event);
this.get('rawEditor').generateDiffEvents.perform();
}
mouseDown(event){
event = normalizeEvent(event);
// TODO: merge handling flow
if (!this.isHandledInputEvent(event)) {
runInDebug( () => {
console.warn('unhandled mouseDown', event); //eslint-disable-line no-console
});
}
else {
let handlers = this.get('inputHandlers').filter(h => h.isHandlerFor(event));
try {
for(let handler of handlers){
let response = handler.handleEvent(event);
if (!response.get('allowBrowserDefault'))
event.preventDefault();
if (!response.get('allowPropagation'))
break;
}
}
catch(e){
warn(`handler failure`, {id: 'contenteditable.mousedown.handler'});
warn(e, {id: 'contenteditable.mousedown.handler'});
}
}
this.get('rawEditor').updateRichNode();
this.get('rawEditor').generateDiffEvents.perform();
}
handleUncapturedEvent(event) {
event = normalizeEvent(event);
if (isEmpty(this.capturedEvents) || this.capturedEvents[0].key !== event.key || this.capturedEvents[0].target !== event.target) {
this.set('capturedEvents', A()); // TODO: added this because tracking of captured events is broken, fix it
this.get('rawEditor').externalDomUpdate('uncaptured input event', () => {});
}
else {
this.capturedEvents.shiftObject();
}
this.performBrutalRepositioningForLumpNode(this.lastKeyDown);
}
/**
* find defined components, and recreate them
*/
extractAndInsertComponents() {
for (let element of this.get('element').querySelectorAll('[data-contenteditable-cw-id]')) {
let name = element.getAttribute('data-contenteditable-cw-name');
let content = JSON.parse(element.getAttribute('data-contenteditable-cw-content'));
let id = element.getAttribute('data-contenteditable-cw-id');
let parent = element.parentNode;
parent.innerHTML = '';
this.rawEditor.insertComponent(parent, name, content, id);
}
}
/**
* specifies whether an input event is "simple" or not
* simple events can be translated to a increment of the cursor position
*
* @method isSimpleTextInputEvent
* @param {DOMEvent} event
*
* @return {Boolean}
* @private
*/
isHandledInputEvent(event) {
event = normalizeEvent(event);
return this.isCtrlZ(event) || this.get('inputHandlers').filter(h => h.isHandlerFor(event)).length > 0;
}
isCtrlZ(event) {
return event.ctrlKey && event.key === 'z';
}
/**
* This is a brutal repositioning of the cursor where in ends up in forbidden zones.
* This is method exists because some elegant handling (ArrowUp,-Down, PageUp)
* When there are some extra rules of where the cursor should be placed in the DOM-tree, which is too complex
* for the current handlers, or not implemented yet in the handlers, this method is your last resort.
* It performs a rather brutal re-positioning, so this could have some funky effect for the users.
* Current implemenation only cares about situations where this repositioning would matter less to the user.
*/
performBrutalRepositioningForLumpNode(previousEvent){
const editor = this.rawEditor;
const textNode = editor.currentNode;
const rootNode = editor.rootNode;
if(! previousEvent || ! textNode) return;
//Handle the lumpNode (the 'lumpNode is lava!'-game) cases
let nextValidTextNode = null;
if(isInLumpNode(textNode, rootNode)){
const parentLumpNode = getParentLumpNode(textNode, rootNode);
animateLumpNode(parentLumpNode);
if(previousEvent.type === "keydown" && (previousEvent.key === 'ArrowUp' || previousEvent.key === 'PageUp')) {
nextValidTextNode = getPreviousNonLumpTextNode(textNode, rootNode);
editor.updateRichNode();
editor.setCarret(nextValidTextNode, nextValidTextNode.length);
}
else if(previousEvent.type === "keydown" && previousEvent.key === 'ArrowDown' || previousEvent.key === 'PageDown'){
nextValidTextNode = getNextNonLumpTextNode(textNode, rootNode);
editor.updateRichNode();
editor.setCarret(nextValidTextNode, 0);
}
}
}
@action
removeComponent(id) {
this.rawEditor.removeComponent(id);
}
} |
JavaScript | class DreamNew extends Component {
constructor(props) {
super(props);
this.state = { // what info is expected from a user
name: '',
description: ''
}
}
handleChange = e => {this.setState({[e.target.name]: e.target.value}); console.log(e.target.value)}
handleSubmit = e => {e.preventDefault(); this.props.addDream(this.state); this.props.history.push('/dreams')}
render() {
return ( // the form itself
<div className="new-dream">
<h2>Create an amazing new dream here</h2>
<form onSubmit={this.handleSubmit}>
<div>
<label htmlFor="nameInput">Dream's name: </label><br /><br />
<input type="text" name="name" id="name" value={this.state.name} onChange={this.handleChange} placeholder="Name your dream" required />
</div>
<br /><br /><br />
<div>
<label htmlFor="nameInput">Dream's details: </label><br /><br />
<textarea type="text" name="description" id="description" rows="10" cols="80" value={this.state.description} onChange={this.handleChange} placeholder="To fully enjoy your custom-made dream, please provide as many details as possible" required />
</div>
<br /><br /><br />
<div>
<input className="btn" type="submit" value="Create a new dream" />
</div>
</form>
</div>
)
}
} |
JavaScript | class AxisLeft {
constructor() {
}
} |
JavaScript | class ItemList extends Component {
constructor(props) {
super(props);
this.state = {
items: []
};
this.getItems = this.getItems.bind(this);
}
componentDidMount() {
this.getItems();
}
getItems() {
const category = this.props.navigation.state.params;
axios.get(`https://one-stop-shop-backend.herokuapp.com/categories/${category.id}`)
.then(response => {
this.setState({items: response.data})
})
.catch(error => {
console.log(error);
});
}
render() {
return (
<ScrollView style={{ backgroundColor: colors.background}}>
{this.state.items.map((item, idx) => (
<Item item={item} getItems={this.getItems} key={idx} />
))}
</ScrollView>
);
}
} |
JavaScript | class Translator {
constructor(naturalLanguageMap, inputStream) {
this.translatedTokens = [];
this.inputStream = inputStream;
this.languageMap = naturalLanguageMap;
this.javascriptCharacters = ['.', '(', ')', ':', ';', '{', '}', '[', ']', '*', '/', '-', '=', '+', '!', '@', '#', ' ', '\n', "'", '\'', '?', '<', '>', '^', '$', '&', ',', '_', '-'];
}
/**
* Indicates whether or not a token is a keyword to be translated or not. Keyword examples include:
* const, let, this, etc...
* @param {string} keyword - The token we want to determine if it is in the language map (i.e.
* if it is a keyword).
* @returns {bool} - True if the token is in the map. False otherwise.
*/
isKeyword(keyword) {
return keyword in this.languageMap.keywords;
}
/**
* Retrieves the translated keyword from the language map.
* @param {string} keyword - The keyword we are wanting to translate.
* @returns {string} - The translated keyword.
*/
translateKeyword(keyword) {
return this.languageMap.keywords[keyword];
}
/**
* Indicates whether or not a token is an api symbol to be translated or not. Api symbol examples include:
* console.log, Array.some, parseInt, etc...
* @param {string} apiSymbol - The token we want to determine if it is in the language map.
*/
isApiSymbol(apiSymbol) {
return apiSymbol in this.languageMap.apiSymbols;
}
/**
* Retrieves the translated api symbol from the language map.
* @param {string} apiSymbol - The apiSymbol we are wanting to translate.
* @returns {string} - The translated apiSymbol.
*/
translateApiSymbol(apiSymbol) {
return this.languageMap.apiSymbols[apiSymbol];
}
/**
* Tokenizes the input stream by converting a string into an array.
* @returns {Array} - The tokenized version of the input stream.
*/
tokenize() {
let buffer = '';
const tokens = [];
[...this.inputStream].forEach((character) => {
// Test to see if that character is in the character arrays.
if(this.javascriptCharacters.some(element => element === character)) {
if(buffer.length > 0) {
// Push the buffer
tokens.push(buffer);
// Push the current character
tokens.push(character);
// Clear the buffer
buffer = '';
} else {
tokens.push(character);
}
} else {
buffer += character;
}
});
return tokens;
}
/**
* Translates the token stream.
*/
translate() {
const tokens = this.tokenize();
let isEmbeddedInString = false;
tokens.forEach((currentToken) => {
// If we are in a string, we don't want to translate the text
if (currentToken === '"' || currentToken === '\'') {
this.translatedTokens.push(currentToken);
isEmbeddedInString = !isEmbeddedInString;
} else if (this.isKeyword(currentToken) && !isEmbeddedInString) { // We have a keyword
this.translatedTokens.push(this.translateKeyword(currentToken));
} else if (this.isApiSymbol(currentToken) && !isEmbeddedInString) { // We have an api symbol
this.translatedTokens.push(this.translateApiSymbol(currentToken));
} else { // It is literally any other token
this.translatedTokens.push(currentToken);
}
});
}
/**
* This is designed to be the public facing method to be consumed (besides the constructor)
* to translate the original input stream.
* @returns {string} - The string that is the translated file.
*/
getTranslatedFile() {
this.translate();
return this.translatedTokens.join('');
}
} |
JavaScript | class UserActivation {
constructor(definition, containingActivation, setOutput, functionArguments) {
this.definition = definition;
// sanity check containingActivation
if (containingActivation) {
assert(containingActivation.definition === definition.containingDefinition);
} else {
assert(!definition.containingDefinition);
}
if (containingActivation) {
containingActivation.activatedClosureOfContainedDefinition(this.definition, this);
}
this.containingActivation = containingActivation; // the activation of our containing definition, i.e. our lexical outer scope
this.setOutput = setOutput;
// Maps from OutPort and InPort objects to their corresponding Stream objects for this activation
this.outPortStream = new Map();
this.inPortStream = new Map();
this.evaluating = false;
this.priorityQueue = new PriorityQueue();
this.currentInstant = 1; // before pump this is next instant, during pump it's current instant
// Map from native applications (within this user-defined function) to their activation wrappers (NativeApplication -> ApplicationWrapper)
// We need this so that we can deactivate these activations if we remove the native application.
this.containedNativeApplicationActivationControl = new Map();
// Map from UserDefinition (contained by this activation's definition) to a Set of its activations scoped under this activation
this.containedDefinitionActivations = new Map();
// Create streams for "internal side" of function inputs and outputs
for (const outPort of definition.definitionInputs) {
const outStream = new Stream();
this.outPortStream.set(outPort, outStream);
}
if (definition.definitionOutput instanceof Map) {
for (const [n, inPort] of definition.definitionOutput) {
const inStream = new Stream();
this.inPortStream.set(inPort, inStream);
this._flowInPortFromOutside(inPort);
}
} else if (definition.definitionOutput) {
const inStream = new Stream();
this.inPortStream.set(definition.definitionOutput, inStream);
this._flowInPortFromOutside(definition.definitionOutput);
}
// Activate native applications (which will create streams, pulling in initial values if any).
// This needs to be done in topological sort order, but we keep them ordered so it's easy.
for (const napp of definition.nativeApplications) {
this._activateNativeApplication(napp);
}
}
evaluate(inputs = []) {
assert(inputs.length === this.definition.definitionInputs.length);
assert(!this.evaluating);
this.evaluating = true;
for (let i = 0; i < inputs.length; i++) {
const outPort = this.definition.definitionInputs[i];
const outStream = this.outPortStream.get(outPort);
const v = inputs[i];
if (outPort.tempo === 'step') {
if (v.changed) {
this._setFlowOutPort(outPort, v.value);
}
} else if (outPort.tempo === 'event') {
if (v.present) {
this._setFlowOutPort(outPort, v.value);
}
} else {
assert(false);
}
}
// Pump to process these updated inputs
this.pump();
this.evaluating = false;
}
destroy() {
for (const actControl of this.containedNativeApplicationActivationControl.values()) {
if (actControl.destroy) {
actControl.destroy();
}
}
if (this.containingActivation) {
this.containingActivation.deactivatedClosureOfContainedDefinition(this.definition, this);
}
this.definition.activationDeactivated(this);
}
definitionChanged(subdefPath) {
assert(!this.evaluating);
this.evaluating = true;
if (subdefPath.length > 0) {
const firstSubdef = subdefPath[0];
const restSubdefs = subdefPath.slice(1);
// These are the activations that could care about the subdef having changed
const apps = this.definition.definitionToUsingApplications.get(firstSubdef);
for (const app of apps) {
const actControl = this.containedNativeApplicationActivationControl.get(app);
// NOTE: We pass the full path here rather than slicing off the first one
actControl.definitionChanged(subdefPath);
}
}
this.pump();
this.evaluating = false;
}
// Let the activation know that a native application was added to the definition
addedNativeApplication(app) {
assert(!this.evaluating);
this._activateNativeApplication(app);
}
// Let the activation know that a native application was removed from the definition
removedNativeApplication(app) {
assert(!this.evaluating);
const actControl = this.containedNativeApplicationActivationControl.get(app);
if (actControl.destroy) {
actControl.destroy();
}
}
// Let the activation know that a connection was added to the definition
addedConnection(cxn) {
assert(!this.evaluating);
// NOTE: I think it should not be necessary to flow the connection if the ports are event-tempo,
// but that's not a very important optimization.
this._flowOutConnection(cxn);
}
// Let the activation know that a connection was removed from the definition
removedConnection(cxn) {
assert(!this.evaluating);
// Flow the removal of the connection
this._flowOutConnection(cxn, true);
}
// Set the settings on an application
setApplicationSettings(app, newSettings) {
const actControl = this.containedNativeApplicationActivationControl.get(app);
actControl.changeSettings(newSettings);
this._insertAppEvalTask(app);
}
// Let this activation know that a closure made from one of its contained definitions was activated
activatedClosureOfContainedDefinition(definition, activation) {
assert(definition.containingDefinition === this.definition);
if (!this.containedDefinitionActivations.has(definition)) {
this.containedDefinitionActivations.set(definition, new Set());
}
this.containedDefinitionActivations.get(definition).add(activation);
}
// Let this activation know that a closure made from one of its contained definitions was deactivated
deactivatedClosureOfContainedDefinition(definition, activation) {
assert(definition.containingDefinition === this.definition);
this.containedDefinitionActivations.get(definition).delete(activation);
}
_gatherNativeApplicationInputs(nativeApplication, initial) {
const inPortToValueChange = (inPort) => {
const stream = this.inPortStream.get(inPort);
if (inPort.tempo === 'step') {
// NOTE: By convention we always set changed to true for initial inputs
if (stream) {
return {
value: stream.latestValue,
changed: initial ? true : (stream.lastChangedInstant === this.currentInstant),
};
} else {
return {
value: undefined,
changed: true,
};
}
} else if (inPort.tempo === 'event') {
// For event-tempo ports, we only provide a value if there is an event present (at the
// current instant)
if (stream && (stream.lastChangedInstant === this.currentInstant)) {
return {
value: stream.latestValue,
present: true,
};
} else {
return {
value: undefined,
present: false,
};
}
} else {
assert(false);
}
}
const inputs = [];
for (const inPort of nativeApplication.inputs) {
inputs.push(inPortToValueChange(inPort));
}
return inputs;
}
// Activate a native application, which is to say activate a native definition within the context of a user activation.
// This will create output streams and set their initial values.
// No return value.
_activateNativeApplication(nativeApplication) {
// Create streams for the output ports of the native function definition,
// and store the streams in the containing activation.
// Create and store the streams
for (const inPort of nativeApplication.inputs) {
const stream = new Stream();
this.inPortStream.set(inPort, stream);
// Flow in initial value if connection comes from an outer scope.
this._flowInPortFromOutside(inPort);
}
const outStreams = []; // We'll use this below
if (nativeApplication.output instanceof Map) {
// Compound output
for (const [n, outPort] of nativeApplication.output) {
const stream = new Stream();
this.outPortStream.set(outPort, stream);
outStreams.push(stream);
}
} else if (nativeApplication.output) {
// Single output
const stream = new Stream();
this.outPortStream.set(nativeApplication.output, stream);
outStreams.push(stream);
}
// Create setOutput callback that sets/flows the changed output streams
const setOutput = (outVal) => {
if (nativeApplication.output instanceof Map) {
// Compound output
for (const [n, v] of outVal) {
this._setFlowOutPort(nativeApplication.output.get(n), v);
}
} else if (nativeApplication.output) {
// Single output
this._setFlowOutPort(nativeApplication.output, outVal);
} else {
assert(false); // callback should not be called if no outputs
}
// If we aren't already evaluating, then this must have been a async output, so we start evaluating.
// NOTE: We could set a flag when we enter/exit activation and update calls to determine
// whether this call is truly async or not, and use this as a sanity check against the
// current state of the evaluating flag (this.evaluating iff not-async-output).
if (!this.evaluating) {
this.evaluating = true;
this.pump();
this.evaluating = false;
}
};
// Create "closures" where we bind the function args of this application to this activation
const functionArguments = new Map();
if (nativeApplication.functionArguments) {
for (const [n, f] of nativeApplication.functionArguments) {
functionArguments.set(n, new UserClosure(f, this));
}
}
const activationControl = activateNativeDefinition(nativeApplication.definition, setOutput, functionArguments, nativeApplication.settings);
// Store the new activation in the containing activation
this.containedNativeApplicationActivationControl.set(nativeApplication, activationControl);
// Insert a task to do the initial evaluation of this application's activation
this._insertAppEvalTask(nativeApplication);
}
_insertAppEvalTask(app) {
const priority = app.sortIndex;
assert(priority !== undefined);
this.priorityQueue.insert(priority, {
tag: 'napp',
nativeApplication: app,
});
}
_insertAppDefChangedTask(app, subdefPath) {
const priority = app.sortIndex;
assert(priority !== undefined);
this.priorityQueue.insert(priority, {
tag: 'napp_defchanged',
nativeApplication: app,
subdefPath,
});
}
_notifyInPort(inPort) {
// See what task is associated with notifying inPort, and insert an element
// into the priority queue, associated with this activation.
const owner = inPort.owner;
switch (owner.tag) {
case 'app':
this._insertAppEvalTask(owner.app);
break;
case 'def':
this.priorityQueue.insert(Infinity, {
tag: 'defout',
});
break;
default:
assert(false);
}
}
// Propagate value change along the given connection within the context of the given activation (at the source/out side),
// and "notify" any input ports whose values have changed.
// If removal argument is true, then flow an undefined value along the connection (because connection is being removed).
_flowOutConnection(cxn, removal = false) {
assert(cxn.outPort.containingDefinition === this.definition);
// Since a connection may go into a contained definition, flowing a connection (within the context of a single activation)
// may cause the value to "fan out" to multiple activations (or none). So first, we compute the set of relevant activations
// on the downstream end of the connection.
let downstreamActivations = [this];
for (const subdef of cxn.path) {
const nextDownstreamActivations = [];
for (const act of downstreamActivations) {
const cda = act.containedDefinitionActivations;
if (cda.has(subdef)) {
for (const subact of cda.get(subdef)) {
nextDownstreamActivations.push(subact);
}
}
}
downstreamActivations = nextDownstreamActivations;
}
let flowValue;
if (removal) {
flowValue = undefined;
} else {
// NOTE: The lastChangedInstant of outStream may not be the current instant,
// e.g. if this copying is the result of flowing a newly added connection.
const outStream = this.outPortStream.get(cxn.outPort);
flowValue = outStream.latestValue;
}
for (const act of downstreamActivations) {
const inStream = act.inPortStream.get(cxn.inPort);
// TODO: Ensure that inStream's last changed instant is less than current instant?
inStream.setValue(flowValue, act.currentInstant);
// Trigger anything "listening" on this port
act._notifyInPort(cxn.inPort);
}
// If we flowed into a sub-definition, then we need to insert a task to call definitionChanged
// on any applications in this activation that take (a closure of) that sub-definition as
// an argument.
if (cxn.path.length > 0) {
const outermostSubdef = cxn.path[0];
for (const napp of this.definition.definitionToUsingApplications.get(outermostSubdef)) {
this._insertAppDefChangedTask(napp, cxn.path);
}
}
}
// Propagate value change along the given connection within the context of the given activation (at the dest/input side)
_flowInConnection(cxn) {
assert(cxn.inPort.containingDefinition === this.definition);
// Find the activation for the ouput end of this connection by walking up our "parent" activations.
let outPortActivation = this;
for (let i = 0; i < cxn.path.length; i++) {
outPortActivation = outPortActivation.containingActivation;
}
const outStream = outPortActivation.outPortStream.get(cxn.outPort);
const inStream = this.inPortStream.get(cxn.inPort);
inStream.setValue(outStream.latestValue, this.currentInstant);
this._notifyInPort(cxn.inPort);
}
// Flow any connection on this inPort if the connection comes from an outer activation (scope)
_flowInPortFromOutside(inPort) {
const cxn = inPort.connection;
if (cxn && (cxn.path.length > 0)) {
this._flowInConnection(cxn);
}
}
// Set the value of the given outPort in the context of activation (which corresponds to a specific stream),
// and flow the change along any outgoing connections.
// NOTE: We take a OutPort+UserActivation rather than Stream because we need the OutPort to find connections.
_setFlowOutPort(outPort, value) {
// Set the stream value
const outStream = this.outPortStream.get(outPort);
// TODO: ensure that stream's last changed instant is less than current instant?
outStream.setValue(value, this.currentInstant);
// Flow the change
for (const cxn of outPort.connections) {
this._flowOutConnection(cxn);
}
}
_emitOutput(mustBePresent) {
// Check definition-output stream(s), and if any have changed then call this.setOutput.
// If mustBePresent is true, then assert if no changes were found.
// NOTE: We only emit outputs that have changed.
if (this.definition.definitionOutput instanceof Map) {
const changedOutputs = new Map();
for (const [n, inPort] of this.definition.definitionOutput) {
const stream = this.inPortStream.get(inPort);
if (stream && (stream.lastChangedInstant === this.currentInstant)) {
changedOutputs.set(n, stream.latestValue);
}
}
assert(!(mustBePresent && changedOutputs.size === 0));
if (changedOutputs.size) {
this.setOutput(changedOutputs);
}
} else if (this.definition.definitionOutput) {
const stream = this.inPortStream.get(this.definition.definitionOutput);
if (stream && (stream.lastChangedInstant === this.currentInstant)) {
this.setOutput(stream.latestValue);
}
} else {
assert(!mustBePresent);
}
}
_priorityQueueTasksEqual(a, b) {
if (a.tag !== b.tag) {
return false;
}
switch (a.tag) {
case 'napp':
return (a.nativeApplication === b.nativeApplication);
default:
assert(false);
}
return (a.task === b.task) && (a.activation === b.activation);
}
pump() {
assert(this.evaluating);
const pq = this.priorityQueue;
const instant = this.currentInstant;
while (!pq.isEmpty()) {
const task = pq.pop();
// Keep popping and discarding as long as next element is a duplicate
while (!pq.isEmpty() && this._priorityQueueTasksEqual(pq.peek(), task)) {
pq.pop();
}
switch (task.tag) {
case 'napp': {
const {nativeApplication} = task;
const activationControl = this.containedNativeApplicationActivationControl.get(nativeApplication);
const inputs = this._gatherNativeApplicationInputs(nativeApplication, false);
activationControl.evaluate(inputs);
}
break;
case 'napp_defchanged': {
const {nativeApplication, subdefPath} = task;
const activationControl = this.containedNativeApplicationActivationControl.get(nativeApplication);
activationControl.definitionChanged(subdefPath);
}
break;
case 'defout':
this._emitOutput(true);
break;
default:
assert(false);
}
}
this.currentInstant++;
}
} |
JavaScript | class Envelope {
constructor(waterfall, parent){
this.parent = parent;
this.waterfall = waterfall;
}
draw ( range, center_freq, visible_range ) {
this.visible_range = visible_range;
let demod_envelope_draw = (range, from, to, color, line) => {
// ____
// Draws a standard filter envelope like this: _/ \_
// Parameters are given in offset frequency (Hz).
// Envelope is drawn on the scale canvas.
// A "drag range" object is returned, containing information about the draggable areas of the envelope
// (beginning, ending and the line showing the offset frequency).
if ( typeof color == "undefined" ){
color="#ffff00"; //yellow
}
let env_bounding_line_w = 5; //
let env_att_w = 5; // _______ ___env_h2 in px ___|_____
let env_h1 = 17; // _/| \_ ___env_h1 in px _/ |_ \_
let env_h2 = 5; // |||env_att_line_w |_env_lineplus
let env_lineplus = 1; // ||env_bounding_line_w
let env_line_click_area = 6;
//range=get_visible_freq_range();
let from_px = this.waterfall.scale_px_from_freq(from,range) + scaleLineWidth;
let to_px = this.waterfall.scale_px_from_freq(to,range) + scaleLineWidth;
if ( to_px < from_px ) {
/* swap'em */
let temp_px = to_px;
to_px = from_px;
from_px = temp_px;
}
/*from_px-=env_bounding_line_w/2;
to_px+=env_bounding_line_w/2;*/
from_px -= ( env_att_w + env_bounding_line_w );
to_px += ( env_att_w + env_bounding_line_w );
// do drawing:
this.waterfall.scale_ctx.lineWidth = 3;
this.waterfall.scale_ctx.strokeStyle = color;
this.waterfall.scale_ctx.fillStyle = color;
var drag_ranges = { envelope_on_screen: false,
line_on_screen: false };
if( !( to_px < 0 ||
from_px > window.innerWidth ) ){
// out of screen?
drag_ranges.beginning = { x1: from_px,
x2: from_px + env_bounding_line_w + env_att_w
};
drag_ranges.ending = { x1: to_px - env_bounding_line_w - env_att_w,
x2: to_px
};
drag_ranges.whole_envelope = { x1: from_px,
x2: to_px
};
drag_ranges.envelope_on_screen = true;
this.waterfall.scale_ctx.beginPath();
this.waterfall.scale_ctx.moveTo( from_px, env_h1 );
this.waterfall.scale_ctx.lineTo( from_px + env_bounding_line_w, env_h1 );
this.waterfall.scale_ctx.lineTo( from_px + env_bounding_line_w + env_att_w, env_h2 );
this.waterfall.scale_ctx.lineTo( to_px - env_bounding_line_w - env_att_w, env_h2 );
this.waterfall.scale_ctx.lineTo( to_px - env_bounding_line_w, env_h1 );
this.waterfall.scale_ctx.lineTo( to_px, env_h1 );
this.waterfall.scale_ctx.globalAlpha = 0.3;
this.waterfall.scale_ctx.fill();
this.waterfall.scale_ctx.globalAlpha = 1;
this.waterfall.scale_ctx.stroke();
}
if ( typeof line != "undefined") {
// out of screen?
let line_px = this.waterfall.scale_px_from_freq( line, range );
if ( ! ( line_px < 0 ||
line_px > window.innerWidth ) ) {
drag_ranges.line = { x1: line_px - env_line_click_area / 2,
x2: line_px + env_line_click_area / 2
};
drag_ranges.line_on_screen = true;
this.waterfall.scale_ctx.moveTo( line_px + scaleLineWidth, env_h1 + env_lineplus );
this.waterfall.scale_ctx.lineTo( line_px + scaleLineWidth , env_h2 - env_lineplus );
this.waterfall.scale_ctx.stroke();
}
}
return drag_ranges;
};
this.drag_ranges = demod_envelope_draw( range ,
center_freq + this.parent.offset_frequency + this.parent.low_cut,
center_freq + this.parent.offset_frequency + this.parent.high_cut,
this.color,
center_freq + this.parent.offset_frequency
);
}
// event handlers
drag_start ( x, key_modifiers ) {
let demod_envelope_where_clicked = (x, drag_ranges, key_modifiers) => {
// Check exactly what the user has clicked based on ranges returned by demod_envelope_draw().
let in_range = ( x, range ) => {
return range.x1 <= x && range.x2 >= x;
};
let dr = Demodulator.draggable_ranges;
if( key_modifiers.shiftKey ) {
//Check first: shift + center drag emulates BFO knob
if( drag_ranges.line_on_screen &&
in_range( x, drag_ranges.line ) ){
return dr.bfo;
}
//Check second: shift + envelope drag emulates PBF knob
if( drag_ranges.envelope_on_screen &&
in_range( x, drag_ranges.whole_envelope ) ){
return dr.pbs;
}
}
if( drag_ranges.envelope_on_screen ){
// For low and high cut:
if( in_range( x, drag_ranges.beginning ) ){
return dr.beginning;
}
if( in_range( x, drag_ranges.ending ) ){
return dr.ending;
}
// Last priority: having clicked anything else on the envelope, without holding the shift key
if( in_range( x, drag_ranges.whole_envelope ) ){
return dr.anything_else;
}
}
return dr.none; //User doesn't drag the envelope for this demodulator
};
this.key_modifiers = key_modifiers;
this.dragged_range = demod_envelope_where_clicked( x, this.drag_ranges, key_modifiers );
//console.log("dragged_range: "+this.dragged_range.toString());
this.drag_origin = {
x: x,
low_cut: this.parent.low_cut,
high_cut: this.parent.high_cut,
offset_frequency: this.parent.offset_frequency
};
return this.dragged_range != Demodulator.draggable_ranges.none;
}
drag_move( bandwidth, x ) {
let dr = Demodulator.draggable_ranges;
if( this.dragged_range == dr.none ){
return false; // we return if user is not dragging (us) at all
}
let freq_change = Math.round( this.visible_range.hps * ( x - this.drag_origin.x ) );
/*if(this.dragged_range==dr.beginning||this.dragged_range==dr.ending)
{
//we don't let the passband be too small
if(this.parent.low_cut+new_freq_change<=this.parent.high_cut-this.parent.filter.min_passband) this.freq_change=new_freq_change;
else return;
}
var new_value;*/
//dragging the line in the middle of the filter envelope while holding Shift does emulate
//the BFO knob on radio equipment: moving offset frequency, while passband remains unchanged
//Filter passband moves in the opposite direction than dragged, hence the minus below.
let minus = ( this.dragged_range == dr.bfo ) ? -1 : 1;
//dragging any other parts of the filter envelope while holding Shift does emulate the PBS knob
//(PassBand Shift) on radio equipment: PBS does move the whole passband without moving the offset
//frequency.
if( this.dragged_range == dr.beginning ||
this.dragged_range == dr.bfo ||
this.dragged_range == dr.pbs) {
//we don't let low_cut go beyond its limits
let new_value = this.drag_origin.low_cut + minus * freq_change;
if( new_value < this.parent.filter.low_cut_limit ){
return true;
}
//nor the filter passband be too small
if( this.parent.high_cut - new_value < this.parent.filter.min_passband ){
return true;
}
//sanity check to prevent GNU Radio "firdes check failed: fa <= fb"
if( new_value >= this.parent.high_cut ){
return true;
}
this.parent.low_cut = new_value;
}
if( this.dragged_range == dr.ending ||
this.dragged_range == dr.bfo ||
this.dragged_range == dr.pbs ) {
let new_value = this.drag_origin.high_cut + minus * freq_change;
//we don't let high_cut go beyond its limits
if( new_value > this.parent.filter.high_cut_limit ){
return true;
}
//nor the filter passband be too small
if( new_value - this.parent.low_cut < this.parent.filter.min_passband ){
return true;
}
//sanity check to prevent GNU Radio "firdes check failed: fa <= fb"
if( new_value <= this.parent.low_cut ){
return true;
}
this.parent.high_cut = new_value;
}
if( this.dragged_range == dr.anything_else ||
this.dragged_range == dr.bfo ) {
//when any other part of the envelope is dragged, the offset frequency is changed (whole passband also moves with it)
let new_value = this.drag_origin.offset_frequency + freq_change;
if( new_value > bandwidth / 2 ||
new_value < -bandwidth / 2 ){
return true; //we don't allow tuning above Nyquist frequency :-)
}
this.parent.offset_frequency = new_value;
}
//now do the actual modifications:
this.waterfall.mkenvelopes( this.visible_range );
this.parent.set();
//will have to change this when changing to multi-demodulator mode:
/* e("webrx-actual-freq").innerHTML=format_frequency("{x} MHz",center_freq+this.parent.offset_frequency,1e6,4);*/
return true;
}
drag_end ( x ) {
//in this demodulator we've already changed values in the drag_move() function so we shouldn't do too much here.
// demodulator_buttons_update();
let to_return = this.dragged_range != Demodulator.draggable_ranges.none; //this part is required for cliking anywhere on the scale to set offset
this.dragged_range = Demodulator.draggable_ranges.none;
return to_return;
}
} |
JavaScript | class Catcher extends Transform {
/**
* @param logger Used for logging events and errors.
*/
constructor(logger) {
super({
objectMode: true
});
/**
* Holds caught stream content.
*/
this.Results = [];
this.Logger = (msg, lvl) => logger(`Catcher > ${msg}`, lvl);
// Set promise
this.Logger("Creating promise with external completion source", LogLevel.Silly);
this.Collected = new Promise(resolve => {
this.Resolve = resolve;
});
}
/**
* Collects incoming chunks.
* @param chunk Incoming chunk to catch.
* @param encoding Its encoding, if applicable.
* @param callback Callback used to indicate method completion.
*/
_transform(chunk, encoding, callback) {
this.Logger("Catching a chunk", LogLevel.Silly);
this.Results.push(chunk);
callback();
}
/**
* Resolves collection promise.
* @param callback Callback used to indicate method completion.
*/
_flush(callback) {
this.Logger("Starting resolution of catcher promise", LogLevel.Silly);
// Ensure promise has had chance to run
const resolver = () => {
/* istanbul ignore else */
if (this.Resolve) {
this.Resolve(this.Results);
this.Logger("Catcher promise has resolved", LogLevel.Silly);
callback();
}
else {
this.Logger("Catcher promise not yet ready, waiting 5ms", LogLevel.Silly);
setTimeout(resolver, 5);
}
};
resolver();
}
} |
JavaScript | class Animation extends GameObject {
constructor(params) {
super(params);
this.start = this.frames[0];
this.end = this.frames[this.frames.length];
this.current = this.start;
this.finished = false;
}
params() {
return ["name", "spriteSheet", "frames"];
}
config() {
return {
fps: 60,
loop: false
};
}
next() {
if (!this.finished) {
this.current += 1;
}
if (this.current > this.end) {
if (this.loop) {
this.current = this.start;
} else {
this.finished = true;
this.current = this.end;
}
}
return this.finished;
}
restart() {
this.current = this.start;
}
} |
JavaScript | class TrustedSystemAuthRequest {
/**
* Constructs a new <code>TrustedSystemAuthRequest</code>.
* @alias module:models/TrustedSystemAuthRequest
* @class
* @param clientId {String} The client id of the shopping application to be encoded in the customer JWT. This is not the same as the OAuth Client ID used to authenticate the API call. The OAuth Client ID is the trusted/private one; this is the untrusted/public one.
* @param login {String} The customer's login.
*/
constructor(clientId, login) {
this.client_id = clientId; this.login = login
}
/**
* Constructs a <code>TrustedSystemAuthRequest</code> from a plain JavaScript object, optionally creating a new instance.
* Copies all relevant properties from <code>data</code> to <code>obj</code> if supplied or a new instance if not.
* @param {Object} data The plain JavaScript object bearing properties of interest.
* @param {module:models/TrustedSystemAuthRequest} obj Optional instance to populate.
* @return {module:models/TrustedSystemAuthRequest} The populated <code>TrustedSystemAuthRequest</code> instance.
*/
static constructFromObject(data, obj) {
if (data) {
obj = obj || new TrustedSystemAuthRequest()
if (data.hasOwnProperty('client_id')) {
obj.client_id = ApiClient.convertToType(data.client_id, 'String')
}
if (data.hasOwnProperty('login')) {
obj.login = ApiClient.convertToType(data.login, 'String')
}
}
return obj
}
/**
* The client id of the shopping application to be encoded in the customer JWT. This is not the same as the OAuth Client ID used to authenticate the API call. The OAuth Client ID is the trusted/private one; this is the untrusted/public one.
* @member {String} client_id
*/
client_id = undefined;
/**
* The customer's login.
* @member {String} login
*/
login = undefined;
} |
JavaScript | class ImageMatchOptions {
/**
* @param options
* @param {string} options.name - The tag of the window to be matched.
* @param {string} options.renderId - The render ID of the screenshot to match.
* @param {Trigger[]} options.userInputs - A list of triggers between the previous matchWindow call and the current matchWindow
* call. Can be array of size 0, but MUST NOT be null.
* @param {boolean} options.ignoreMismatch - Tells the server whether or not to store a mismatch for the current window as
* window in the session.
* @param {boolean} options.ignoreMatch - Tells the server whether or not to store a match for the current window as window in
* the session.
* @param {boolean} options.forceMismatch - Forces the server to skip the comparison process and mark the current window as a
* mismatch.
* @param {boolean} options.forceMatch - Forces the server to skip the comparison process and mark the current window as a
* match.
* @param {ImageMatchSettings} options.imageMatchSettings - Settings specifying how the server should compare the image.
* @param {string} options.source
*/
constructor({
name,
renderId,
userInputs,
ignoreMismatch,
ignoreMatch,
forceMismatch,
forceMatch,
imageMatchSettings,
source,
} = {}) {
if (arguments.length > 1) {
throw new TypeError('Please, use object as a parameter to the constructor!')
}
ArgumentGuard.notNull(userInputs, 'userInputs')
this._name = name
this._renderId = renderId
this._userInputs = userInputs
this._ignoreMismatch = ignoreMismatch
this._ignoreMatch = ignoreMatch
this._forceMismatch = forceMismatch
this._forceMatch = forceMatch
this._imageMatchSettings = imageMatchSettings
this._source = source
}
/**
* @return {string}
*/
getName() {
return this._name
}
/**
* @return {string}
*/
getRenderId() {
return this._renderId
}
/**
* @return {Trigger[]}
*/
getUserInputs() {
return this._userInputs
}
/**
* @return {boolean}
*/
getIgnoreMismatch() {
return this._ignoreMismatch
}
/**
* @return {boolean}
*/
getIgnoreMatch() {
return this._ignoreMatch
}
/**
* @return {boolean}
*/
getForceMismatch() {
return this._forceMismatch
}
/**
* @return {boolean}
*/
getForceMatch() {
return this._forceMatch
}
/**
* @return {ImageMatchSettings}
*/
getImageMatchSettings() {
return this._imageMatchSettings
}
/**
* @return {string}
*/
getSource() {
return this._source
}
/**
* @override
*/
toJSON() {
return GeneralUtils.toPlain(this)
}
/**
* @override
*/
toString() {
return `Options { ${JSON.stringify(this)} }`
}
} |
JavaScript | class CustomWebGLCubeRenderTarget {
constructor(width, options, renderer) {
this.width = width
this.options = options
this.renderer = renderer
var scene = new Scene()
var shader = {
uniforms: {
time: { value: 0.5 }
},
vertexShader: `
varying vec3 vWorldDirection;
vec3 transformDirection( in vec3 dir, in mat4 matrix ) {
return normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );
}
void main() {
vWorldDirection = transformDirection( position, modelMatrix );
#include <begin_vertex>
#include <project_vertex>
}
`,
fragmentShader: `
varying vec3 vWorldDirection;
#define RECIPROCAL_PI 0.31830988618
#define RECIPROCAL_PI2 0.15915494
uniform float time;
const mat2 m = mat2( 0.80, 0.60, -0.60, 0.80 );
float noise( in vec2 p ) {
return sin(p.x)*sin(p.y);
}
float fbm4( vec2 p ) {
float f = 0.0;
f += 0.5000 * noise( p ); p = m * p * 2.02;
f += 0.2500 * noise( p ); p = m * p * 2.03;
f += 0.1250 * noise( p ); p = m * p * 2.01;
f += 0.0625 * noise( p );
return f / 0.9375;
}
float fbm6( vec2 p ) {
float f = 0.0;
f += 0.500000*(0.5 + 0.5 * noise( p )); p = m*p*2.02;
f += 0.250000*(0.5 + 0.5 * noise( p )); p = m*p*2.03;
f += 0.125000*(0.5 + 0.5 * noise( p )); p = m*p*2.01;
f += 0.062500*(0.5 + 0.5 * noise( p )); p = m*p*2.04;
f += 0.031250*(0.5 + 0.5 * noise( p )); p = m*p*2.01;
f += 0.015625*(0.5 + 0.5 * noise( p ));
return f/0.96875;
}
float pattern (vec2 p) {
float vout = fbm4( p + time + fbm6( p + fbm4( p + time )) );
return abs(vout);
}
void main() {
vec3 direction = normalize( vWorldDirection );
vec2 sampleUV;
sampleUV.y = asin( clamp( direction.y, - 1.0, 1.0 ) ) * RECIPROCAL_PI + 0.5;
sampleUV.x = atan( direction.z, direction.x ) * RECIPROCAL_PI2 + 0.5;
gl_FragColor = vec4(vec3(
0.35 + pattern(sampleUV * 1.70123 + -0.17 * cos(time * 0.05)),
0.35 + pattern(sampleUV * 1.70123 + 0.0 * cos(time * 0.05)),
0.35 + pattern(sampleUV * 1.70123 + 0.17 * cos(time * 0.05))
), 1.0);
}
`
}
var material = new ShaderMaterial({
type: 'CubemapFromEquirect',
uniforms: shader.uniforms,
vertexShader: shader.vertexShader,
fragmentShader: shader.fragmentShader,
side: BackSide,
blending: NoBlending
})
var mesh = new Mesh(new BoxBufferGeometry(5, 5, 5), material)
scene.add(mesh)
var cubeRtt = new WebGLCubeRenderTarget(this.width, this.options)
let texture = cubeRtt.texture
cubeRtt.texture.type = texture.type
cubeRtt.texture.format = texture.format
cubeRtt.texture.encoding = texture.encoding
this.texture = cubeRtt.texture
var camera = new CubeCamera(1, 100000, cubeRtt)
camera.update(this.renderer, scene)
this.compute = () => {
shader.uniforms.time.value += 1 / 60
camera.update(this.renderer, scene)
}
}
} |
JavaScript | class Create extends BaseAction {
/**
* Create an instance of the Create action.
* @param {Object} config - The configuration for the action.
*/
constructor(config) {
super('create', config)
}
/**
* Generate an action creator with the provided data.
* @param {String} instance - Instance key where changes should be applied
* @param {Object} record - Record to be created.
*
* @returns {Function} - Returns the create action thunk.
*/
do = (instance, record) => {
// Make sure record is an immutable map
record = Immutable.Iterable.isIterable(record) ? record : Immutable.fromJS(record)
// Validate instance key
this.validateInstance(instance)
return dispatch => {
// Create data object to be dispatched with actions
const { uidField, creator } = this.config
const isAsync = typeof creator === 'function'
const data = { instance, record, uidField, isAsync }
// Call BaseAction.start with dispatch and the action data
this.start(dispatch, data)
// If config.creator is provided, call it
if (isAsync) {
// Prepare BaseAction.success and BaseAction.error handlers
// by currying with dispatch and action data
const success = this.success.bind(this, dispatch, data)
const error = this.error.bind(this, dispatch, data)
// Call creator
const creatorAction = creator(record, success, error)
// Return the action promise
return isPromise(creatorAction) ? creatorAction : creatorAction(dispatch)
}
}
}
} |
JavaScript | class DirectionalLight extends AmbientLight
{
/**
* @constructor
* @param direction {Array(3)} Vettore direzione del raggio luminoso
* @param color {Array(3)} Vettore che indica l'intensità luminosa rgb della luce
*/
constructor(direction, color)
{
super(color);
this.direction = glMatrix.vec3.fromValues(direction[0], direction[1], direction[2]);
}
} |
JavaScript | class Images extends React.Component {
/**
* Deserialize the raw initial state.
*
* @type {Object}
*/
state = {
state: Raw.deserialize(initialState)
};
/**
* Render the app.
*
* @return {Element} element
*/
render = () => {
return (
<div>
{this.renderToolbar()}
{this.renderEditor()}
</div>
)
}
/**
* Render the toolbar.
*
* @return {Element} element
*/
renderToolbar = () => {
return (
<div className="menu toolbar-menu">
<span className="button" onMouseDown={this.onClickImage}>
<span className="material-icons">image</span>
</span>
</div>
)
}
/**
* Render the editor.
*
* @return {Element} element
*/
renderEditor = () => {
return (
<div className="editor">
<Editor
state={this.state.state}
renderNode={this.renderNode}
onChange={this.onChange}
/>
</div>
)
}
/**
* Render a `node`.
*
* @param {Node} node
* @return {Element}
*/
renderNode = (node) => {
return NODES[node.type]
}
/**
* On change.
*
* @param {State} state
*/
onChange = (state) => {
this.setState({ state })
}
/**
* On clicking the image button, prompt for an image and insert it.
*
* @param {Event} e
*/
onClickImage = (e) => {
e.preventDefault()
const src = window.prompt('Enter the URL of the image:')
if (!src) return
this.insertImage(src)
}
/**
* Insert an image with `src` at the current selection.
*
* @param {String} src
*/
insertImage = (src) => {
let { state } = this.state
if (state.isExpanded) {
state = state
.transform()
.delete()
.apply()
}
const { anchorBlock, selection } = state
let transform = state.transform()
if (anchorBlock.text != '') {
if (selection.isAtEndOf(anchorBlock)) {
transform = transform
.splitBlock()
}
else if (selection.isAtStartOf(anchorBlock)) {
transform = transform
.splitBlock()
.collapseToStartOfPreviousBlock()
}
else {
transform = transform
.splitBlock()
.splitBlock()
.collapseToStartOfPreviousBlock()
}
}
state = transform
.setBlock({
type: 'image',
isVoid: true,
data: { src }
})
.apply()
this.setState({ state })
}
} |
JavaScript | class AreaChart extends Chart {
/**
* Creates an instance of the AreaChart class
* @param {string} data - JSON string containing the data columns.
*/
constructor(data) {
super(data)
}
/**
* Alter the parameters of the chart using the provided grammar.
* @param {string} grammar - Simple grammar string describing the chart.
* @returns {boolean} - Returns true if the grammar is parsed.
*/
do(grammar) {
if (!super.do(grammar)) {
if (grammar.match(new RegExp('where [0-9a-zA-Z\\-]+ as area-spline'))) {
let areaSplineDataLabel = grammar.match(new RegExp('where [0-9a-zA-Z\\-]+ as area-spline'))[0].split(' ')[1]
this._outputJson.data.types[areaSplineDataLabel] = 'area-spline'
return true
} else if (grammar.match(new RegExp('where [0-9a-zA-Z\\-]+ as area'))) {
let areaDataLabel = grammar.match(new RegExp('where [0-9a-zA-Z\\-]+ as area'))[0].split(' ')[1]
this._outputJson.data.types[areaDataLabel] = 'area'
return true
} else {
throw new InvalidGrammarError()
}
}
}
} |
JavaScript | class AuthContextProvider extends Component {
state = initAuthState;
constructor(props) {
super(props);
this.state.user = props.user;
this.state.token = props.token;
}
loginRequest = (user) => {
console.log("loginRequest");
this.setState({
isLoggedIn: false,
loading: true,
error: null
});
AuthService.login(user, this.loginSuccess, this.loginFailed);
};
loginSuccess = async ({user, token} = {}) => {
cookie.set("user", user, {expires: 1});
cookie.set("token", token, {expires: 1});
this.setState({
isLoggedIn: true,
loading: false,
error: null,
user: user,
token: token,
});
return await redirectTo(RoutesInfo.Home.path, {status: 301});
};
loginFailed = async (err) => {
cookie.remove("user");
cookie.remove("token");
this.setState({
isLoggedIn: false,
loading: false,
error: err,
user: null,
token: null,
});
return await redirectTo(RoutesInfo.Login.path);
};
logoutRequest = async () => {
cookie.remove("user");
cookie.remove("token");
this.setState({
isLoggedIn: false,
loading: false,
error: null,
user: null,
token: null,
});
return await redirectTo(RoutesInfo.Login.path);
};
render() {
return (
<AuthContext.Provider
value={{
isLoggedIn: this.state.isLoggedIn,
loading: this.state.loading,
error: this.state.error,
user: this.state.user,
token: this.state.token,
loginRequest: this.loginRequest,
logoutRequest: this.logoutRequest,
loginSuccess: this.loginSuccess,
}}
>
{this.props.children}
</AuthContext.Provider>
);
}
} |
JavaScript | class Footer extends React.Component {
render() {
return (
<MDBFooter
color="blue darken-1"
className="page-footer font-small pt-1 mt-4"
>
<MDBContainer className="mt-5 mb-4 text-center text-md-left">
<MDBRow className="mt-3">
<MDBCol md="4" className="mb-4">
<h6 className="text-uppercase font-weight-bold">
<strong>yourdomainname.com</strong>
</h6>
<hr
className="teal accent-1 mb-4 mt-0 d-inline-block mx-auto"
style={{ width: `165px` }}
/>
<p>
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec
eget nulla at velit varius finibus. Pellentesque porttitor
faucibus felis, quis aliquet odio mattis vitae. Donec at
convallis nisi. Vestibulum nec sagittis quam.
</p>
</MDBCol>
<MDBCol md="2" className="mb-4">
<h6 className="text-uppercase font-weight-bold">
<strong>My Links</strong>
</h6>
<hr
className="teal accent-1 mb-4 mt-0 d-inline-block mx-auto"
style={{ width: `85px` }}
/>
<p>
<a href="https://linkedin.com/jacobjessecavazos/">
My LinkedIn
</a>
</p>
<p>
<a href="https://github.com/jjcav84/">My Github</a>
</p>
<p>
<a href="https://twitter.com/jcavazos84">My Twitter</a>
</p>
</MDBCol>
<MDBCol md="3" className="mb-4">
<h6 className="text-uppercase font-weight-bold">
<strong>Useful links</strong>
</h6>
<hr
className="teal accent-1 mb-4 mt-0 d-inline-block mx-auto"
style={{ width: `108px` }}
/>
<p>
<a href="https://mdbootstrap.com/material-design-for-bootstrap/?utm_ref_id=38136">
Material Design for Bootstrap
</a>
</p>
<p>
<a href="https://gatsbyjs.org">Gatsby</a>
</p>
</MDBCol>
<MDBCol md="3" className="mb-4">
<h6 className="text-uppercase font-weight-bold">
<strong>Contact</strong>
</h6>
<hr
className="teal accent-1 mb-4 mt-0 d-inline-block mx-auto"
style={{ width: `73px` }}
/>
<p>
<i className="fa fa-envelope mr-3" />
<a href="mailto:[email protected]">[email protected]</a>
</p>
<p>
<i className="fa fa-phone mr-3" /> +1 (210) 724-5909
</p>
</MDBCol>
</MDBRow>
</MDBContainer>
<div className="footer-copyright text-center py-3">
<MDBContainer fluid>
<p>© {new Date().getFullYear()} Copyright: Jacob Cavazos</p>
</MDBContainer>
</div>
</MDBFooter>
)
}
} |
JavaScript | class TimeFieldExample extends Component {
constructor() {
super();
this.state = {
disabled: false
};
}
toggleDisabled() {
this.setState({ disabled: !this.state.disabled });
}
render() {
const { disabled } = this.state;
return (
<Container
platformConfig={{
phone: {
layout: 'fit'
},
"!phone": {
layout: 'center',
padding: 10
}
}}
>
<FormPanel
ref={form => this.form = form}
shadow
padding="20"
platformConfig={{
"!phone": {
maxHeight: 500,
width: 350
}
}}
>
<FieldSet ref="personal" title="Personal Info" defaults={{labelAlign: "placeholder"}}>
<TimeField required label="Time Field" value="3:42 PM" name="time" disabled={disabled}/>
</FieldSet>
<Toolbar shadow={false} docked="bottom" layout={{ type: 'hbox', pack: 'right' }}>
<Button text={disabled ? 'Enable All' : 'Disable All'} margin="0 10 0 0" handler={this.toggleDisabled.bind(this)}/>
<Button text="Reset" handler={() => this.form.cmp.reset()}/>
</Toolbar>
</FormPanel>
</Container>
);
}
} |
JavaScript | class Home extends Component{
//books are fetched
async componentDidMount(){
try{
const books = await BooksAPI.getAll();
this.props.addBooks(books);
console.log(books);
}catch(error){
console.log(error)
}
}
render(){
return(
<div className="list-books">
<div className="list-books-title">
<h1>MyReads</h1>
</div>
{/**Render each shelf with filtered books from Context */}
<div className="list-books-content">
<Shelf title ="Currently Reading" books = {this.props.currReading} moveBook={this.props.moveBook}/>
<Shelf title ="Want to read" books = {this.props.wantToRead} moveBook={this.props.moveBook}/>
<Shelf title ="Read" books = {this.props.read} moveBook={this.props.moveBook}/>
</div>
<SearchBtn/>
</div>
)
}
} |
JavaScript | class VideoPlayUrl {
/**
* @param {string} definition
* @param {string} playUrl
*/
constructor(definition, playUrl) {
/** @type {string} */
this.definition = definition;
/** @type {string} */
this.playUrl = playUrl;
}
} |
JavaScript | class DummyComponentToExportProps extends React.Component {
render() { // render hidden placeholder
return <span hidden>{' '}</span>
}
// IMPORTANT
// use 'componentWillMount' instead of 'componentDidMount',
// or there will be all sorts of partially renddered components
componentWillMount() {
// assign functions after component is created (context is picked up)
translate = (...params) => this.translateHandler('string', ...params)
translateHtml = (...params) => this.translateHandler('html', ...params)
translatePlural = (...params) => this.translateHandler('plural', ...params)
translateNumber = (...params) => this.translateHandler('number', ...params)
}
translateHandler(translateType, id, values, options) {
const { formatMessage, formatHTMLMessage, formatPlural, formatNumber } = this.props.intl
// choose which method of rendering to choose: normal string or string with html
// handler = translateType === 'string' ? formatMessage : formatHTMLMessage
let handler
switch (translateType) {
case 'string':
handler = formatMessage; break
case 'html':
handler = formatHTMLMessage; break
case 'plural':
handler = formatPlural; break
case 'number':
handler = formatNumber; break
default:
throw new Error('unknown translate handler type')
}
// check if right parameters were used before running function
if (isString(id)) {
if (!isUndefined(values) && !isObject(values)) throw new Error('translating function second parameter must be an object!');
// map parameters for react-intl,
// which uses formatMessage({id: 'stringId', values: {some: 'values'}, options: {}}) structure
// 'formatNumber' uses formatNumber(value: number) structure
// else if (translateType == 'number') return handler(Number(id))
else if (translateType == 'number') return Number(id).toLocaleString('en', { minimumFractionDigits: 2, maximumFractionDigits: 2 })
// everything else uses formatMessage({id: 'stringId', values: {some: 'values'}, options: {}}) structure
else return handler({id}, values, options)
}
else throw new Error('translating function first parameter must be a string!');
}
} |
JavaScript | class Translator extends React.Component {
render() {
/* LANGUAGE PICKER */
// Define user's language. Different browsers have the user locale defined
// on different fields on the `navigator` object, so we make sure to account
// for these different by checking all of them
let language = this.props.locale; // usually 'en'
if (process.env.BROWSER) {
const storredLanguage = store.get('language')
if (storredLanguage) language = storredLanguage
}
// let language = DEFAULT_LANGUAGE; // usually 'en'
// while Server Side Rendering is in process, 'navigator' is undefined
// currently commented out, because in golos we need only russian
// if (process.env.BROWSER) language = navigator
// ? (navigator.languages && navigator.languages[0])
// || navigator.language
// || navigator.userLanguage
// : DEFAULT_LANGUAGE;
//Split locales with a region code (ie. 'en-EN' to 'en')
const languageWithoutRegionCode = language.toLowerCase().split(/[_-]+/)[0];
return <IntlProvider
// to ensure dynamic language change, "key" property with same "locale" info must be added
// see: https://github.com/yahoo/react-intl/wiki/Components#multiple-intl-contexts
key={languageWithoutRegionCode}
defaultLocale={DEFAULT_LANGUAGE}
locale={languageWithoutRegionCode}
messages={messages[languageWithoutRegionCode]}
>
<div>
<DummyComponentToExportProps />
{this.props.children}
</div>
</IntlProvider>
}
} |
JavaScript | class JoiValidate {
/**
* @param {JoiValidateOptions} options
*/
constructor(options) {
this.options = options;
// Compile json schema
for (let key in this.options) {
if (this.options[key].json) {
this.options[key] = {
json: this.options[key].json,
schema: Joi.compile(
this.options[key].json).options({ abortEarly: false }
),
};
} else {
this.options[key] = {
json: null,
schema: this.options[key].schema.options({
abortEarly: false,
}),
};
}
}
this.mid = this.mid.bind(this);
return this.mid;
}
/**
* Express middleware to validate request
* @param {Object} req
* @param {Object} res
* @param {Function} next
*/
mid(req, res, next) {
// Validate - query, params, body
for (let key in this.options) {
const { error } = Joi.validate(
req[key],
this.options[key].schema
);
if (error === null) {
next();
} else {
// Send the errors
let response = new Response(req, res, next);
// If debug mode is on Set original errors to response
if (this.debugErrors) {
response.data(error.details);
}
for (let i in error.details) {
let { type, context: { key } } = error.details[i];
response.error(key, JoiErrorsMap[type]
? JoiErrorsMap[type] : JoiErrorsMap.other
);
}
response
.status(HttpCodes.UNPROCESSABLE_ENTITY)
.send();
}
}
};
} |
JavaScript | class PetriNet {
constructor() {
this.placeCount = 0;
this.places = {};
this.transitions = {};
}
/**
* Builds a properly sized [0]*n vector for this model.
*/
emptyVector() {
const out = [];
for (let i=0; i < this.placeCount; i++) {
out.push(0);
}
return out;
}
/**
* Collect initial place conditions into a vector.
* Used to initialize state machine when transacting with a Model.
*/
initialState() {
const out = [];
for ( const label in this.places) {
const p = this.places[label];
out[p.offset] = p.initial || 0;
}
return out;
}
/**
* Collect capacity limits into a vector
*/
stateCapacity() {
const out = [];
for ( const label in this.places) {
const p = this.places[label];
out[p.offset] = p.capacity || 0;
}
return out;
}
} |
JavaScript | class SearchActions {
constructor() {
this.generateActions(
'searchSuccess',
'searchFail'
);
}
// Sending new add information to DB
getPost(category) {
console.log("category search actions", category);
fetch(`/api/search/${category}`)
.then((response) => {
return response.json()
})
.then((results) => {
this.actions.searchSuccess(results);
})
.catch((err) => {
this.actions.searchFail(err);
});
}
} |
JavaScript | class Users extends Base {
/**
* Constructor
*
* @constructor
*/
constructor() {
super();
const oThis = this;
oThis.resource = 'https://api.twitter.com/1.1/users';
}
/**
* Get Users by twitterIds(followed by current user)
*
* @returns {Promise<*>}
*/
async lookup(params) {
const oThis = this;
let twitterIds = params.twitterIds,
includeEntities = params.includeEntities || false;
let completeUrl = oThis.resource + '/lookup.json';
let requestParams = { user_id: twitterIds.join(), include_entities: includeEntities };
let oAuthCredentials = {
oAuthConsumerKey: coreConstants.TWITTER_CONSUMER_KEY,
oAuthConsumerSecret: coreConstants.TWITTER_CONSUMER_SECRET,
oAuthToken: params.oAuthToken,
oAuthTokenSecret: params.oAuthTokenSecret
},
twitterRequestParams = {
requestType: 'GET',
completeUrl: completeUrl,
oAuthCredentials: oAuthCredentials,
requestParams: requestParams
};
let response = await oThis._fireRequest(twitterRequestParams);
let parsedResponse = await oThis._parseJsonResponse(response.data);
if (parsedResponse.isFailure()) {
return parsedResponse;
}
let finalResp = {};
for (let i = 0; i < parsedResponse.data.response.length; i++) {
let userEntity = new UserTwitterEntityClass(parsedResponse.data.response[i]);
finalResp[userEntity.idStr] = userEntity;
}
return responseHelper.successWithData({ response: finalResp });
}
} |
JavaScript | class Player{
constructor(name){
this._name = name;
this.init();
}
init(){
this._points = 0;
this._wins = 0;
this._ties = 0;
this._loses = 0;
}
get name() {
return this._name;
}
set name(name){
this._name = name;
}
set points(points){
this._points = points;
}
get points(){
return this._points;
}
set wins(wins){
this._wins = wins;
}
get wins(){
return this._wins;
}
set ties(ties){
this._ties = ties;
}
get ties(){
return this._ties;
}
set loses(loses){
this._loses = loses;
}
get loses(){
return this._loses;
}
get result(){
return [this._name, this._points, this._wins, this._ties, this._loses];
}
get toString(){
return `Hello ${this._name}`;
}
} |
JavaScript | class Computer extends Player{
constructor(){
super("Computer");
}
makeMove(){
if(!won && spotsLeft >0){
let moveX = Math.floor((Math.random() * MAX));
let moveY = Math.floor((Math.random() * MAX));
//get an open spot in the array
while((Game.checkIfSpotTaken(moveX+1,moveY+1))){
moveX = Math.floor((Math.random() * MAX));
moveY = Math.floor((Math.random() * MAX));
}
f[moveX][moveY] = 'o';
spotsLeft--;
boxes[(moveX*3)+moveY].querySelector('.symbol').innerHTML = 'o';
boxes[(moveX*3)+moveY].classList.add("green-box");
Game.checkIfWon("Computer");
}
}
} |
JavaScript | class Human extends Player{
constructor(name){
super(name);
}
//makes a move and also checks if spot is already taken
makeMove(x,y, shape, div){
if((x > MAX) || (y > MAX) || (y < 1) || (x < 1)){
return false;
}
if((f[x-1][y-1] !== 'x') && (f[x-1][y-1] !== 'o')){
console.log("NO SHAPE" + f[x-1][y-1] + " x " + x+ " y " + y);
f[x-1][y-1] = shape;
spotsLeft--;
div.querySelector('.symbol').innerHTML = 'x';;
div.classList.add("blue-box");
return true;
}else{
return false;
}
}
} |
JavaScript | class Game{
/*Default Constructor*/
constructor(iMax, jMax){
this.createArray(iMax , jMax)
}
/*Create initial empty array*/
createArray(iMax, jMax){
for (let i = 0; i < iMax; i++) {
f[i]=new Array();
for (let j=0; j < jMax; j++) {
f[i][j]=0;
}
}
}
/*Creates one instance of game*/
static getInstance(){
if(!instance){
instance = this.createInstance();
}
}
static createInstance(){
return new Game(3,3);
}
static checkIfWon(nameOfWinner){
//traverse all the array to check if we won
let i = 0, j = 0;
for(; i < 3; i++){
if(((f[i][0] === 'x') && (f[i][1] ==='x') && (f[i][2] =='x'))
||((f[i][0] === 'o') && (f[i][1] ==='o') && (f[i][2] =='o'))){
won = true;
}//horizontal
else if(((f[0][i] === 'x') && (f[1][i] ==='x') && (f[2][i] =='x'))
||((f[0][i] === 'o') && (f[1][i] ==='o') && (f[2][i] =='o'))){
won = true;
}//vertical
}
if(((f[0][0] === 'x') && (f[1][1] ==='x') && (f[2][2] =='x'))
||((f[0][0] === 'o') && (f[1][1] ==='o') && (f[2][2] =='o'))){
won = true;
}else if(((f[2][0] === 'x') && (f[1][1] ==='x') && (f[0][2] =='x'))
||((f[2][0] === 'o') && (f[1][1] ==='o') && (f[0][2] =='o'))){
won = true;
}else if(spotsLeft == 0 && !won){
computer.points += 2;
human.points +=2;
human.ties++;
computer.ties++;
updateTable();
document.getElementById("play-again").classList.remove("hide");
}
if(won){
alert(nameOfWinner + " is the winner.");
if(nameOfWinner==="Computer"){
computer.points += 5;
computer.wins++;
human.loses++;
}else{
human.points +=5;
computer.loses++;
human.wins++;
}
document.getElementById("play-again").classList.remove("hide");
boxcontainer.removeEventListener("click", clickEvents, false);
updateTable();
}
}
static checkIfSpotTaken(x, y){
return (f[x-1][y-1] != 0);
}
} |
JavaScript | class Polygon
{
constructor(sides)
{
this.sides=sides;
}
perimeter()
{
var sum=0;
for(var i=0; i<this.sides.length;i++)
sum=sum+this.sides[i];
return sum;
}
} |
JavaScript | class CognitiveServicesResourceAndSku {
/**
* Create a CognitiveServicesResourceAndSku.
* @property {string} [resourceType] Resource Namespace and Type
* @property {object} [sku] The SKU of Cognitive Services account.
* @property {string} [sku.name] Gets or sets the sku name. Required for
* account creation, optional for update.
* @property {string} [sku.tier] Gets the sku tier. This is based on the SKU
* name. Possible values include: 'Free', 'Standard', 'Premium'
*/
constructor() {
}
/**
* Defines the metadata of CognitiveServicesResourceAndSku
*
* @returns {object} metadata of CognitiveServicesResourceAndSku
*
*/
mapper() {
return {
required: false,
serializedName: 'CognitiveServicesResourceAndSku',
type: {
name: 'Composite',
className: 'CognitiveServicesResourceAndSku',
modelProperties: {
resourceType: {
required: false,
serializedName: 'resourceType',
type: {
name: 'String'
}
},
sku: {
required: false,
serializedName: 'sku',
type: {
name: 'Composite',
className: 'Sku'
}
}
}
}
};
}
} |
JavaScript | class IntegerArgumentType extends Argument {
constructor(client) {
super(client, 'integer');
}
// Check if a string can be parsed into an int
validate(val, arg) {
const int = Number.parseInt(val);
if (Number.isNaN(int)) return false;
if (arg.min !== null && typeof arg.min !== 'undefined' && int < arg.min) {
return `Please enter a number above or exactly ${arg.min}.`;
}
if (arg.max !== null && typeof arg.max !== 'undefined' && int > arg.max) {
return `Please enter a number below or exactly ${arg.max}.`;
}
return true;
}
// Check if a string can be converted to an int
baseValidate(val) {
return Number.isNaN(Number.parseInt(val));
}
// Convert a string integer to an int
parse(val) {
return Number.parseInt(val);
}
// Check if a string could be the start of an int
isPossibleStart(val) {
return this.baseValidate(val);
}
} |
JavaScript | class Git {
/**
* Constructor
*/
constructor (options = {}) {
this.NO_CHANGES = 'NO_CHANGES'
this.BRANCH_CREATED = 'BRANCH_CREATED'
this.logger = options.logger || console
this.shell = new Shell({ logger: this.logger })
this.username = null
this.password = null
this.request = new Request()
}
/**
* Configure local git and set class-wide values
* @param {string} username the auth username
* @param {string} password the auth password
* @param {string} [name] the git config user.name
* @param {string} [email] the git config user.email
* @returns {Promise} the shell result of the final shell config command
*/
configure (username, password, name, email) {
this.username = username
this.password = password
return this.shell.exec('git', ['config', '--global', 'user.name', name]).then(() => {
return this.shell.exec('git', ['config', '--global', 'user.email', email])
})
}
/**
* Will translate a normal URL into an http-authenticated URL, e.g. https://username:password@[the url]
* @param {string} url the regular url, repo url
* @returns {string} the url with username and password injected
*/
getAuthenticatedUrl (url) {
const encodedCreds = encodeURIComponent(this.username) + ':' + encodeURIComponent(this.password)
return url.replace(/http(s)?:\/\//, `http$1://${encodedCreds}@`)
}
/**
* Gets the default branch according to a remote
* @param {string} localClonePath the local path to a repo clone
* @param {string} [remoteName=origin] the remote name
* @returns {Promise} Promise result is the branch name
*/
getRemoteDefaultBranch (localClonePath, remoteName = 'origin') {
return this.shell.exec('git', ['remote', 'show', remoteName], { cwd: localClonePath, silent: true }).then((result) => {
let branch = null
result.stdout.split('\n').forEach((line) => {
if (line.match(/(\s+)?HEAD branch:/)) {
branch = line.split(':')[1].trim()
}
})
return branch
})
}
/**
* Gets the URL of the remote "origin" from a local clone
*
* @param {string} localClonePath the local path to a repo clone
* @retursn {Promise} Promise result is the trimmed stdout of the 'git remote get-url origin' command
*/
getRemoteOriginUrl (localClonePath) {
return this.shell.exec('git', ['remote', 'get-url', 'origin'], { cwd: localClonePath, silent: true }).then((result) => {
return result.stdout.trim()
})
}
/**
* Run a general diff b/w two branches
* @param {string} localClonePath the local path to a repo clone
* @param {string} branch1 the name of the first branch to diff
* @param {string} branch2 the name of the second branch to diff
* @returns {Promise} Promise result is the trimmed stdout of the git diff
*/
diffBranches (localClonePath, branch1, branch2) {
return this.shell.exec('git', ['diff', branch1, branch2], { cwd: localClonePath }).then((result) => {
return result.stdout.trim()
})
}
/**
* Clone a remote repo to a local location and optionally check out a branch that isn't the default one
* @param {string} repoUrl https URL of the repo
* @param {string} toPath path to the local clone location
* @param {string} [branch=null] name branch to checkout after cloning
* @param {boolean} [newBranch=true] whether or not the branch to check out is new
* @returns {Promise} Promise result is the shell result
*/
clone (repoUrl, toPath, branch = null, newBranch = true) {
return this.shell.exec('git', ['clone', this.getAuthenticatedUrl(repoUrl), toPath], { mask: [ encodeURIComponent(this.password) ]}).then(() => {
if (branch !== null) {
const args = ['checkout']
if (newBranch) args.push('-b')
args.push(branch)
return this.shell.exec('git', args, { cwd: toPath })
}
})
}
/**
* Adds, commits, and pushes changes in a single operation, does nothing if no changes need be
* committed/pushed based on the state of the local clone
*
* @param {string} localClonePath the local path to a repo clone
* @param {string} commitMessage the commit message to apply
* @param {Object} [options={}] commit and push options
* @param {boolean} [options.force=false] whether or not to run a <code>git push -f</code>
* @param {boolean} [options.openPullRequest=false] whether or not to automatically open a pull request (only triggered if pushed branch is different than the default)
* @param {string} [options.pullRequestDestination=<local clone origin>] optional repository url where the pull request should be submitted, useful for forks
* @param {string} [options.pullRequestDescription=Pull request submitted by generators] the description to add to the PR
* @returns {Promise} Promise result is the shell result of the push
*/
commitAndPush (localClonePath, commitMessage, options = {}) {
let remoteOriginUrl = null
let branchToPush = null
options = Object.assign({
force: false,
openPullRequest: false,
pullRequestDestination: null,
pullRequestDescription: 'Pull request submitted by generators',
}, options)
return this.shell.exec('git', ['status', '-s'], { cwd: localClonePath }).then((result) => {
return result.stdout.trim() == '' ? this.NO_CHANGES : this.shell.exec('git', ['add', '.'], { cwd: localClonePath })
}).then((result) => {
return result == this.NO_CHANGES ? result : this.shell.exec('git', ['commit', '-m', commitMessage], { cwd: localClonePath })
}).then((result) => {
return result == this.NO_CHANGES ? result : this.shell.exec('git', ['rev-parse', '--abbrev-ref', 'HEAD'], { cwd: localClonePath })
}).then((result) => {
if (result == this.NO_CHANGES) return result
branchToPush = result.stdout.trim()
let pushArgs = ['push']
if (options.force) pushArgs.push('-f')
pushArgs.push('origin')
pushArgs.push(branchToPush)
return this.shell.exec('git', pushArgs, { cwd: localClonePath, mask: [ encodeURIComponent(this.password) ] })
}).then((result) => {
if (result == this.NO_CHANGES) return result
if (options.openPullRequest) {
return this.getRemoteOriginUrl(localClonePath)
}
return this.BRANCH_CREATED
}).then((result) => {
if (result == this.NO_CHANGES || result == this.BRANCH_CREATED) return result
remoteOriginUrl = result
if (options.pullRequestDestination === null) {
options.pullRequestDestination = remoteOriginUrl
}
return this.getRemoteDefaultBranch(localClonePath)
}).then((result) => {
if (result == this.NO_CHANGES || result == this.BRANCH_CREATED) return result
return this.openPullRequest(remoteOriginUrl, branchToPush, {
defaultBranch: result,
destinationRepoUrl: options.pullRequestDestination,
description: options.pullRequestDescription,
})
})
}
/**
* Filter the given repo url from prompts
*
* @param {string} repoUrl
* @returns {string} the formatted url for use internally for cloning
*/
getRepoHttpsCloneUrl (url) {
const repoUrlParts = this.getRepoUrlParts(url)
return `https://stash.us.cray.com/scm/${repoUrlParts.projectName}/${repoUrlParts.repoName}.git`
}
/**
* Validate the given repo url from prompts
*
* @param {string} repoUrl
* @returns {bool} if validation passes
*/
validateRepoHttpsCloneUrl (url) {
if (url.match(/^https:\/\/stash\.us\.cray\.com\/scm\/.*\.git/)) {
return true
}
return false
}
/**
* Parse a repo url to get the project/user and repo name
*
* @param {string} repoUrl URL of the repo, can either be an ssh (git remote get-url) or the https
* @returns {Object} { projectName, repoName }
*/
getRepoUrlParts (repoUrl) {
if (!repoUrl.match(/^(http(s)?|ssh):\/\//)) {
throw new Error(`Invalid repoUrl: ${repoUrl}`)
}
let regex = new RegExp('^(http(s)?|ssh):\\/\\/:')
let urlLessProtocol = repoUrl.replace(regex, '')
let parts = urlLessProtocol.split('/')
let projectName = parts[parts.length - 2].replace(/\.git$/, '')
let repoName = parts[parts.length - 1].replace(/\.git$/, '')
return { projectName, repoName }
}
/**
* Opens a pull request against a repos default branch
*
* @param {string} repoUrl URL of the source repo, can either be an ssh (git remote get-url) or the https
* @param {string} branchName source branch name from which to initiate a pull request
* @param {Object} [options={}] pull request options
* @param {string} [options.defaultBranch=develop] the default branch of the destination repo for the pull request, where we want the changes to end up
* @param {string} [options.destinationRepoUrl=<repoUrl>] the repo where the pull request should be opened, defaults to the repoUrl parameter
* @param {string} [options.description=''] the description of the PR
* @returns {Promise} the request result/response
*/
openPullRequest (repoUrl, branchName, options = {}) {
options = Object.assign({
defaultBranch: 'develop',
destinationRepoUrl: repoUrl,
description: ''
}, options)
const sourceUrlParts = this.getRepoUrlParts(repoUrl)
const destUrlParts = this.getRepoUrlParts(options.destinationRepoUrl)
const uri = 'https://stash.us.cray.com/rest/api/1.0/projects/' +
`${destUrlParts.projectName}/repos/${destUrlParts.repoName}/pull-requests`
const requestOptions = {
uri: uri,
method: 'POST',
json: true,
body: {
title: `Cray Generators ${branchName}`,
description: options.description,
fromRef: {
id: `refs/heads/${branchName}`,
repository: {
slug: sourceUrlParts.repoName,
name: null,
project: {
key: sourceUrlParts.projectName,
},
},
},
toRef: {
id: `refs/heads/${options.defaultBranch}`,
repository: {
slug: destUrlParts.repoName,
name: null,
project: {
key: destUrlParts.projectName,
},
},
},
},
auth: {
user: this.username,
password: this.password,
},
}
return this.request.request(requestOptions, (error, response, body) => {
if (error) return error
if (response && response.statusCode != 201 && response.statusCode != 409) {
return `Received response code ${response.statusCode} from ${uri} ` +
`attempting to open a pull request, body: ${JSON.stringify(body)}`
}
return true
})
}
/**
* Forks a repo to a destination project/user space in stash
*
* @param {string} repoUrl URL of the source repo, can either be an ssh (git remote get-url) or the https
* @param {string} destinationProject The destination project/user space
* @returns {Promise} the request result/response
*/
fork (repoUrl, destinationProject) {
const urlParts = this.getRepoUrlParts(repoUrl)
const uri = `https://stash.us.cray.com/rest/api/1.0/projects/${urlParts.projectName}/repos/${urlParts.repoName}`
const requestOptions = {
uri: uri,
method: 'POST',
json: true,
body: {
name: urlParts.repoName,
project: {
key: destinationProject
}
},
auth: {
user: this.username,
password: this.password,
},
}
return this.request.request(requestOptions, (error, response, body) => {
if (error) return error
if (response && response.statusCode != 201) {
return `Received response code ${response.statusCode} from ${uri} ` +
`attempting to create a fork, body: ${JSON.stringify(body)}`
}
return true
})
}
} |
JavaScript | class CandyGen {
// Copyright © 2021 Vanessa Sochat MIT License
// See github.com/vsoch/candy-generator for full license
// Keep record of candy bases!
items = {
templates: [],
choices: {}
};
// The constructor is called when we create a Candy Gen object
constructor(candy, width, height, divid, resetButton, formButton, githubButton) {
// Choose a random template to start with
this.width = width || 800;
this.height = height || 500;
this.divid = divid || "#candy";
// Loaded candy json
this.candy = candy;
this.items.templates = Object.keys(this.candy);
// Button identifiers
this.resetButton = resetButton || "#resetCandy"
this.textureButton = resetButton || "#candy-texture"
this.formButton = formButton || "#candy-form"
this.githubButton = githubButton || "#github-button"
// Variables for the svg, and candy image svg within
this.reset();
// Setup color choosers
this.setupChoosers()
// Tell the user the chosen parameters
this.status()
// Event binding for buttons, setup of color picker
$(this.resetButton).on("click", {client: this}, this.reset);
$(this.textureButton).on("change", {client: this}, this.changeTexture);
$(this.formButton).on("change", {client: this}, this.changeForm);
$(this.githubButton).on("click", {client: this}, this.loadGitHub);
$(this.saveButton).on("click", {client: this}, this.saveSVG);
}
// Print a status for the user
status() {
console.log("template: " + this.items.choices["template"])
}
// Choose a template, either randomly or by choice
chooseTemplate(choice, client) {
client = client || this
// If a choice is provided and it is in the array
if (choice != null && client.items.templates.includes(choice)) {
var choice = client.items.choices["template"] = this.candy[choice];
this.items.choices["template"] = choice;
// Otherwies choose randomly
} else {
var index = Math.floor(Math.random() * client.items.templates.length);
client.items.choices["template"] = this.candy[client.items.templates[index]];
}
}
// Set the candy texture
changeTexture(event) {
var client = event.data.client
var texture = $(this).val();
client.setTexture(texture, client)
}
// Change the candy form (background)
changeForm(event) {
var client = event.data.client
var form = $(this).val();
client.chooseTemplate(form, client);
client.setTemplate();
client.setFacts();
client.setTexture(null, client);
client.setFont(client);
client.setTitleColor(client);
}
loadGitHub(event) {
var client = event.data.client
var uri = $("#github-uri").val();
if (uri == "") {
$.notify("Please enter the name of a repository!", "warning");
return
}
// Split into org/repo
var parts = uri.split("/")
if (parts.length != 2) {
$.notify("The repository should be in the format ORG/NAME", "warning");
return
}
// Otherwise, make the GitHub call
fetch('https://api.github.com/repos/' + uri)
.then(response => response.json())
.then(data => {
console.log(data);
window.github_data = data;
})
.catch(error => console.error(error));
// timeout to see data - yeah yeah I know, imperfect :)
setTimeout(function(){ client.renderGitHub(client) }, 500);
}
// Whatever GitHub data we have, render it
renderGitHub(client) {
client.setFacts()
console.log(window.github_data);
}
// Update font color
setFont(client) {
var color = client.items.choices["font_color"]
client.setTemplate();
client.setTexture(null, client);
client.setFacts();
}
// Update title color
setTitleColor(client) {
var color = client.items.choices["title_color"]
client.setTemplate();
client.setTexture(null, client);
client.setFacts();
}
// Actually set a texture
setTexture(texture, client) {
// If no client provided, use this
client = client || this
// Default texture is current
texture = texture || client.items.choices['texture']
// If solid texture, set fill to selected color
if (texture == "solid") {
console.log("updating texture")
client.paths.style("fill", client.items.choices['color']);
// Diagonal lines
} else if (texture == "lines") {
var t = textures.lines()
.orientation("diagonal")
.size(40)
.strokeWidth(26)
.stroke(client.items.choices["color"])
.background(client.items.choices['texture_color']);
client.svg.call(t);
client.paths.style("fill", t.url());
} else if (texture == "checkers") {
var t = textures.lines()
.orientation("3/8", "7/8")
.size(40)
.stroke(client.items.choices["texture_color"])
.background(client.items.choices['color']);
client.svg.call(t);
client.paths.style("fill", t.url());
} else if (texture == "circles") {
var t = textures.circles()
.size(40)
.fill(client.items.choices["texture_color"])
.background(client.items.choices['color']);
client.svg.call(t);
client.paths.style("fill", t.url());
} else if (texture == "patch") {
var t = textures.circles()
.size(35)
.complement()
.fill(client.items.choices["texture_color"])
.background(client.items.choices['color']);
client.svg.call(t);
client.paths.style("fill", t.url());
} else if (texture == "honeycomb") {
var t = textures.paths()
.d("hexagons")
.size(14)
.strokeWidth(2)
.background(client.items.choices['color'])
.stroke(client.items.choices["texture_color"]);
client.svg.call(t);
client.paths.style("fill", t.url());
} else if (texture == "caps" || texture == "crosses" || texture == "woven") {
var t = textures.paths()
.d(texture)
.lighter()
.thicker()
.size(40)
.strokeWidth(2)
.background(client.items.choices['color'])
.stroke(client.items.choices["texture_color"]);
client.svg.call(t);
client.paths.style("fill", t.url());
} else if (texture == "waves") {
var t = textures.paths()
.d("waves")
.thicker()
.strokeWidth(2)
.size(40)
.background(client.items.choices['color'])
.stroke(client.items.choices["texture_color"]);
client.svg.call(t);
client.paths.style("fill", t.url());
} else if (texture == "nylon") {
var t = textures.paths()
.d("nylon")
.lighter()
.strokeWidth(2)
.size(40)
.shapeRendering("crispEdges")
.background(client.items.choices['color'])
.stroke(client.items.choices["texture_color"]);
client.svg.call(t);
client.paths.style("fill", t.url());
} else if (texture == "squares") {
var t = textures.paths()
.d("squares")
.thicker()
.strokeWidth(2)
.size(40)
.background(client.items.choices['color'])
.stroke(client.items.choices["texture_color"]);
client.svg.call(t);
client.paths.style("fill", t.url());
}
client.items.choices['texture'] = texture;
}
setupChoosers() {
var client = this
// Fill in options for candy form
for (var name of this.items.templates) {
$("#candy-form").append("<option>" + name + "</option>");
}
// Callback to update color of candy
function updateColor (event) {
console.log("Updating color to " + event.target.value);
d3.select("#candy-path").attr("fill", event.target.value);
client.items.choices["color"] = event.target.value;
client.setTexture(client.items.choices["texture"], client)
}
function updateTexture (event) {
console.log("Updating texture color to " + event.target.value);
client.items.choices["texture_color"] = event.target.value;
client.setTexture(client.items.choices["texture"], client)
}
function updateFont (event) {
console.log("Updating font color to " + event.target.value);
client.items.choices["font_color"] = event.target.value;
client.setFont(client)
}
function updateTitleColor (event) {
console.log("Updating title color to " + event.target.value);
client.items.choices["title_color"] = event.target.value;
client.setTitleColor(client)
}
this.colorChooser = document.querySelector("#candy-color");
this.colorChooser.addEventListener("change", updateColor, false);
this.textureColorChooser = document.querySelector("#texture-color");
this.textureColorChooser.addEventListener("change", updateTexture, false);
this.fontColorChooser = document.querySelector("#font-color");
this.fontColorChooser.addEventListener("change", updateFont, false);
this.titleColorChooser = document.querySelector("#title-color");
this.titleColorChooser.addEventListener("change", updateTitleColor, false);
}
// set the chosen template
setTemplate() {
var choice = this.items.choices['template']
d3.select(this.divid).html("");
var client = this;
this.svg = d3.select(this.divid).append("svg")
.attr("id", "svg")
.attr("width", this.width)
.attr("height", this.height);
this.group = this.svg.selectAll('paths')
.data(Array(choice))
.enter()
.append("g")
.attr("transform", function(d) {return d.transform})
this.paths = this.group.append('svg:path')
.attr('d', function(d) {return d.paths})
.attr('id', "candy-path")
.attr('transform', function(d) {return "scale("+ d.scale + ")"})
// Set any attributes provided by default
.each(function (d) {
for (var attr of d.attrs) {
d3.select(this).attr(attr[0], attr[1])
if (attr[0] == "fill") {
d3.select("#candy-color").value = attr[1];
}
}
})
this.group.append("text")
.attr("x", function(d) { var center = getTextLocation(d3.select("#candy-path"), d.xoffset, d.yoffset); return center[0]; })
.attr("y", function(d) { var center = getTextLocation(d3.select("#candy-path"), d.xoffset, d.yoffset); return center[1]; })
.attr("fill", client.items.choices['title_color'])
.attr("font-size", 26)
.attr("id", "candy-title")
.text(function(d) { return "Happy Halloween!"; });
// Date the candy for the right year
this.group.append("text")
.attr("x", function(d) { var center = getTextLocation(d3.select("#candy-path"), d.xoffset, d.yoffset); return center[0] + 500; })
.attr("y", function(d) { var center = getTextLocation(d3.select("#candy-path"), d.xoffset, d.yoffset); return center[1] - 10; })
.attr("fill", client.items.choices['font_color'])
.attr("font-size", 16)
.text(function(d) {
var date = new Date();
return date.getFullYear()
});
// Reference to repository
this.group.append("text")
.attr("x", function(d) { var center = getTextLocation(d3.select("#candy-path"), d.xoffset, d.yoffset); return center[0] + 350; })
.attr("y", function(d) { var center = getTextLocation(d3.select("#candy-path"), d.xoffset, d.yoffset); return center[1] + 140; })
.attr("fill", client.items.choices['font_color'])
.attr("font-size", 10)
.attr("font-style", "italic")
.attr("opacity", "0.3")
.attr("font-family", "Arial")
.text("Created by https://vsoch.github.io/candy-generator");
this.group.append("text")
.attr("x", function(d) { var center = getTextLocation(d3.select("#candy-path"), d.xoffset, d.yoffset); return center[0]; })
.attr("y", function(d) { var center = getTextLocation(d3.select("#candy-path"), d.xoffset, d.yoffset); return center[1] + 20; })
.attr("fill", "yellow")
.attr("font-size", 14)
.classed('nutrition-box', true)
.style('display', 'none')
.attr("id", "candy-subtitle")
.text("");
// Nutrition facts
this.group.append('rect')
.attr('width', '300')
.attr('height', '60')
.attr('x', function(d) { var center = getTextLocation(d3.select("#candy-path"), d.xoffset, d.yoffset); return center[0]})
.attr('y', function(d) { var center = getTextLocation(d3.select("#candy-path"), d.xoffset, d.yoffset); return center[1] + 60})
.attr('fill', 'rgba(0,0,0,0)')
.attr('stroke', client.items.choices['font_color'])
.attr('stroke-dasharray', '10,5')
.classed('nutrition-box', true)
.style('display', 'none')
.attr('stroke-linecap', 'butt')
// Add text that says NUTRITION FACTS
this.group.append("text")
.attr("x", function(d) { var center = getTextLocation(d3.select("#candy-path"), d.xoffset, d.yoffset); return center[0]; })
.attr("y", function(d) { var center = getTextLocation(d3.select("#candy-path"), d.xoffset, d.yoffset); return center[1] + 55; })
.attr("fill", client.items.choices['font_color'])
.attr("font-size", 12)
.attr("font-family", "Arial")
.classed('nutrition-box', true)
.style('display', 'none')
.text("NUTRITION FACTS");
// Hidden spot for eventual avatar image
this.group.append("svg:image")
.attr("x", function(d) { var center = getTextLocation(d3.select("#candy-path"), d.xoffset, d.yoffset); return center[0] + 400; })
.attr("y", function(d) { var center = getTextLocation(d3.select("#candy-path"), d.xoffset, d.yoffset); return center[1] + 10; })
.attr('width', 100)
.attr('height', 100)
.classed('nutrition-box', true)
.attr('id', 'avatar-image')
.attr("xlink:href", "")
var start = 75;
for (var i=1; i<=5; i++) {
this.group.append("text")
.attr("x", function(d) { var center = getTextLocation(d3.select("#candy-path"), d.xoffset, d.yoffset); return center[0] + 5; })
.attr("y", function(d) { var center = getTextLocation(d3.select("#candy-path"), d.xoffset, d.yoffset); return center[1] + start; })
.attr("fill", client.items.choices['font_color'])
.attr("font-size", 10)
.attr("font-family", "Arial")
.classed('nutrition-box', true)
.attr('id', 'nutrition-facts' + i)
.style('display', 'none')
.text("");
start += 10;
}
}
// Set title for the candy
setTitle(title) {
if (title != null) {
$("#candy-title").text(title);
}
}
setSubtitle(subtitle) {
if (subtitle != null) {
if (subtitle.length > 60) {
subtitle = subtitle.slice(0, 59) + "..."
}
$("#candy-subtitle").text(subtitle);
}
}
// Set nutrition facts in the box
setFacts() {
if (window.github_data != null) {
this.setTitle(window.github_data['full_name'])
this.setSubtitle(window.github_data['description'])
var lang = window.github_data['language']
var license = "unknown";
if (window.github_data.license != null) {
license = window.github_data['license']['name']
}
var issues = window.github_data['open_issues']
var stars = window.github_data['stargazers_count']
var subscribers = window.github_data['subscribers_count']
var watchers = window.github_data['watchers_count']
var size = window.github_data['size']
var owner = window.github_data['owner']['login']
var logo = window.github_data['owner']['avatar_url']
var line1 = "INGREDIENTS: " + "language " + lang + ";";
var line2 = "license: " + license + ";";
var line3 = "issues: " + issues + "; stars ⭐️: " + stars + "; watchers 👀️: " + watchers;
var line4 = "subscribers: " + subscribers + "; " + "size: " + size + ";";
var line5 = "owner: " + owner + ";";
$("#nutrition-facts1").text(line1);
$("#nutrition-facts2").text(line2);
$("#nutrition-facts3").text(line3);
$("#nutrition-facts4").text(line4);
$("#nutrition-facts5").text(line5);
$("#avatar-image").attr("xlink:href", logo);
$("#avatar-image").attr("src", logo);
$("#avatar-image").attr("href", logo);
$(".nutrition-box").show();
}
}
// Reset Choices and Chandy
reset(event) {
var client;
if (event != null) {client = event.data.client} else {client = this}
this.svg = null;
this.img = null;
client.items.choices = {"texture": "solid", "texture_color": "green", "color": "#482f1e", "font_color": "white", "title_color": "white"};
client.chooseTemplate("crunch");
client.setTemplate();
client.setFacts();
}
} |
JavaScript | class Line extends DrawPrimitive {
/**
* The default constructor for the Line object.
*
* board - Reference to the parent game board.
* type - Specifies type of line. Either `horizontal` or `vertical`.
* index - array location of the line in the game board's array of lines
* vertex1 - One of Vertex objects that define the Line.
* vertex2 - Other Vertex object that define the Line.
*/
constructor(board, type, index, vertex1, vertex2) {
super();
this._renderer = board;
this._type = type;
this._index = index;
this._vertex1 = vertex1;
this._vertex2 = vertex2;
this._owner = null;
this._outline = 'black';
this._fill = 'black';
}
/**
* Draws the Line as a straight between two dots.
*/
draw() {
let that = this;
let line = document.createElementNS("http://www.w3.org/2000/svg", "line");
line.setAttribute('class', 'segment');
line.setAttribute('data-index', this.index);
line.setAttribute('x1', this.vertex1.radius + this.vertex1.x * this.board.squareWidth);
line.setAttribute('y1', this.vertex1.radius + this.vertex1.y * this.board.squareHeight);
line.setAttribute('x2', this.vertex2.radius + this.vertex2.x * this.board.squareWidth);
line.setAttribute('y2', this.vertex2.radius + this.vertex2.y * this.board.squareHeight);
/* Set id, for this line, in order to retrieve later. */
line.setAttribute(
'id',
'line-' + this.vertex1.x + '-' + this.vertex1.y + '-' + this.vertex2.x + '-' + this.vertex2.y
);
/* Attach the click event. */
line.addEventListener('click', function (e) {
that.board.game.completeTurn(that);
});
this.board.svg.appendChild(line);
};
/**
* Mark, that this line is owned now.
* Also update the color.
*/
claimOwnership(owner) {
if (!this.isOwned) {
/* Get the element. */
let lineDOM = document.getElementById(
'line-' + this.vertex1.x + '-' + this.vertex1.y + '-' + this.vertex2.x + '-' + this.vertex2.y
);
/* Update it's color and the owner. */
lineDOM.setAttribute('style', 'stroke: ' + owner.color + ' !important');
this._owner = owner;
/* Propagate the owner update further into child objects. */
this.vertex1.claimOwnership(owner);
this.vertex2.claimOwnership(owner);
}
}
/* Getter functions for this class. */
get isOwned() {
return !!this._owner;
}
get owner() {
return this._owner;
}
get board() {
return this._renderer;
}
get getType() {
return this._type;
}
get index() {
return this._index;
}
get vertex1() {
return this._vertex1;
}
get vertex2() {
return this._vertex2;
}
} |
JavaScript | class DefaultGameState extends BaseGameState {
constructor(gsm, data) {
if (data === undefined) data = {};
data.id = 'init_j2d';
super(gsm, data);
}
// init(data) {
// return BaseGameState.prototype.init.call(this, data);
// }
//
// load(data) {
// return BaseGameState.prototype.load.call(this, data);
// }
update(timestamp, data) {
setTimeout(function () {
this.gsm.setNextState();
}.bind(this), 1000);
return true;
}
// render(timestamp, data) {
// return true;
// }
//
// unload(data) {
// return BaseGameState.prototype.unload.call(this, data);
// }
} |
JavaScript | class TransformUtils {
/**
* Get a new name for temporary variable
* @param {string} varPrefix prefix for the variable
* @param {TransformNode} transformNode transform node for which the new temp variable is created
* @returns {Expression} temporary var expression
* @memberof TransformNodeMapper
*/
static getNewTempVarName(transformNode, varPrefix = VarPrefix.VAR) {
const varNameRegex = new RegExp(varPrefix + '[\\d]*');
const tempVarSuffixes = [];
transformNode.body.getStatements().forEach((stmt) => {
let variables = [];
if (TreeUtil.isAssignment(stmt)) {
variables = stmt.getVariables();
} else if (TreeUtil.isVariableDef(stmt)) {
variables.push(stmt.getVariable());
}
variables.forEach((varExp) => {
const expStr = varExp.getSource();
if (varNameRegex.test(expStr)) {
const index = Number.parseInt(expStr.substring(varPrefix.length + 1), 10) || 0;
tempVarSuffixes.push(index);
}
});
});
// numeric sort by difference
tempVarSuffixes.sort((a, b) => a - b);
const index = (tempVarSuffixes[tempVarSuffixes.length - 1] || 0) + 1;
return varPrefix + index;
}
} |
JavaScript | class pieSelect {
constructor(cfg) {
let hovertemplate = `<b>%{label}</b><br><span style='font-size:1.1em;'>${visText.total.en}: <b style='color:#ebdf9a'> %{value} </b></span> <extra></extra>`
if (globalThis.lang == 'ur')
hovertemplate = `<b>%{label}</b><br><span style='font-size:1.1em;'><b style='color:#ebdf9a'> %{value} </b> :${visText.total.ur}</span> <extra></extra>`
let layout = {
showlegend: true,
// legend: { y: 1.5 },
// height: props.height,
// width: props.width,
margin: { t: 40, r: 5, b: 30, l: 50 },
// transition: { easing: "cubic-in-out" }
legend: {
font: { family: "PT Sans Narrow" },
// x: globalThis.lang == 'ur' ? 0 : 1
},
font: { family: "PT Sans Narrow" },
};
let data = [{
hole: .2,
type: 'pie',
marker: {
colors: ['#6388b4', '#ef6f6a', '#8cc2ca', '#55ad89', '#c3bc3f', '#bb7693', '#baa094', '#a9b5ae', '#767676', '#ffae34'],
},
// textinfo: "label+percent",
// textposition: "inside",
// insidetextorientation: "radial",
hovertemplate: hovertemplate,
hoverlabel: {
align: globalThis.lang == 'ur' ? 'right' : 'left',
bgcolor: '#444',
// font: { size: 16 },
},
automargin: true,
title: { font: { family: "PT Sans Narrow" } },
legendgrouptitle: { font: { family: "PT Sans Narrow" } },
// hoverlabel: { font: { family: "PT Sans Narrow" } },
textfont: { font: { family: "PT Sans Narrow" } },
insidetextfont: { font: { family: "PT Sans Narrow" } },
outsidetextfont: { font: { family: "PT Sans Narrow" } },
sort: false
}];
let config = { displayModeBar: false, responsive: true };
let def = {
selector: { root: "", select: "#select", vis: "#vis", info: "#info" },
// startCategory:"",
categoryOrder: d => d.sort(),
enable: { pull: true, outline: true, andOr: false, pieClick: true },
marker: { pullLen: 0.012, outline: { width: 2, color: "#444" } }, // colors
infoText: {}, // or {category:"text"} or {category:{en:"text"}}
categories: {},
plotly: { layout, data, config, beforeRender: null }
}
this.cfg = mergeDeep(def, cfg || {});
this.categories = pGet(this.cfg, "categories", "aKey");
this.category = cfg.startCategory;
let colors = pGet(this.cfg, "marker.colors", "uVal");
if (colors)
this.plotly.data[0].colors = colors;
// Selection UI
let select = document.querySelector(this.cfg.selector.root + ' ' + this.cfg.selector.select);
let selectEl = document.createElement("select");
select.append(selectEl)
this.categories.forEach(d => {
let o = document.createElement("option");
o.setAttribute('value', d);
selectEl.append(o);
o.text = selectCategories[d][globalThis.lang]; // d.replaceAll('_', ' ');
});
// select event
selectEl.addEventListener('change',
(d => {
this.category = d.srcElement.value;
// HACK: forget selections for non-region categories
this.selectState = "region" in this.selectState ? { region: this.selectState.region } : {};
this.react();
}).bind(this));
this.react();
}
setInfo(category) {
let infoEl = document.querySelector(this.cfg.selector.root + ' ' + this.cfg.selector.info);
let defInfoText = pGet(this.cfg, `infoText.${this.cfg.language}`, "uVal");
let catInfoText = pGet(this.cfg.categories, `${category}.infoText.${this.cfg.language}`, "uVal");
if (catInfoText)
infoEl.innerText = catInfoText;
else
infoEl.innerText = defInfoText; // Default
}
react() {
let c = this.cfg;
this.el = document.querySelector(c.selector.root + ' ' + c.selector.vis);
// reset
pSet(c.plotly.data[0], "pull", []);
pSet(c.plotly.data[0], "marker.line.width", []);
let sState = pGet(this, `selectState.${this.category}`, "uVal");
if (sState) {
// marker effects
if (pGet(this.cfg, "enable.pull", "uVal"))
c.plotly.data[0].pull = this.selectState[this.category].map(d => d * this.cfg.marker.pullLen);
if (pGet(this.cfg, "enable.outline", "uVal"))
c.plotly.data[0].marker.line.width = this.selectState[this.category].map(d => d * this.cfg.marker.outline.width);
}
if (c.plotly.beforeRender)
c.plotly.beforeRender(this.cfg);
let data = this.getLabVals(this.category);
c.plotly.data[0].labels = Object.keys(data).sort();
console.log(c.plotly.data[0].labels);
c.plotly.data[0].values = c.plotly.data[0].labels.map(d => data[d]);
c.plotly.data[0].name = this.category;
if (this.vis) {
Plotly.react(this.el, c.plotly.data, c.plotly.layout, c.plotly.config);
} else {
this.vis = Plotly.newPlot(this.el, c.plotly.data, c.plotly.layout, c.plotly.config);
if (this.cfg.enable.pieClick) {
this.selectState = {};
let d = c.plotly.data[0];
if (c.enable.pull && !c.plotly.data[0].pull)
c.plotly.data[0].pull = c.plotly.data[0].labels.map(d => 0);
if (c.enable.outline && !pGet(c.plotly.data[0], "marker.line", "uVal")) {
c.plotly.data[0].marker.line = {
width: c.plotly.data[0].labels.map(d => 0)
}
let mlColors = pGet(this.cfg, "marker.outline.color", "uVal");
if (mlColors)
c.plotly.data[0].marker.line.color = mlColors;
}
if (this.cfg.enable.pieClick)
this.clickInit();
}
}
this.setInfo(this.category);
// Event
let eData = {
category: this.category,
selectState: {},
regions: {},
filter: null
};
pGet(this, "selectState", "aKey").forEach(d => {
eData.selectState[d] = this.selectState[d].selected;
});
pGet(this.cfg, "data", "aKey").forEach(d => {
let selected = pGet(this, `selectState.${this.category}.selected`, "uVal"); // some selected
if (!selected || !(selected.length)) selected = pGet(this.cfg.data, d + '.' + this.category, "aKey"); // none selected, return total
let row = this.cfg.data[d][this.category];
if (selected.length && row)
eData.regions[d] = selected.map(d => row[d] || 0).reduce((a, b) => a + b);
});
if (this.cfg.eventFilter) eData.filter = this.cfg.eventFilter(this.cfg.data);
var event = new CustomEvent("pieselect-change", { detail: eData });
document.dispatchEvent(event);
}
clickInit() {
this.el.on('plotly_click', (function(data) {
// console.log(data.points[0].label, data);
let c = this.cfg.plotly;
let idx = c.data[0].labels.indexOf(data.points[0].label);
let category = data.points[0].fullData.name;
if (!(category in this.selectState)) // init state
this.selectState[category] = Array(c.data[0].labels.length).fill(0);
if (!pGet(this.cfg.categories, `${category}.multiSelect`, "uVal")) { // singleSelect
this.selectState[category] = this.selectState[category].map((d, i) => {
if (i == idx) return this.selectState[category][i]
return 0
});
}
this.selectState[category][idx] = !this.selectState[category][idx];
this.selectState[category].selected = [];
this.selectState[category].forEach((d, i) => {
if (this.selectState[category][i])
this.selectState[category].selected.push(data.points[0].fullData.labels[i]);
});
this.react();
}).bind(this))
}
// make list of pie slice keys/values
getLabVals(category) {
let values = {};
let regions = pGet(this.cfg, "data", "aKey");
let selected = pGet(this, "selectState.region.selected", "uVal");
if (selected && selected.length) // subset data by region
regions = regions.filter(d => selected.includes(d.split('~')[0]) || d == 'pakistan');
regions.forEach(d => { // region
// add specified options
let specifiedOptions = pGet(this.cfg, `categories.${category}.options`, 'aVal');
if (!specifiedOptions.length) { // if not predefined && is a district
// for all rows, brute force tally option qtys
pGet(this.cfg.data[d], category, 'aKey').forEach(e => {
values[e] = (values[e] || 0) + (this.cfg.data[d][category][e] || 0);
})
} else { // or populate w predefined vals
let preDefVals = pGet(this.cfg.categories, `${category}.values`, "aVal");
specifiedOptions.forEach((e, i) => {
values[e] = e in values ? values[e] : preDefVals[i];
});
}
})
return values;
}
} |
JavaScript | class Polling {
/**
* The polling functions queue
*
* @field queue
* @type Object
* @static
*/
queue = [];
/**
* A flag that controls if the polling is locked
*
* @field lock
* @type boolean
* @static
*/
lock = false;
/**
* Pushes a polling function in the queue
*
* @method enqueue
* @static
*/
enqueue (name, fn) {
if (typeof name === 'function') {
fn = name
name = ''
}
if (
this.getFunctionIndex(fn) < 0 &&
(name === '' || this.getFunctionIndex(name) < 0)
) {
this.queue.push({ name, fn, enabled: true })
} else {
throw new SSException(
'301',
'The function is already in the polling queue.'
)
}
}
/**
* Removes a polling function from the queue
*
* @method dequeue
* @static
*/
dequeue (fn) {
this.queue.splice(this.getFunctionIndex(fn), 1)
}
/**
* Enables an specific polling function
*
* @method enable
* @static
*/
enable (fn) {
this.queue[this.getFunctionIndex(fn)].enabled = true
}
/**
* Disables an specific polling function, but preserving it in the polling queue
*
* @method disable
* @static
*/
disable (fn) {
this.queue[this.getFunctionIndex(fn)].enabled = false
}
/**
* Gets the position of a polling function in the queue based on its name or the function itself
*
* @method getFunctionIndex
* @static
*/
getFunctionIndex (fn) {
if (typeof fn === 'function') {
return this.queue.map(p => p.fn).indexOf(fn)
} else if (typeof fn === 'string') {
return this.queue.map(p => p.name).indexOf(fn)
}
throw new SSException(
'302',
'Invalid argument for getFunctionIndex method. Expected a string (the polling function name) or a function (the polling function itself).'
)
}
/**
* Unlocks the polling and starts the checking process
*
* @method start
* @static
*/
start () {
this.lock = false
this.doPolling()
}
/**
* Stops the polling process
*
* @method stop
* @static
*/
stop () {
this.lock = true
}
/**
* Clear the polling queue
*
* @method clear
* @static
*/
clear () {
const lock = this.lock
this.lock = true
this.queue = []
this.lock = lock
}
/**
* Starts the polling process
*
* @method doPolling
* @static
*/
doPolling () {
if (!this.lock) {
// Using timeout to avoid the queue to not complete in a cycle
setTimeout(
() => {
this.queue.forEach(pollingFunction => {
pollingFunction.enabled && pollingFunction.fn()
})
this.doPolling()
},
pollingDuration
)
}
}
} |
JavaScript | class ZipsceneDataClient {
constructor(rpcClient, profileType, options = {}) {
this.client = rpcClient;
this.methodBase = profileType.toLowerCase();
this.fileServiceClient = options.fileServiceClient;
if (options.profiles) this.methodBase += '.profile';
}
/**
* Gets a single object by id.
*
* @method get
* @param {String} id
* @param {Object} [options]
* @param {String[]} options.fields
* @param {Number} options.timeout
* @return {Object} - The request object
*/
async get(id, options = {}) {
let result = await this.client.request(this.methodBase + '.get', objtools.merge({}, options, {
keys: { id }
}));
return result.result;
}
/**
* Executes a query.
*
* @method query
* @param {Object} query
* @param {Object} [options]
* @param {String[]} options.fields
* @param {String[]} options.sort
* @param {Number} options.skip
* @param {Number} options.limit
* @param {Number} options.timeout
* @return {Object[]} - Array of results
*/
async query(query, options = {}) {
let result = await this.client.request(this.methodBase + '.query', objtools.merge({}, options, {
query: query
}));
return result.results;
}
/**
* Exports a DMP data stream.
*
* @method export
* @param {Object} query
* @param {Object} [options]
* @param {String[]} options.fields
* @param {String[]} options.sort
* @param {Number} options.limit
* @param {Number} options.timeout
* @param {String} options.strategy - Export strategy, either 'file' to download via file service or 'stream' to stream directly from DMP
* @return {Readable} - A readable object stream
*/
export(query, options = {}) {
const getStream = async() => {
let strategy;
if (options.strategy === 'stream') {
strategy = 'stream';
} else {
// Check if DMP supports file service
let dmpOptions = await this.client.request('get-dmp-options', {});
if (dmpOptions.fileService && this.fileServiceClient) {
strategy = 'file';
} else {
if (options.strategy === 'file') {
if (!this.fileServiceClient) {
throw new XError(XError.UNSUPPORTED_OPERATION, 'File service not configured');
} else {
throw new XError(XError.UNSUPPORTED_OPERATION, 'File service not enabled in DMP');
}
}
strategy = 'stream';
}
}
if (strategy === 'stream') {
return this.client.requestStream(this.methodBase + '.export', {
query: query,
fields: options.fields,
sort: options.sort,
limit: options.limit,
timeout: options.timeout
});
} else {
// Start the export to file
let result = await this.client.request(this.methodBase + '.file-export', {
query: query,
fields: options.fields,
sort: options.sort,
limit: options.limit,
timeout: options.timeout
});
let fileId = result.fileId;
// Poll file service until file is complete
for (;;) {
await pasync.setTimeout(FILE_SERVICE_POLL_INTERVAL);
let fileState = await this.fileServiceClient.request('get-file-status', { fileId });
switch (fileState.status) {
case 'PENDING':
case 'FINISHED':
case 'READY':
break;
case 'CANCELLED':
throw new XError(XError.INTERNAL_ERROR, 'File export cancelled');
case 'ERROR':
if (fileState.error && fileState.error.code && fileState.error.message) {
throw new XError.fromObject(fileState.error);
} else {
throw new XError(XError.INTERNAL_ERROR, 'Error exporting file');
}
default:
throw new XError(XError.INTERNAL_ERROR, 'Unexpected file service state: ' + fileState.status);
}
if (fileState.status === 'READY') break;
}
// Stream downloaded file from file service
let retStream = this.fileServiceClient.requestRaw('download-file', { fileId })
.pipe(new zstreams.SplitStream())
.through((line) => {
try {
return JSON.parse(line);
} catch (err) {
throw new XError(XError.INVALID_ARGUMENT, 'Error parsing export line', { error: err, line });
}
});
// Clean up file on file service after download is finished
retStream.on('finish', () => {
this.fileServiceClient.request('delete-file', { fileId })
.catch((err) => {
console.error('Error deleting downloaded file from file service', err);
});
});
return retStream;
}
};
let passthrough = new zstreams.PassThrough({ objectMode: true });
getStream()
.then((stream) => {
stream.pipe(passthrough);
}, (err) => {
passthrough.triggerChainError(err);
//passthrough.emit('error', err);
})
.catch(pasync.abort);
return passthrough;
}
/**
* Executes a count.
*
* @method count
* @param {Object} query
* @param {Object} [options}
* @param {Number} options.timeout
* @return {Number}
*/
async count(query, options = {}) {
let result = await this.client.request(this.methodBase + '.count', objtools.merge({}, options, {
query: query
}));
return result.result;
}
/**
* Executes one or more aggregates.
*
* @method aggregate
* @param {Object} query
* @param {Object|Object[]} agg - Aggregate spec, or array of aggregate specs
* @param {Object} [options]
* @param {String[]} options.sort
* @param {Number} options.limit
* @param {Number} options.scanLimit
* @param {Number} options.timeout
* @return {Mixed} - Aggregate results, or array of aggregate results if 'agg' is an array
*/
async aggregate(query, agg, options = {}) {
let aggMap = {};
if (Array.isArray(agg)) {
for (let i = 0; i < agg.length; ++i) {
aggMap['a' + i] = agg[i];
}
} else {
aggMap.a0 = agg;
}
let result = await this.client.request(this.methodBase + '.aggregate', objtools.merge({}, options, {
query: query,
aggregates: aggMap
}));
let resultMap = result.results;
if (Array.isArray(agg)) {
let retArray = [];
for (let key in resultMap) {
retArray[parseInt(key.slice(1))] = resultMap[key];
}
return retArray;
} else {
return resultMap.a0;
}
}
} |
JavaScript | class Parser {
/**
* @constructor
*/
constructor() {
/**
* Token input
* @type {Array}
*/
this.tokens = null;
/**
* Token index
* @type {Number}
*/
this.index = 0;
/**
* Operator precedences
* @type {Array}
*/
this.precedence = pr.precedence;
/**
* node
* @type {Object}
* @getter
*/
Object.defineProperty(this, "node", {
get: function() {
return (this.tokens[this.index]);
}
});
}
/**
* Parse
* @param {Array} tokens
* @return {Object}
*/
parse(tokens) {
this.tokens = tokens;
this.index = 0;
let ast = new NODE_LIST.Program();
let length = this.tokens.length;
let block = null;
for (;;) {
if (this.index >= length) break;
if ((block = this.parseBlock()) === null) continue;
ast.body.push(block);
};
return (ast);
}
/**
* Increase token index
*/
next() {
this.index++;
}
/**
* Node type acception
* @param {String} type
* @return {Boolean}
*/
accept(type) {
if (this.node === void 0) return (false);
if (this.node.name === type) {
return (true);
}
return (false);
}
/**
* Node type expection
* @param {String} name
*/
expect(name) {
for (;true;) {
if (this.node.name === name) {
this.next();
break;
}
this.next();
}
return void 0;
}
/**
* Accept precedence state
* @param {String} state
* @return {Boolean}
*/
acceptPrecedenceState(state) {
return (
state !== void 0 &&
this.node !== void 0 &&
state.indexOf(this.node.name) > -1
);
}
} |
JavaScript | class b2JointEdge {
constructor(joint) {
this._other = null; ///< provides quick access to the other body attached.
this.prev = null; ///< the previous joint edge in the body's joint list
this.next = null; ///< the next joint edge in the body's joint list
this.joint = joint;
}
get other() {
!!B2_DEBUG && b2Assert(this._other !== null);
return this._other;
}
set other(value) {
!!B2_DEBUG && b2Assert(this._other === null);
this._other = value;
}
Reset() {
this._other = null;
this.prev = null;
this.next = null;
}
} |
JavaScript | class b2JointDef {
constructor(type) {
/// The joint type is set automatically for concrete joint types.
this.type = 0 /* e_unknownJoint */;
/// Use this to attach application specific data to your joints.
this.userData = null;
/// Set this flag to true if the attached bodies should collide.
this.collideConnected = false;
this.type = type;
}
} |
JavaScript | class b2Joint {
constructor(def) {
this.m_type = 0 /* e_unknownJoint */;
this.m_prev = null;
this.m_next = null;
this.m_edgeA = new b2JointEdge(this);
this.m_edgeB = new b2JointEdge(this);
this.m_islandFlag = false;
this.m_collideConnected = false;
this.m_userData = null;
this._logIndex = 0;
!!B2_DEBUG && b2Assert(def.bodyA !== def.bodyB);
this.m_type = def.type;
this.m_edgeA.other = def.bodyB;
this.m_edgeB.other = def.bodyA;
this.m_bodyA = def.bodyA;
this.m_bodyB = def.bodyB;
this.m_collideConnected = b2Maybe(def.collideConnected, false);
this.m_userData = b2Maybe(def.userData, null);
}
/// Get the type of the concrete joint.
GetType() {
return this.m_type;
}
/// Get the first body attached to this joint.
GetBodyA() {
return this.m_bodyA;
}
/// Get the second body attached to this joint.
GetBodyB() {
return this.m_bodyB;
}
/// Get the next joint the world joint list.
GetNext() {
return this.m_next;
}
/// Get the user data pointer.
GetUserData() {
return this.m_userData;
}
/// Set the user data pointer.
SetUserData(data) {
this.m_userData = data;
}
/// Short-cut function to determine if either body is inactive.
IsActive() {
return this.m_bodyA.IsActive() && this.m_bodyB.IsActive();
}
/// Get collide connected.
/// Note: modifying the collide connect flag won't work correctly because
/// the flag is only checked when fixture AABBs begin to overlap.
GetCollideConnected() {
return this.m_collideConnected;
}
/// Shift the origin for any points stored in world coordinates.
// eslint-disable-next-line @typescript-eslint/no-empty-function
ShiftOrigin(newOrigin) { }
} |
JavaScript | class DoctorCalenderController extends Base {
add = (req, res, next) => {
user.findOne({ email: '[email protected]' }, function(err, us) {
const model = DoctorCalender
model.findOne({ doctor: us._id, appointment_date_at: req.body.params.appointment_date_at }, function(
err,
objSelect
) {
let obj = objSelect
if (!obj) obj = model(req.body.params)
console.log('ob1j', obj)
obj.doctor = us._id
return obj.save((err, doc) => {
if (err) {
return this._respondError(res, err, 'doctor calender add')
}
const timeSelect = req.body.params.timeSelect
timeSelect.map(select => {
const modelPart = doctorCalenderPart
const objPart = modelPart()
objPart.doctor_calender = obj._id
objPart.time_limit_start = select.start
objPart.time_limit_end = select.end
objPart.user_id = null
objPart.save(error => {
if (error) {
// console.log(error)
return this._respondError(res, err, 'doctor calender part add')
}
})
})
return res.json({ status: 'success' })
})
})
}).catch()
}
get = (req, res, next) => {
const model = doctorCalender
let doctorID = req.query.doctor
const dateSelect = req.query.date
let cc = new Date(dateSelect)
let dateStart = cc.setHours('0', '0', '0')
let dateEnd = cc.setHours('23', '59', '59')
var ObjectId = mongoose.Types.ObjectId
model.findOne(
{
doctor: new ObjectId(doctorID),
appointment_date_at: {
$gte: new Date(dateStart),
$lte: new Date(dateEnd),
},
},
function(err, doctorCalenderObj) {
if (err) return res.end({ error: err })
if (!doctorCalenderObj) return res.json({ status: 'fail' })
doctorCalenderPart
.find({ doctor_calender: new ObjectId(doctorCalenderObj._id) })
.lean()
.exec(function(err, users) {
return res.end(JSON.stringify(users))
})
}
)
}
booking = (req ,res , next) => {
const model = doctorCalenderPart;
// console.log(req.body.params)
let doctorCalenderPartId = req.body.params.doctorCalenderPartId
model.findById(doctorCalenderPartId,function(err , obj){
obj.user_id = '6007e6de4c713b5308a32dea'
obj.is_reserved = true;
obj.save()
return res.json({ status: 'success' })
})
}
} |
JavaScript | class EditWebhookForm extends BaseComponent {
elements() {
this.$fields = this.$el.find(WEBHOOK_FORM_FIELDS);
}
toggle() {
this.$el.toggle();
const visible = this.$el.is(':visible');
if (visible) {
this.$fields.first().focus();
}
}
} |
JavaScript | class LinearProbingHash {
constructor(size) {
this.size = size;
this.values = [];
}
/**
* @param {String} Key
*/
hash(key) {
if (!key) {
throw new Error('Key must be a string.');
}
const len = key.length;
let sum = 0;
for (let index = 0; index < len; index++) {
sum += key.charCodeAt(index);
}
return sum % this.size;
}
put(key, value) {
const hashedIndex = this.hash(key);
let pos = hashedIndex;
let count = 1;
let node = this.values[pos];
while (node && node.key !== key && count < this.size) {
pos++;
pos = pos % this.size;
count++;
node = this.values[pos];
}
if (node && node.key !== key) {
throw new Error('The hashing table run out of space');
}
this.values[pos] = new Node(key, value);
}
get(key) {
const hashedIndex = this.hash(key);
let pos = hashedIndex;
let count = 1;
let foundKey = this.values[pos] && this.values[pos].key;
while (foundKey !== key && count < this.size) {
pos++;
pos = pos % this.size;
count++;
foundKey = this.values[pos] && this.values[pos].key;
}
// no matching key found
if (count >= this.size) {
return;
}
return this.values[pos] && this.values[pos].value;
}
delete(key) {
const hashedIndex = this.hash(key);
let count = 1;
let sameHashedList = [];
if (!this.values[hashedIndex]) {
return;
}
sameHashedList.push(hashedIndex);
// find all same hashed values
let next;
let index = hashedIndex;
do {
index++;
index = index % this.size;
count++;
next = this.values[index];
// Find all values which has same hashed index added before
if (next && this.hash(next.key) === hashedIndex) {
sameHashedList.push(index);
}
} while (next && count < this.size)
if (sameHashedList.length > 1) {
for (let index = 0; index < sameHashedList.length - 1; index++) {
// shift up all values which has same hashed index
let currentIndex = sameHashedList[index];
let nextIndex = sameHashedList[index + 1];
this.values[currentIndex] = this.values[nextIndex];
}
}
let lastIndex = sameHashedList[sameHashedList.length - 1];
this.values[lastIndex] = undefined;
}
} |
JavaScript | class Cli {
constructor(config = {}) {
this.config = config;
this.componentsFolder = path.join(
config.rootFolder,
config.appFolder,
config.componentsFolder
)
this.templatePath = path.join(
process.cwd(),
this.config.rootCliTemplatePath
)
this.render = new Render(this.config);
}
validatePath(componentPath) {
return !fs.existsSync(componentPath);
}
createComponent(componentPath, componentName) {
const config = {...this.config};
this.createComponentFolder(componentPath);
if(config.createIndex) {
this.createIndexJs(componentPath, componentName);
}
if(config.createScss) {
this.createComponentScss(componentPath, componentName);
}
if(config.createTest) {
this.createComponentTestJs(componentPath, componentName);
}
if(config.createData) {
this.createComponentData(componentPath, componentName);
}
if(this.config.usePure) {
this.createPureComponentJs(componentPath, componentName);
} else {
this.createClassComponentJs(componentPath, componentName);
}
if(this.config.updateIndexJs) {
this.addToIndexJs(componentName);
}
if(this.config.updateIndexScss) {
this.addToIndexScss(componentName, componentPath);
}
}
deleteComponent(componentPath, componentName) {
this.addToIndexJs(componentName, true);
this.addToIndexScss(componentName, componentPath, true);
this.deleteComponentFolder(componentPath);
}
createComponentFolder(componentPath) {
fs.ensureDirSync(componentPath);
Log.info(`Created folder: ${componentPath}`)
}
createIndexJs(componentPath, componentName) {
const filePath = path.join(componentPath, `index.js`);
const message = `Created index.js at: ${filePath}`;
this._createFile(filePath, componentName, 'componentIndex', message);
}
createPureComponentJs(componentPath, componentName) {
const filePath = path.join(componentPath, `${componentName}.js`);
const message = `Created ${componentName}.js at: ${filePath}`;
this._createFile(filePath, componentName, 'componentPure', message);
}
createClassComponentJs(componentPath, componentName) {
const filePath = path.join(componentPath, `${componentName}.js`);
const message = `Created ${componentName}.js at: ${filePath}`;
this._createFile(filePath, componentName, 'componentClass', message);
}
createComponentTestJs(componentPath, componentName) {
const filePath = path.join(componentPath, `${componentName}.test.js`);
const message = `Created ${componentName}.test.js at: ${filePath}`;
this._createFile(filePath, componentName, 'componentTest', message);
}
createComponentScss(componentPath, componentName) {
const filePath = path.join(componentPath, `${componentName}.scss`);
const message = `Created ${componentName}.scss at: ${filePath}`;
this._createFile(filePath, componentName, 'componentScss', message);
}
createComponentData(componentPath, componentName) {
const filePath = path.join(componentPath, `${componentName}.json`);
const message = `Created ${componentName}.json at: ${filePath}`;
this._createFile(filePath, componentName, 'componentData', message);
}
scaffoldComponent(componentPath, componentName, subComponentName) {
const templateString = this._getTemplateString('containerWithComponent');
const template = eval('`' + templateString + '`');
_writeFile(componentPath, template);
const message = `Updated ${componentName}.js at: ${componentPath}`;
Log.info(message)
}
addToIndexJs(componentName, remove=false) {
const filePath = path.join(this.componentsFolder, 'index.js');
let index = fs.readFileSync(filePath, 'utf8');
let newComponent = `import ${componentName} from './${componentName}';
`;
if(remove) {
index = index.replace(newComponent, '');
index = index.replace(
`
${componentName},`, '');
} else {
index = newComponent.concat(index);
index = index.replace(`export {`, `export {
${componentName},`);
}
_writeFile(filePath, index);
Log.info(`Updated index.js: ${filePath}`)
}
addToIndexScss(componentName, componentPath, remove=false) {
const scssFolder = path.join(
this.config.rootFolder,
this.config.appFolder,
this.config.scssFolder,
);
let scssFile = 'index.scss';
if(componentPath.indexOf(this.config.componentsFolder) !== -1) {
scssFile = 'components.scss';
}
if(componentPath.indexOf(this.config.containersFolder) !== -1) {
scssFile = 'containers.scss';
}
const filePath = path.join(scssFolder, scssFile);
let index = fs.readFileSync(filePath, 'utf8');
let compPath = path.relative(scssFolder, componentPath);
compPath = compPath.replace(/\\/g, '/');
const importString = `@import '${compPath}/${componentName}';
`;
if(remove) {
index = index.replace(importString, '');
} else {
index = index.concat(importString);
}
_writeFile(filePath, index);
Log.info(`Updated index.scss: ${filePath}`)
}
publishComponents(outputPath) {
this.publishListing(outputPath);
this.publishAllComponents(outputPath);
this.publishAllContainers(outputPath);
this.publishDevFiles(outputPath);
this.copyStaticFiles(outputPath);
}
copyStaticFiles(outputPath) {
const config = this.config;
fs.ensureDirSync(outputPath);
const statics = path.join(config.rootFolder, config.outputPath);
fs.copySync(statics, path.join(outputPath, config.publicPath))
}
publishDevFiles(outputPath) {
const config = this.config;
fs.ensureDirSync(outputPath);
const rootTemplatePath = this.config.rootServerTemplatePath;
const devJsPath = `${path.posix.join(config.rootFolder, rootTemplatePath, 'devserver.js')}`;
const devJsOutputPath = path.resolve(config.rootFolder, config.outputPathHtmlFolder, `devserver.js`);
const devJs = fs.readFileSync(devJsPath);
const devCssPath = `${path.posix.join(config.rootFolder, rootTemplatePath, 'devserver.css')}`;
const devCssOutputPath = path.resolve(config.rootFolder, config.outputPathHtmlFolder, `devserver.css`);
const devCss = fs.readFileSync(devCssPath);
_writeFile(devJsOutputPath, devJs);
_writeFile(devCssOutputPath, devCss);
}
publishAllComponents(outputPath) {
fs.ensureDirSync(outputPath);
const components = this.render.getComponents();
components.map((item) => {
const componentFolder = path.join(outputPath, item);
fs.ensureDirSync(componentFolder);
const componentFile = path.join(componentFolder, `index.html`);
const component = this.render.renderServerComponent(item);
_writeFile(componentFile, component);
})
}
publishAllContainers(outputPath) {
fs.ensureDirSync(outputPath);
const containers = this.render.getContainers();
containers.map((item) => {
const componentFolder = path.join(outputPath, item);
fs.ensureDirSync(componentFolder);
const componentFile = path.join(componentFolder, `index.html`);
const component = this.render.renderServerComponent(item);
_writeFile(componentFile, component);
})
}
publishListing(outputPath) {
fs.ensureDirSync(outputPath);
const listingFile = path.join(outputPath, `index.html`);
const listing = this.render.renderListing();
_writeFile(listingFile, listing);
}
deleteComponentFolder(componentPath) {
_deleteFolderRecursive(componentPath)
}
_createFile(filePath, componentName, templateName, message = ``) {
const templateString = this._getTemplateString(templateName);
const template = eval('`' + templateString + '`');
_writeFile(filePath, template);
Log.info(message)
}
_getTemplateString(templateName, templatePath = this.templatePath) {
const filePath = path.join(templatePath, templateName);
const templateString = fs.readFileSync(filePath, 'utf8');
return templateString;
}
} |
JavaScript | class CandidateModal extends React.Component {
constructor({props}){
super(props) ;
this.showRegisterError = this.showRegisterError.bind(this);
this.showRegisterMessage = this.showRegisterMessage.bind(this);
}
state = {
name: '',
phone: '',
email: '',
password: '',
ConfirmPassword: '',
workAddress: '',
physicalAddress: '',
referee1name: '',
referee1phone: '',
referee2name: '',
referee2phone: '',
registerErrorText: '',
registerSuccessText: ''
};
emailText = (event) => {
this.setState({email : event.target.value})
EMAIL_REGEX.test(this.state.email)? this.setState({emailError:''}):this.setState({emailError:'Invalid Email'})
};
showRegisterError = (message) => {
this.setState({registerErrorText: message})
setTimeout(()=>{ this.setState({registerErrorText: ''}) },5*1000)
}
showRegisterMessage = (message) => {
this.setState({registerSuccessText: message})
}
render() {
// const registerType = 0;
return (
<Grid>
<MuiThemeProvider muiTheme={muiThemebtn}>
<div
className="register-wrapper"
>
<p className="form-header">
Details
</p>
<Row className="register-form" >
<Col md="6" sm="12">
<TextField
underlineFocusStyle={{borderColor: "#0c6053"}}
floatingLabelFocusStyle={{color: "#0c6053"}}
style={styles.textfield}
// hintText={registerType == 0 ? 'e.g John Doe' : registerType == 1 ? 'e.g Google' : 'Adviser Fullname'}
fullWidth={true}
errorText=''
value={this.state.name}
onChange={(e) => this.setState({name : e.target.value})}
floatingLabelText='Fullname'
type="text"
/>
<TextField
underlineFocusStyle={{borderColor: "#0c6053"}}
floatingLabelFocusStyle={{color: "#0c6053"}}
// hintText="[email protected]"
fullWidth={true}
errorText=''
value={this.state.email}
onChange={(e) => this.setState({email : e.target.value})}
floatingLabelText="Email"
type="text"
/>
<TextField
underlineFocusStyle={{borderColor: "#0c6053"}}
floatingLabelFocusStyle={{color: "#0c6053"}}
// hintText="Password"
fullWidth={true}
value={this.state.password}
onChange={(e) => this.setState({password : e.target.value})}
errorText=''
floatingLabelText="Password"
type="password"
/>
<TextField
underlineFocusStyle={{borderColor: "#0c6053"}}
floatingLabelFocusStyle={{color: "#0c6053"}}
// hintText="Password"
fullWidth={true}
value={this.state.ConfirmPassword}
onChange={(e) => this.setState({ConfirmPassword : e.target.value})}
errorText=''
floatingLabelText="Confirm Password"
type="password"
/>
</Col>
<Col md="6" sm="12">
<TextField
underlineFocusStyle={{borderColor: "#0c6053"}}
floatingLabelFocusStyle={{color: "#0c6053"}}
hintText="eg. +1818855611"
fullWidth={true}
errorText=''
value={this.state.phone}
onChange={(e) => this.setState({phone : e.target.value})}
floatingLabelText="Phone"
type="text"
/>
<TextField
underlineFocusStyle={{borderColor: "#0c6053"}}
floatingLabelFocusStyle={{color: "#0c6053"}}
style={styles.textfield}
// hintText={registerType == 0 ? 'e.g John Doe' : registerType == 1 ? 'e.g Google' : 'Adviser Fullname'}
fullWidth={true}
errorText=''
value={this.state.physicalAddress}
onChange={(e) => this.setState({physicalAddress : e.target.value})}
floatingLabelText='Physical Address'
type="text"
/>
<TextField
underlineFocusStyle={{borderColor: "#0c6053"}}
floatingLabelFocusStyle={{color: "#0c6053"}}
// hintText="[email protected]"
fullWidth={true}
errorText=''
value={this.state.workAddress}
onChange={(e) => this.setState({workAddress : e.target.value})}
floatingLabelText="Work Address (if applicable)"
type="text"
/>
</Col>
</Row>
<br/>
<p className="form-header top-padding">
Referees
</p>
<Row className="referees-form" >
<Col md="6" sm="12">
<TextField
underlineFocusStyle={{borderColor: "#0c6053"}}
floatingLabelFocusStyle={{color: "#0c6053"}}
style={styles.textfield}
// hintText={registerType == 0 ? 'e.g John Doe' : registerType == 1 ? 'e.g Google' : 'Adviser Fullname'}
fullWidth={true}
errorText=''
value={this.state.referee1name}
onChange={(e) => this.setState({referee1name : e.target.value})}
floatingLabelText='Referee Name'
type="text"
/>
<TextField
underlineFocusStyle={{borderColor: "#0c6053"}}
floatingLabelFocusStyle={{color: "#0c6053"}}
// hintText="[email protected]"
fullWidth={true}
errorText=''
value={this.state.referee1phone}
onChange={(e) => this.setState({referee1phone : e.target.value})}
floatingLabelText="Referee phone"
type="text"
/>
</Col>
<Col md="6" sm="12">
<TextField
underlineFocusStyle={{borderColor: "#0c6053"}}
floatingLabelFocusStyle={{color: "#0c6053"}}
style={styles.textfield}
// hintText={registerType == 0 ? 'e.g John Doe' : registerType == 1 ? 'e.g Google' : 'Adviser Fullname'}
fullWidth={true}
errorText=''
value={this.state.referee2name}
onChange={(e) => this.setState({referee2name : e.target.value})}
floatingLabelText='Referee Name'
type="text"
/>
<TextField
underlineFocusStyle={{borderColor: "#0c6053"}}
floatingLabelFocusStyle={{color: "#0c6053"}}
// hintText="[email protected]"
fullWidth={true}
errorText=''
value={this.state.referee2phone}
onChange={(e) => this.setState({referee2phone : e.target.value})}
floatingLabelText="Referee phone"
type="text"
/>
</Col>
</Row>
{this.state.registerErrorText && (
<p className='login-error-text'>{this.state.registerErrorText}</p>
)}
{this.state.registerSuccessText && (
<p className='login-success-text'>{this.state.registerSuccessText}</p>
)}
<br />
{/* <RaisedButton
className="register-button"
label="Register"
backgroundColor='#0c6053'
labelColor="white"
onClick={this.props.close}
/> */}
<RegisterButton {...this.state}
showRegisterError={this.showRegisterError}
showRegisterMessage={this.showRegisterMessage}/>
<style jsx>{`
.register-wrapper{
padding-bottom: 5em;
}
.top-padding{
padding-top: 0.4em;
}
.form-header{
font-size : 18px ;
line-height : 30px ;
}
.register-form {
// margin: 0px auto 60px;
width: 40%;
}
.login-error-text {
padding-top: 10px;
color: #ec1818;
text-size-adjust: 100%;
font-family: Roboto,sans-serif;
font-size: 16px;
line-height: 1.6;
word-wrap: break-word;
}
.login-success-text {
padding-top: 10px;
color: #094211;
text-size-adjust: 100%;
font-family: Roboto,sans-serif;
font-size: 16px;
line-height: 1.6;
word-wrap: break-word;
}
::-webkit-scrollbar {
width: 3px;
}
::-webkit-scrollbar-track {
webkit-box-shadow: inset 0 0 6px #e3ebef;
-webkit-border-radius: 10px;
border-radius: 10px;
background: #e3ebef;
}
::-webkit-scrollbar-thumb {
-webkit-border-radius: 10px;
border-radius: 10px;
background: #9fb6c3;
-webkit-box-shadow: none;
}
::-webkit-scrollbar-thumb:window-inactive {
background: #9fb6c3;
}
`}</style>
</div>
</MuiThemeProvider>
</Grid>
)
}
} |
JavaScript | class RotationButton extends MvuElement {
constructor() {
super({ liveRotation: 0 });
const { TranslationService: translationService } = $injector.inject('TranslationService');
this._translationService = translationService;
this._timeoutId = null;
}
/**
* @override
*/
update(type, data, model) {
switch (type) {
case Update_Live_Rotation:
return { ...model, liveRotation: data };
}
}
/**
* @override
*/
onInitialize() {
/**
* liveRotation value changes on a high frequency, therefore we throttle the view's update down to avoid a flickering icon
*/
const update = throttled(RotationButton.THROTTLE_DELAY_MS, liveRotation => this.signal(Update_Live_Rotation, liveRotation));
/**
* When a user rotates the map, the icon button will be hidden when the maps rotation angle is below a threshold and
* it will be shown again above this value.
* In order to avoid a flickering icon, we delay hiding the icon.
*/
this.observe(store => store.position.liveRotation, liveRotation => {
if (Math.abs(liveRotation) >= RotationButton.VISIBILITY_THRESHOLD_RAD) {
if (this._timeoutId) {
clearTimeout(this._timeoutId);
this._timeoutId = null;
}
}
else {
if (!this._timeoutId) {
this._timeoutId = setTimeout(() => {
update(liveRotation);
}, RotationButton.HIDE_BUTTON_DELAY_MS);
}
}
update(liveRotation);
}, true);
}
/**
* @override
*/
createView(model) {
const { liveRotation } = model;
const translate = (key) => this._translationService.translate(key);
if (!this._timeoutId) {
const onClick = () => {
changeRotation(0);
};
const styles = {
transform: `rotate(${liveRotation}rad)`
};
return html`
<style>${css}</style>
<div>
<button class="rotation-button" style="${styleMap(styles)}" @click=${onClick} title=${translate('map_rotationButton_title')} >
<i class="icon rotation-icon"></i>
</button>
</div>
`;
}
return nothing;
}
static get tag() {
return 'ba-rotation-button';
}
static get HIDE_BUTTON_DELAY_MS() {
return 1000;
}
static get THROTTLE_DELAY_MS() {
return 10;
}
static get VISIBILITY_THRESHOLD_RAD() {
return .1;
}
} |
JavaScript | class Task{
constructor(name, priority, time){
this.name = name;
this.priority = priority;
this.time = time;
}
} |
JavaScript | class UI{
//crear un elemento con los datos de tarea cuando se guarda
addTask(task){
const taskList = document.getElementById("task-list")
const element = document.createElement("div")
let colorPriority = ""
let textPriority = ""
if(task.priority == "Medium"){
colorPriority = "border-warning"
textPriority = "text-warning"
registeredMedium += 1
document.getElementById("modalMedium").innerText=registeredMedium
}
else if(task.priority == "High"){
colorPriority = "border-danger"
textPriority = "text-danger"
registeredHigh += 1
document.getElementById("modalHigh").innerText=registeredHigh
}
else{
colorPriority = "border-dark"
textPriority = "text-dark"
registeredLow += 1
document.getElementById("modalLow").innerText=registeredLow
}
element.innerHTML = `
<div class="card mb-2 text-center bg-light border ${colorPriority} animate__animated animate__backInRight">
<div class="card-body">
<strong>Task:</strong> ${task.name}
<strong>Time:</strong> ${task.time}h
<strong class="btn-task ${textPriority} element-close fas fa-star ml-2" title="${task.priority}" name="info"></strong>
<strong><a href="#" class="btn-task text-dark element-close far fa-check-circle ml-2" title="Completed Task" name="complete"></a></strong>
<strong><a href="#" class="btn-task text-dark element-close far fa-times-circle" title="Delete Task" name="delete"></a></strong>
</div>
</div>
`
taskList.appendChild(element)
countTask(1)
}
//reinicial el formulario
resetForm(){
document.getElementById("task-form").reset()
}
//eliminamos el elemento padre <div> que tenga el name=delete de donde se ejecuto el evento de click
deleteTask(element){
if(element.name === "delete" || element.name === "complete"){
if(element.name === "delete"){
//console.log("delete")
element.parentElement.parentElement.parentElement.remove()
// mostrar mnensaje para eliminar
this.showMessage("Task Deleted Successfully", "danger", "fa-calendar-times")
}
if(element.name === "complete"){
//console.log("delete")
element.parentElement.parentElement.parentElement.remove()
// mostrar mnensaje para eliminar
this.showMessage("Task Completed Successfully", "warning", "fa-trophy" )
countTaskW(1)
}
countTask(-1)
}
}
showMessage(message, cssClass, iconClass){
const div = document.createElement("div")
const icon = document.createElement("li")
icon.className = `fa ${iconClass} iconMessage`
div.className = `message text-center alert alert-${cssClass} mt-2 animate__animated animate__fadeIn`
div.appendChild(icon)
div.appendChild(document.createTextNode(message))
const container = document.querySelector(".container")
const app = document.querySelector("#App")
container.insertBefore(div, app)
//quitar mensage
setTimeout(function(){
document.querySelector(".message").remove()
}, 3000);
}
} |
JavaScript | class SettingsController {
/**
* Initialize global variables for this controller
* @param $window Angular's reference to the browser's window object
* @param $document Angular's jQuery wrapper for window.document object
* @param $interval Angular's wrapper for window.setInterval
* @param $location Exposes browser address bar URL (window.location)
* @param $routeParams Retrieves the current set of route parameters
* @param UserService Transacts users and user data with the server
* @param FieldService Transacts fields with the server
* @param ConfigService Transacts app configurations with the server
*
* @ngInject
*/
constructor($window, $document, $interval, $location, $routeParams,
UserService, FieldService, ConfigService) {
this.$window = $window;
this.$document = $document;
this.$interval = $interval;
this.$location = $location;
this.$routeParams = $routeParams;
this.UserService = UserService;
this.FieldService = FieldService;
this.ConfigService = ConfigService;
}
/* Callback when component is mounted and ready */
$onInit() {
this.loading = true;
this.error = false;
this.visibleTab = 'general'; // default tab
// does the url specify a tab in hash
let tab = this.$location.hash();
if (tab) { // if there is a tab specified and it's a valid tab
if (tab === 'general' || tab === 'views' || tab === 'cron' ||
tab === 'col' || tab === 'theme' || tab === 'password') {
this.visibleTab = tab;
}
}
this.newCronQueryProcess = '0';
this.newCronQueryAction = 'tag';
this.getThemeColors();
this.themeDisplays = [
{ name: 'Purp-purp', class: 'default-theme' },
{ name: 'Blue', class: 'blue-theme' },
{ name: 'Green', class: 'green-theme' },
{ name: 'Cotton Candy', class: 'cotton-candy-theme' },
{ name: 'Green on Black', class: 'dark-2-theme' },
{ name: 'Dark Blue', class: 'dark-3-theme' }
];
this.UserService.getCurrent()
.then((response) => {
// only admins can edit other users' settings
if (response.createEnabled && this.$routeParams.userId) {
if (response.userId === this.$routeParams.userId) {
// admin editing their own user so the routeParam is unnecessary
this.$location.search('userId', null);
} else { // admin editing another user
this.userId = this.$routeParams.userId;
}
} else { // normal user has no permission, so remove the routeParam
// (even if it's their own userId because it's unnecessary)
this.$location.search('userId', null);
}
// always get the user's settings because current user is cached
// so response.settings might be stale
this.getSettings();
// get all the other things!
this.getViews();
this.getCronQueries();
this.getColConfigs();
})
.catch((error) => {
this.error = error.text;
this.loading = false;
});
this.ConfigService.getMolochClusters()
.then((response) => {
this.molochClusters = response;
});
this.FieldService.get(true)
.then((response) => {
this.fields = response;
this.fieldsPlus = response;
this.fieldsPlus.push({
dbField : 'ip.dst:port',
exp : 'ip.dst:port',
help : 'Destination IP:Destination Port'
});
// add custom columns to the fields array
for (let key in customCols) {
if (customCols.hasOwnProperty(key)) {
this.fields.push(customCols[key]);
}
}
// build fields map for quick lookup by dbField
this.fieldsMap = {};
for (let i = 0, len = this.fields.length; i < len; ++i) {
let field = this.fields[i];
this.fieldsMap[field.dbField] = field;
}
});
}
/* fired when controller's containing scope is destroyed */
$onDestroy() {
if (interval) { this.$interval.cancel(interval); }
}
/* service functions --------------------------------------------------- */
/* retrieves the specified user's settings */
getSettings() {
this.UserService.getSettings(this.userId)
.then((response) => {
this.settings = response;
this.loading = false;
this.setTheme();
this.startClock();
})
.catch((error) => {
this.loading = false;
this.error = error.text;
});
}
/* retrieves the specified user's views */
getViews() {
this.UserService.getViews(this.userId)
.then((response) => {
this.views = response;
})
.catch((error) => {
this.viewListError = error.text;
});
}
/* retrieves the specified user's cron queries */
getCronQueries() {
this.UserService.getCronQueries(this.userId)
.then((response) => {
this.cronQueries = response;
})
.catch((error) => {
this.cronQueryListError = error.text;
});
}
/* retrieves the specified user's custom column configurations */
getColConfigs() {
this.UserService.getColumnConfigs(this.userId)
.then((response) => {
this.colConfigs = response;
})
.catch((error) => {
this.colConfigError = error.text;
});
}
/* page functions ------------------------------------------------------ */
/* opens a specific settings tab */
openView(tabName) {
this.visibleTab = tabName;
this.$location.hash(tabName);
}
/* remove the message when user is done with it or duration ends */
messageDone() {
this.msg = null;
this.msgType = null;
}
/* starts the clock for the timezone setting */
startClock() {
this.tick();
interval = this.$interval(() => { this.tick(); }, 1000);
}
/* GENERAL ------------------------------------------------------------- */
/**
* saves the user's settings and displays a message
* @param updateTheme whether to update the UI theme
*/
update(updateTheme) {
this.UserService.saveSettings(this.settings, this.userId)
.then((response) => {
// display success message to user
this.msg = response.text;
this.msgType = 'success';
if (updateTheme) {
let now = Date.now();
if ($('link[href^="user.css"]').length) {
$('link[href^="user.css"]').remove();
}
$('head').append(`<link rel="stylesheet"
href="user.css?v${now}" type="text/css" />`);
}
})
.catch((error) => {
// display error message to user
this.msg = error.text;
this.msgType = 'danger';
});
}
/* updates the date and format for the timezone setting */
tick() {
this.date = new Date();
if (this.settings.timezone === 'gmt') {
this.dateFormat = 'yyyy/MM/dd HH:mm:ss\'Z\'';
} else {
this.dateFormat = 'yyyy/MM/dd HH:mm:ss';
}
}
/* updates the displayed date for the timzeone setting
* triggered by the user changing the timezone setting */
updateTime() {
this.tick();
this.update();
}
/**
* Displays the field.exp instead of field.dbField in the
* field typeahead inputs
* @param {string} value The dbField of the field
*/
formatField(value) {
for (let i = 0, len = this.fields.length; i < len; i++) {
if (value === this.fields[i].dbField) {
return this.fields[i].exp;
}
}
}
/**
* Gets the field that corresponds to a field's dbField value
* @param {string} dbField The fields dbField value
* @returns {object} field The field that corresponds to the entered dbField
*/
getField(dbField) {
for (let i = 0, len = this.fields.length; i < len; i++) {
if (dbField === this.fields[i].dbField) {
return this.fields[i];
}
}
}
/* VIEWS --------------------------------------------------------------- */
/* creates a view given the view name and expression */
createView() {
if (!this.newViewName || this.newViewName === '') {
this.viewFormError = 'No view name specified.';
return;
}
if (!this.newViewExpression || this.newViewExpression === '') {
this.viewFormError = 'No view expression specified.';
return;
}
let data = {
viewName : this.newViewName,
expression: this.newViewExpression
};
this.UserService.createView(data, this.userId)
.then((response) => {
// add the view to the view list
this.views[data.viewName] = {
expression: data.expression,
name : data.viewName
};
this.viewFormError = false;
// clear the inputs
this.newViewName = null;
this.newViewExpression = null;
// display success message to user
this.msg = response.text;
this.msgType = 'success';
})
.catch((error) => {
// display error message to user
this.msg = error.text;
this.msgType = 'danger';
});
}
/**
* Deletes a view given its name
* @param {string} name The name of the view to delete
*/
deleteView(name) {
this.UserService.deleteView(name, this.userId)
.then((response) => {
// remove the view from the view list
this.views[name] = null;
delete this.views[name];
// display success message to user
this.msg = response.text;
this.msgType = 'success';
})
.catch((error) => {
// display error message to user
this.msg = error.text;
this.msgType = 'danger';
});
}
/**
* Sets a view as having been changed
* @param {string} key The unique id of the changed view
*/
viewChanged(key) {
this.views[key].changed = true;
}
/**
* Cancels a view change by retrieving the view
* @param {string} key The unique id of the view
*/
cancelViewChange(key) {
this.UserService.getViews(this.userId)
.then((response) => {
this.views[key] = response[key];
})
.catch((error) => {
this.viewListError = error.text;
});
}
/**
* Updates a view
* @param {string} key The unique id of the view to update
*/
updateView(key) {
let data = this.views[key];
if (!data) {
this.msg = 'Could not find corresponding view';
this.msgType = 'danger';
return;
}
if (!data.changed) {
this.msg = 'This view has not changed';
this.msgType = 'warning';
return;
}
data.key = key;
this.UserService.updateView(data, this.userId)
.then((response) => {
// update view list
this.views = response.views;
// display success message to user
this.msg = response.text;
this.msgType = 'success';
// set the view as unchanged
data.changed = false;
})
.catch((error) => {
// display error message to user
this.msg = error.text;
this.msgType = 'danger';
});
}
/* CRON QUERIES -------------------------------------------------------- */
/* creates a cron query given the name, expression, process, and tags */
createCronQuery() {
if (!this.newCronQueryName || this.newCronQueryName === '') {
this.cronQueryFormError = 'No cron query name specified.';
return;
}
if (!this.newCronQueryExpression || this.newCronQueryExpression === '') {
this.cronQueryFormError = 'No cron query expression specified.';
return;
}
if (!this.newCronQueryTags || this.newCronQueryTags === '') {
this.cronQueryFormError = 'No cron query tags specified.';
return;
}
let data = {
enabled : true,
name : this.newCronQueryName,
query : this.newCronQueryExpression,
action : this.newCronQueryAction,
tags : this.newCronQueryTags,
since : this.newCronQueryProcess,
};
this.UserService.createCronQuery(data, this.userId)
.then((response) => {
// add the cron query to the view
this.cronQueryFormError = false;
data.count = 0; // initialize count to 0
this.cronQueries[response.key] = data;
// reset fields
this.newCronQueryName = null;
this.newCronQueryTags = null;
this.newCronQueryExpression = null;
// display success message to user
this.msg = response.text;
this.msgType = 'success';
})
.catch((error) => {
// display error message to user
this.msg = error.text;
this.msgType = 'danger';
});
}
/**
* Deletes a cron query given its key
* @param {string} key The cron query's key
*/
deleteCronQuery(key) {
this.UserService.deleteCronQuery(key, this.userId)
.then((response) => {
// remove the cron query from the view
this.cronQueries[key] = null;
delete this.cronQueries[key];
// display success message to user
this.msg = response.text;
this.msgType = 'success';
})
.catch((error) => {
// display error message to user
this.msg = error.text;
this.msgType = 'danger';
});
}
/**
* Sets a cron query as having been changed
* @param {string} key The unique id of the cron query
*/
cronQueryChanged(key) {
this.cronQueries[key].changed = true;
}
/**
* Cancels a cron query change by retrieving the cron query
* @param {string} key The unique id of the cron query
*/
cancelCronQueryChange(key) {
this.UserService.getCronQueries(this.userId)
.then((response) => {
this.cronQueries[key] = response[key];
})
.catch((error) => {
this.cronQueryListError = error.text;
});
}
/**
* Updates a cron query
* @param {string} key The unique id of the cron query to update
*/
updateCronQuery(key) {
let data = this.cronQueries[key];
if (!data) {
this.msg = 'Could not find corresponding cron query';
this.msgType = 'danger';
return;
}
if (!data.changed) {
this.msg = 'This cron query has not changed';
this.msgType = 'warning';
return;
}
data.key = key;
this.UserService.updateCronQuery(data, this.userId)
.then((response) => {
// display success message to user
this.msg = response.text;
this.msgType = 'success';
// set the cron query as unchanged
data.changed = false;
})
.catch((error) => {
// display error message to user
this.msg = error.text;
this.msgType = 'danger';
});
}
/* THEMES -------------------------------------------------------------- */
setTheme() {
// default to default theme if the user has not set a theme
if (!this.settings.theme) { this.settings.theme = 'default-theme'; }
if (this.settings.theme.startsWith('custom')) {
this.settings.theme = 'custom-theme';
this.creatingCustom = true;
}
}
/* changes the ui theme (picked from existing themes) */
changeTheme() {
bodyElem.removeClass();
bodyElem.addClass(this.settings.theme);
this.update();
this.getThemeColors();
}
/* changes a color value of a custom theme and applies the theme */
changeColor() {
bodyElem.removeClass();
bodyElem.addClass('custom-theme');
this.setThemeString();
this.settings.theme = `custom1:${this.themeString}`;
this.update(true);
}
/* retrievs the theme colors from the document body's property values */
getThemeColors() {
let styles = this.$window.getComputedStyle(this.$document[0].body);
this.background = styles.getPropertyValue('--color-background').trim() || '#FFFFFF';
this.foreground = styles.getPropertyValue('--color-foreground').trim() || '#333333';
this.foregroundAccent = styles.getPropertyValue('--color-foreground-accent').trim();
this.primary = styles.getPropertyValue('--color-primary').trim();
this.primaryLightest = styles.getPropertyValue('--color-primary-lightest').trim();
this.secondary = styles.getPropertyValue('--color-secondary').trim();
this.secondaryLightest = styles.getPropertyValue('--color-secondary-lightest').trim();
this.tertiary = styles.getPropertyValue('--color-tertiary').trim();
this.tertiaryLightest = styles.getPropertyValue('--color-tertiary-lightest').trim();
this.quaternary = styles.getPropertyValue('--color-quaternary').trim();
this.quaternaryLightest = styles.getPropertyValue('--color-quaternary-lightest').trim();
this.water = styles.getPropertyValue('--color-water').trim();
this.land = styles.getPropertyValue('--color-land').trim() || this.primary;
this.src = styles.getPropertyValue('--color-src').trim() || '#CA0404';
this.dst = styles.getPropertyValue('--color-dst').trim() || '#0000FF';
this.setThemeString();
}
updateThemeString() {
let colors = this.themeString.split(',');
this.background = colors[0];
this.foreground = colors[1];
this.foregroundAccent = colors[2];
this.primary = colors[3];
this.primaryLightest = colors[4];
this.secondary = colors[5];
this.secondaryLightest = colors[6];
this.tertiary = colors[7];
this.tertiaryLightest = colors[8];
this.quaternary = colors[9];
this.quaternaryLightest = colors[10];
this.water = colors[11];
this.land = colors[12];
this.src = colors[13];
this.dst = colors[14];
this.changeColor();
}
setThemeString() {
this.themeString = `${this.background},${this.foreground},${this.foregroundAccent},${this.primary},${this.primaryLightest},${this.secondary},${this.secondaryLightest},${this.tertiary},${this.tertiaryLightest},${this.quaternary},${this.quaternaryLightest},${this.water},${this.land},${this.src},${this.dst}`;
}
/* COLUMN CONFIGURATIONS ----------------------------------------------- */
/**
* Deletes a previously saved custom column configuration
* @param {string} name The name of the column config to remove
* @param {int} index The index in the array of the column config to remove
*/
deleteColConfig(name, index) {
this.UserService.deleteColumnConfig(name, this.userId)
.then((response) => {
this.colConfigs.splice(index, 1);
// display success message to user
this.msg = response.text;
this.msgType = 'success';
})
.catch((error) => {
// display error message to user
this.msg = error.text;
this.msgType = 'danger';
});
}
/* PASSWORD ------------------------------------------------------------ */
/* changes the user's password given the current password, the new password,
* and confirmation of the new password */
changePassword() {
if (!this.userId && (!this.currentPassword || this.currentPassword === '')) {
this.changePasswordError = 'You must enter your current password';
return;
}
if (!this.newPassword || this.newPassword === '') {
this.changePasswordError = 'You must enter a new password';
return;
}
if (!this.confirmNewPassword || this.confirmNewPassword === '') {
this.changePasswordError = 'You must confirm your new password';
return;
}
if (this.newPassword !== this.confirmNewPassword) {
this.changePasswordError = 'Your passwords don\'t match';
return;
}
let data = {
newPassword : this.newPassword,
currentPassword : this.currentPassword
};
this.UserService.changePassword(data, this.userId)
.then((response) => {
this.changePasswordError = false;
this.currentPassword = null;
this.newPassword = null;
this.confirmNewPassword = null;
// display success message to user
this.msg = response.text;
this.msgType = 'success';
})
.catch((error) => {
// display error message to user
this.msg = error.text;
this.msgType = 'danger';
});
}
} |
JavaScript | class Store {
/**
* @hideconstructor
*/
constructor(connection) {
this._connection = connection;
}
/**
* Gets the value of key
* @param {string} key Key of the stored data
* @example extension.store.get('key').then((value) => console.log(value)) // will log value for the given key
* @return {external:Promise}
*/
get(key) {
if (!key || typeof key !== 'string') { throw new Error('Kindly provide valid parameters'); }
return this._connection.sendToParent('store', { action: 'get', key })
.then(event => Promise.resolve(event.data)).catch(onError);
}
/**
* Gets an object with all the stored key-value pairs.
* @example extension.store.getAll().then((obj) => obj)
* @return {external:Promise}
*/
getAll() {
return this._connection.sendToParent('store', { action: 'getAll' })
.then(({ data = {} }) => Promise.resolve(data)).catch(onError);
}
/**
* Sets the value of a key
* @param {string} key Key of the stored data.
* @param {*} value Data to be stored.
* @example extension.store.set('key', 'value').then((success) => console.log(success)) // will log ‘true’ when value is set
* @return {external:Promise}
*/
set(key, value) {
if (!key || !value || typeof key !== 'string') {
throw new Error('Kindly provide valid parameters');
}
return this._connection.sendToParent('store', { action: 'set', key, value })
.then(() => Promise.resolve(true)).catch(onError);
}
/**
* Removes the value of a key
* @param {string} key Key of the data to be removed from the store
* @example extension.store.remove('key').then((success) => console.log(success)) // will log ‘true’ when value is removed
* @return {external:Promise}
*/
remove(key) {
if (!key || typeof key !== 'string') { throw new Error('Kindly provide valid parameters'); }
return this._connection.sendToParent('store', { action: 'remove', key })
.then(() => Promise.resolve(true)).catch(onError);
}
/**
* Clears all the stored data of an extension
* @example extension.store.clear().then((success) => console.log(success)) // will log ‘true’ when values are cleared
* @return {external:Promise}
*/
clear() {
return this._connection.sendToParent('store', { action: 'clear' })
.then(() => Promise.resolve(true)).catch(onError);
}
} |
JavaScript | class Booth extends Base {
constructor(booth, client) {
super(client);
this.isLocked = booth.isLocked;
this.shouldCycle = booth.shouldCycle;
}
_setLock(lock) {
return this.isLocked = lock;
}
_setCycle(cycle) {
return this.shouldCycle = cycle;
}
setLock(lock, clear) {
return this._client.setLock(lock, clear);
}
setCycle(cycle) {
return this._client.setCycle(cycle);
}
/**
* Unlocks the queue
* @returns {Promise}
*/
unlock() {
return this.setLock(false);
}
/**
* Locks the queue
* @returns {Promise}
*/
lock() {
return this.setLock(true);
}
/**
* Clears and locks the queue
* @returns {Promise}
*/
clear() {
return this.setLock(true, true);
}
/**
* Enables queue cycling
* @returns {Promise}
*/
enableCycle() {
return this.setCycle(true);
}
/**
* Disables queue cycling
* @returns {Promise}
*/
disableCycle() {
return this.setCycle(false);
}
} |
JavaScript | class PageDots extends base {
constructor() {
super();
this.$.dots.addEventListener('click', event => {
const dot = event.target;
const dotIndex = this.dots.indexOf(dot);
if (dotIndex >= 0) {
this.selectedIndex = dotIndex;
}
});
}
get dots() {
return [].slice.call(this.$.dots.querySelectorAll('.dot'));
}
[symbols.itemsChanged]() {
if (super[symbols.itemsChanged]) { super[symbols.itemsChanged](); }
renderArrayAsElements(this.items, this.$.dots, (item, element) => {
// We don't use the item parameter, because any item will produce an
// identical corresponding dot.
if (!element) {
element = document.createElement('div');
element.classList.add('dot');
element.classList.add('style-scope');
element.classList.add('basic-page-dots');
element.setAttribute('role', 'none');
return element;
}
});
refreshDots(this);
}
[symbols.itemSelected](item, selected) {
if (super[symbols.itemSelected]) { super[symbols.itemSelected](item, selected); }
const index = this.items.indexOf(item);
// See if the corresponding dot has already been created.
// If not, the correct dot will be selected when it gets created.
const dots = this.dots;
if (dots && dots.length > index) {
const dot = this.dots[index];
if (dot) {
toggleClass(dot, 'selected', selected);
}
}
}
/**
* The distance the user has moved the first touchpoint since the beginning
* of a drag, expressed as a fraction of the element's width.
*
* @type number
*/
get selectedFraction() {
return super.selectedFraction;
}
set selectedFraction(value) {
if ('selectedFraction' in base.prototype) { super.selectedFraction = value; }
renderTransition(this, this.selectedIndex, value);
}
get selectedIndex() {
return super.selectedIndex;
}
set selectedIndex(index) {
if ('selectedIndex' in base.prototype) { super.selectedIndex = index; }
refreshDots(this);
}
get [symbols.template]() {
const baseTemplate = super[symbols.template] || '';
return `
<style>
:host {
display: -webkit-flex;
display: flex;
position: relative;
}
#dots {
bottom: 0;
display: -webkit-flex;
display: flex;
-webkit-justify-content: center;
justify-content: center;
position: absolute;
width: 100%;
z-index: 1;
}
#dotNavigationContainer {
display: -webkit-flex;
display: flex;
-webkit-flex: 1;
flex: 1;
position: relative;
z-index: 0;
}
#container ::slotted(*) {
-webkit-flex: 1;
flex: 1;
}
.dot {
background: rgb(255, 255, 255);
border-radius: 7px;
box-shadow: 0 0 1px 1px rgba(0, 0, 0, 0.5);
box-sizing: border-box;
cursor: pointer;
height: 8px;
margin: 7px 5px;
opacity: 0.4;
padding: 0;
transition: background 0.2s box-shadow 0.2s;
width: 8px;
}
.dot:hover {
background: rgba(0, 0, 0, 0.75);
box-shadow: 0 0 1px 3px rgba(255, 255, 255, 0.5);
}
.dot.selected {
opacity: 0.95;
}
@media (min-width: 768px) {
.dot {
height: 12px;
width: 12px;
}
}
</style>
<div id="dots" role="none"></div>
<div id="dotNavigationContainer" role="none">
${baseTemplate}
</div>
`;
}
} |
JavaScript | class AzureClientCredentials {
/**
* Creates a new AzureClientCredentials class.
* @param {string} tenant - The Azure AD tenant.
* @param {string} clientId - The client App ID URI.
* @param {string} clientSecret - The client secret from Azure AD.
*/
constructor(tenant, clientId, clientSecret) {
this.tenant = tenant;
this.clientId = clientId;
this.clientSecret = clientSecret;
this.tokens = {};
}
/**
* Gets the access token from the login service or returns a cached
* access token if the token expiration time has not been exceeded.
* @param {string} resource - The App ID URI for which access is requested.
* @returns A promise that is resolved with the access token.
*/
getAccessToken(resource) {
let token = this.tokens[resource];
if (token) {
if (Date.now() < token.exp) {
return Promise.resolve(token.val);
}
}
return this._requestAccessToken(resource);
}
/**
* Requests the access token using the OAuth 2.0 client credentials flow.
* @param {string} resource - The App ID URI for which access is requested.
* @returns A promise that is resolved with the access token.
*/
_requestAccessToken(resource) {
let params = {
grant_type: 'client_credentials',
client_id: this.clientId,
client_secret: this.clientSecret,
resource: resource
};
return this._httpsPost('token', params).then(body => {
let exp = Date.now() + parseInt(body.expires_in) * 1000;
this.tokens[resource] = {
val: body.access_token,
exp: exp - FIVE_MINUTE_BUFFER
};
return body.access_token;
});
}
/**
* Sends an HTTPS POST request to the specified endpoint.
* The endpoint is the last part of the URI (e.g., "token").
* @param {string} endpoint - The last part of the URI.
* @param {object} params - The form parameters to send.
* @returns A promise that is resolved with the response body.
*/
_httpsPost(endpoint, params) {
const options = {
method: 'POST',
baseUrl: MICROSOFT_LOGIN_URL,
uri: `/${this.tenant}/oauth2/${endpoint}`,
form: params,
json: true,
encoding: 'utf8'
};
return new Promise((resolve, reject) => {
request(options, (err, response, body) => {
if (err) return reject(err);
if (body.error) {
err = new Error(body.error_description.split(/\r?\n/)[0]);
err.code = body.error;
return reject(err);
}
resolve(body);
});
});
}
} |
JavaScript | class Streamer extends Feature {
registry_ = null;
selectionManager_ = null;
streamer_ = null;
constructor() {
super();
// Depends on settings to configure the properties of vehicle streaming on the server.
const settings = this.defineDependency('settings');
// The streamer wraps the PlaygroundJS-provided streaming plane, and makes sure that its
// information continues to be up-to-date.
this.streamer_ = server.isTest() ? new MockVehicleStreamer(settings)
: new VehicleStreamer(settings);
// Keeps track of which streamable vehicles have been created on the server.
this.registry_ = new VehicleRegistry(settings, this.streamer_);
// Responsible for taking information from the vehicle streamer, and ensuring that those
// vehicles are created on the server. The meaty bit of our streamer.
this.selectionManager_ = new VehicleSelectionManager(
this.registry_, settings, this.streamer_);
if (!server.isTest())
this.selectionManager_.select();
}
// ---------------------------------------------------------------------------------------------
// Public API of the Streamer feature
// ---------------------------------------------------------------------------------------------
// Creates a new streamable vehicle on the server. The |vehicle| must thus follow the syntax of
// the StreamableVehicleInfo object. An instance of StreamableVehicle will be returned. Vehicles
// without a `respawnDelay` setting will be considered ephemeral.
createVehicle(vehicleInfo, immediate = false) {
if (!isInstance(vehicleInfo, 'StreamableVehicleInfo'))
throw new Error(`The vehicle info must be given as a StreamableVehicleInfo instance.`);
const streamableVehicle = this.registry_.createVehicle(vehicleInfo);
if (immediate)
this.selectionManager_.requestCreateVehicle(streamableVehicle);
return streamableVehicle;
}
// Deletes the given |vehicle| from the server, which must be a StreamableVehicle instance.
// Ephemeral vehicles may be
deleteVehicle(vehicle) {
if (!isInstance(vehicle, 'StreamableVehicle'))
throw new Error(`The vehicle must be given as a StreamableVehicle instance.`);
this.registry_.deleteVehicle(vehicle);
// Request deletion of any live representations of this vehicle as well.
this.selectionManager_.requestDeleteVehicle(vehicle);
}
// ---------------------------------------------------------------------------------------------
// Requests the streamer plane to be optimised. Technically, this will re-insert all vehicles in
// the RTree which allows for them to be better balanaced.
optimise() { this.streamer_.optimise(); }
// Queries the streaming radius around the given |position| to understand the number of vehicles
// and vehicle models that exist in that area.
query(position) { return this.registry_.query(position); }
// Gets statistics about the vehicle streamer, to understand how it's performing and what's
// been created on the server. Useful to understand whether the streamer is working well.
stats() {
return {
// Total number of vehicles known to the streamer.
totalVehicles: this.streamer_.size,
// Total number of vehicles that have been created on the server.
liveVehicles: this.selectionManager_.liveVehicles,
// Total number of vehicles that have been streamed in.
streamedVehicles: this.selectionManager_.streamedVehicles,
// Total number of vehicles that have been cached.
cachedVehicles: this.selectionManager_.cachedVehicles,
// Total number of vehicles that are currently on the respawn queue.
respawnQueueVehicles: this.selectionManager_.respawnQueueVehicles,
}
}
// ---------------------------------------------------------------------------------------------
// Public API intended for testing purposes of the Streamer feature
// ---------------------------------------------------------------------------------------------
// Gets the number of vehicles that exist on the streamer. Should only be used for testing.
get sizeForTesting() { return this.streamer_.size; }
// Streams all created vehicles, triggering creation and disposal of the real vehicles based on
// the positions of the given |players|, which must be an iterable of Player instances.
async streamForTesting(players) {
if (!server.isTest())
throw new Error(`The streamForTesting() method is only available during tests.`);
this.streamer_.setPlayersForTesting(players);
this.selectionManager_.updateSelection(new Set([ ...await this.streamer_.stream() ]));
}
// ---------------------------------------------------------------------------------------------
dispose() {
this.registry_.dispose();
this.registry_ = null;
this.streamer_.dispose();
this.streamer_ = null;
this.selectionManager_.dispose();
this.selectionManager_ = null;
}
} |
JavaScript | class M20eItem extends Item {
/**
* creates a derived class for specific item types
* @override
*/
constructor(data, context) {
if (data.type in CONFIG.Item.documentClasses && !context?.isExtendedClass) {
// instanciate our custom item subclass here
return new CONFIG.Item.documentClasses[data.type](data, { ...{ isExtendedClass: true }, ...context });
}
//default behavior, just call super and do all the default Item inits.
super(data, context);
}
/* -------------------------------------------- */
/* New Item Creation */
/* -------------------------------------------- */
/**
* Added sourceId when cloning
* @override
*/
clone(data, options) {
data = data || {};
data['flags.core.sourceId'] = this.uuid;
super.clone(data, options);
}
/* -------------------------------------------- */
//TODO : replace create dialog
/**
* Mostly vanilla function with support for subType selection
* @override
*/
/*
static async createDialog(data={}, options={}) {
debugger
const documentName = this.metadata.name;
const types = game.system.entityTypes[documentName];
const folders = game.folders.filter(f => (f.data.type === documentName) && f.displayed);
const label = game.i18n.localize(this.metadata.label);
const title = game.i18n.localize('M20E.new.createItem');
const itemCreate = new ItemCreateDlg(data, options);
itemCreate.render(true);
}
*/
/* -------------------------------------------- */
/**
* adds image path and systemDescription before sending the whole thing to the database
* prompts for subType if that particular item type does require one,
* in order to get the matching img and systemDesc.
* @override
*/
async _preCreate(data, options, user) {
await super._preCreate(data, options, user);
const itemData = this.data;
//check if item is from existing item (going in or out a compendiumColl or drag from actorSheet)
if (itemData.flags.core?.sourceId || itemData._id) { return; }
//item is brand new => set some default values before sending it to the database
const updateData = { data: {} };
// prompt for subtype if relevant
if (itemData.data.subType && !options.fromActorSheet) {
const newSubType = await this.promptForSubType(itemData);
updateData.data.subType = newSubType || itemData.data.subType;
}
//get specific type (subtype if any, otherwise base type)
const specificType = updateData.data.subType || itemData.data.subType || itemData.type;
//get appropriate default image
updateData.img = CONFIG.M20E.defaultImg[specificType] || CONFIG.M20E.defaultImg[itemData.type] || CONFIG.M20E.defaultImg['default'];
//get appropriate systemDescription
if (itemData.data.systemDescription === '') {
updateData.data.systemDescription = await utils.getDefaultDescription(specificType);
}
itemData.update(updateData);
}
/* -------------------------------------------- */
/**
* Prompts the user for a subType from dropDown list of available subtypes for this particular itemType
* @param {ItemData} itemData an instance of ItemData
*
* @returns {Promise<String|null>} selected subType or null if user escaped the prompt
*/
async promptForSubType(itemData) {
const itemType = itemData.type;
//build list of subTypes to be fed to the promptSelect()
const subTypes = Object.entries(
foundry.utils.getProperty(CONFIG.M20E, `${itemType}SubTypes`))
.map(([key, value]) => {
return { value: key, name: game.i18n.localize(value) };
});
return utils.promptSelect({
title: itemData.name,
promptString: game.i18n.format('M20E.prompts.subTypeContent', {
type: game.i18n.localize(`ITEM.Type${itemType.capitalize()}`)
}),
curValue: subTypes[0].key,
options: subTypes
});
}
/* -------------------------------------------- */
/* Item Preparation */
/* -------------------------------------------- */
/** @override */
prepareData() {
super.prepareData();
const itemData = this.data;
itemData.data.path = this.getPath();
//check if item type is amongst protected types
const protectedTypes = CONFIG.M20E.protectedCategories.reduce((acc, cur) => {
const itemType = CONFIG.M20E.categoryToType[cur]
return itemType ? [...acc, itemType] : acc;
}, []);
itemData.isProtectedType = protectedTypes.includes(itemData.type);
//create restricted array from string
if ( itemData.data.restrictions ) {
itemData.data.restricted = itemData.data.restrictions.split(',').map(entry => entry.trim());
}
//deal with armor types
if ( itemData.type === 'armor' ) {
//check for effect
const armorEffect = this.effects.get(Array.from(this.effects.keys())[0]);
if ( armorEffect ) {
itemData.data.dextPenalty = -1* armorEffect.data.changes[0].value;
} else {
itemData.data.dextPenalty = 0;
}
}
}
/* -------------------------------------------- */
//get that's displayed on the actorsheet
getMiniFlavor() {
const itemData = this.data;
let miniFlavor = '';
if ( itemData.type === 'armor' ) {//todo maybe make armor types their own class ?
miniFlavor = `${game.i18n.localize("M20E.labels.absorbtion")} : ${itemData.data.value}D`;
return miniFlavor;
}
}
/* -------------------------------------------- */
/**
* Computes and returns a valid trait path from itemData.
* @returns path like "category.subType.key" or "category.key"
*/
getPath() {
const cat = CONFIG.M20E.traitToCat[this.data.type];
const subType = CONFIG.M20E.traitToCat[this.data.data.subType];
const key = utils.sanitize(this.data.name);
return `${cat}.${subType ? subType + '.' : ''}${key}`;
}
/* -------------------------------------------- */
/**
* returns a pair {path, data} to populate the actor's stats in the _prepateItemStats()
* @returns {Object}
*/
getStatData() {
const itemData = this.data;
return {
path: this.getPath(),
name: itemData.name,
statData: {
value: parseInt(itemData.data.value),
itemId: itemData._id
}
}
}
/* -------------------------------------------- */
/**
* returns all necessary data to roll this stat.
* called by actor.extendStats().
* note : value could actually be fetched from either
* itemData.data.value or itemData.data._overrideValue.
* @param {String} path
*/
getExtendedTraitData(path) {
const itemData = this.data;
if ( this.isUnequipped ) { throw {msg: 'unequipped'}}
return {
name: itemData.name,
displayName: itemData.data.displayName ?? null,
value: this.actor._getStat(path, 'value'),
specialty: itemData.data.specialty ?? null
};
}
/* -------------------------------------------- */
/**
* Returns a Trait instance from item's constructed path and itemId
* @returns {Trait}
*/
toTrait() {
const itemData = this.data;
return new Trait({ path: this.getPath(), itemId: this.data._id });
}
/* -------------------------------------------- */
/**
* called at the end of actor._prepareData to deal with owned items whose data depend on the actor.
* Implemented in subClasses
*/
_prepareOwnedItem() {
//to be overridde
this.data.data.miniFlavor = this.getMiniFlavor();
}
/* -------------------------------------------- */
/**
* Displays an item trait in chat.
* Prepares some templateData before feeding the to chat.displayCard
* overridden in subclasses
* atm only for stat items (ie not events, misc etc)
*/
linkInChat() {
const itemData = this.data;
if (!this.isStat) {
ui.notifications.warn(game.i18n.localize('M20E.notifications.notImplemented'));
return;
}
const templateData = {
category: CONFIG.M20E.traitToCat[itemData.type],
subType: CONFIG.M20E.traitToCat[itemData.data.subType],
key: utils.sanitize(itemData.name),
itemId: itemData._id
};
templateData.path = `${templateData.category}.${templateData.subType ?
templateData.subType + '.' : ''}${templateData.key}`;
//build the trait's data
templateData.traitData = {
type: game.i18n.localize(`M20E.category.${templateData.category}`),
name: itemData.name,
img: itemData.img,
data: itemData.data
};
//display the card
chat.displayCard(this.actor, templateData);
}
/* -------------------------------------------- */
/* Shorthands */
/* -------------------------------------------- */
get isRollable() {
return this.data.data.isRollable === true;
}
get isStat() {
return this.data.data.isStat === true;
}
get isActive() { // todo : not sure atm
return this.data.data.isActive === true;
}
get isEquipable() {
return this.data.data.isEquipable === true;
}
/**
* To be considered unequipped, item needs to be an equipable first !
*/
get isUnequipped() {
return this.isEquipable && this.data.data.equipped === false;
}
} |
JavaScript | class InputValidatorComponent extends Component {
restrictedSymb;
minlength = '13';
maxlength = '13';
@tracked value;
@tracked error = false;
@tracked validated = false;
@action
validateInput(event) {
this.restrictedSymb = /[^0-9]/g;
this.value = event.target.value.replace(this.restrictedSymb, '');
if (event.key == 'Backspace' || 'Delete') {
this.error = false;
}
[this.restrictedSymb, this.error] = [...this.validateSymbol(this.value)];
this.args.value(this.value);
this.validated = this.validateFinal(this.value, this.minlength, this.error);
this.args.validated(this.validated);
}
/* check each symbol according to restricted */
validateSymbol(value) {
let restrictedSymb;
let error = false;
if (value) {
[...value].forEach((sym, pos) => {
restrictedSymb = this.returnRestricted(pos, value);
error += this.toggleError(sym, restrictedSymb);
});
}
return [restrictedSymb, error];
}
/* check if value is final and set validated param */
validateFinal(value, minlength, error) {
return value.length == minlength && error == false ? true : false;
}
/* trigger error in case of unacceptable number */
toggleError(symbol, restricted) {
return symbol.match(restricted) ? true : false;
}
/* check number according to position, more complex verifications have dedicated methods */
returnRestricted(position, value) {
switch (position) {
case 0:
return /[^1,2,5,6,7,8]/g;
case 3:
return /[^0,1]/g;
case 5:
return /[^0,1,2,3]/g;
case 7:
return /[^0,1,2,3,4,5,8]/g;
case 8:
return this.verifyJ2(value[position - 1]);
case 12:
return this.verifyC(value);
default:
return /[^0-9]/g;
}
}
verifyJ2(prevValue) {
if (prevValue == 4) {
return /[^0-8]/g;
} else if (prevValue == 5) {
return /[^0,1]/g;
} else {
return /[^0-9]/g;
}
}
verifyC(value) {
let v = [...value];
v.pop();
let verConst = '279146358279';
let sumConst = v.reduce((acc, cur, ind) => {
let tempVal = cur * verConst[ind];
acc += tempVal;
return parseInt(acc);
}, 0);
let resConst = sumConst % 11;
return resConst < 10 ? new RegExp(`[^${resConst}]`, 'g') : /[^1]/g;
}
} |
JavaScript | class DSA_Yii extends DSA_Base {
/**
* @inheritdoc
*/
constructor(settings = {}) {
settings.inputId = settings.inputId || 'dsa_yii_search_input';
settings.baseDocsUrl = settings.baseDocsUrl || 'https://www.yiiframework.com/doc-2.0';
settings.docsVersion = settings.docsVersion || '2.0';
settings.searchUrl = settings.searchUrl || '';
super(settings);
}
/**
* @inheritdoc
*/
search(searchQuery) {
var data = DSA_YII_JSSEARCH.search(searchQuery);
var resultItems = this.getResultItemsHtml(data);
if (resultItems) {
this._resultsContainer.innerHTML = resultItems;
this.showResultsContainer();
} else {
this.hideResultsContainer();
}
}
/**
* Resolves single result item's link.
*
* @param {String} path
* @return {String}
*/
getLink(path = '') {
var normalizedBaseUrl = this.baseDocsUrl.endsWith('/') ? this.baseDocsUrl.slice(0, -1) : this.baseDocsUrl;
var normalizedPath = path.startsWith('/') ? path.slice(0, -1) : path;
return normalizedBaseUrl + '/' + normalizedPath;
}
/**
* @inheritdoc
*/
getResultItemsHtml(data) {
var self = this;
if (!data || !data.length) {
return (
'<a href="' + self.getFallbackSearchLink('Yii ' + self._searchInput.value) + '" class="' + self.resultsItemClass + ' ' + self.noResultsItemClass + '" target="_blank">' +
self.noResultsMessage + ' ' +
'<span class="dsa-search-result-accent">' + self.falbackSearchMessage +'</span>' +
'</a>'
);
}
var resultItems = '';
for (let i in data) {
let itemData = data[i].file || {};
resultItems += '<a href="' + self.getLink(itemData.u.substr(3)) + '" class="' + self.resultsItemClass + '" target="_blank">';
if (itemData.t) {
resultItems += '<div class="dsa-search-result-title">' + itemData.t + '</div>';
}
if (itemData.d) {
resultItems += '<div class="dsa-search-result-item-content">' + itemData.d + '</div>';
}
resultItems += '</a>';
}
return resultItems;
}
} |
JavaScript | class PrintableQR extends React.Component {
render() {
return (
<div className="print-container">
<canvas id="qr-canvas-print"></canvas>
<div className="print-ssid">
<b>SSID:</b>
<div>{this.props.ssid}</div>
</div>
{this.props.password.length > 0 &&
<div className="print-password">
<b>Password:</b>
<div>{this.props.password}</div>
</div>
}
</div>
);
}
} |
JavaScript | class ExperimentalSettings extends PureComponent {
static propTypes = {
/**
/* navigation object required to push new views
*/
navigation: PropTypes.object,
};
static navigationOptions = ({ navigation }) =>
getNavigationOptionsTitle(strings('app_settings.experimental_title'), navigation);
goToWalletConnectSessions = () => {
this.props.navigation.navigate('WalletConnectSessionsView');
};
render = () => (
<ScrollView style={styles.wrapper}>
<View style={styles.setting}>
<View>
<Text style={styles.title}>{strings('experimental_settings.wallet_connect_dapps')}</Text>
<Text style={styles.desc}>{strings('experimental_settings.wallet_connect_dapps_desc')}</Text>
<StyledButton
type="normal"
onPress={this.goToWalletConnectSessions}
containerStyle={styles.clearHistoryConfirm}
>
{strings('experimental_settings.wallet_connect_dapps_cta')}
</StyledButton>
</View>
</View>
</ScrollView>
);
} |
JavaScript | class CLIAnalyzeCommand extends CLICommand {
/**
* Class constructor.
* @ignore
*/
constructor() {
super();
/**
* The instruction needed to trigger the command.
* @type {string}
*/
this.command = 'analyze [target]';
/**
* A description of the command for the help interface.
* @type {string}
*/
this.description = 'Build a target that can be bundled and open the bundle analyzer';
/**
* Enable unknown options so other services can customize the run command.
* @type {boolean}
*/
this.allowUnknownOptions = true;
this.addOption(
'type',
'-t, --type [type]',
'Which build type: development (default) or production',
'development'
);
}
} |
JavaScript | class App {
static get appLanguage() {
const localStorageLng = localStorage.getItem("lng");
console.log("Local stored language: ", localStorageLng);
if (localStorageLng)
return localStorageLng;
const phoneLang = navigator.language;
console.log("Phone language: ", phoneLang);
if (phoneLang === "it" || phoneLang === "it-IT")
return "it";
else
return "en";
}
/** Flag that states the application is in expert mode. */
static get isExpertMode() { return localStorage.getItem("mode") === "true" };
/** The name of the local database. */
static get localDbName() { return "LandslideSurvey" };
/** The current version of the local database. */
static get localDbVersion() { return 1 }
/**
* Creates and initializes the activity as well as the internationalization service.
*
* @constructor
*/
constructor() {
// If the mode is not stored in the local storage, set it to false
if (!localStorage.getItem("mode")) localStorage.setItem("mode", "false");
// Flag that states if the position watcher has to be reattached after a "pause" event
this._toReattachPositionWatcher = false;
// The number of time the back button has been sequentially pressed
this._backPressedCount = 0;
// Flag that states if the user is using the application as a guest (i.e. no internet connection so no login)
this.isGuest = false;
// Array with the stack of activities currently open
this.activityStack = [];
// Attach the function to be fired when a "pause" or a "resume" event occurs
document.addEventListener("pause", this.onPause, false);
document.addEventListener("resume", this.onResume, false);
// Add a listener for the click of the black button
document.addEventListener("backbutton", () => this.onBackPressed(), false);
// Initialize the local database
this.initLocalDb()
.then(() => {
// Initialize the internationalization service
this.initInternationalization();
})
.catch(() => {
// Set the db to null
this.db = null;
// Alert the user
utils.createAlert("", i18next.t("dialogs.openLocalDbError"), i18next.t("dialogs.btnOk"));
// Initialize the internationalization service
this.initInternationalization();
});
}
/** Defines the behaviour of the back button for the whole application. */
onBackPressed() {
// If any loader or alert dialog is open, return
if (utils.isLoaderOpen || utils.isAlertOpen) return;
// If the image screen is open
if (utils.isImgScreenOpen) {
// Close the image screen
utils.closeImgScreen();
// Return
return;
}
// Perform the "onBackPressed" method of the last activity in the stack
app.activityStack[app.activityStack.length - 1].onBackPressed();
}
/** Opens the first activity based on the authentication status. */
open() {
// If there is not a valid session stored, open the login page
if (!LoginActivity.getInstance().getAuthStatus()) LoginActivity.getInstance().open();
// If there is a valid session in storage, open the map
else MapActivity.getInstance().open();
// Hide the splash screen
$("#splash").hide();
}
/** Initializes the internationalization service using i18next. */
initInternationalization() {
console.log("Setting language to: ", App.appLanguage);
// Initialize the internationalization service
i18next
.use(i18nextXHRBackend)
.init({
lng : App.appLanguage,
fallbackLng: "en",
ns : "general",
defaultNS : "general",
backend : { loadPath: "./locales/{{lng}}/{{ns}}.json" }
})
.then(() => {
// Attach the function to be fired when the language is changed
i18next.on("languageChanged", () => console.log(`lng changed to ${i18next.language}`));
// Initialize the jQuery plugin
jqueryI18next.init(i18next, $);
// Translate the body
$("body").localize();
// Open the first activity
this.open();
});
}
/** Initializes the local database using the IndexedDB API. */
initLocalDb() {
// Initialize the database variable
this.db = null;
return new Promise((resolve, reject) => {
// Create an open request
const dbOpenRequest = window.indexedDB.open(App.localDbName, App.localDbVersion);
// Fired if an error occurs
dbOpenRequest.onerror = err => {
console.error("Error opening the db", err);
// Reject the promise
reject();
};
// Fired if the opening is successful
dbOpenRequest.onsuccess = () => {
console.log("Db opened");
// Save the result in the database variable
this.db = dbOpenRequest.result;
// Resolve the promise
resolve();
};
// Fired if the db needs to be upgraded or created
dbOpenRequest.onupgradeneeded = () => {
console.log("Upgrading or creating db...");
// Save the result in the database variable
this.db = dbOpenRequest.result;
// Fired if an error occurs
this.db.onerror = err => {
console.error("Error upgrading or creating the db", err);
// Reject the promise
reject();
};
// Create a new object store
const objectStore = this.db.createObjectStore("landslides", { keyPath: "_id" });
// Fired if an error occurs
objectStore.transaction.onerror = err => {
console.error("Error creating the object store", err);
// Alert the user
// utils.createAlert("", i18next.t("dialogs.createLocalDbError"), i18next.t("dialogs.btnOk"));
// Reject the promise
reject();
};
// Fired if the creation is successful
objectStore.transaction.oncomplete = () => {
console.log("Object store created");
// Resolve the promise
resolve();
}
}
});
}
/** When the application is paused, it detaches the position watcher. */
onPause() {
console.log("onPause");
// If an instance of MapActivity has already been created
if (MapActivity.hasInstance()) {
// If the position watcher was attached before the pause event
if (MapActivity.getInstance().isPositionWatcherAttached) {
// Set the flag to true
app._toReattachPositionWatcher = true;
// Detach the position watcher
MapActivity.getInstance().detachPositionWatcher();
}
}
}
/** When the application is resumed, it re-attaches the position watcher. */
onResume() {
console.log("onResume");
// If the position watcher has to be re-attached
if (app._toReattachPositionWatcher) {
// Check if the gps is on and eventually attach the position watcher
MapActivity.getInstance().checkGPSOn(() => MapActivity.getInstance().attachPositionWatcher());
// Set the flag to false
app._toReattachPositionWatcher = false;
}
}
} |
JavaScript | class CustomizeService {
constructor(configManager, appService, xssService) {
this.configManager = configManager;
this.appService = appService;
this.xssService = xssService;
}
/**
* initialize custom css strings
*/
initCustomCss() {
const uglifycss = require('uglifycss');
const rawCss = this.configManager.getConfig('crowi', 'customize:css') || '';
// uglify and store
this.customCss = uglifycss.processString(rawCss);
}
getCustomCss() {
return this.customCss;
}
getCustomScript() {
return this.configManager.getConfig('crowi', 'customize:script') || '';
}
initCustomTitle() {
let configValue = this.configManager.getConfig('crowi', 'customize:title');
if (configValue == null || configValue.trim().length === 0) {
configValue = '{{pagename}} - {{sitename}}';
}
this.customTitleTemplate = configValue;
}
generateCustomTitle(pageOrPath) {
const path = pageOrPath.path || pageOrPath;
const dPagePath = new DevidedPagePath(path, true, true);
const customTitle = this.customTitleTemplate
.replace('{{sitename}}', this.appService.getAppTitle())
.replace('{{pagepath}}', path)
.replace('{{page}}', dPagePath.latter) // for backward compatibility
.replace('{{pagename}}', dPagePath.latter);
return this.xssService.process(customTitle);
}
generateCustomTitleForFixedPageName(title) {
// replace
const customTitle = this.customTitleTemplate
.replace('{{sitename}}', this.appService.getAppTitle())
.replace('{{page}}', title)
.replace('{{pagepath}}', title)
.replace('{{pagename}}', title);
return this.xssService.process(customTitle);
}
} |
JavaScript | class NewLetter extends Component {
constructor(props) {
super(props);
this.state = {
init: false,
cached: {},
templates: List(),
template: {},
listFocused: true,
listToggled: false,
};
}
/**
* @async
* @method UNSAFE_componentWillMount
* @summary ToDo: Describe the method
* @todo Write the documentation
*/
async UNSAFE_componentWillMount() {
const { windowId, docId, handleCloseLetter } = this.props;
try {
const res = await createLetter(windowId, docId);
this.setState({
...res.data,
init: true,
cached: res.data,
});
try {
await this.getTemplates();
} catch (error) {
// eslint-disable-next-line no-console
console.error(error);
}
} catch (error) {
handleCloseLetter();
}
}
/**
* @method getTemplates
* @summary ToDo: Describe the method
* @todo Write the documentation
*/
getTemplates = async () => {
const res = await getTemplates();
this.setState({
templates: List(res.data.values),
});
};
/**
* @method handleTemplate
* @summary ToDo: Describe the method
* @param {*} option
* @todo Write the documentation
*/
handleTemplate = async (option) => {
const { letterId, template } = this.state;
if (template === option) {
return;
}
const response = await patchRequest({
entity: 'letter',
docType: letterId,
property: 'templateId',
value: option,
});
this.setState({
...response.data,
template: option,
});
};
/**
* @method handleChange
* @summary ToDo: Describe the method
* @param {object} target
* @todo Write the documentation
*/
handleChange = ({ target: { value: message } }) => {
this.setState({
message,
});
};
/**
* @async
* @method handleBlur
* @summary ToDo: Describe the method
* @param {object} target
* @todo Write the documentation
*/
handleBlur = async ({ target: { value: message } }) => {
const { letterId } = this.state;
if (this.state.cached.message === message) {
return;
}
const response = await patchRequest({
entity: 'letter',
docType: letterId,
property: 'message',
value: message,
});
this.setState({
...response.data,
cached: response.data,
listFocused: false,
});
};
/**
* @method handleListFocus
* @summary ToDo: Describe the method
* @todo Write the documentation
*/
handleListFocus = () => {
this.setState({
listFocused: true,
});
};
/**
* @method handleListBlur
* @summary ToDo: Describe the method
* @todo Write the documentation
*/
handleListBlur = () => {
this.setState({
listFocused: false,
});
};
/**
* @method closeTemplatesList
* @summary ToDo: Describe the method
* @todo Write the documentation
*/
closeTemplatesList = () => {
this.setState({
listToggled: false,
});
};
/**
* @method openTemplatesList
* @summary ToDo: Describe the method
* @todo Write the documentation
*/
openTemplatesList = () => {
this.setState({
listToggled: true,
});
};
/**
* @async
* @method renderCancelButton
* @summary ToDo: Describe the method
* @todo Write the documentation
*/
complete = async () => {
const { letterId } = this.state;
const { handleCloseLetter, dispatch } = this.props;
await completeLetter(letterId);
handleCloseLetter();
await dispatch(
addNotification('Letter', 'Letter has been sent.', 5000, 'success')
);
};
/**
* @method render
* @summary ToDo: Describe the method
* @todo Write the documentation
*/
render() {
const { handleCloseLetter } = this.props;
const {
init,
message,
templates,
template,
letterId,
listFocused,
listToggled,
} = this.state;
if (!init) {
return false;
}
return (
<div className="screen-freeze">
<div className="panel panel-modal panel-letter panel-modal-primary">
<div className="panel-letter-header-wrapper">
<div className="panel-letter-header panel-letter-header-top">
<span className="letter-headline">
{counterpart.translate('window.letter.new')}
</span>
<a
href={`${config.API_URL}/letter/${letterId}/printPreview`}
target="_blank"
rel="noopener noreferrer"
className="input-icon input-icon-lg letter-icon-print"
>
<i className="meta-icon-print" />
</a>
{templates.size > 0 && (
<div className="letter-templates">
<RawList
rank="primary"
list={templates}
onSelect={(option) => this.handleTemplate(option)}
selected={template}
isFocused={listFocused}
isToggled={listToggled}
onOpenDropdown={this.openTemplatesList}
onCloseDropdown={this.closeTemplatesList}
onFocus={this.handleListFocus}
onBlur={this.handleListBlur}
/>
</div>
)}
<div
className="input-icon input-icon-lg letter-icon-close"
onClick={handleCloseLetter}
>
<i className="meta-icon-close-1" />
</div>
</div>
</div>
<div className="panel-letter-body">
<textarea
value={message ? message : ''}
onChange={this.handleChange}
onBlur={this.handleBlur}
/>
</div>
<div className="panel-letter-footer">
<button
onClick={this.complete}
className="btn btn-meta-success btn-sm btn-submit"
>
{counterpart.translate('window.letter.create')}
</button>
</div>
</div>
</div>
);
}
} |
JavaScript | class VigenereCipheringMachine {
constructor(modification) {
if (modification === false) this.reverse = false;
}
reverse = true;
encrypt(message, key) {
if (!message || !key) throw new Error('Incorrect arguments!');
const messageUpper = message.toUpperCase(),
keyUpper = key.toUpperCase();
let result = '';
for (let i = 0, j = 0; i <= messageUpper.length - 1; i++) {
if (messageUpper[i].charCodeAt() < 65 || messageUpper[i].charCodeAt() > 90) {
result += messageUpper[i];
continue;
}
result += String.fromCharCode(((messageUpper[i].charCodeAt() + keyUpper[j].charCodeAt() - 130) % 26) + 65);
j++;
j % keyUpper.length === 0 ? (j = 0) : j;
}
return this.reverse === true ? result : result.split('').reverse().join('');
}
decrypt(message, key) {
if (!message || !key) throw new Error('Incorrect arguments!');
let result = '';
const keyUpper = key.toUpperCase();
for (let i = 0, j = 0; i <= message.length - 1; i++) {
if (message[i].charCodeAt() < 65 || message[i].charCodeAt() > 90) {
result += message[i];
continue;
}
result += String.fromCharCode(((message[i].charCodeAt() - keyUpper[j].charCodeAt() + 26) % 26) + 65);
j++;
j % keyUpper.length === 0 ? (j = 0) : j;
}
return this.reverse === true ? result : result.split('').reverse().join('');
}
} |
JavaScript | class MenuConfiguration {
/**
* Creates a new instance of MenuConfiguration
* @class
*/
constructor () {
this._mainMenuLayout = null;
this._submenuLayout = null;
}
/**
* Gets the main menu layout
* @returns {MenuLayout} - The default main menu layout.
*/
getMenuLayout () {
return this._mainMenuLayout;
}
/**
* Sets the main menu layout
* @param {MenuLayout} mainMenuLayout - Changes the default main menu layout.
* @returns {MenuConfiguration} - A reference to this instance to support method chaining
*/
setMenuLayout (mainMenuLayout) {
this._mainMenuLayout = mainMenuLayout;
return this;
}
/**
* Gets the sub menu layout
* @returns {MenuLayout} - The default submenu layout. To change this for an individual submenu, set the
* menuLayout property on the MenuCell constructor for creating a cell with sub-cells.
*/
getSubMenuLayout () {
return this._submenuLayout;
}
/**
* Sets the sub menu layout
* @param {MenuLayout} submenuLayout - Changes the default submenu layout. To change this for an individual submenu, set the
* menuLayout property on the MenuCell constructor for creating a cell with sub-cells.
* @returns {MenuConfiguration} - A reference to this instance to support method chaining
*/
setSubMenuLayout (submenuLayout) {
this._submenuLayout = submenuLayout;
return this;
}
/**
* Checks whether two MenuConfigurations can be considered equivalent
* @param {MenuConfiguration} other - The object to compare
* @returns {Boolean} - Whether the objects are the same or not
*/
equals (other) {
if (other === null || other === undefined) {
return false;
}
if (this === other) {
return true;
}
if (!(other instanceof MenuConfiguration)) {
return false;
}
// main comparison check
if (this.getMenuLayout() !== other.getMenuLayout()) {
return false;
}
if (this.getSubMenuLayout() !== other.getSubMenuLayout()) {
return false;
}
return true;
}
} |
JavaScript | class FileWithChangedPermissionsByFDSync extends AsyncObject {
constructor (fd, mode) {
super(fd, mode)
}
syncCall () {
return (fd, mode, callback) => {
fs.fchmodSync(fd, mode, callback)
return fd
}
}
} |
JavaScript | class StopWatch extends Component {
constructor(props) {
super(props);
this.state = {
isTimerStart: true,
isStopwatchStart: true,
timerDuration: 90000,
resetTimer: false,
resetStopwatch: false,
};
this.startStopTimer = this.startStopTimer.bind(this);
this.resetTimer = this.resetTimer.bind(this);
this.startStopStopWatch = this.startStopStopWatch.bind(this);
this.resetStopwatch = this.resetStopwatch.bind(this);
}
startStopTimer() {
this.setState({
isTimerStart: !this.state.isTimerStart,
resetTimer: false,
});
}
resetTimer() {
this.setState({ isTimerStart: false, resetTimer: true });
}
startStopStopWatch() {
this.setState({
isStopwatchStart: !this.state.isStopwatchStart,
resetStopwatch: false,
});
}
resetStopwatch() {
this.setState({ isStopwatchStart: false, resetStopwatch: true });
}
getFormattedTime(time) {
this.currentTime = time;
}
render() {
return (
<View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>
<View
style={{
flex: 1,
marginTop: 5,
alignItems: 'center',
justifyContent: 'center',
}}>
<Stopwatch
laps
secs
start={this.state.isStopwatchStart}
//To start
reset={this.state.resetStopwatch}
//To reset
options={options}
//options for the styling
getTime={this.getFormattedTime}
/>
</View>
</View>
);
}
} |
JavaScript | class DocumentListElementSupport extends Plugin {
/**
* @inheritDoc
*/
static get requires() {
return [ DataFilter ];
}
/**
* @inheritDoc
*/
static get pluginName() {
return 'DocumentListElementSupport';
}
/**
* @inheritDoc
*/
init() {
const editor = this.editor;
if ( !editor.plugins.has( 'DocumentListEditing' ) ) {
return;
}
const schema = editor.model.schema;
const conversion = editor.conversion;
const dataFilter = editor.plugins.get( DataFilter );
const documentListEditing = editor.plugins.get( 'DocumentListEditing' );
// Register downcast strategy.
// Note that this must be done before document list editing registers conversion in afterInit.
documentListEditing.registerDowncastStrategy( {
scope: 'item',
attributeName: 'htmlLiAttributes',
setAttributeOnDowncast( writer, attributeValue, viewElement ) {
setViewAttributes( writer, attributeValue, viewElement );
}
} );
documentListEditing.registerDowncastStrategy( {
scope: 'list',
attributeName: 'htmlListAttributes',
setAttributeOnDowncast( writer, viewAttributes, viewElement ) {
setViewAttributes( writer, viewAttributes, viewElement );
}
} );
dataFilter.on( 'register', ( evt, definition ) => {
if ( ![ 'ul', 'ol', 'li' ].includes( definition.view ) ) {
return;
}
evt.stop();
// Do not register same converters twice.
if ( schema.checkAttribute( '$block', 'htmlListAttributes' ) ) {
return;
}
schema.extend( '$block', { allowAttributes: [ 'htmlListAttributes', 'htmlLiAttributes' ] } );
schema.extend( '$blockObject', { allowAttributes: [ 'htmlListAttributes', 'htmlLiAttributes' ] } );
schema.extend( '$container', { allowAttributes: [ 'htmlListAttributes', 'htmlLiAttributes' ] } );
conversion.for( 'upcast' ).add( dispatcher => {
dispatcher.on( 'element:ul', viewToModelListAttributeConverter( 'htmlListAttributes', dataFilter ), { priority: 'low' } );
dispatcher.on( 'element:ol', viewToModelListAttributeConverter( 'htmlListAttributes', dataFilter ), { priority: 'low' } );
dispatcher.on( 'element:li', viewToModelListAttributeConverter( 'htmlLiAttributes', dataFilter ), { priority: 'low' } );
} );
} );
// Make sure that all items in a single list (items at the same level & listType) have the same properties.
// Note: This is almost an exact copy from DocumentListPropertiesEditing.
documentListEditing.on( 'postFixer', ( evt, { listNodes, writer } ) => {
const previousNodesByIndent = []; // Last seen nodes of lower indented lists.
for ( const { node, previous } of listNodes ) {
// For the first list block there is nothing to compare with.
if ( !previous ) {
continue;
}
const nodeIndent = node.getAttribute( 'listIndent' );
const previousNodeIndent = previous.getAttribute( 'listIndent' );
let previousNodeInList = null; // It's like `previous` but has the same indent as current node.
// Let's find previous node for the same indent.
// We're going to need that when we get back to previous indent.
if ( nodeIndent > previousNodeIndent ) {
previousNodesByIndent[ previousNodeIndent ] = previous;
}
// Restore the one for given indent.
else if ( nodeIndent < previousNodeIndent ) {
previousNodeInList = previousNodesByIndent[ nodeIndent ];
previousNodesByIndent.length = nodeIndent;
}
// Same indent.
else {
previousNodeInList = previous;
}
// This is a first item of a nested list.
if ( !previousNodeInList ) {
continue;
}
if ( previousNodeInList.getAttribute( 'listType' ) == node.getAttribute( 'listType' ) ) {
const value = previousNodeInList.getAttribute( 'htmlListAttributes' );
if ( !isEqual( node.getAttribute( 'htmlListAttributes' ), value ) ) {
writer.setAttribute( 'htmlListAttributes', value, node );
evt.return = true;
}
}
if ( previousNodeInList.getAttribute( 'listItemId' ) == node.getAttribute( 'listItemId' ) ) {
const value = previousNodeInList.getAttribute( 'htmlLiAttributes' );
if ( !isEqual( node.getAttribute( 'htmlLiAttributes' ), value ) ) {
writer.setAttribute( 'htmlLiAttributes', value, node );
evt.return = true;
}
}
}
} );
}
/**
* @inheritDoc
*/
afterInit() {
const editor = this.editor;
if ( !editor.commands.get( 'indentList' ) ) {
return;
}
// Reset list attributes after indenting list items.
this.listenTo( editor.commands.get( 'indentList' ), 'afterExecute', ( evt, changedBlocks ) => {
editor.model.change( writer => {
for ( const node of changedBlocks ) {
// Just reset the attribute.
// If there is a previous indented list that this node should be merged into,
// the postfixer will unify all the attributes of both sub-lists.
writer.setAttribute( 'htmlListAttributes', {}, node );
}
} );
} );
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.