language
stringclasses
5 values
text
stringlengths
15
988k
JavaScript
class DockNode { constructor(d) { this.d = d; } /** @returns {DockContainer} */ get container() { return new DockContainer(grok_DockNode_Get_Container(this.d)); } /** Detaches this node from parent. */ detachFromParent() { return grok_DockNode_DetachFromParent(this.d); } /** Removes a child node. * @param {DockNode} childNode */ removeChild(childNode) { return grok_DockNode_RemoveChild(this.d, childNode); } }
JavaScript
class DockContainer { constructor(d) { this.d = d; } /** Container element. * @returns {HTMLDivElement} */ get containerElement() { return grok_DockContainer_Get_ContainerElement(this.d); } /** Destroys and detaches the container. */ destroy() { grok_DockContainer_Destroy(this.d); } /** Undocks a panel and converts it into a floating dialog window * It is assumed that only leaf nodes (panels) can be undocked */ float() { grok_DockContainer_Float(this.d); } /** Removes a dock container from the dock layout hierarcy * @returns {DockNode} - the node that was removed from the dock tree */ //remove() { return new DockNode(grok_DockContainer_Remove(this.d)); } }
JavaScript
class DockManager { constructor(d) { this.d = d; } get element() { return grok_DockManager_Get_Element(this.d); } get rootNode() { return new DockNode(grok_DockManager_Get_RootNode(this.d)); } /** * The document view is then central area of the dock layout hierarchy. * This is where more important panels are placed (e.g. the text editor in an IDE, * 3D view in a modeling package etc */ get documentContainer() { return new DockContainer(grok_DockManaget_Get_DocumentContainer(this.d)); } /** * Docks the element relative to the reference node. * @param {HTMLElement} element - Element to dock * @param {DockType} dockType - Dock type (left | right | top | bottom | fill). * @param {DockNode|null} refNode - reference node * @param {number} ratio - Ratio of the area to take (relative to the reference node). * @param {string=} title - Name of the resulting column. Default value is agg(colName). * @returns {DockNode} * */ dock(element, dockType = DG.DOCK_TYPE.LEFT, refNode = null, title = '', ratio = 0.5) { return new DockNode(grok_DockManager_Dock(this.d, refNode === null ? null : refNode.d, element, dockType, title, ratio)); } // /** // * Docks the element relative to the reference node. // * @param {DockType} dockType - Dock type (left | right | top | bottom | fill). // * @param {number} ratio - Ratio of the area to take (relative to the reference node). // * @param {string=} title - Name of the resulting column. Default value is agg(colName). // * @returns {DockNode} // * */ // dockDialog(element, dockType, refNode, title = '') { // return new DockNode(grok_DockManager_DockDialog(this.d, refNode == null ? null : refNode.d, element, dockType, title)); // } }
JavaScript
class LinearIcons extends Component { static dependencies() { return typeof module !== 'undefined' ? module.children : []; } render() { const keys = Object.keys(Icon); keys.sort(); return ( <Fragment> <p className={'mb-32 text-center'}> A collection of SVGs from the{' '} <a href={'https://linearicons.com/'} target={'_blank'} style={{ textDecoration: 'underline' }}> Linearicons </a>{' '} package </p> <div className={'mb--32'}> <div className={'row'}> {keys.map((item, i) => { const Ico = Icon[item]; return ( <div key={`icon-${i}`} className={'col-xs-4 col-sm-2 col-xl-1'}> <div className={'text-center'}> <Ico width={24} height={24} /> <div className={ 'text-center small mt-16 mb-32' }> {item} </div> </div> </div> ); })} </div> </div> </Fragment> ); } }
JavaScript
class Util { static uniqid (len = 7) { return Math.random().toString(35).substr(2, len) } // Helper function that extends one object with all the properies of other objects static extend (obj, ...src) { const dest = obj for (let i in src) { let copy = src[i] for (let prop in copy) { if (copy.hasOwnProperty(prop)) { dest[prop] = copy[prop] } } } return dest } // In order to stay true to the latest spec, RGB values must be clamped between 0 and 255. If we don't do this, weird things happen. static clampRGB (val) { if (val < 0) { return 0 } if (val > 255) { return 255 } return val } static copyAttributes (from, to, opts = {}) { for (let i in from.attributes) { let attr = from.attributes[i] if (opts.except && opts.except.indexOf(attr.nodeName) !== -1) { continue } to.setAttribute(attr.nodeName, attr.nodeValue) } } // Support for browsers that don't know Uint8Array (such as IE9) static dataArray (length = 0) { if (Uint8ClampedArray) { return new Uint8ClampedArray(length) } return new Array(length) } }
JavaScript
class List { /** * Construct a new List. Children in this list MUST have `id=` attributes which contain sequential numbers. * @param {string} idPrefix The prefix to remove from the `id=` attribute of children, if any. * @param {number} debounceTime The number of milliseconds to wait before invoking the callback on intersection change. * @param {function} callback The callback that will be invoked when the intersection has changed. It is called with * args for the startIndex, endIndex (inclusive). */ constructor(idPrefix, debounceTime, callback) { this.debounceTimeoutId = null; this.debounceTime = debounceTime; this.idPrefix = idPrefix; this.visibleIndexes = {}; // e.g "44" meaning index 44 this.intersectionObserver = new IntersectionObserver( (entries) => { entries.forEach((entry) => { let key = entry.target.id.substring(this.idPrefix.length); if (entry.isIntersecting) { this.visibleIndexes[key] = true; } else { delete this.visibleIndexes[key]; } }); // we will process the intersections after a short period of inactivity to not thrash the server clearTimeout(this.debounceTimeoutId); this.debounceTimeoutId = setTimeout(() => { let startIndex = -1; let endIndex = -1; Object.keys(this.visibleIndexes).forEach((roomIndex) => { // e.g "44" let i = Number(roomIndex); if (startIndex === -1 || i < startIndex) { startIndex = i; } if (endIndex === -1 || i > endIndex) { endIndex = i; } }); callback(startIndex, endIndex); }, this.debounceTime); }, { threshold: [0], } ); } resize(container, count, createElement) { let addCount = 0; let removeCount = 0; // ensure we have the right number of children, remove or add appropriately. while (container.childElementCount > count) { this.intersectionObserver.unobserve(container.lastChild); container.removeChild(container.lastChild); removeCount += 1; } for (let i = container.childElementCount; i < count; i++) { const cell = createElement(i); container.appendChild(cell); this.intersectionObserver.observe(cell); addCount += 1; } if (addCount > 0 || removeCount > 0) { console.log( "resize: added ", addCount, "nodes, removed", removeCount, "nodes" ); } } }
JavaScript
class App extends React.Component { render() { const { classes } = this.props; return ( <div> <AppBar position="static"> <Toolbar> <IconButton className={classes.menuButton} color="inherit" aria-label="Menu"> <MenuIcon /> </IconButton> <Typography variant="title" color="inherit" className={classes.flex}> Mikes Bikes </Typography> </Toolbar> </AppBar> <Switch> <Route exact path="/" component={PlacesListPage} /> <Route exact path="/places" component={PlacesListPage} /> <Route exact path="/places/:id" component={PlaceDetailsPage} /> <Route component={NotFoundPage} /> </Switch> </div> ); } }
JavaScript
class Singleton { constructor(clz) { this.instance = null; return { getInstance(opt) { if (!this.instance) { this.instance = new clz(opt); } return this.instance; } } } }
JavaScript
class TestConfig extends Config { /** */ constructor() { super({ configpath: testConfigPath }); } }
JavaScript
class ParserJsonTest extends JsonTest { packages = ['ams', 'base']; settings = {tags: 'none'}; name = ''; /** * @override */ constructor(json) { super(json); this.packages = this.json['packages'] || this.packages; this.name = this.json['name'] || this.name; this.settings = this.json['settings'] || this.settings; this.processSettings(); } processSettings() { // Processing regular expressions. for (let set of ['digits', 'letter', 'special']) { if (this.settings[set]) { this.settings[set] = RegExp(this.settings[set]); } } } document(options) { return mathjax.document('<html></html>', { InputJax: new TeX(options) }); } /** * @override */ runTest(name, tex, expected, rest) { test( name, () => { return mathjax.handleRetriesFor(function() { let options = {packages: this.packages}; Object.assign(options, this.settings); let root = this.document(options).convert(tex, {end: STATE.CONVERT}); let jv = new JsonMmlVisitor(); root.setTeXclass(null); return jv.visitTree(root); }.bind(this)).then(data => { expect(data).toEqual(expected); }); } ); } }
JavaScript
class ParserOutputTest extends ParserJsonTest { /** * @override */ document(options) { return mathjax.document('<html></html>', { InputJax: new TeX(options), OutputJax: new SVG() }); } }
JavaScript
class ParserMultirelTest extends ParserJsonTest { constructor(json) { // Just some things bogus attributes for testing. new CharacterMap('shadow', ParseMethods.mathchar0mo, { sim: ['\u223C', {something: 'nothing'}], simeq: ['\u2243', {something: 'nothing'}], asymp: ['\u224D', {something: 'else'}], cong: ['\u224D', {anything: 'nothing'}], lesssim: ['\u2272', {lspace: '1pt'}], gtrsim: ['\u2278', {rspace: '1pt'}] }); Configuration.create('multirel-test', {handler: {macro: ['shadow']}, priority: 4}); super(json); this.packages = ['base', 'ams', 'multirel-test']; } }
JavaScript
class ParserConfigMacrosTest extends ParserJsonTest { constructor(json) { super(json); this.packages = ['base', 'configmacros']; Object.assign(this.settings, {macros:{}}); } runTest(name, input, expected, {macro, control}) { Object.assign(this.settings.macros, macro); super.runTest(name, control, expected); super.runTest(name, input, expected); } }
JavaScript
class Container { render() { const Elem = styled.section` position: relative; top: 0; bottom: 0; `; const Item = Elem.extend` margin: 25px; `; const List = styled.ul.attrs({ padding: getPadding(), })` background-color: blue; color: white; `; return ( <main> <Elem /> <List> <Item /> <Item /> <Item /> </List> </main> ); } }
JavaScript
class MobileMenu { constructor(link) { this.link = link; this.button = this.link.querySelector('.hamburger'); } }
JavaScript
class SearchBar extends React.Component { //state: a plain javascript object that use for record and react to user events //when state changes, the component and its children components immediately re-renders //all js classes have a special function constructor and will call automatically when the class is created constructor(props) { // super(props); //each class-based component has its own state object //make tern equals to the input value everytime when input changes //initalizing state this.state = {term: 'Lu'}; //error: this is undefined in 'onInputChange' so add this line!!! //ES6 React.Component doesn't auto bind methods to itself. You need to bind them yourself in constructor. //solved at https://stackoverflow.com/questions/33973648/react-this-is-undefined-inside-a-component-function this.onInputChange = this.onInputChange.bind(this); } //must have render, it is a function render() { //change event of input element!! //input re-render when state changes return ( <div className="search-bar"> <input value = {this.state.term} onChange={this.onInputChange} /> </div> ); } //when input changes, trigger onInputChange(event) { const term = event.target.value; //to do: resarch on event object!! console.log(term); //update state, always use setState!! this.setState( {term: term} ); this.props.onSearchTermChange(term); } }
JavaScript
class GeoidGrid { /** * @param {Extent} extent The geographic extent of the geoid height grid data. * @param {THREE.Vector2} step The distance between two consecutive points of the geoid height grid. The * `x` value stands for the distance along the West-East direction, and the * `y` value stands for the distance along the South-North direction. * @param {function} getData A method that allows reading a value in the geoid height grid from its * vertical and horizontal indexes. The lower an index, the lower the * coordinate on the corresponding axis - 0 being the index of the minimal * coordinate of the gridded data on a given axis. In other words : * - `getData(0, 0)` must return the geoid height value at the SOUTH-WEST * corner of your data extent. * - `getData(0, j)` must return a geoid height on the southern limit of your * data extent. * - `getData(i, 0)` must return a geoid height on the western limit of your * data extent. * - if your gridded data has dimensions (rowNumber, colNumber), * `getData(rowNumber - 1, colNumber - 1)` must return the geoid height at * the NORTH-EAST corner of your data extent. */ constructor( extent, step, getData, ) { CRS.isGeographic(extent.crs); this.extent = extent; this.step = new THREE.Vector2(step.x, step.y || step.x); this.dimensions = this.extent.planarDimensions(); this.dataSize = new THREE.Vector2().addVectors(this.step, this.dimensions).divide(this.step).round(); this.getData = getData; } /** * Get the value of the geoid height at given geographic `{@link Coordinates}`. The geoid height value is * bi-linearly interpolated from the gridded data accessed by the `GeoidGrid` instance. * * @param {Coordinates} coordinates Geographic coordinates to get the geoid height value at. * * @returns {number} The geoid height value at the given `{@link Coordinates}`, bi-interpolated from the gridded * data accessed by the `GeoidGrid` instance. */ getHeightAtCoordinates(coordinates) { coordinates.as(this.extent.crs, coord); indexes.set( (this.dataSize.x - 1) * (coord.x - this.extent.west) / (this.dimensions.x), (this.dataSize.y - 1) * (coord.y - this.extent.south) / (this.dimensions.y), ); // TODO : add management for global GeoidGrid. if ( indexes.x < 0 || indexes.x >= this.dataSize.x - 1 || indexes.y < 0 || indexes.y >= this.dataSize.y - 1 ) { return 0; } return biLinearInterpolation(indexes, this.getData); } }
JavaScript
class SearchBar extends Component { constructor(props) { super(props); // Only used in the component to initilise the state this.state = { term: ''}; } // We can use this.state.term only to reference not for updating the value // So this.state.term = 'vaibhav' is a bad idea. // To render JSX its a react.component method // onChange is a react defined property. render() { return ( <div className="search-bar"> <input value={this.state.term} onChange={event => this.onInputChange(event.target.value)}/> {/* <button className="search-button" onClick={() => this.onInputChange()} type="button"><i className="fa fa-search"></i></button> */} </div> ) } // Method to check when ever the input text changes. onInputChange(term) { this.setState({term}); this.props.onSearchTermChange(term); } }
JavaScript
class TruckModal extends React.Component { constructor(props) { super(props); this.state = { modalStyles: REGULAR_STYLES, modalIsOpen: this.props.openTruckModal, truck: this.props.truck }; // Remember! This binding is necessary to make `this` work in the callback this.handleAfterOpenModal = this.handleAfterOpenModal.bind(this); } componentWillUnmount() { console.log("Unmounting truck modal"); } static getDerivedStateFromProps(nextProps, prevState) { // set modal open/close state (source of truth in parent component - app.js) let newState = {}; if (nextProps.truck !== prevState.truck) { newState.truck = nextProps.truck; } return { ...newState, modalIsOpen: nextProps.openTruckModal }; } componentDidUpdate() {} componentDidMount() {} handleAfterOpenModal() { // this.subtitle.style.color = 'yellow' } dispatchTruck() { /* method to make API request to transfer stock (PATCH request). */ // copy truck obj to work on, by converting to string representation, then back (use JSON obj representation) let truck = JSON.parse(JSON.stringify(this.props.truck)); if (truck.length > 0) { try { /* if transferring, delete all superfluous fields from the query to prevent auth issues */ truck.forEach((consignment, index) => { let cargo = consignment.cargo; truck[index] = { id: cargo.id, units_to_transfer: cargo.units_to_transfer }; }); // hit the api const apiRequest = processRequest({ stockRecord: { records: truck }, apiMode: this.props.apiOptions.PATCH_STOCK }); if (apiRequest) { apiRequest .then(response => { if (response) { if (response.status === 200) { this.props.emptyTruck(); // update the main table with the new values this.props.openTruckModalHandler({ actionCancelled: false, returnedRecords: response.data }); } } }) .catch(error => { console.log(`API error: ${error}`); this.props.setMessage({ message: "Transfer failed! The API rejected the request.", messageClass: "alert alert-danger" }); this.props.openTruckModalHandler({ actionCancelled: false }); }); } } catch (err) { // allow fall through to return false by default console.log(`API error: ${err}`); this.props.openTruckModalHandler({ actionCancelled: false }); } } } render() { if (this.props.stockRecord) { const dispatchButtonClasses = [ "btn", "btn", "btn-warning", "m-2", "table-btn" ]; if (!this.state.truck.length > 0) { dispatchButtonClasses.push("d-none"); } return ( <Modal isOpen={this.state.modalIsOpen} onAfterOpen={this.handleAfterOpenModal} onRequestClose={this.handleCloseModal} style={this.state.modalStyles} closeTimeoutMS={250} contentLabel="Truck Action" > <div className="container"> <div className="row"> <div className="col-sm"> <h2 ref={subtitle => (this.subtitle = subtitle)}>Truck</h2> </div> <TruckTable truck={this.state.truck} changeUnits={this.props.changeTruckUnits} /> <div className="col-sm modal-button-cell"> <button className={dispatchButtonClasses.join(" ")} onClick={() => { this.dispatchTruck(); }} > Request Truck Dispatch! </button> <button className={"btn btn btn-outline-light close-button"} onClick={() => { this.props.openTruckModalHandler({ actionCancelled: true }); }} > Cancel </button> </div> </div> </div> </Modal> ); } return null; } }
JavaScript
class HoveredNodeManager { constructor() { /** @public {?GraphNode} */ this.hoveredNode = null; /** @private {?GraphNode} */ this.realHoveredNode_ = null; /** @private {boolean} */ this.isDragging_ = false; } setDragging(isDragging) { this.isDragging_ = isDragging; if (!this.isDragging_) { // When the drag ends, update the hovered node. this.hoveredNode = this.realHoveredNode_; } } setHoveredNode(hoveredNode) { this.realHoveredNode_ = hoveredNode; if (!this.isDragging_) { // The hovered node can only be updated when not dragging. this.hoveredNode = this.realHoveredNode_; } } }
JavaScript
class HullColorManager { constructor() { this.colorIndex_ = 0; this.hullColors_ = new Map(); } /** * Gets the next color from the array of colors `HULL_COLORS`. When all the * colors of the array are used, starts from the beginning again. * @return {string} The next color to use. */ getNextColor_() { this.colorIndex_ = (this.colorIndex_ + 1) % HULL_COLORS.length; return HULL_COLORS[this.colorIndex_]; } /** * Gets the color associated with a given hull, generating a color for it if * there isn't one already. * @param {string} hullKey A key uniquely identifying the hull. * @return {string} The color associated with the hull's key. */ getColorForHull(hullKey) { if (!this.hullColors_.has(hullKey)) { this.hullColors_.set(hullKey, this.getNextColor_()); } return this.hullColors_.get(hullKey); } }
JavaScript
class GraphView { /** * Initializes some variables and performs one-time setup of the SVG canvas. * Currently just binds to the only 'svg' object, as things get more complex * we can maybe change this to bind to a given DOM element if necessary. */ constructor() { /** @private {number} */ this.edgeCurveOffset_ = EDGE_CURVE_OFFSET.CURVED; /** @private {boolean} */ this.colorEdgesOnlyOnHover_ = true; /** @private {string} */ this.graphEdgeColor_ = GraphEdgeColor.DEFAULT; /** @private {!HoveredNodeManager} */ this.hoveredNodeManager_ = new HoveredNodeManager(); /** @private {!HullColorManager} */ this.hullColorManager_ = new HullColorManager(); /** @private @type {?GetNodeGroupCallback} */ this.getNodeGroup_ = null; /** @private @type {?OnNodeClickedCallback} */ this.onNodeClicked_ = null; /** @private @type {?OnNodeDoubleClickedCallback} */ this.onNodeDoubleClicked_ = null; const svg = d3.select('#graph-svg'); const graphGroup = svg.append('g'); // Contains entire graph (for zoom/pan). this.svgDefs_ = svg.append('defs'); // Add an arrowhead def for every possible edge target color. for (const {target, targetDefId} of Object.values(EDGE_COLORS)) { addArrowMarkerDef(this.svgDefs_, targetDefId, target, 10, 6); } // Set up zoom and pan on the entire graph. svg.call(d3.zoom() .scaleExtent([0.25, 10]) .on('zoom', () => graphGroup.attr('transform', d3.event.transform), )) .on('dblclick.zoom', null); // The order of these groups decide the SVG paint order (since we append // sequentially), we want hulls below edges below nodes below labels. /** @private {*} */ this.hullGroup_ = graphGroup.append('g') .classed('graph-hull', true) .attr('stroke-width', 1) .attr('fill-opacity', 0.1); /** @private {*} */ this.edgeGroup_ = graphGroup.append('g') .classed('graph-edges', true) .attr('stroke-width', 1) .attr('fill', 'transparent'); /** @private {*} */ this.nodeGroup_ = graphGroup.append('g') .classed('graph-nodes', true); /** @private {*} */ this.hullLabelGroup_ = graphGroup.append('g') .classed('graph-hull-labels', true) .attr('pointer-events', 'none'); /** @private {*} */ this.labelGroup_ = graphGroup.append('g') .classed('graph-labels', true) .attr('pointer-events', 'none'); /** @private {!Array<!PhantomTextNode>} */ this.phantomTextNodes_ = []; // Using .style() instead of .attr() gets px-based measurements of // percentage-based widths and heights. const width = parseInt(svg.style('width'), 10); const height = parseInt(svg.style('height'), 10); const centeringStrengthY = 0.07; const centeringStrengthX = centeringStrengthY * (height / width); /** @private {*} */ this.simulation_ = d3.forceSimulation() .alphaMin(SIMULATION_SPEED_PARAMS.ALPHA_MIN) .force('chargeForce', d3.forceManyBody().strength(node => { if (node.isPhantomTextNode) { return -1100; } return -3000; })) .force('centerXForce', d3.forceX(width / 2).strength(node => { if (node.isPhantomTextNode) { return 0; } if (node.visualizationState.selectedByFilter) { return centeringStrengthX * 15; } if (node.visualizationState.outboundDepth <= 1) { return centeringStrengthX * 5; } return centeringStrengthY; })) .force('centerYForce', d3.forceY(height / 2).strength(node => { if (node.isPhantomTextNode) { return 0; } if (node.visualizationState.selectedByFilter) { return centeringStrengthY * 15; } if (node.visualizationState.outboundDepth <= 1) { return centeringStrengthY * 5; } return centeringStrengthY; })); /** @private {number} */ this.reheatTicks_ = countNumReheatTicks(); /** * @callback LinearScaler * @param {number} input The input value between [0, 1] inclusive. * @returns {number} The input scaled linearly to new bounds. */ /** @private {LinearScaler} */ this.velocityDecayScale_ = d3.scaleLinear() .domain([0, 1]) .range([SIMULATION_SPEED_PARAMS.VELOCITY_DECAY_MIN, SIMULATION_SPEED_PARAMS.VELOCITY_DECAY_MAX]); } /** * Binds the event when a node is clicked in the graph to a given callback. * @param {!OnNodeClickedCallback} onNodeClicked The callback to bind to. */ registerOnNodeClicked(onNodeClicked) { this.onNodeClicked_ = onNodeClicked; } /** * Binds the event when a node is double-clicked in the graph to a given * callback. * @param {!OnNodeDoubleClickedCallback} onNodeDoubleClicked The callback to * bind to. */ registerOnNodeDoubleClicked(onNodeDoubleClicked) { this.onNodeDoubleClicked_ = onNodeDoubleClicked; } /** * Assigns the node group accessor to a given function. * @param {!GetNodeGroupCallback} getNodeGroup The function to assign to. */ registerGetNodeGroup(getNodeGroup) { this.getNodeGroup_ = getNodeGroup; } /** * Computes the velocityDecay for our current progress in the reheat process. * * See https://github.com/d3/d3-force#simulation_velocityDecay. We animate new * nodes on the page by starting off with a high decay (slower nodes), easing * to a low decay (faster nodes), then easing back to a high decay at the end. * This makes the node animation seem more smooth and natural. * @param {number} currentTick The number of ticks passed in the reheat. * @return {number} The velocityDecay for the current point in the reheat. */ getEasedVelocityDecay(currentTick) { // The input to the ease function has to be in [0, 1] inclusive. Since // velocity is multiplied by (1 - decay) and we want speeds of // slow-fast-slow, the midpoint of the process should correspond to 0 and // the beginning and end to 1 (ie. the decay should look like \/). const normalizedCurrentTick = Math.abs( 1 - 2 * (currentTick / this.reheatTicks_)); const normalizedEaseTick = d3.easeQuadInOut(normalizedCurrentTick); // Since the ease returns a value in [0, 1] inclusive, we have to scale it // back to our desired velocityDecay range before returning. return (this.velocityDecayScale_(normalizedEaseTick)); } /** Synchronizes the path of all edges to their underlying data. */ syncEdgePaths() { this.edgeGroup_.selectAll('path') .attr('d', edge => { // To calculate the control point, consider the edge vector [dX, dY]: // * Flip over Y axis (since SVGs increase y downwards): [dX, -dY] // * Rotate 90 degrees clockwise: [-dY, -dX] // * Flip over Y again to get SVG coords: [-dY, dX] // * Scale and add to midpoint: [midX, midY] + scaleFactor * [-dY, dX] // where `scaleFactor` rescales [-dY, dX] to have the length of // `this.edgeCurveOffset_`. const deltaX = edge.target.x - edge.source.x; const deltaY = edge.target.y - edge.source.y; if (deltaX === 0 && deltaY === 0) { return null; // Do not draw paths for self-edges. } const midX = (edge.source.x + edge.target.x) / 2; const midY = (edge.source.y + edge.target.y) / 2; const [offsetX, offsetY] = resizeVector( deltaX, deltaY, this.edgeCurveOffset_); const controlPointX = midX - offsetY; const controlPointY = midY + offsetX; const path = d3.path(); path.moveTo(edge.source.x, edge.source.y); path.quadraticCurveTo( controlPointX, controlPointY, edge.target.x, edge.target.y); return path.toString(); }); } /** Synchronizes the color of all edges to their underlying data. */ syncEdgeColors() { const hoveredNode = this.hoveredNodeManager_.hoveredNode; const edgeTouchesHoveredNode = edge => edge.source === hoveredNode || edge.target === hoveredNode; const nodeTouchesHoveredNode = node => { return node === hoveredNode || hoveredNode.inbound.has(node) || hoveredNode.outbound.has(node); }; // Point the associated gradient in the direction of the line. this.svgDefs_.selectAll('linearGradient') .attr('x1', edge => edge.source.x) .attr('y1', edge => edge.source.y) .attr('x2', edge => edge.target.x) .attr('y2', edge => edge.target.y); this.edgeGroup_.selectAll('path') .attr('marker-end', edge => { if (edge.source === edge.target) { return null; } else if (!this.colorEdgesOnlyOnHover_ || edgeTouchesHoveredNode(edge)) { return `url(#${EDGE_COLORS[this.graphEdgeColor_].targetDefId})`; } return `url(#${EDGE_COLORS[GraphEdgeColor.DEFAULT].targetDefId})`; }) .attr('stroke', edge => { if (!this.colorEdgesOnlyOnHover_ || edgeTouchesHoveredNode(edge)) { return `url(#${edge.id})`; } return DEFAULT_EDGE_COLOR; }) .classed('non-hovered-edge', edge => { return this.colorEdgesOnlyOnHover_ && hoveredNode !== null && !edgeTouchesHoveredNode(edge); }); this.labelGroup_.selectAll('text') .classed('non-hovered-text', node => { return this.colorEdgesOnlyOnHover_ && hoveredNode !== null && !nodeTouchesHoveredNode(node); }); } /** Updates the colors of the edge gradients to match the selected color. */ syncEdgeGradients() { const {source, target} = EDGE_COLORS[this.graphEdgeColor_]; const gradientSelection = this.svgDefs_.selectAll('linearGradient'); gradientSelection.selectAll('stop').remove(); gradientSelection.append('stop') .attr('offset', '0%') .attr('stop-color', source); gradientSelection.append('stop') .attr('offset', '100%') .attr('stop-color', target); } /** * Groups nodes together by using the current group accessor function. * @param {!Array<!GraphNode>} nodes The nodes to group. * @return {!Map<string, !Array<!GraphNode>>} The map from group key to the * list of nodes included in that group. */ getNodeGroups(nodes) { const groups = new Map(); for (const node of nodes) { const groupKey = this.getNodeGroup_(node); // If the key is null, the node should not be grouped. if (groupKey !== null) { if (!groups.has(groupKey)) { groups.set(groupKey, [node]); } else { groups.get(groupKey).push(node); } } } return groups; } /** * Data representing a convex hull surrounding a certain group. * @typedef {Object} HullData * @property {string} key The unique key for the hull. * @property {string} color The color to display the hull as. * @property {!Array<number>} labelPosition An [x, y] point representing where * this hull's label should be rendered. * @property {!Array<!Array<number>>} points A list of [x, y] points making up * the hull. */ /** * Given the node grouping from `getNodeGroups`, constructs a list of convex * hulls, one per node group. * @param {!Map<string, !Array<!GraphNode>>} nodeGroups The node groupings. * @return {!Array<!HullData>} A list of convex hulls to display. */ getConvexHullData(nodeGroups) { const resultHulls = []; for (const [key, nodes] of nodeGroups.entries()) { const nodePolygon = getValidHullPolygon(nodes); const baseHull = d3.polygonHull(nodePolygon); // To expand the hull, we move each point a set distance away from the // hull's centroid (https://en.wikipedia.org/wiki/Centroid). const [centroidX, centroidY] = d3.polygonCentroid(baseHull); const expandedPolygon = baseHull.map(([nodeX, nodeY]) => { const deltaX = nodeX - centroidX; const deltaY = nodeY - centroidY; const [expandX, expandY] = resizeVector(deltaX, deltaY, HULL_EXPANSION); return [nodeX + expandX, nodeY + expandY]; }); // A decent heuristic is for the hull's label to be displayed above its // highest node. Recall that on an SVG, lower y-values are higher. let highestPoint = [0, Number.POSITIVE_INFINITY]; for (const point of expandedPolygon) { if (point[1] < highestPoint[1]) { highestPoint = point; } } resultHulls.push({ key, color: this.hullColorManager_.getColorForHull(key), labelPosition: highestPoint, points: expandedPolygon, }); } return resultHulls; } /** * Synchronizes the color and position of all convex hulls with their * underlying data. * @param {!Array<!HullData>} hullData A list of convex hulls to display for * the current data. */ updateHullData(hullData) { this.hullLabelGroup_.selectAll('text') .data(hullData, hull => hull.key) .join(enter => enter.append('text') .text(hull => hull.key) .attr('fill', hull => hull.color) .attr('dy', -8) .attr('x', hull => hull.labelPosition[0]) .attr('y', hull => hull.labelPosition[1]), update => update .attr('x', hull => hull.labelPosition[0]) .attr('y', hull => hull.labelPosition[1])); // The SVG path generator for the hull outlines. const getHullLine = d3.line().curve(d3.curveCatmullRomClosed.alpha(0.75)); this.hullGroup_.selectAll('path') .data(hullData, hull => hull.key) .join(enter => enter.append('path') .attr('d', hull => getHullLine(hull.points)) .attr('stroke', hull => hull.color) .attr('fill', hull => hull.color), update => update.attr('d', hull => getHullLine(hull.points))); } /** * Reheats the simulation, allowing all nodes to move according to the physics * simulation until they cool down again. * @param {boolean} shouldEase Whether the node movement should be eased. This * should not be used when dragging nodes, since the speed at the start of * the ease will be used all throughout the drag. */ reheatSimulation(shouldEase) { let tickNum = 0; // The simulation updates position variables in the data every tick, it's up // to us to update the visualization to match. const tickActions = () => { this.syncEdgePaths(); this.syncEdgeColors(); this.nodeGroup_.selectAll('circle') .attr('cx', node => node.x) .attr('cy', node => node.y); this.labelGroup_.selectAll('text') .attr('x', label => label.x) .attr('y', label => label.y); const hullData = this.getConvexHullData( this.getNodeGroups(this.nodeGroup_.selectAll('circle').data())); this.updateHullData(hullData); tickNum ++; if (shouldEase) { this.simulation_.velocityDecay(this.getEasedVelocityDecay(tickNum)); } // Reset phantom nodes to their fixed positions this.phantomTextNodes_.forEach(phantomNode => { phantomNode.x = phantomNode.refNode.x + phantomNode.dist; phantomNode.y = phantomNode.refNode.y; }); }; // If we don't ease, the default decay is sufficient for the entire reheat. const startingVelocityDecay = shouldEase ? this.getEasedVelocityDecay(0) : SIMULATION_SPEED_PARAMS.VELOCITY_DECAY_DEFAULT; this.simulation_ .on('tick', tickActions) .velocityDecay(startingVelocityDecay) .alpha(SIMULATION_SPEED_PARAMS.ALPHA_ON_REHEAT) .restart(); } /** * Updates the display settings for the visualization. * @param {!DisplaySettingsData} displaySettings The display config. */ updateDisplaySettings(displaySettings) { const { curveEdges, colorOnlyOnHover, graphEdgeColor, } = displaySettings; this.edgeCurveOffset_ = curveEdges ? EDGE_CURVE_OFFSET.CURVED : EDGE_CURVE_OFFSET.STRAIGHT; this.colorEdgesOnlyOnHover_ = colorOnlyOnHover; this.graphEdgeColor_ = graphEdgeColor; this.syncEdgeGradients(); this.syncEdgePaths(); this.syncEdgeColors(); } /** * Generates sparse integers subset in [0, n] that's roughly evenly * distributed. * @generator * @param {number} upperBound Exclusive upper bound on generated values. * @param {number} separation Ideal separation between generated values. * @yields {number} Generated integers. */ *generateSparseInts(upperBound, separation) { for (let i = separation; i < upperBound; i += separation) { yield i; } // Add an endpoint if the upper bound is far from the last value generated. if (upperBound % separation >= separation / 2) { yield upperBound - 1; } } /** * Updates the data source used for the visualization. * * @param {!D3GraphData} inputData The new data to use. */ updateGraphData(inputData) { const DIST_MULTIPLIER = 6.6; const {nodes: inputNodes, edges: inputEdges} = inputData; this.phantomTextNodes_ = []; // Generate the phantom text nodes, the list of nodes to be included in the // physics simulation at the place where node labels will be rendered. for (const node of inputNodes) { // A heuristic in the absence of exact label width: place phantom nodes // approximately every 10 characters away from the real node. for (const pos of this.generateSparseInts(node.displayName.length, 10)) { this.phantomTextNodes_.push({ isPhantomTextNode: true, refNode: node, dist: pos * DIST_MULTIPLIER, }); } } this.simulation_ .nodes([...inputNodes, ...this.phantomTextNodes_]) .force('links', d3.forceLink(inputEdges).id(edge => edge.id)); let nodesAddedOrRemoved = false; this.svgDefs_.selectAll('linearGradient') .data(inputEdges, edge => edge.id) .join(enter => enter.append('linearGradient') .attr('id', edge => edge.id) .attr('gradientUnits', 'userSpaceOnUse')); // TODO(yjlong): Determine if we ever want to render self-loops (will need // to be a loop instead of a straight line) and handle accordingly. this.edgeGroup_.selectAll('path') .data(inputEdges, edge => edge.id) .join(enter => enter.append('path')); this.nodeGroup_.selectAll('circle') .data(inputNodes, node => node.id) .join(enter => { if (!enter.empty()) { nodesAddedOrRemoved = true; } return enter.append('circle') .attr('r', 5) .attr('stroke', node => getNodeColor(node)) .on('dblclick', node => this.onNodeDoubleClicked_(node)) .on('mousedown', node => this.onNodeClicked_(node)) .on('mouseenter', node => { this.hoveredNodeManager_.setHoveredNode(node); this.syncEdgeColors(); }) .on('mouseleave', () => { this.hoveredNodeManager_.setHoveredNode(null); this.syncEdgeColors(); }) .call(d3.drag() .on('start', () => this.hoveredNodeManager_.setDragging(true)) .on('drag', (node, idx, nodes) => { this.reheatSimulation(/* shouldEase */ false); d3.select(nodes[idx]).classed('locked', true); // Fix the node's position after it has been dragged. node.fx = d3.event.x; node.fy = d3.event.y; }) .on('end', () => this.hoveredNodeManager_.setDragging(false))) .on('click', (node, idx, nodes) => { if (d3.event.defaultPrevented) { return; // Skip drag events. } const pageNode = d3.select(nodes[idx]); if (pageNode.classed('locked')) { node.fx = null; node.fy = null; this.reheatSimulation(/* shouldEase */ true); } else { node.fx = node.x; node.fy = node.y; } // TODO(yjlong): Change this so the style is tied to whether the // fx/fy are non-null instead of toggling it each time. pageNode.classed('locked', !pageNode.classed('locked')); }); }, update => update.attr('stroke', node => getNodeColor(node)), exit => { if (!exit.empty()) { nodesAddedOrRemoved = true; } // When a node is removed from the SVG, it should lose all // position-related data. return exit.each(node => { node.x = null; node.y = null; node.fx = null; node.fy = null; }).remove(); }) .attr('fill', node => { const nodeGroup = this.getNodeGroup_(node); if (nodeGroup === null) { return '#fff'; } return this.hullColorManager_.getColorForHull(nodeGroup); }); const nodeGroupings = this.getNodeGroups(inputNodes); this.updateHullData(this.getConvexHullData(nodeGroupings)); // Create a link force between every pair of nodes in a group, causing the // nodes to group together in the visualization. for (const [key, nodes] of nodeGroupings.entries()) { const links = []; // If performance is an issue, this can be replaced by picking a // representative node and connecting all other group members to it. This // has the downside of inconsistent node interactions: Dragging the // representative node pulls the entire group with it, while dragging // non-representative nodes doesn't affect the group as much. for (let sourceIndex = 0; sourceIndex < nodes.length; sourceIndex++) { for (let targetIndex = sourceIndex + 1; targetIndex < nodes.length; targetIndex++) { links.push({ source: nodes[sourceIndex], target: nodes[targetIndex], }); } } this.simulation_.force(key, d3.forceLink(links)); } this.labelGroup_.selectAll('text') .data(inputNodes, node => node.id) .join(enter => enter.append('text') .attr('dx', 12) .attr('dy', '.35em') .text(label => label.displayName)); // The graph should not be reheated on a no-op (eg. adding a visible node to // the filter which doesn't add/remove any new nodes). if (nodesAddedOrRemoved) { this.simulation_.stop(); this.reheatSimulation(/* shouldEase */ true); } } }
JavaScript
class CCommentState extends CppCommentState_1.CppCommentState { /** * Either delegate to a comment-handling state, or return a token with just a slash in it. * @param scanner A textual string to be tokenized. * @param tokenizer A tokenizer class that controls the process. * @returns The next token from the top of the stream. */ nextToken(scanner, tokenizer) { let firstSymbol = scanner.read(); let line = scanner.line(); let column = scanner.column(); if (firstSymbol != this.SLASH) { scanner.unread(); throw new Error("Incorrect usage of CCommentState."); } let secondSymbol = scanner.read(); if (secondSymbol == this.STAR) { return new Token_1.Token(TokenType_1.TokenType.Comment, "/*" + this.getMultiLineComment(scanner), line, column); } else { if (!utilities_1.CharValidator.isEof(secondSymbol)) { scanner.unread(); } if (!utilities_1.CharValidator.isEof(firstSymbol)) { scanner.unread(); } return tokenizer.symbolState.nextToken(scanner, tokenizer); } } }
JavaScript
class CollapseTreeNode { constructor(value, parent) { assert('value must have an array of children', isArray(get(value, 'children'))); set(this, 'value', value); if (parent) { // Changes to the value directly should properly update all computeds on this // node, but we need to manually propogate changes upwards to notify any other // watchers addObserver(this, 'length', () => Ember.propertyDidChange(parent, 'length')); } } /** Whether or not the node is leaf of the CollapseTree. A node is a leaf if the wrapped value's children have no children. If so, there is no need to create another level of nodes in the tree - true leaves of the passed in value tree don't require any custom logic, so we can index directly into the array of children in `objectAt`. @type boolean */ @computed('[email protected].[]') get isLeaf() { return !get(this, 'value.children').some(child => { let children = get(child, 'children'); return isArray(children) && get(children, 'length') > 0; }); } /** The children of this node, if they exist. Children can be other nodes, or spans (arrays) of leaf value-nodes. For instance: ``` A └── B ├── C └── D └── E ``` In this example, A would have the following children: ``` children = [ [B, C], Node(D) ]; ``` This allows us to do a binary search on the list of children without creating a node for each span, arrays simply represent x-children in a segment before a given node. @type Array<Node|Array<object>> */ @computed('value.children.[]', 'isLeaf') get children() { if (get(this, 'isLeaf')) { return null; } let valueChildren = get(this, 'value.children'); let children = []; let sliceStart = false; valueChildren.forEach((child, index) => { let grandchildren = get(child, 'children'); if (isArray(grandchildren) && get(grandchildren, 'length') > 0) { if (sliceStart !== false) { children.push(valueChildren.slice(sliceStart, index)); sliceStart = false; } children.push(new CollapseTreeNode(child, this)); } else if (sliceStart === false) { sliceStart = index; } }); if (sliceStart !== false) { children.push(valueChildren.slice(sliceStart)); } return children; } /** The length of the node. Branches in three directions: 1. If the node is collapsed, then the length of the node is 1, the node itself. This means that the parent node will only index into this child if it is trying to get exactly the child node, effectively hiding its children. 2. If the node is a leaf, then the length is the node itself plus the length of its value-children. 3. Otherwise, the length is the sum of the lengths of its children. */ @computed('collapsed', 'value.{collapsed,children.[]}', 'isLeaf') get length() { if (get(this, 'value.collapsed') === true || get(this, 'collapsed') === true) { return 1; } else if (get(this, 'isLeaf')) { return 1 + get(this, 'value.children.length'); } else { return 1 + get(this, 'children').reduce((sum, child) => sum + get(child, 'length'), 0); } } /** Calculates a list of the summation of offsets of children to run a binary search against. Given: ``` A ├── B │ ├── C │ └── D ├── E(c) │ ├── F │ └── G └── H │ ├── I │ └── J │ └── K └── L └── M ``` The offsetList for A would be: `[0, 3, 6, 10, 11]`. Each item in this list is the offset of the corresponding child, or the summation of the lengths of all children preceding it. It is effectively the starting index of that child. So, if I'm trying to find index 9 in A, which is item K (not counting A itself), then I'm going to want to traverse down H, which is the 3rd child. I run a binary search against these offsets, which are ordered, and find the closest starting index which is strictly less than 9, which is the 3rd index. I know I can then recurse down that node and I should eventually find the item I'm after. */ @computed('length', 'isLeaf') get offsetList() { if (get(this, 'isLeaf')) { return null; } let offset = 0; let offsetList = []; for (let child of get(this, 'children')) { offsetList.push(offset); offset += get(child, 'length'); } return offsetList; } /** Finds the object at the given index, where an index n is defined as the n-th item visited during a depth first traversal of the tree. To do this, we either 1. Return the current node at index 0 2. If the node is a leaf, return the value child at the corresponding index 3. Otherwise, find the correct child to walk down to and call `objectAt` on it with a normalized index `objectAt` also tracks the depth to pass back as meta information, something that is useful for displaying the tree as a list. `index` and `depth` are normalized as we traverse the tree, every time you "pass" a node you subtract it from the index for the next `objectAt` call, and you add 1 to depth for every `objectAt` call. @param {number} index - the index to find @param {Array<object>} parents - the parents of the current node in the traversal @return {{ value: object, parents: Array<object> }} */ objectAt(index, parents) { assert( 'index must be gte than 0 and less than the length of the node', index >= 0 && index < get(this, 'length') ); let value = get(this, 'value'); // The first index in a node is the node itself, since nodes are addressable if (index === 0) { return { value, parents, isCollapsed: get(this, 'collapsed'), toggleCollapse: this.toggleCollapse, }; } // Passed this node, remove it from the index and go one level deeper index = index - 1; parents.push(value); if (get(this, 'isLeaf')) { let value = objectAt(get(this, 'value.children'), index); return { value, parents, isCollapsed: false }; } let children = get(this, 'children'); let offsetList = get(this, 'offsetList'); let offsetIndex = closestLessThan(offsetList, index); index = index - offsetList[offsetIndex]; let child = children[offsetIndex]; if (Array.isArray(child)) { return { value: child[index], parents }; } return child.objectAt(index, parents); } toggleCollapse = () => { let value = get(this, 'value'); if (value.hasOwnProperty('collapsed')) { set(value, 'collapsed', !get(value, 'collapsed')); } else { set(this, 'collapsed', !get(this, 'collapsed')); } }; }
JavaScript
class ParkourConfig extends Component { /** * @constructor */ constructor() { super({ store, element: document.querySelector('#parkour-custom-tab'), eventName: 'parkourConfigChange' }); } /** * Renders the parkour parameters. */ render() { // TERRAIN CONFIG const terrainConfig = store.state.parkourConfig.terrain; let dict = window.lang_dict[store.state.language]['parkourConfig']; // Sections titles this.element.querySelector('#terrain-generation-title').innerHTML = dict['terrainGeneration']; this.element.querySelector('#general-parameters-title').innerText = dict['generalParameters']; this.element.querySelector('#creepers-title').innerText = dict['creepers']; // Terrain generation tabs buttons this.element.querySelector('#draw-tab-btn').innerText = dict['drawTabBtn']; this.element.querySelector('#proc-gen-tab-btn').innerText = dict['procGenTabBtn']; // Procedural Generation text this.element.querySelector('#proc-gen-text').innerHTML = dict['procGenText']; // Parameters labels this.element.querySelector('#smoothing-label').innerText = dict['smoothing']; this.element.querySelector('#water-level-label').innerText = dict['waterLevel']; this.element.querySelector('#creepers-width-label').innerText = dict['creepersWidth']; this.element.querySelector('#creepers-height-label').innerText = dict['creepersHeight']; this.element.querySelector('#creepers-spacing-label').innerText = dict['creepersSpacing']; //this.element.querySelector('#creepers-type-label').innerText = dict['creepersType']; this.element.querySelector('#rigid-otpion').innerText = dict['rigid']; this.element.querySelector('#swingable-option').innerText = dict['swingable']; // Sliders values this.element.querySelector("#dim1Slider").value = terrainConfig.dim1; this.element.querySelector("#dim2Slider").value = terrainConfig.dim2; this.element.querySelector("#dim3Slider").value = terrainConfig.dim3; this.element.querySelector("#smoothingSlider").value = terrainConfig.smoothing; this.element.querySelector("#waterSlider").value = terrainConfig.waterLevel; // Sliders text values this.element.querySelector("#dim1Value").innerText = terrainConfig.dim1; this.element.querySelector("#dim2Value").innerText = terrainConfig.dim2; this.element.querySelector("#dim3Value").innerText = terrainConfig.dim3; this.element.querySelector("#smoothingValue").innerText = terrainConfig.smoothing; this.element.querySelector("#waterValue").innerText = terrainConfig.waterLevel; // CREEPERS CONFIG const creepersConfig = store.state.parkourConfig.creepers; this.element.querySelector("#creepersWidthSlider").value = creepersConfig.width; this.element.querySelector("#creepersHeightSlider").value = creepersConfig.height; this.element.querySelector("#creepersSpacingSlider").value = creepersConfig.spacing; this.element.querySelector("#creepersWidthValue").innerText = creepersConfig.width; this.element.querySelector("#creepersHeightValue").innerText = creepersConfig.height; this.element.querySelector("#creepersSpacingValue").innerText = creepersConfig.spacing; this.element.querySelector("#creepersType").value = creepersConfig.type; } }
JavaScript
class FileRef { /** * @hideconstructor * @param input */ constructor(input) { Object.defineProperty(this, 'input', { value: input, writable: false }); Object.freeze(this); } /** * Creates a FileRef instance from a local file path. If no media type is provided, it will be inferred from the file * extension. * <p> * @param {!string} filePath - Local file path, either absolute path or relative to the working directory. * @param {string=} mediaType - Media type to identify the local file format. * @returns {FileRef} A FileRef instance. */ static createFromLocalFile(filePath, mediaType) { const fileInfo = new FileInfo(filePath, mediaType, inputTypes.localFile); return new FileRef(fileInfo); } /** * Creates a FileRef instance from a readable stream using the specified media type. * <p> * The stream is not read by this method but by consumers of file content i.e. the execute method of * an operation such as {@link CreatePDFOperation#execute} . * * @param {!stream.Readable} inputStream - Readable Stream representing the file. * @param {!string} mediaType - Media type to identify the file format. * @returns {FileRef} A FileRef instance. */ static createFromStream(inputStream, mediaType) { const fileInfo = new FileInfo(inputStream, mediaType, inputTypes.stream); return new FileRef(fileInfo); } /** * * Saves this file to the location specified by <code>destinationFilePath</code>. * If this FileRef instance refers to a temporary local file created by the SDK, that temporary file is deleted. * <p> * The directories mentioned in the specified argument are created if they do not exist. * * @param {!string} destinationFilePath - Local file path, either an absolute path or relative to the working directory. * @throws {Error} If the file already exists. * @throws {Error} If this FileRef instance does not represent an operation result. * @returns {Promise<void>} A `Promise` that resolves when the fileRef instance has been moved to the specified location. * */ saveAsFile(destinationFilePath) { return this.input.saveAsFile(destinationFilePath); } /** * Writes the contents of this file to <code>writableStream</code>. * If this FileRef instance refers to a temporary local file created by the SDK, that temporary file is deleted. * <br> * Note: This method does not close the <code>writableStream</code>. * * @param {!stream.Writable} writableStream - The destination writable stream. * @throws {Error} If this FileRef instance does not represent an operation result. * */ writeToStream(writableStream) { this.input.writeToStream(writableStream); } }
JavaScript
class Textile { constructor(options) { this.opts = options || {}; /** @property {Peer} peer - Manage Textile node information */ this.peer = new Peer(this.opts); /** @property {Schema} schemas - Manage Textile schema definitions */ this.schemas = new Schemas(this.opts); /** @property {Thread} threads - Manage Textile thread objects */ this.threads = new Threads(this.opts); /** @property {Block} blocks - Manage Textile block objects */ this.blocks = new Blocks(this.opts); /** @property {File} files - Manage existing files in a Textile node */ this.files = new Files(this.opts); } }
JavaScript
class ProcessJob extends J.IPCJob { /** class constructr * @param {string} name - name * @param {object} data - data */ constructor(name, data) { super(name, data); if (this.isFork) { this.log = require('../../../../api/utils/log.js')('job:push:process/' + process.pid + '/' + this.data.fork + '/' + this._id); } else { this.log = require('../../../../api/utils/log.js')('job:push:process/' + process.pid + '/-/' + this._id); } this.log.d('initializing ProcessJob with %j & %j', name, data); } /** gets cid * @returns {string} cid */ get cid() { return this.data.cid; } /** gets aid * @returns {string} aid */ get aid() { return this.data.aid; } /** gets data.field * @returns {object} data.field */ get field() { return this.data.field; } /** gets platform * @returns {string} data.field.substr(0, 1) */ get platform() { return this.data.field.substr(0, 1); } /** checks if is fork * @returns {boolean} true - if fork */ get isFork() { return !!this.data.fork; } /** prepares job * @param {object} manager - manager * @param {object} db - db connection * @returns {Promise} - resolved or rejected */ prepare(manager, db) { this.log.d('Loading credentials for %j', this.data); this.creds = new C.Credentials(this.data.cid); return new Promise((resolve, reject) => { this.creds.load(db).then(() => { let cid = typeof this.cid === 'string' ? this.cid : this.cid.toString(), aid = typeof this.aid === 'string' ? db.ObjectID(this.aid) : this.aid; db.collection('apps').findOne({_id: aid, $or: [{'plugins.push.i._id': cid}, {'plugins.push.a._id': cid}]}, (err, app) => { if (err) { return reject(err); } else if (!app) { return reject('No app or no such credentials'); } this.loader = new Loader(this.creds, this.field, db, app); resolve(); }); }, async err => { this.log.e('Error while preparing process job: %j', err.stack || err); let loader = new Loader({_id: this.cid}, this.field, db, {_id: this.aid}), counts = await loader.counts(this.now()), ids = Object.keys(counts).filter(k => k !== 'total'), error = err.message || err.code || JSON.stringify(err).substr(0, 30); if (counts.total) { this.log.e('Adding resourceErrors to notes %j', ids); await loader.updateNotes({_id: {$in: ids.map(db.ObjectID)}}, {$set: {error: error}, $push: {'result.resourceErrors': {$each: [{date: this.now(), field: this.field, error: error}], $slice: -5}}}); } }); }); } /** gets resource name * @returns {string} name */ resourceName() { return 'process:' + this.cid + ':' + this.field; } /** creates resource * @param {string} _id - id * @param {string} name - name * @param {object} db - db connection * @returns {object} Resource */ createResource(_id, name, db) { return new Resource(_id, name, {cid: this.cid, field: this.field}, db); } /** gets new retry policy * @returns {object} retry policy */ retryPolicy() { return new R.IPCRetryPolicy(3); } /** rescedule * @param {number} date - timestamp * @returns {Promise} - resolved if updated */ reschedule(date) { return this.replaceAfter(date); } /** fork * @returns {Promise} promise */ fork() { if (!this.maxFork) { this.maxFork = 0; } let data = Object.assign({}, this.data); data.fork = ++this.maxFork; return ProcessJob.insert(this.db(), {name: this.name, status: 0, data: data, next: Date.now()}); } /** gets current timestamp * @returns {number} timestamp */ now() { return Date.now(); } /** * @param {object} notes - notes * @param {object} msgs - messages * @returns {object} m */ compile(notes, msgs) { // let pm, pn, pp, po; return msgs.map(m => { let note = notes[m.n.toString()]; if (note) { m.m = note.compile(this.platform, m); // if (pn && pn === note && pp === m.p && po === m.o) { // m.m = pm; // } else { // pn = note; // pp = m.p; // po = m.o; // pm = m.m = note.compile(this.platform, m); // } } return m; }).filter(m => !!m.m); } /** finish * @param {object} err - error message or object */ async _finish(err) { if (err) { let counts = await this.loader.counts(Date.now() + SEND_AHEAD, this._id); if (counts.total) { this.log.w('Not reloaded jobbed counts %j, reloading', counts); let notes = await this.loader.notes(Object.keys(counts).filter(k => k !== 'total')); await this.handleResults(err, Object.values(notes)); await this.loader.reload(this._id); } else { counts = await this.loader.counts(Date.now() + SEND_AHEAD); if (counts.total) { this.log.w('Not reloaded not-jobbed counts %j, reloading', counts); let notes = await this.loader.notes(Object.keys(counts).filter(k => k !== 'total')); await this.handleResults(err, Object.values(notes)); } } } return await super._finish(err); } /** run * @param {object} db - db connection * @param {function} done - callback function */ async run(db, done) { let resourceError, affected; try { let count = await this.loader.count(this.now() + SEND_AHEAD), recheck = [], sending = new Set(); if (count === 0) { return done(); } else if (this.isFork && count < FORK_WHEN_MORE_THAN) { this.log.i('Won\'t run fork since there\'s less than forkable number of tokens'); return done(); } do { let date = this.now() + SEND_AHEAD, discarded = await this.loader.discard(date - 3600000); // some notifications are too late to send if (discarded.total) { Object.keys(discarded).filter(k => k !== 'total').forEach(mid => { let n = discarded[mid], l = `Discarding ${n} messages for ${mid}`; this.log.i(l); db.collection('messages').update({_id: db.ObjectID(mid)}, {$inc: {'result.processed': discarded[mid], 'result.errors': discarded[mid], 'result.errorCodes.skiptz': discarded[mid]}}, this.log.logdb(l)); }); } // load counts & messages let counts = await this.loader.counts(date), notes = await this.loader.notes(Object.keys(counts).filter(k => k !== 'total')); this.log.d('Counts: %j', counts); // check for aborted or deleted messages, delete notes if needed if (!this.isFork) { await Promise.all(Object.values(notes).filter(n => (n.result.status & (N.Status.Aborted | N.Status.Deleted)) > 0).map(note => { let count1 = counts[note._id.toString()]; this.log.w('Note %s has been aborted, clearing %d notifications', note._id, count1); return this.loader.abortNote(note._id, count1, this.now(), this.field, (note.result.status & N.Status.Aborted) ? 'Aborted' : 'Deleted'); })); } // load next batch let msgs = await this.loader.load(this._id, date, BATCH); // no messages left, break from the loop if (!msgs.length) { break; } // mark messages as being sent await Promise.all(Object.values(notes).map(json => this.loader.updateNote(json._id, {$addToSet: {jobs: this._id}, $bit: {'result.status': {or: N.Status.Sending}}}))); Object.values(notes).map(n => n._id.toString()).forEach(id => sending.add(id)); // send & remove notifications from the collection let statuses; try { let nts = this.compile(notes, msgs); if (nts.length !== msgs.length) { this.log.e('Some notifications didn\'t compile'); } this.log.i('Sending %d', nts.length); [statuses, resourceError] = await this.resource.send(nts); this.log.i('Send of %d returned %d statuses', nts.length, statuses.length); if (this.platform === N.Platform.IOS && statuses && statuses.length) { statuses.forEach(s => { if (s[2]) { try { s[2] = s[1] === -200 ? undefined : JSON.parse(s[2]).reason; } catch (e) { this.log.e('Error parsing error from APNS: %j, %j', s[2], e.stack || e); } } }); } } catch (e) { this.log.e('Caught resource error %s', e && e.message || JSON.stringify(e), e.stack); if (Array.isArray(e)) { statuses = e[0]; resourceError = e[1]; } else { resourceError = e; statuses = []; } } let acked = await this.loader.ack(statuses.map(s => s[0])); // smth bad happened if (acked !== statuses.length) { this.log.w('Acked number %d is not equal to number of statuses %d, resource error %j', acked, statuses.length, resourceError); } // array: <msg id>, <response code>[, <response error>][, <valid token>] // [-200,''] - Invalid token (unset) // [-200,'','something'] - Invalid token with valid token (replace old with new) // [-200,'something'] - Invalid token with error (unset + report error) // [200,'something'] - Some error with status 200 (don't report error) // [200] - Success let sent = {}, // {mid: 1} processed = {}, // {mid: 2} reset = {}, // {appid: [uid, value?]} msgincs = {}, // {appid: {mid: [uid1, uid2]}} errorsInc = {}; // {mid: {'result.errorCodes.400+BadToken': 123}} statuses.forEach((s, i) => { let msg = msgs[i], [_id, code, error, token] = s; if (msg._id !== _id) { msg = msgs.filter(m => m._id === _id)[0]; if (!msg) { this.log.e('Didn\'t find the message with id %j', _id); return; } } let uid = msg.u, mid = msg.n.toString(), note = notes[mid]; if (!processed[mid]) { processed[mid] = 0; } processed[mid]++; if (code === 200 || (code === -200 && token)) { if (!sent[mid]) { sent[mid] = 0; } sent[mid]++; note.apps.forEach(appid => { let aid = appid.toString(); if (!msgincs[aid]) { msgincs[aid] = {}; } if (!msgincs[aid][mid]) { msgincs[aid][mid] = []; } msgincs[aid][mid].push(uid); }); } if (code === -200) { note.apps.forEach(appid => { let aid = appid.toString(); if (!reset[aid]) { reset[aid] = []; } reset[aid].push([uid, token]); }); } if (error) { if (!errorsInc[mid]) { errorsInc[mid] = {}; } let key = `result.errorCodes.${this.creds.platform}${Math.abs(code)}` + (error ? '+' + error : ''); errorsInc[mid][key] = (errorsInc[mid][key] || 0) + 1; key = 'result.errors'; errorsInc[mid][key] = (errorsInc[mid][key] || 0) + 1; } }); // smth bad happened if (Object.values(processed).reduce((a, b) => a + b, 0) !== msgs.length) { this.log.w('Got %d statuses while %d is expected', Object.values(processed).reduce((a, b) => a + b, 0), msgs.length); } // update messages with processed / sent / errors let updates = Object.values(notes).map(note => { let mid = note._id.toString(); // no such message in statuses, but we marked it as being sent, unmark it if (!processed[mid]) { return this.loader.updateNote(mid, {$bit: {'result.status': {and: ~N.Status.Sending}}}); // return this.loader.updateNote(mid, {$bit: {'result.status': {and: ~N.Status.Sending, or: N.Status.Error}}}); } let update = {$inc: {'result.processed': processed[mid]}, $bit: {'result.status': {or: N.Status.Success}}}, errors = errorsInc[mid]; if (sent[mid]) { update.$inc['result.sent'] = sent[mid]; this.loader.recordSentEvent(note, sent[mid]); } this.log.i('Message %s total %d, processed %d, done in this batch %d', mid, note.result.total, note.result.processed, processed[mid]); if (note.result.total === note.result.processed + processed[mid]) { if (note.tx || note.auto) { update.$bit['result.status'].and = ~N.Status.Sending; update.$bit['result.status'].or = N.Status.Success; } else { update.$bit['result.status'].and = ~(N.Status.Sending | N.Status.Scheduled); update.$bit['result.status'].or = N.Status.Success | N.Status.Done; } if (recheck.indexOf(mid) !== -1) { recheck.splice(recheck.indexOf(mid), 1); } } else { recheck.push(mid); } if (errors) { if (!update.$inc) { update.$inc = {}; } Object.keys(errors).forEach(k => { update.$inc[k] = errors[k]; }); } return this.loader.updateNote(mid, update); }); // update app_users with new tokens, unset bad tokens & push sent messages let appids = Array.from(new Set(Object.keys(reset).concat(Object.keys(msgincs)))); updates = updates.concat(appids.map(appid => { let unsets = reset[appid] ? reset[appid].filter(arr => !arr[1]).map(arr => arr[0]) : [], resets = reset[appid] ? reset[appid].filter(arr => !!arr[1]) : [], msginc = msgincs[appid]; return Promise.all([ unsets.length ? this.loader.unsetTokens(unsets) : Promise.resolve(), resets.length ? Promise.all(resets.map(arr => this.loader.resetToken(arr[0], arr[1]))) : Promise.resolve(), msginc ? Promise.all(Object.keys(msginc).map(mid => this.loader.pushNote(mid, msginc[mid], this.now()))) : Promise.resolve() ]); })); // wait for all updates to apply await Promise.all(updates); if (resourceError) { await this.loader.reload(this._id); this.log.e('Stopping job %s execution because of resource error %s %j', this._id, resourceError && resourceError.message || JSON.stringify(resourceError), resourceError); let left = msgs.filter(msg => statuses.filter(st => st[0] === msg._id).length === 0); affected = Object.values(notes).filter(note => { let id = note._id.toString(); for (var i = left.length - 1; i >= 0; i--) { let msg = left[i]; if (msg.n.toString() === id) { return true; } } }); this.log.e('Following notifications affected: %j', affected.map(n => n._id.toString())); break; } // get next count count = await this.loader.count(this.now()); // fork if parallel processing needed if (!this.maxFork && !resourceError && count > FORK_WHEN_MORE_THAN) { for (let i = 0; i < Math.min(Math.floor(count / FORK_WHEN_MORE_THAN), FORK_MAX); i++) { this.log.i('Forking %d since %d > %d', i, count, FORK_WHEN_MORE_THAN); await this.fork(); } } } while (count); // unset sending flag if message doesn't have any jobs running await Promise.all([...sending].map(id => new Promise((resolve, reject) => { this.loader.updateNote(id, {$pull: {jobs: this._id}}).then(() => { db.collection('messages').findAndModify({_id: db.ObjectID(id), jobs: {$size: 0}}, {}, {$bit: {'result.status': {and: ~N.Status.Sending}}}, {new: true}, (err, doc) => { if (err) { reject(err); } else if (!doc || !doc.ok || !doc.value) { this.log.i('Message %s is still being sent', id); } else { let note = doc.value; if (!note.jobs || !note.jobs.length) { this.log.i('Pulled job %s, paused message %s', this._id, id); } } resolve(); }); }, err => { this.log.w('Error when pulling job from message array: %j', err); resolve(); }); }))); // for forked jobs it's possible that they update notifiations simultaniously and don't mark them as done if (recheck.length) { await new Promise(resolve => setTimeout(resolve, 10000)); let notes = await this.loader.notes(recheck); await Promise.all(Object.values(notes).map(note => { if (note.result.total === note.result.processed) { let update = {$bit: {'result.status': {}}}; if (note.tx || note.auto) { update.$bit['result.status'].and = ~N.Status.Sending; update.$bit['result.status'].or = N.Status.Success; } else { update.$bit['result.status'].and = ~(N.Status.Sending | N.Status.Scheduled); update.$bit['result.status'].or = N.Status.Success | N.Status.Done; } return this.loader.updateNote(note._id, update); } else { return Promise.resolve(); } })); } await this.handleResults(resourceError, affected || []); // once out of while loop, we're done done(resourceError); } catch (e) { this.log.e('Error when running job: %s / %j / %j', e.message || e.code, e, e.stack); try { await this.loader.reload(this._id); } catch (err) { this.log.e('Error when reloading for %s: %j', this._id, err); } done(e); } } /** result handling * @param {object} resourceError - error object or string * @param {array} affected - list of affected * @returns {boolean} true or false */ async handleResults(resourceError, affected) { // in case main job ends with resource error, record it in all messages affected // when too much same errors gathered in messages within retry period of 30 minutes, don't reschedule this process job let skip = false, error = resourceError ? resourceError.code || resourceError.message || (typeof resourceError === 'string' && resourceError) || JSON.stringify(resourceError) : undefined, date = this.now(), max = 0; if (this.isFork) { return false; } this.log.d('Handling results of %s: error %j, %d affected', this.id, resourceError, affected.length); if (affected && affected.length) { await Promise.all(affected.map(note => this.loader.updateNote(note._id, { $bit: {'result.status': {or: N.Status.Error}}, $push: {'result.resourceErrors': {$each: [{date: date, field: this.field, error: error}], $slice: -5}} // $addToSet: {'result.resourceErrors': {date: date, field: this.field, error: error}} }).then(() => { let same = (note.result.resourceErrors || []).filter(r => r.field === this.field && r.error === error), recent = same.filter(r => (this.now() - r.date) < 30 * 60000); if (recent.length) { max = Math.max(max, Math.max(...recent.map(r => this.now() - r.date))); } if (recent.length >= 2) { skip = note._id; } }, err => { this.log.e('Error while updating note %s with resourceError %s: %j', note._id, error, err); }))); } if (skip) { this.log.w('Won\'t reschedule %s since resourceError repeated 3 times within 30 minutes for %s', this._id, skip); let counts = await this.loader.counts(), ids = Object.keys(counts).filter(n => n !== 'total'); if (counts.total) { this.log.w('Aborting all notifications from %s collection: %j', this.loader.collectionName, ids); await Promise.all(ids.map(id => this.loader.abortNote(id, counts[id], date, this.field, error))); // await this.loader.clear(); } } else { // reschedule job if needed with exponential backoff: // first time it's rescheduled for 1 minute later, then for 3 minutes later, then 9, totalling 13 minutes // when message is rescheduled from dashboard, this logic can result in big delays between attempts, but no more than 90 minutes let next = resourceError ? this.now() + (max ? max * 3 : 1 * 60000) : await this.loader.next(); if (next) { this.log.i('Rescheduling %s to %d', this.cid, next); if (resourceError && affected && affected.length) { this.log.i('Resetting nextbatch of %j to %d', affected.map(n => n._id), next); let q = { $and: [ {_id: {$in: affected.map(n => n._id)}}, { $or: [ {'result.nextbatch': {$exists: false}}, {'result.nextbatch': {$eq: null}}, {'result.nextbatch': {$lt: next}} ] } ] }; this.loader.updateNotes(q, {$set: {'result.nextbatch': next}}).catch(this.log.e.bind(this.log, 'Error while updating note nextbatch: %j')); } await this.reschedule(next); return true; } } } }
JavaScript
class Todos extends Component { render() { // return this.props.daily.map((daily)=>( // <TodoItem daily={daily} markComplete = {this.props.markComplete} delTodo={this.props.delTodo}/> // )) if (this.props.loc === '/today') { return (this.props.daily.map((daily) => ( <TodoItem loc={this.props.loc} daily={daily} markComplete={this.props.markComplete} delTodo={this.props.delTodo} /> )) ) } else if (this.props.loc === '/week') { return this.props.weekly.map((weekly) => ( <TodoItem loc={this.props.loc} weekly={weekly} markComplete={this.props.markComplete} delTodo={this.props.delTodo} /> )) } else { return this.props.monthly.map((monthly) => ( <TodoItem loc={this.props.loc} monthly={monthly} markComplete={this.props.markComplete} delTodo={this.props.delTodo} /> )) } } }
JavaScript
class MyBCABus { constructor() { this.firstRender = true; this.towns = {}; this.inputElement = document.querySelector('.town__search'); this.favoriteContainer = document.querySelector('.favorite__container'); this.townContainer = document.querySelector('.town__container'); this._handleInput = this._handleInput.bind(this); this._poll(); } /** @returns {Object} town element */ get favorite() { return this.favoriteElement; } set favorite(element) { if (this.favoriteElement) { this.favoriteContainer.removeChild(this.favoriteElement); this.townContainer.insertAdjacentElement('beforeend', this.favoriteElement); } this.favoriteElement === element ? this.favoriteElement = void 0 : this.favoriteContainer.insertAdjacentElement('beforeend', this.favoriteElement = element); if ('Storage' in window) localStorage.setItem('favorite', void(!this.favoriteElement || this.favoriteElement.dataset.town)); } /** * @desc Pull data from the spreadsheet on each render. * @async * @protected */ async _poll() { const data = await fetch(SPREADSHEET_URL); const json = await data.json(); // Populate the state json.feed.entry.forEach(entry => { if ('gsx$_cre1l' in entry && 'gsx$townsbuslocation_2' in entry) this.towns[entry.gsx$townsbuslocation_2.$t] = entry.gsx$_cre1l.$t; if ('gsx$_cokwr' in entry && 'gsx$townsbuslocation' in entry) this.towns[entry.gsx$townsbuslocation.$t] = entry.gsx$_cokwr.$t; }); this._render(); this._poll(); } /** * @desc Render the application state. * @protected */ _render() { if (this.firstRender) { this.firstRender = false; this.townList = document.querySelectorAll('.town'); Object.keys(this.towns).forEach(this._createTown, this); } else { this.townList.forEach(townElement => { const town = townElement.dataset.town; const townLocationElement = townElement.children[1]; townLocationElement.textContent = this.towns[town]; }); this.inputElement.addEventListener('input', this._handleInput); } } /** * @description Handles search field value changes. * @protected */ _handleInput() { document.querySelectorAll('.town').forEach(town => town.style.display = 'flex'); // Cheaply hide irrelevant towns if (this.inputElement.value) document.querySelectorAll(`.town:not([data-town*="${this.inputElement.value}" i])`).forEach(town => town.style.display = 'none'); } /** * @description Creates town element on first render. * @param {string} town the town name * @protected */ _createTown(town) { const townElement = document.createElement('div'); townElement.classList.add('town'); townElement.dataset.town = town; townElement.insertAdjacentHTML('beforeend', ` <span class="town__name">${town}</span> <span class="town__loc">${this.towns[town]}</span> `); townElement.addEventListener('click', () => this.favorite = townElement); if ('Storage' in window && localStorage.getItem('favorite') === town) this.favorite = townElement; else this.townContainer.insertAdjacentElement('beforeend', townElement); } }
JavaScript
class GitHub { constructor() { this._client_id = config.github.client_id; this._client_secret = config.github.client_secret; this._access_url = 'https://github.com/login/oauth/access_token'; this._api_url = 'https://api.github.com'; this._code = null; this._token = null; this._login = null; this._id = null; this._email = null; } get data() { return { login: this.login, email: this.email, token: this.token, id: this.id, }; } get token() { return this._token; } get login() { return this._login; } get id() { return this._id; } get email() { return this._email; } header(customHeader) { let headers = { Accept: 'application/json', 'User-Agent': 'githubnize-api', }; if (this._token) { headers.Authorization = `Bearer ${this._token}`; } if (customHeader) { headers = { ...headers, ...customHeader, }; } return headers; } apiUrl(query) { return this._api_url + query; } setUser() { return fetch(this.apiUrl('/user'), { method: 'GET', headers: this.header(), }).then((response) => { // eslint-disable-line return response.json().then((json) => { this._login = json.login; this._id = json.id; this._email = json.email; return Promise.resolve(); }); }); } setCode(reqUrl) { const data = url.parse(reqUrl, true).query; this._code = data.code; } prepare(reqUrl) { this.setCode(reqUrl); return fetch(this._access_url, { method: 'POST', headers: this.header({ 'Content-Type': 'application/x-www-form-urlencoded' }), body: qs.stringify({ code: this._code, client_id: this._client_id, client_secret: this._client_secret, }), }).then((response) => { // eslint-disable-line return response.json().then((json) => { this._token = json.access_token; return this.setUser(); }); }); } }
JavaScript
class WordCluster { /** * Creates a new WordCluster instance * @param {Word[]} words - An array of the Words that this cluster will cover * @param {String} val - The raw text for this cluster's label */ constructor(words = [], val) { this.eventIds = []; this.val = val; this.words = words; this.links = []; // SVG elements: // 2 groups for left & right brace, containing: // a path appended to each of the two groups // a text label appended to the left group // The SVG groups are children of the main SVG document rather than the // Word's SVG group, since WordClusters technically exceed the bounds of // their individual Words. this.svgs = []; this.lines = []; this.svgText = null; // The main API instance for the visualisation this.main = null; // Main Config object for the parent instance; set by `.init()` this.config = null; // Cached SVG BBox values this._textBbox = null; words.forEach(word => word.clusters.push(this)); } /** * Any event IDs (essentially arbitrary labels) that this WordCluster is * associated with * @param id */ addEventId(id) { if (this.eventIds.indexOf(id) < 0) { this.eventIds.push(id); } } /** * Sets the text of this WordCluster, or returns this WordCluster's SVG text * element * @param val * @return {*} */ text(val) { if (val === undefined) { return this.svgText; } this.val = val; this.svgText.text(this.val); this._textBbox = this.svgText.bbox(); if (this.editingRect) { let bbox = this.svgText.bbox(); if (bbox.width > 0) { this.editingRect .width(bbox.width + 8) .height(bbox.height + 4) .x(bbox.x - 4) .y(bbox.y - 2); } else { this.editingRect.width(10) .x(this.svgText.x() - 5); } } } /** * Initialise this WordCluster against the main API instance. * Will be called once each by every Word within this cluster's coverage, * but we are really only interested in the first Word and the last Word * @param {Word} word - A Word within this cluster's coverage. * @param main */ init(word, main) { const idx = this.endpoints.indexOf(word); if (idx < 0) { // Not a critical word return; } this.main = main; this.config = main.config; // A critical Word. Prepare the corresponding SVG group. const mainSvg = main.svg; if (!this.svgs[idx]) { let svg = this.svgs[idx] = mainSvg.group() .addClass("tag-element") .addClass("word-cluster"); this.lines[idx] = svg.path() .addClass("tag-element"); // Add the text label to the left arm if (idx === 0) { this.svgText = svg.text(this.val).leading(1); this._textBbox = this.svgText.bbox(); this.svgText.node.oncontextmenu = (e) => { e.preventDefault(); mainSvg.fire("tag-right-click", {object: this, event: e}); }; this.svgText.click(() => mainSvg.fire("tag-edit", {object: this})); } } // Perform initial draw if both arms are ready if (this.lines[1] && this.endpoints[1].row) { this.draw(); } } /** * Draws in the SVG elements for this WordCluster * https://codepen.io/explosion/pen/YGApwd */ draw() { if (!this.lines[1] || !this.endpoints[1].row) { // The Word/WordClusters are not ready for drawing return; } /** @type {Word} */ const leftAnchor = this.endpoints[0]; /** @type {Word} */ const rightAnchor = this.endpoints[1]; const leftX = leftAnchor.x; const rightX = rightAnchor.x + rightAnchor.boxWidth; if (leftAnchor.row === rightAnchor.row) { // Draw in full curly brace between anchors const baseY = this.getBaseY(leftAnchor.row); const textY = baseY - this.config.wordTopTagPadding - this._textBbox.height; const centre = (leftX + rightX) / 2; this.svgText.move(centre, textY); this._textBbox = this.svgText.bbox(); // Each arm consists of two curves with relatively tight control // points (to preserve the "hook-iness" of the curve). // The following x-/y- values are all relative. const armWidth = (rightX - leftX) / 2; const curveWidth = armWidth / 2; const curveControl = Math.min(curveWidth, this.config.linkCurveWidth); const curveY = -this.config.wordTopTagPadding / 2; // Left arm this.lines[0].plot( "M" + [leftX, baseY] + "c" + [0, curveY, curveControl, curveY, curveWidth, curveY] + "c" + [curveWidth - curveControl, 0, curveWidth, 0, curveWidth, curveY] ); // Right arm this.lines[1].plot( "M" + [rightX, baseY] + "c" + [0, curveY, -curveControl, curveY, -curveWidth, curveY] + "c" + [-curveWidth + curveControl, 0, -curveWidth, 0, -curveWidth, curveY] ); } else { // Extend curly brace to end of first Row, draw intervening rows, // finish on last Row const textY = leftAnchor.row.baseline - leftAnchor.boxHeight - this._textBbox.height - this.config.wordTopTagPadding; let centre = (leftX + leftAnchor.row.rw) / 2; this.svgText.move(centre, textY); this._textBbox = this.svgText.bbox(); // Left arm const leftY = this.getBaseY(leftAnchor.row); const armWidth = (leftAnchor.row.rw - leftX) / 2; const curveWidth = armWidth / 2; const curveControl = Math.min(curveWidth, this.config.linkCurveWidth); const curveY = -this.config.wordTopTagPadding / 2; this.lines[0].plot( "M" + [leftX, leftY] + "c" + [0, curveY, curveControl, curveY, curveWidth, curveY] + "c" + [curveWidth - curveControl, 0, curveWidth, 0, curveWidth, curveY] ); // Right arm, first Row let d = ""; d += "M" + [leftAnchor.row.rw, leftY + curveY] + "c" + [-armWidth + curveControl, 0, -armWidth, 0, -armWidth, curveY]; // Intervening rows for (let i = leftAnchor.row.idx + 1; i < rightAnchor.row.idx; i++) { const thisRow = this.main.rowManager.rows[i]; const lineY = this.getBaseY(thisRow); d += "M" + [0, lineY + curveY] + "L" + [thisRow.rw, lineY + curveY]; } // Last Row const rightY = this.getBaseY(rightAnchor.row); d += "M" + [rightX, rightY] + "c" + [0, curveY, -curveControl, curveY, -rightX, curveY]; this.lines[1].plot(d); // // draw right side of brace extending to end of row and align text // let center = (-left + this.endpoints[0].row.rw) / 2 + 10; // this.x = center + lOffset; // this.svgText.x(center + lOffset); // // this.lines[0].plot("M" + lOffset // + ",33c0,-10," + [center, 0, center, -8] // + "c0,10," + [center, 0, center, 8] // ); // this.lines[1].plot("M" + rOffset // + ",33c0,-10," + [-right + 8, 0, -right + 8, -8] // + "c0,10," + [-right + 8, 0, -right + 8, 8] // ); } // propagate draw command to parent links this.links.forEach(l => l.draw(this)); } /** * Calculates what the absolute y-value for the base of this cluster's curly * brace should be if it were drawn on the given Row * @param row */ getBaseY(row) { // Use the taller of the endpoint's boxes as the base const wordHeight = Math.max( this.endpoints[0].boxHeight, this.endpoints[1].boxHeight ); return row.baseline - wordHeight; } remove() { this.svgs.forEach(svg => svg.remove()); this.words.forEach(word => { let i = word.clusters.indexOf(this); if (i > -1) { word.clusters.splice(i, 1); } }); } listenForEdit() { this.isEditing = true; let bbox = this.svgText.bbox(); this.svgs[0] .addClass("tag-element") .addClass("editing"); this.editingRect = this.svgs[0].rect(bbox.width + 8, bbox.height + 4) .x(bbox.x - 4) .y(bbox.y - 2) .rx(2) .ry(2) .back(); } stopEditing() { this.isEditing = false; this.svgs[0].removeClass("editing"); this.editingRect.remove(); this.editingRect = null; this.val = this.val.trim(); if (!this.val) { this.remove(); } } /** * Returns an array of the first and last Words covered by this WordCluster * @return {Word[]} */ get endpoints() { return [ this.words[0], this.words[this.words.length - 1] ]; } get row() { return this.endpoints[0].row; } /** * Returns the absolute y-position of the top of the WordCluster's label * (for positioning Links that point at it) * @return {Number} */ get absoluteY() { // The text label lives with the left arm of the curly brace const thisHeight = this.svgs[0].bbox().height; return this.endpoints[0].absoluteY - thisHeight; } /** * Returns the height of this WordCluster, from Row baseline to the top of * its label */ get fullHeight() { // The text label lives with the left arm of the curly brace const thisHeight = this.svgs[0].bbox().height; return this.endpoints[0].boxHeight + thisHeight; } get idx() { return this.endpoints[0].idx; } /** * Returns the x-position of the centre of this WordCluster's label * @return {*} */ get cx() { return this._textBbox.cx; } /** * Returns the width of the bounding box of the WordTag's SVG text element * @return {Number} */ get textWidth() { return this._textBbox.width; } // =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= // Debug functions /** * Draws the outline of this component's bounding box */ drawBbox() { const bbox = this.svgs[0].bbox(); this.svgs[0].polyline([ [bbox.x, bbox.y], [bbox.x2, bbox.y], [bbox.x2, bbox.y2], [bbox.x, bbox.y2], [bbox.x, bbox.y]]) .fill("none") .stroke({width: 1}); } /** * Draws the outline of the text element's bounding box */ drawTextBbox() { const bbox = this.svgText.bbox(); this.svgs[0].polyline([ [bbox.x, bbox.y], [bbox.x2, bbox.y], [bbox.x2, bbox.y2], [bbox.x, bbox.y2], [bbox.x, bbox.y]]) .fill("none") .stroke({width: 1}); } }
JavaScript
class Pacto { constructor(promiseCallback) { this.state = PENDING this.result = null this.listeners = [] const doResolve = realize(this, DONE) const doReject = realize(this, FAILED) const [resolve, reject] = functionGroup( (value) => handleValue(this, doResolve, doReject, value), (value) => doReject(value) ) promiseCallback(resolve, reject) } then(onFulfilled, onRejected) { return this._chainNewPromise(onFulfilled, onRejected) } catch(onRejected) { return this._chainNewPromise(null, onRejected) } _chainNewPromise(onFulfilled, onRejected) { const promise = new Pacto((resolve, reject) => { const perState = { [DONE]: [onFulfilled, resolve], [FAILED]: [onRejected, reject] } this._onFinished((result) => { const [next, finish] = perState[this.state] if (!isFn(next)) { return finish(this.result) } try { resolve(next(result)) } catch (e) { reject(e) } }) this._maybeFireCallbacks() }); return promise } _onFinished(callback) { this.listeners.push(callback) } // Hide it from outside access _maybeFireCallbacks() { if (this.state !== PENDING) { config.async(() => { let nextCb; while ((nextCb = this.listeners.shift()) != null) { nextCb(this.result) } }) } } }
JavaScript
class App extends React.PureComponent { /** * Constructor for the class * * @param {array} props * @memberof App */ constructor(props) { super(props); this.state = { // CONFIGURATION accountId: null, apiserver: '', apikey: '', apikeyS: '***', appkeyS: '***', appkey: '', setupComplete: false, lastUpdate: '', selectedMenu: 0, loadingContent: true, writingSetup: false, fetchingData: false, hasErrorFetch: false, // DASHBOARDS dataDashboards: [], emptyData: false, // MONITORS monitorsTotal: 0, monitorsGraph: [ { name: 'Host', uv: 0, pv: 0 }, { name: 'Metric', uv: 0, pv: 0 }, { name: 'Anomaly', uv: 0, pv: 0 }, { name: 'Outlier', uv: 0, pv: 0 } ], monitorsData: [], // INFRASTRUCTURE infrastructureDataGraph: [], infraestructureList: [], totalActive: 0, total: 0, // LOGS logsData: { archives: [], pipelines: [], metrics: [], archivesStatus: 0, pipelinesStatus: 0, metricsStatus: 0 }, // Metrics metrics: [], fetchingMetrics: false, progressMetrics: 0, errorMetric: false, historyUpdateMetric: null, // SYNTHETICS testTotal: 0, testList: [], // LogsDashport logs: [], completed: 0, deleteSetup: false, datadogService: null }; } /** * Method called when the component was mounted * * @memberof App */ componentWillMount() { this.setState({ loadingContent: true }); this.loadAccount(); } /** * Method that changes the selected option in menu * * @param {number} value * @memberof App */ handleChangeMenu = value => { const { fetchingData, deleteSetup } = this.state; if (fetchingData) { Toast.showToast({ title: 'WAIT..', description: 'Please wait until the search is over', type: Toast.TYPE.NORMAL }); } else if (deleteSetup) { Toast.showToast({ title: 'WAIT..', description: 'Please wait delete data', type: Toast.TYPE.NORMAL }); } else { this.setState({ selectedMenu: value }); } }; /** * Method that change progress when fetching metrics is active * * @memberof App */ updateProgressMetrics = value => { value = parseInt(value); this.setState({ progressMetrics: value }); }; /** * Method that change the selected menu from other component * * @param {number} value * @memberof App */ ChangeMenuExternal = value => { this.setState({ selectedMenu: value }); }; /** * Method that instance datadog service for fetch metrics * * @param {*} keyApi * @param {*} keyApp * @returns * @memberof App */ createDatadogServiceInstance(keyApi, keyApp, region) { const datadogClient = new DatadogClient( keyApi, keyApp, region, this.reportLogFetch ); return new DatadogService(datadogClient); } /** * Method that load from NerdStorage the information from account * * @memberof App */ async loadAccount() { const accountId = await loadAccountId(); this.setState({ accountId }); const dataSetup = await readNerdStorage( accountId, 'setup', 'datadog', this.reportLogFetch ); if (dataSetup) { let retrys = 0; let keyApi = null; let keyApp = null; const keysName = ['apikey', 'appkey']; while (retrys !== 5) { if (!keyApi) keyApi = await readSingleSecretKey(keysName[0]); if (!keyApp) keyApp = await readSingleSecretKey(keysName[1]); if (keyApi && keyApp) { retrys = 5; } else { retrys += 1; } } if (keyApi && keyApp) { const datadogService = this.createDatadogServiceInstance( keyApi, keyApp, dataSetup.apiserver ); this.setState({ setupComplete: true, apikey: keyApi, apikeyS: dataSetup.apikeyS, appkey: keyApp, appkeyS: dataSetup.appkeyS, apiserver: dataSetup.apiserver, datadogService: datadogService }); const dateFetch = await readNerdStorage( accountId, 'ddFetch', 'dateFetch', this.reportLogFetch ); await this.loadViewData(); if (dateFetch !== null) { this.setState({ lastUpdate: dateFetch.lastUpdate }); } else { this.setState({ lastUpdate: 'never' }); } } else { this.setState({ selectedMenu: 0 }); } } this.setState({ loadingContent: false }); } /** * Method that loads the data from NerdStorage * @memberof App */ async loadViewData() { const { accountId, fetchingData } = this.state; // DASHBOARDS try { const list = []; let emptyData = false; const sizeList = await readNerdStorageOnlyCollection( accountId, 'dashboards', this.reportLogFetch ); for (let i = 0; i < sizeList.length - 1; i++) { const page = await readNerdStorage( accountId, 'dashboards', `dashboards-${i}`, this.reportLogFetch ); if (page) { for (const iterator of page) { list.push(iterator); } } } const dashboardObj = await readNerdStorage( accountId, 'dashboards', `dashboards-obj`, this.reportLogFetch ); if (dashboardObj && dashboardObj.status === 'EMPTY') { emptyData = true; } if (fetchingData) { this.updateProgressFetch(5); } this.setState({ dataDashboards: list, emptyData }); } catch (err) { const response = { message: err.message, type: 'Error', event: `Recove dashboards data`, date: new Date().toLocaleString() }; this.reportLogFetch(response); } // ALERTS try { const data = await readNerdStorage( accountId, 'monitors', 'monitors-obj', this.reportLogFetch ); if (data) { const sizeMonitors = await readNerdStorageOnlyCollection( accountId, 'monitors-monitors', this.reportLogFetch ); const listMonitors = []; for (let i = 0; i < sizeMonitors.length; i++) { let page = []; page = await readNerdStorage( accountId, 'monitors-monitors', `monitors-${i}`, this.reportLogFetch ); for (const iterator of page) { listMonitors.push(iterator); } } const sizeTypes = await readNerdStorageOnlyCollection( accountId, 'monitors-types', this.reportLogFetch ); const listTypes = []; for (let i = 0; i < sizeTypes.length; i++) { let page = []; page = await readNerdStorage( accountId, 'monitors-types', `monitors-${i}`, this.reportLogFetch ); for (const iterator of page) { listTypes.push(iterator); } } data.data.type = listTypes; data.data.monitors = listMonitors; let total = 0; for (const iterator of data.data.type) { total += iterator.count; } data.data.total = total; const monitorsGraph = []; for (const monitor of data.data.monitors) { const index = monitorsGraph.findIndex( element => element.name === monitor.type ); if (index !== -1) { monitorsGraph[index].uv = monitorsGraph[index].uv + 1; } else { monitorsGraph.push({ name: monitor.type, pv: data.data.monitors.length, uv: 1 }); } } this.setState({ monitorsTotal: data.data.total, monitorsGraph: monitorsGraph, monitorsData: data.data.monitors }); } if (fetchingData) { this.updateProgressFetch(5); } } catch (err) { const response = { message: err.message, type: 'Error', event: `Recove alerts data`, date: new Date().toLocaleString() }; this.reportLogFetch(response); } // INFRASTRUCTURE try { const infraestructureObj = await readNerdStorage( accountId, 'infraestructure', 'infraestructure-obj', this.reportLogFetch ); if (infraestructureObj) { const sizeInfraestructure = await readNerdStorageOnlyCollection( accountId, 'infraestructure', this.reportLogFetch ); const hostList = []; for (let i = 0; i < sizeInfraestructure.length - 1; i++) { let page = []; page = await readNerdStorage( accountId, 'infraestructure', `infraestructure-${i}`, this.reportLogFetch ); for (const iterator of page) { hostList.push(iterator); } } const sizeTypes = await readNerdStorageOnlyCollection( accountId, 'infraestructure-types', this.reportLogFetch ); const types = []; for (let i = 0; i < sizeTypes.length; i++) { let page = []; page = await readNerdStorage( accountId, 'infraestructure-types', `infraestructure-types-${i}`, this.reportLogFetch ); for (const iterator of page) { types.push(iterator); } } const { total, totalActive } = infraestructureObj.data; const hostsData = []; for (const type of types) { hostsData.push({ name: type.platform, uv: Math.abs(type.count), pv: Math.abs(total - type.count) }); } this.setState({ infrastructureDataGraph: hostsData, infraestructureList: hostList, totalActive, total }); } if (fetchingData) { this.updateProgressFetch(5); } } catch (err) { const response = { message: err.message, type: 'Error', event: `Recove infraestructure data`, date: new Date().toLocaleString() }; this.reportLogFetch(response); } // LOGS try { const archivesStatus = await readNerdStorage( accountId, 'logs', 'logs-archives-obj', this.reportLogFetch ); const sizeArchives = await readNerdStorageOnlyCollection( accountId, 'logs-archives', this.reportLogFetch ); const archives = []; for (let i = 0; i < sizeArchives.length; i++) { let page = []; page = await readNerdStorage( accountId, 'logs-archives', `logs-archives-${i}`, this.reportLogFetch ); for (const iterator of page) { archives.push(iterator); } } // metric log const metricsStatus = await readNerdStorage( accountId, 'logs', 'logs-metrics-obj', this.reportLogFetch ); const sizeMetricLog = await readNerdStorageOnlyCollection( accountId, 'logs-metrics', this.reportLogFetch ); const metricsLogs = []; for (let i = 0; i < sizeMetricLog.length; i++) { let page = []; page = await readNerdStorage( accountId, 'logs-metrics', `logs-metrics-${i}`, this.reportLogFetch ); for (const iterator of page) { metricsLogs.push(iterator); } } // Pipelines const pipelinesStatus = await readNerdStorage( accountId, 'logs', 'logs-pipelines-obj', this.reportLogFetch ); const sizePipelines = await readNerdStorageOnlyCollection( accountId, 'logs-pipelines', this.reportLogFetch ); const pipelines = []; for (let i = 0; i < sizePipelines.length; i++) { let page = []; page = await readNerdStorage( accountId, 'logs-pipelines', `logs-pipelines-${i}`, this.reportLogFetch ); for (const iterator of page) { pipelines.push(iterator); } } this.setState({ logsData: { metrics: metricsLogs, archives: archives, pipelines: pipelines, archivesStatus, pipelinesStatus, metricsStatus } }); if (fetchingData) { this.updateProgressFetch(5); } } catch (err) { const response = { message: err.message, type: 'Error', event: `Recove logs data`, date: new Date().toLocaleString() }; this.reportLogFetch(response); } // METRICS try { const metrics = await readNerdStorage( accountId, 'metrics', 'metrics-obj', this.reportLogFetch ); if (metrics) { const sizeMetrics = await readNerdStorageOnlyCollection( accountId, 'metrics', this.reportLogFetch ); const listMetrics = []; for (let j = 0; j < sizeMetrics.length - 1; j++) { let page = []; page = await readNerdStorage( accountId, 'metrics', `metrics-${j}`, this.reportLogFetch ); for (const iterator of page) { listMetrics.push(iterator); } } let historyUpdateMetric = await readNerdStorage( accountId, 'metricsUpdate', 'metricsUpdate', this.reportLogFetch ); if ( historyUpdateMetric && Object.entries(historyUpdateMetric).length === 0 ) historyUpdateMetric = null; metrics.data = listMetrics; this.setState({ metrics: metrics.data, historyUpdateMetric }); } if (fetchingData) { this.updateProgressFetch(5); } } catch (err) { const response = { message: err.message, type: 'Error', event: `Recove metrics data`, date: new Date().toLocaleString() }; this.reportLogFetch(response); } // SYNTHETICS try { const synthetics = await readNerdStorage( accountId, 'synthetics', 'synthetics-obj', this.reportLogFetch ); if (synthetics) { const sizeList = await readNerdStorageOnlyCollection( accountId, 'synthetics-list', this.reportLogFetch ); const listSynthetics = []; for (let i = 0; i < sizeList.length; i++) { let page = []; page = await readNerdStorage( accountId, 'synthetics-list', `synthetics-${i}`, this.reportLogFetch ); for (const iterator of page) { listSynthetics.push(iterator); } } synthetics.list = listSynthetics; if (fetchingData) { this.updateProgressFetch(5); } this.setState({ testTotal: listSynthetics.length, testList: listSynthetics }); } } catch (err) { const response = { message: err.message, type: 'Error', event: `Recove synthetics data`, date: new Date().toLocaleString() }; this.reportLogFetch(response); } this.sendLogs(); } /** * Method that read nerdstorage * * @memberof App */ readNerdStorage = async (collection, documentId) => { let result = null; const { accountId } = this.state; await readNerdStorage( accountId, collection, documentId, this.reportLogFetch ).then(data => { result = data; }); return result; }; /** * Method that reads an document on the nerdStorage * @param {String} collection the document id to search * * @memberof App */ readNerdStorageOnlyCollection = async collection => { let result = null; const { accountId } = this.state; await readNerdStorageOnlyCollection( accountId, collection, this.reportLogFetch ).then(data => { result = data; }); return result; }; /** * Method that save data for parser file * * @memberof App */ finalDataWriter = async (collectionName, data) => { const { accountId, completed } = this.state; switch (collectionName) { case 'monitors': { const listMonitors = data.data.monitors; const listTypes = data.data.type; data.data.monitors = []; data.data.type = []; const monitorObj = data; await writeNerdStorage( accountId, collectionName, `${collectionName}-obj`, monitorObj, this.reportLogFetch ).catch(err => { throw err; }); const pagesMonitors = this.pagesOfData(listMonitors); for (const keyMonitor in pagesMonitors) { if (pagesMonitors[keyMonitor]) { await writeNerdStorage( accountId, `${collectionName}-monitors`, `${collectionName}-${keyMonitor}`, pagesMonitors[keyMonitor], this.reportLogFetch ).catch(err => { throw err; }); } } const pagesTypes = this.pagesOfData(listTypes); for (const keyTypes in pagesTypes) { if (pagesTypes[keyTypes]) { await writeNerdStorage( accountId, `${collectionName}-types`, `${collectionName}-${keyTypes}`, pagesTypes[keyTypes], this.reportLogFetch ).catch(err => { throw err; }); } } } break; case 'dashboards': { const listDashboards = data.data.list; data.data.list = []; const dashBoardObj = data.data; listDashboards.length > 0 ? (dashBoardObj.status = 'OK') : (dashBoardObj.status = 'EMPTY'); await writeNerdStorage( accountId, collectionName, `${collectionName}-obj`, dashBoardObj, this.reportLogFetch ).catch(err => { throw err; }); const pagesDashboards = this.pagesOfData(listDashboards); for (const keyDashboard in pagesDashboards) { if (pagesDashboards[keyDashboard]) { await writeNerdStorage( accountId, collectionName, `${collectionName}-${keyDashboard}`, pagesDashboards[keyDashboard], this.reportLogFetch ).catch(err => { throw err; }); } } } break; case 'infraestructure': { // guardar el objeto // guardar la lista const pagesHost = this.pagesOfData(data.data.hostList); for (const keyHost in pagesHost) { if (pagesHost[keyHost]) { await writeNerdStorage( accountId, collectionName, `${collectionName}-${keyHost}`, pagesHost[keyHost], this.reportLogFetch ).catch(err => { throw err; }); } } data.data.hostList = []; const pagesTypes = this.pagesOfData(data.data.types); for (const keyTypes in pagesTypes) { if (pagesTypes[keyTypes]) { await writeNerdStorage( accountId, `${collectionName}-types`, `${collectionName}-types-${keyTypes}`, pagesTypes[keyTypes], this.reportLogFetch ).catch(err => { throw err; }); } } data.data.types = []; await writeNerdStorage( accountId, collectionName, `${collectionName}-obj`, data, this.reportLogFetch ).catch(err => { throw err; }); } break; case 'logs': { await writeNerdStorage( accountId, collectionName, `${collectionName}-archives-obj`, data.data.archivesStatus, this.reportLogFetch ); const pagesArchives = this.pagesOfData(data.data.archives); for (const keyArchives in pagesArchives) { if (pagesArchives[keyArchives]) { await writeNerdStorage( accountId, `${collectionName}-archives`, `${collectionName}-archives-${keyArchives}`, pagesArchives[keyArchives], this.reportLogFetch ).catch(err => { throw err; }); } } await writeNerdStorage( accountId, collectionName, `${collectionName}-metrics-obj`, data.data.metricsStatus, this.reportLogFetch ).catch(err => { throw err; }); const pagesMetricsLogs = this.pagesOfData(data.data.metricsLogs); for (const keyMetricLog in pagesMetricsLogs) { if (pagesMetricsLogs[keyMetricLog]) { await writeNerdStorage( accountId, `${collectionName}-metrics`, `${collectionName}-metrics-${keyMetricLog}`, pagesMetricsLogs[keyMetricLog], this.reportLogFetch ).catch(err => { throw err; }); } } await writeNerdStorage( accountId, collectionName, `${collectionName}-pipelines-obj`, data.data.pipelinesStatus, this.reportLogFetch ).catch(err => { throw err; }); const pagesPipelines = this.pagesOfData(data.data.pipelines); for (const keyPipeline in pagesPipelines) { if (pagesPipelines[keyPipeline]) { await writeNerdStorage( accountId, `${collectionName}-pipelines`, `${collectionName}-pipelines-${keyPipeline}`, pagesPipelines[keyPipeline], this.reportLogFetch ).catch(err => { throw err; }); } } } break; case 'metrics': { const listMetrics = data.data; data.data = []; const metricObj = data; await writeNerdStorage( accountId, collectionName, `${collectionName}-obj`, metricObj, this.reportLogFetch ).catch(err => { throw err; }); const pagesMetrics = this.pagesOfData(listMetrics); for (const keyMetric in pagesMetrics) { if (pagesMetrics[keyMetric]) { await writeNerdStorage( accountId, collectionName, `${collectionName}-${keyMetric}`, pagesMetrics[keyMetric], this.reportLogFetch ).catch(err => { throw err; }); } } } break; case 'synthetics': { const list = data.data.test; // const listLocations = data.data.locations; data.data.list = []; // data.data.locations = []; const syntheticObj = data.data; await writeNerdStorage( accountId, collectionName, `${collectionName}-obj`, syntheticObj, this.reportLogFetch ).catch(err => { throw err; }); const pagesList = this.pagesOfData(list); for (const keyList in pagesList) { if (pagesList[keyList]) { await writeNerdStorage( accountId, `${collectionName}-list`, `${collectionName}-${keyList}`, pagesList[keyList], this.reportLogFetch ).catch(err => { throw err; }); } } } break; case 'accounts': { const listUsers = data.data.data; data.data.data = []; const accountObj = data; await writeNerdStorage( accountId, collectionName, `${collectionName}-obj`, accountObj, this.reportLogFetch ).catch(err => { throw err; }); const pagesAccounts = this.pagesOfData(listUsers); for (const keyAccount in pagesAccounts) { if (pagesAccounts[keyAccount]) { await writeNerdStorage( accountId, collectionName, `${collectionName}-${keyAccount}`, pagesAccounts[keyAccount], this.reportLogFetch ).catch(err => { throw err; }); } } } break; default: { const response = { message: 'Collection name not found', type: 'Error', event: `Write data final`, date: new Date().toLocaleString() }; this.reportLogFetch(response); } break; } if (completed + 5 <= 70) { this.updateProgressFetch(5); } }; /** * Method that saves a log * * @param {Object} response Response object, expected: message, event, type, date * @memberof App */ reportLogFetch = async response => { const { logs } = this.state; const arrayLogs = logs; arrayLogs.push({ log: response.message, event: response.event, type: response.type, date: response.date }); this.setState({ logs: arrayLogs }); }; /** * Method that fetch the data from Datadog * * @memberof App */ fetchData = async () => { this.setState({ fetchingData: true, completed: 0 }); let error = false; const data = { lastUpdate: '' }; const { accountId, apikey, apiserver, appkey, datadogService } = this.state; const DDConfig = { DD_API_KEY: apikey, DD_APP_KEY: appkey, DD_SITE: apiserver, DD_SUMMARY: 'DashportData' }; await DD.callApis( DDConfig, this.dataWriter, this.reportLogFetch, datadogService ) .then(res => { data.lastUpdate = res.toLocaleString(); const response = { message: 'Call apis finish great', type: 'Sucess', event: `Call apis`, date: new Date().toLocaleString() }; this.reportLogFetch(response); }) .catch(err => { error = true; const response = { message: err, type: 'Error', event: 'Call apis', date: new Date().toLocaleString() }; this.reportLogFetch(response); }); if (!error) { await DS.apiDataDigest( this.readNerdStorage, this.finalDataWriter, this.reportLogFetch, this.readNerdStorageOnlyCollection ) .then(() => { const response = { message: 'Call format finish', type: 'Sucess', event: `Format data`, date: new Date().toLocaleString() }; this.reportLogFetch(response); }) .catch(err => { error = true; const response = { message: err, type: 'Error', event: 'Format data', date: new Date().toLocaleString() }; this.reportLogFetch(response); }); } if (error) { Toast.showToast({ title: 'FAILED FETCH ELEMENTS', description: 'something went wrong please retry', type: Toast.TYPE.CRITICAL, sticky: true }); if (this.state.lastUpdate !== 'never') { this.setState({ fetchingData: false, hasErrorFetch: true }); } else { this.setState({ fetchingData: false, lastUpdate: 'never' }); } } else { let lastUpdate = null; await writeNerdStorageReturnData( accountId, 'ddFetch', 'dateFetch', data, this.reportLogFetch ) .then(({ data }) => { lastUpdate = data.nerdStorageWriteDocument.lastUpdate; }) .catch(err => { const response = { message: err, type: 'Error', event: 'Write dateFetch', date: new Date().toLocaleString() }; this.reportLogFetch(response); }); await this.sendLogs(); await this.loadViewData(); this.setState({ fetchingData: false, lastUpdate, completed: 100 }); } }; /** * Method that call function for fetching metrics * * @memberof App */ updateMetricsSection = async (from, timeRangeMetrics) => { this.setState({ historyUpdateMetric: timeRangeMetrics }); const { datadogService, accountId, historyUpdateMetric } = this.state; let error = false; this.setState({ fetchingMetrics: true }); const metrics = await datadogService .fetchMetrics(from, null, this.updateProgressMetrics) .catch(err => { error = true; const response = { message: err, type: 'Error', event: 'Format data', date: new Date().toLocaleString() }; this.reportLogFetch(response); }); if (error) { Toast.showToast({ title: 'FAILED FETCH UPDATE METRICS', description: 'something went wrong please retry', type: Toast.TYPE.CRITICAL, sticky: true }); this.setState({ fetchingMetrics: false, errorMetric: true, historyUpdateMetric }); } else { await this.dataWriter('Get All Active Metrics', metrics).catch(err => { const response = { message: err, type: 'Error', event: 'Format data', date: new Date().toLocaleString() }; this.reportLogFetch(response); error = true; }); if (error) { Toast.showToast({ title: 'FAILED FETCH UPDATE METRICS', description: 'something went wrong please retry', type: Toast.TYPE.CRITICAL, sticky: true }); this.setState({ fetchingMetrics: false, errorMetric: true, historyUpdateMetric }); } else { await this.finalDataWriter('metrics', { data: metrics }).catch(err => { const response = { message: err, type: 'Error', event: 'Format data', date: new Date().toLocaleString() }; this.reportLogFetch(response); error = true; }); if (error) { Toast.showToast({ title: 'FAILED FETCH UPDATE METRICS', description: 'something went wrong please retry', type: Toast.TYPE.CRITICAL, sticky: true }); this.setState({ fetchingMetrics: false, errorMetric: true, historyUpdateMetric }); } else { // Guardar update await writeNerdStorageReturnData( accountId, 'metricsUpdate', 'metricsUpdate', timeRangeMetrics, this.reportLogFetch ); this.setState({ metrics: metrics, fetchingMetrics: false, progressMetrics: 100, historyUpdateMetric: timeRangeMetrics }); } } } }; /** * Method for view keys save for the user * * @memberof App */ viewKeyAction = async keyInput => { const { apikeyS, appkeyS } = this.state; if (keyInput === 'apikey') { if (apikeyS && apikeyS[0] === '*') { const keyRecove = await readSingleSecretKey(keyInput); if (keyRecove) { this.setState({ apikeyS: keyRecove }); } } else { this.setState({ apikeyS: '*'.repeat(apikeyS.length) }); } } else if (keyInput === 'appkey') { if (appkeyS && appkeyS[0] === '*') { const keyRecove = await readSingleSecretKey(keyInput); if (keyRecove) { this.setState({ appkeyS: keyRecove }); } } else { this.setState({ appkeyS: '*'.repeat(appkeyS.length) }); } } }; /** * Method for send logs to channel external * * @memberof App */ async sendLogs() { const { logs, accountId } = this.state; if (logs.length !== 0) { await sendLogsSlack(logs, accountId); this.setState({ logs: [] }); } } /** * Method that saves the fetch data on the NerdStorage * * @param {String} documentName Document name * @param {Object} documentData Document data * @memberof App */ dataWriter = async (documentName, documentData) => { const { accountId, completed } = this.state; switch (documentName) { case 'Get Dashboards Manual': { const allDashboards = documentData.dashboard_lists; const pagesDashboards = this.pagesOfData(allDashboards); for (const keyAllDashboard in pagesDashboards) { if (pagesDashboards[keyAllDashboard]) { await writeNerdStorage( accountId, documentName, `${documentName}-${keyAllDashboard}`, pagesDashboards[keyAllDashboard], this.reportLogFetch ).catch(err => { throw err; }); } } } break; case 'Get all Dashboards': { const allDashboards = documentData.dashboards; const pagesDashboards = this.pagesOfData(allDashboards); for (const keyAllDashboard in pagesDashboards) { if (pagesDashboards[keyAllDashboard]) { await writeNerdStorage( accountId, documentName, `${documentName}-${keyAllDashboard}`, pagesDashboards[keyAllDashboard], this.reportLogFetch ).catch(err => { throw err; }); } } } break; case 'Get all archives': { const archiverList = documentData.data.data; const archiveObj = documentData.status; const pagesArchives = this.pagesOfData(archiverList); // guardo obj metrics await writeNerdStorage( accountId, documentName, `${documentName}-obj`, archiveObj, this.reportLogFetch ).catch(err => { throw err; }); for (const keyArchives in pagesArchives) { if (pagesArchives[keyArchives]) { await writeNerdStorage( accountId, documentName, `${documentName}-${keyArchives}`, pagesArchives[keyArchives], this.reportLogFetch ).catch(err => { throw err; }); } } } break; case 'Get all log based metrics': { const basedMetrics = documentData.data.data; const basedObj = documentData.status; const pagesLogsMetrics = this.pagesOfData(basedMetrics); // guardo obj metrics await writeNerdStorage( accountId, documentName, `${documentName}-obj`, basedObj, this.reportLogFetch ).catch(err => { throw err; }); for (const keyLogsMetrics in pagesLogsMetrics) { if (pagesLogsMetrics[keyLogsMetrics]) { await writeNerdStorage( accountId, documentName, `${documentName}-${keyLogsMetrics}`, pagesLogsMetrics[keyLogsMetrics], this.reportLogFetch ).catch(err => { throw err; }); } } } break; case 'Get a Dashboard': { const pagesDashboard = this.pagesOfData(documentData); for (const keyDashboard in pagesDashboard) { if (pagesDashboard[keyDashboard]) { await writeNerdStorage( accountId, documentName, `${documentName}-${keyDashboard}`, pagesDashboard[keyDashboard], this.reportLogFetch ).catch(err => { throw err; }); } } } break; case 'Get Items of a Dashboard List': { const pagesDashboardList = this.pagesOfData(documentData); for (const keyItemDashboard in pagesDashboardList) { if (pagesDashboardList[keyItemDashboard]) { await writeNerdStorage( accountId, documentName, `${documentName}-${keyItemDashboard}`, pagesDashboardList[keyItemDashboard], this.reportLogFetch ).catch(err => { throw err; }); } } } break; case 'Get all Dashboard Lists': { const dashboards_list = documentData.dashboard_lists; const pagesAllDashboardsList = this.pagesOfData(dashboards_list); for (const keyAllDashboardList in pagesAllDashboardsList) { if (pagesAllDashboardsList[keyAllDashboardList]) { await writeNerdStorage( accountId, documentName, `${documentName}-${keyAllDashboardList}`, pagesAllDashboardsList[keyAllDashboardList], this.reportLogFetch ).catch(err => { throw err; }); } } } break; case 'Get a Dashboard List': { const pagesDashboardsList = this.pagesOfData(documentData); for (const keyDashboardList in pagesDashboardsList) { if (pagesDashboardsList[keyDashboardList]) { await writeNerdStorage( accountId, documentName, `${documentName}-${keyDashboardList}`, pagesDashboardsList[keyDashboardList], this.reportLogFetch ).catch(err => { throw err; }); } } } break; case 'Get all embeddable graphs': { const pagesEmbeddable = this.pagesOfData(documentData); for (const keyEmbeddablet in pagesEmbeddable) { if (pagesEmbeddable[keyEmbeddablet]) { await writeNerdStorage( accountId, documentName, `${documentName}-${keyEmbeddablet}`, pagesEmbeddable[keyEmbeddablet], this.reportLogFetch ).catch(err => { throw err; }); } } } break; case 'Search hosts': { const hostList = documentData.host_list; documentData.host_list = []; const hostObj = documentData; const pagesHostList = this.pagesOfData(hostList); // guardo el host obj await writeNerdStorage( accountId, documentName, `${documentName}-obj`, hostObj, this.reportLogFetch ).catch(err => { throw err; }); // guardo la lista de host con el for for (const keyHostList in pagesHostList) { if (pagesHostList[keyHostList]) { await writeNerdStorage( accountId, documentName, `${documentName}-${keyHostList}`, pagesHostList[keyHostList], this.reportLogFetch ).catch(err => { throw err; }); } } } break; case 'Get all indexes': { const { indexes } = documentData; const pagesIndexes = this.pagesOfData(indexes); // Guardo con el for normal for (const keyIndexes in pagesIndexes) { if (pagesIndexes[keyIndexes]) { await writeNerdStorage( accountId, documentName, `${documentName}-${keyIndexes}`, pagesIndexes[keyIndexes], this.reportLogFetch ).catch(err => { throw err; }); } } } break; case 'Get indexes order': { const { index_names } = documentData; const pagesIndexesNames = this.pagesOfData(index_names); for (const keyIndexesNames in pagesIndexesNames) { if (pagesIndexesNames[keyIndexesNames]) { await writeNerdStorage( accountId, documentName, `${documentName}-${keyIndexesNames}`, pagesIndexesNames[keyIndexesNames], this.reportLogFetch ).catch(err => { throw err; }); } } } break; case 'Get Pipeline Order': { const { pipeline_ids } = documentData; const pagesPipeline = this.pagesOfData(pipeline_ids); for (const keyPipeLine in pagesPipeline) { if (pagesPipeline[keyPipeLine]) { await writeNerdStorage( accountId, documentName, `${documentName}-${keyPipeLine}`, pagesPipeline[keyPipeLine], this.reportLogFetch ).catch(err => { throw err; }); } } } break; case 'Get all Pipelines': { const pipelineList = documentData.data; documentData.data = []; const pipeObj = documentData.status; const pagesAllPipeline = this.pagesOfData(pipelineList); // guardo obj metrics await writeNerdStorage( accountId, documentName, `${documentName}-obj`, pipeObj, this.reportLogFetch ).catch(err => { throw err; }); for (const keyAllPipeLine in pagesAllPipeline) { if (pagesAllPipeline[keyAllPipeLine]) { await writeNerdStorage( accountId, documentName, `${documentName}-${keyAllPipeLine}`, pagesAllPipeline[keyAllPipeLine], this.reportLogFetch ).catch(err => { throw err; }); } } } break; case 'Monitors meta': { const countsTypeList = documentData.countsType; documentData.countsType = []; const monitorObj = documentData; const pagesCountsTypeList = this.pagesOfData(countsTypeList); // guardo obj metrics await writeNerdStorage( accountId, documentName, `${documentName}-obj`, monitorObj, this.reportLogFetch ).catch(err => { throw err; }); // guardo lista de metricas for (const keyMonitorMeta in pagesCountsTypeList) { if (pagesCountsTypeList[keyMonitorMeta]) { await writeNerdStorage( accountId, documentName, `${documentName}-${keyMonitorMeta}`, pagesCountsTypeList[keyMonitorMeta], this.reportLogFetch ).catch(err => { throw err; }); } } } break; case 'Monitor Search Pages': { const pagesMonitorsSearch = this.pagesOfData(documentData); for (const keyMonitorSearch in pagesMonitorsSearch) { if (pagesMonitorsSearch[keyMonitorSearch]) { await writeNerdStorage( accountId, documentName, `${documentName}-${keyMonitorSearch}`, pagesMonitorsSearch[keyMonitorSearch], this.reportLogFetch ).catch(err => { throw err; }); } } } break; case 'Get all tests': { const testList = documentData.tests; const pagesTest = this.pagesOfData(testList); for (const keyTest in pagesTest) { if (pagesTest[keyTest]) { await writeNerdStorage( accountId, documentName, `${documentName}-${keyTest}`, pagesTest[keyTest], this.reportLogFetch ).catch(err => { throw err; }); } } } break; case 'Get devices for browser checks': { const devicesList = documentData.devices; const pageDevices = this.pagesOfData(devicesList); for (const keyDevices in pageDevices) { if (pageDevices[keyDevices]) { await writeNerdStorage( accountId, documentName, `${documentName}-${keyDevices}`, pageDevices[keyDevices], this.reportLogFetch ).catch(err => { throw err; }); } } } break; case 'Get available locations': { const locationsList = documentData.locations; const pageLocations = this.pagesOfData(locationsList); for (const keyLocations in pageLocations) { if (pageLocations[keyLocations]) { await writeNerdStorage( accountId, documentName, `${documentName}-${keyLocations}`, pageLocations[keyLocations], this.reportLogFetch ).catch(err => { throw err; }); } } } break; case 'Get all users': { const dataList = documentData.data; const includedList = documentData.included; documentData.data = []; documentData.included = []; const allUserObj = documentData; const pagesData = this.pagesOfData(dataList); const pagesIncluded = this.pagesOfData(includedList); // Guardo el objeto await writeNerdStorage( accountId, documentName, `${documentName}-obj`, allUserObj, this.reportLogFetch ).catch(err => { throw err; }); // guardo la lista de pages data for (const keyData in pagesData) { if (pagesData[keyData]) { await writeNerdStorage( accountId, `${documentName}-data`, `${documentName}-${keyData}`, pagesData[keyData], this.reportLogFetch ).catch(err => { throw err; }); } } // guardo la lista de pages include for (const keyIncluded in pagesIncluded) { if (pagesIncluded[keyIncluded]) { await writeNerdStorage( accountId, `${documentName}-included`, `${documentName}-${keyIncluded}`, pagesIncluded[keyIncluded], this.reportLogFetch ).catch(err => { throw err; }); } } } break; case 'Monitor Group Search': { const listGroups = documentData.groups; documentData.groups = []; const monitorSearchObj = documentData; const pagesGroups = this.pagesOfData(listGroups); await writeNerdStorage( accountId, documentName, `${documentName}-obj`, monitorSearchObj, this.reportLogFetch ).catch(err => { throw err; }); // guardo la lista de pages include for (const keyIncluded in pagesGroups) { if (pagesGroups[keyIncluded]) { await writeNerdStorage( accountId, `${documentName}`, `${documentName}-${keyIncluded}`, pagesGroups[keyIncluded], this.reportLogFetch ).catch(err => { throw err; }); } } } break; case 'Get Tags': { const keysArr = Object.keys(documentData.tags); const valuesArr = Object.values(documentData.tags); const tags = []; for (const key in keysArr) { if (keysArr[key]) { tags.push({ tag: keysArr[key], data: valuesArr[key] }); } } const pagesTags = this.pagesOfData(tags); for (const keyTags in pagesTags) { if (pagesTags[keyTags]) { await writeNerdStorage( accountId, `${documentName}`, `${documentName}-${keyTags}`, pagesTags[keyTags], this.reportLogFetch ).catch(err => { throw err; }); } } } break; case 'Get All Active Metrics': { const metricsList = documentData.metrics; documentData.metrics = []; const metricObj = documentData; const pagesMetricsList = this.pagesOfData(metricsList); // guardo obj metrics await writeNerdStorage( accountId, documentName, `${documentName}-obj`, metricObj, this.reportLogFetch ).catch(err => { throw err; }); // guardo lista de metricas for (const keyMetrics in pagesMetricsList) { if (pagesMetricsList[keyMetrics]) { await writeNerdStorage( accountId, documentName, `${documentName}-${keyMetrics}`, pagesMetricsList[keyMetrics], this.reportLogFetch ).catch(err => { throw err; }); } } await writeNerdStorageReturnData( accountId, 'metricsUpdate', 'metricsUpdate', { value: '30 minutes', label: '30 minutes' }, this.reportLogFetch ); } break; default: // Guardo el get task tal cual // Guardo el Host totals tal cual await writeNerdStorage( accountId, documentName, `${documentName}-obj`, documentData, this.reportLogFetch ).catch(err => { throw err; }); break; } if (completed <= 50) { if (completed + 2 === 48) { this.updateProgressFetch(4); } else { this.updateProgressFetch(2); } } }; /** * Method that update progress of fetch principal * * @memberof App */ updateProgressFetch = value => { this.setState(prevState => ({ completed: prevState.completed + value })); }; pagesOfData = list => { const limit = 1000000; let page = []; const book = []; let pageTemporal = []; for (const key in list) { if (list[key]) { pageTemporal = [...page]; if (page) { pageTemporal.push(list[key]); if (JSON.stringify(pageTemporal).length >= limit) { if (page.length !== 0) { book.push(page); } page = []; page.push(list[key]); } else { page = pageTemporal; pageTemporal = []; } if (parseInt(key) === parseInt(list.length - 1)) { book.push(page); } } } } return book; }; /** * Method that validate the data and writes the form API into the datadog-setup document on NerdStorage * * @param {Object} values * @memberof App */ writeSetup = async values => { try { this.setState({ writingSetup: true }); const { accountId } = this.state; const { appkey, apikey } = values; let region = 'com'; let validKeys = await DD.validateKeys(apikey, appkey, 'com'); if (!validKeys.appkey && !validKeys.apikey) { validKeys = await DD.validateKeys(apikey, appkey, 'eu'); region = 'eu'; } const data = { apiserver: region, apikeyS: '*'.repeat(apikey.length), appkeyS: '*'.repeat(appkey.length) }; if (validKeys.apikey) { if (validKeys.appkey) { // guardar en el vault let saveApiKey = null; let saveAppKey = null; let retrys = 0; while (retrys !== 5) { if (!saveApiKey || saveApiKey.status !== 'SUCCESS') saveApiKey = await writeSecretKey('apikey', apikey); if (!saveAppKey || saveAppKey.status !== 'SUCCESS') saveAppKey = await writeSecretKey('appkey', appkey); if ( saveAppKey && saveAppKey.status === 'SUCCESS' && saveAppKey && saveAppKey.status === 'SUCCESS' ) { retrys = 5; } else { retrys++; } } if ( (saveApiKey && saveApiKey.status !== 'SUCCESS') || (saveAppKey && saveAppKey.status !== 'SUCCESS') ) { Toast.showToast({ title: 'FAILED', description: 'something went wrong please retry', type: Toast.TYPE.NORMAL }); this.setState({ writingSetup: false }); } else { await writeNerdStorageReturnData( accountId, 'setup', 'datadog', data, this.reportLogFetch ) .then(() => { const datadogService = this.createDatadogServiceInstance( apikey, appkey, region ); this.setState({ writingSetup: false, apikey: apikey, appkey: appkey, apikeyS: '*'.repeat(apikey.length), appkeyS: '*'.repeat(appkey.length), apiserver: region, setupComplete: true, lastUpdate: 'never', datadogService: datadogService }); Toast.showToast({ title: 'VALID KEY', description: 'Valid key and correctly encrypted', type: Toast.TYPE.NORMAL }); }) .catch(err => { const response = { message: err, type: 'Error', event: 'Write setup', date: new Date().toLocaleString() }; this.reportLogFetch(response); Toast.showToast({ title: 'FAILED', description: 'something went wrong', type: Toast.TYPE.NORMAL }); this.setState({ writingSetup: false }); }); } } else { Toast.showToast({ title: 'FAILED', description: 'The application key is not valid', type: Toast.TYPE.NORMAL }); this.setState({ writingSetup: false }); } } else { Toast.showToast({ title: 'FAILED', description: 'The API key is not valid', type: Toast.TYPE.NORMAL }); this.setState({ writingSetup: false }); } } catch (err) { Toast.showToast({ title: 'FAILED', description: 'Something went wrong', type: Toast.TYPE.NORMAL }); this.setState({ writingSetup: false }); const response = { message: err, type: 'Error', event: 'Write setup function', date: new Date().toLocaleString() }; this.reportLogFetch(response); } this.sendLogs(); }; /** * Method that open a Toast notification from confirm delete API setup * * @memberof App */ openToast = () => { const { accountId } = this.state; Toast.showToast({ title: 'ALERT', description: 'Are you sure you want to delete the datadog configuration?', actions: [ { label: 'DELETE', onClick: async () => { this.setState({ deleteSetup: true, writingSetup: true }); await deleteSetup(accountId); this.setState({ apikey: '', appkey: '', apiserver: '', lastUpdate: '', setupComplete: false, writingSetup: false, deleteSetup: false }); } } ], type: Toast.TYPE.NORMAL }); }; /** * Method that changes the component to render according to the selected menu option * * @returns * @memberof App */ renderContent() { const { selectedMenu, monitorsGraph, monitorsTotal, monitorsData, infrastructureDataGraph, infraestructureList, metrics, testTotal, testList, fetchingData, writingSetup, logsData, apikey, apikeyS, appkey, appkeyS, lastUpdate, setupComplete, completed, deleteSetup, dataDashboards, fetchingMetrics, progressMetrics, emptyData, errorMetric, hasErrorFetch, historyUpdateMetric, total, totalActive } = this.state; switch (selectedMenu) { case 0: return ( <Setup completed={completed} hasErrorFetch={hasErrorFetch} setupComplete={setupComplete} deleteSetup={deleteSetup} viewKeyAction={this.viewKeyAction} apikeyS={apikeyS} fetchingData={fetchingData} apikey={apikey} appkey={appkey} lastUpdate={lastUpdate} writingSetup={writingSetup} appkeyS={appkeyS} handlePlatformChange={this.handlePlatformChange} fetchData={this.fetchData} writeSetup={this.writeSetup} openToast={this.openToast} /> ); case 2: return ( <Dashboard dataDashboards={dataDashboards} emptyData={emptyData} /> ); case 3: return ( <Monitors monitorsGraph={monitorsGraph} monitorsTotal={monitorsTotal} monitorsData={monitorsData} /> ); case 4: return ( <Infrastructure infrastructureDataGraph={infrastructureDataGraph} infraestructureList={infraestructureList} total={total} totalActive={totalActive} /> ); case 5: return <Logs logsData={logsData} />; case 6: return ( <Metrics metrics={metrics} errorMetric={errorMetric} completed={progressMetrics} fetchingMetrics={fetchingMetrics} historyUpdateMetric={historyUpdateMetric} updateMetricsSection={this.updateMetricsSection} updateProgressMetrics={this.updateProgressMetrics} /> ); case 7: return <Synthetics testTotal={testTotal} testList={testList} />; default: return <div />; } } render() { const { loadingContent, selectedMenu, lastUpdate } = this.state; return ( <> {loadingContent ? ( <Spinner type={Spinner.TYPE.DOT} /> ) : ( <div className="main"> <> <div className="sidebar-container h100"> <Menu lastUpdate={lastUpdate} selectedMenu={selectedMenu} handleChangeMenu={this.handleChangeMenu} /> </div> <div className="h100" style={{ background: '#eceeee' }}> <div style={{ paddingTop: '1.8%', paddingRight: '1%', paddingLeft: '1.8%', height: '96%' }} > {this.renderContent()} </div> </div> </> </div> )} </> ); } }
JavaScript
class SpinningIcon extends React.Component { static propTypes = { loading: React.PropTypes.array, icon: React.PropTypes.string.isRequired, } static defaultProps = { loading: [false, false], } constructor(props) { super(props); this.state = { spinValue: new Animated.Value(0), }; } componentDidMount() { if (this.isAnyPropLoading(this.props)) { this.spin(); /* this.timer = setInterval(() => { this.stopSpin(); }, 2000);*/ } } componentWillReceiveProps(nextProps) { if (this.hasPropsChanged(nextProps)) { if (this.isAnyPropLoading(nextProps) === true) { this.spin(); } else { this.stopSpin(); } } } /** * Check if any props changed. */ hasPropsChanged(nextProps) { if (this.props.loading.length !== nextProps.loading.length) { return true; } for (let i = 0; i < this.props.loading.length; i++) { if (this.props.loading[i] !== nextProps.loading[i]) { return true; } } return false; } /** * Checks if any boolean in the loading prop list are true. */ isAnyPropLoading(props) { for (let i = 0; i < props.loading.length; i++) { if (props.loading[i] === true) { return true; } } return false; } /** * Starts spinning the icon. */ spin() { this.state.spinValue.setValue(0); Animated.timing( this.state.spinValue, { toValue: 1, duration: 1000, easing: Easing.linear, } ).start(endState => { if (endState.finished) { if (this.props.loading) { this.spin(); } } }); } /** * Stops the spinning. */ stopSpin() { this.state.spinValue.stopAnimation(); } render() { const getStartValue = () => '0deg'; const getEndValue = () => '360deg'; const spin = this.state.spinValue.interpolate({ inputRange: [0, 1], outputRange: [getStartValue(), getEndValue()], }); /* This also works, just using above example to show functions instead of strings /* /* const spin = this.state.spinValue.interpolate({ inputRange: [0, 1], outputRange: ['0deg', '360deg'] }) */ return ( <Animated.View style={[styles.container, { transform: [{ rotate: spin }] }]}> <Icon style={{ marginRight: 10 }} name={this.props.icon} color="#4D4D4D" size={90} /> </Animated.View> ); } }
JavaScript
class MultiRegex { constructor() { this.matchIndexes = {}; // @ts-ignore this.regexes = []; this.matchAt = 1; this.position = 0; } // @ts-ignore addRule(re, opts) { opts.position = this.position++; // @ts-ignore this.matchIndexes[this.matchAt] = opts; this.regexes.push([opts, re]); this.matchAt += countMatchGroups(re) + 1; } compile() { if (this.regexes.length === 0) { // avoids the need to check length every time exec is called // @ts-ignore this.exec = function () { return null; }; } var terminators = this.regexes.map(function (el) { return el[1]; }); this.matcherRe = langRe(join(terminators), true); this.lastIndex = 0; } /** @param {string} s */ exec(s) { this.matcherRe.lastIndex = this.lastIndex; var match = this.matcherRe.exec(s); if (!match) { return null; } // eslint-disable-next-line no-undefined var i = match.findIndex(function (el, i) { return i > 0 && el !== undefined; }); // @ts-ignore var matchData = this.matchIndexes[i]; // trim off any earlier non-relevant match groups (ie, the other regex // match groups that make up the multi-matcher) match.splice(0, i); return Object.assign(match, matchData); } }
JavaScript
class ResumableMultiRegex { constructor() { // @ts-ignore this.rules = []; // @ts-ignore this.multiRegexes = []; this.count = 0; this.lastIndex = 0; this.regexIndex = 0; } // @ts-ignore getMatcher(index) { if (this.multiRegexes[index]) { return this.multiRegexes[index]; } var matcher = new MultiRegex(); this.rules.slice(index).forEach(function (ref) { var re = ref[0]; var opts = ref[1]; return matcher.addRule(re, opts); }); matcher.compile(); this.multiRegexes[index] = matcher; return matcher; } resumingScanAtSamePosition() { return this.regexIndex !== 0; } considerAll() { this.regexIndex = 0; } // @ts-ignore addRule(re, opts) { this.rules.push([re, opts]); if (opts.type === "begin") { this.count++; } } /** @param {string} s */ exec(s) { var m = this.getMatcher(this.regexIndex); m.lastIndex = this.lastIndex; var result = m.exec(s); // The following is because we have no easy way to say "resume scanning at the // existing position but also skip the current rule ONLY". What happens is // all prior rules are also skipped which can result in matching the wrong // thing. Example of matching "booger": // our matcher is [string, "booger", number] // // ....booger.... // if "booger" is ignored then we'd really need a regex to scan from the // SAME position for only: [string, number] but ignoring "booger" (if it // was the first match), a simple resume would scan ahead who knows how // far looking only for "number", ignoring potential string matches (or // future "booger" matches that might be valid.) // So what we do: We execute two matchers, one resuming at the same // position, but the second full matcher starting at the position after: // /--- resume first regex match here (for [number]) // |/---- full match here for [string, "booger", number] // vv // ....booger.... // Which ever results in a match first is then used. So this 3-4 step // process essentially allows us to say "match at this position, excluding // a prior rule that was ignored". // // 1. Match "booger" first, ignore. Also proves that [string] does non match. // 2. Resume matching for [number] // 3. Match at index + 1 for [string, "booger", number] // 4. If #2 and #3 result in matches, which came first? if (this.resumingScanAtSamePosition()) { if (result && result.index === this.lastIndex) ; else { // use the second matcher result var m2 = this.getMatcher(0); m2.lastIndex = this.lastIndex + 1; result = m2.exec(s); } } if (result) { this.regexIndex += result.position + 1; if (this.regexIndex === this.count) { // wrap-around to considering all matches again this.considerAll(); } } return result; } }
JavaScript
class GameObject { /** * This is the root class in the small class hierarchy of the game. * */ constructor() { this.frameCounter = 0; /** * Is this object still required? Set this value to true (via the invalidate function) to mark it for * deletion before the next frame. */ this.invalid = false; /**Returns an array of 2 arrays. //X positions occupied = array 0. Y positions occupied = array 1. **/ } }
JavaScript
class CompileRouter extends Router { constructor(options = {}) { super() this.options = options this.compileService = options.compileService } /** * Initializes routes for CompileRoute Class * @param {Object} app - Koa app object * @throws {Error} throws an error if one occurs while running */ init(app) { try { this.prefix(process.env.PREFIX) this.post('/compile', ctx => this.compile(ctx)) app.use(this.routes()) app.use(this.allowedMethods()) } catch (err) { throw err } } /** * Compiles syntax for various programming languages * @param {Object} ctx - Koa context object * @returns {Promise<Object>} Compile code * @throws {Error} Throws an error if one occurs while running */ async compile(ctx) { try { const response = await this.compileService.compile(ctx.request.body) ctx.body = { stdout: response.stdout, stderr: response.stderr || '', code: response.code || 1 } } catch (err) { ctx.body = { code: 0, stderr: err.toString() || '' } throw err } } }
JavaScript
class SignService { constructor( base64Service = new Base64Service(), signerFactory = new SignerFactory(), signedDataFactory = new SignedDataFactory(), ) { /** * @type {Base64Service} */ this.base64Service = base64Service; /** * @type {SignerFactory} */ this.signerFactory = signerFactory; /** * @type {SignedDataFactory} */ this.signedDataFactory = signedDataFactory; } /** * Create a basic electronic signature (CAdES-BES) * @param {string} payload * @param {Certificate} certificate * @param options Sign Options */ async signBes(payload, certificate, options = { detached: false }) { const { detached } = options; const payloadOption = options.payloadOptions || { encodeToBase64: true }; const signedDataOptions = options.signedDataOptions || { contentEncodingType: CADESCOM_CONTENT_ENCODING_TYPE.CADESCOM_BASE64_TO_BINARY, }; const signerOptions = options.signerOptions || { certificateInclude: CAPICOM_CERTIFICATE_INCLUDE_OPTION.CAPICOM_CERTIFICATE_INCLUDE_END_ENTITY_ONLY, }; const payloadToSign = payloadOption.encodeToBase64 ? this.base64Service.encode(payload) : payload; if (!payloadToSign) { throw new Error('No payload to sign'); } const signer = await this.signerFactory.create(); await signer.withCertificate(certificate); await signer.withCertificateInclude(signerOptions.certificateInclude); const signedData = await this.signedDataFactory.create(); await signedData.withContentEncoding(signedDataOptions.contentEncodingType); await signedData.withContent(payloadToSign); try { return await signedData.signCades(signer, CADESCOM_CADES_TYPE.CADESCOM_CADES_BES, detached); } catch (e) { logger('error', 'Failed to sign the payload', e); throw e; } } }
JavaScript
class Database { constructor() { this.db = new sqlite3.Database(':memory:'); // we wanna use in-memory DB } /** * This method is fired once on server start * It creates the necessary table if it doesn't exist */ init() { let vm = this.db; this.db.serialize(() => { vm.run(` CREATE TABLE IF NOT EXISTS metric ( metric_key VAR(255), metric_value INTEGER, created_at TIMESTAMP ) `); }); } /** * This specified the table name for the current DB operation * @param tableName (string) * @returns {Database} */ setTable(tableName) { this.table = tableName; return this; } /** * This performs the DB insert * @param data key-value object to insert into DB * @returns {Promise<*>} */ async insert(data) { let columns = Object.keys(data).join(','); let values = Object.values(data); let placeholders = values.reduce((a, v, i) => i===0 ? a+'?' : a+',?', ''); return this.db.run(`INSERT INTO ${this.table}(${columns}) VALUES(${placeholders})`, values); } /** * * @param sql (string) - SQL query to be executed * @param params (Array) - the query params to be bind to the query * @param callback (function) - the function to be executed after query completion * @returns {Promise<*>} */ async select(sql, params, callback) { return this.db.get(sql, params, callback); } /** * RUn arbitrary SQL query * @param sql (string) - SQL query to be executed * @param callback (function) - function to be executed after query completion * @returns {Promise<*>} */ async query(sql, callback) { return this.db.run(sql, [], callback); } /** * This helps remove entries older than 1 hour from the DB table * @returns {Promise<void>} */ async cleanup() { let lastHour = new Date().getTime() - (60 * 60 * 1000); /* 1 hr ago */ let tableName = 'metric'; this.query(`DELETE FROM ${tableName} WHERE created_at <= ${lastHour}`, () => { let today = new Date(); console.log('Clean ran at', today.getHours() + ":" + today.getMinutes() + ":" + today.getSeconds()); }) } /** * Close the DB connection */ close () { this.db.close(); } }
JavaScript
class Car { constructor(name, year) { this.name = name; this.year = year; } }
JavaScript
class Car1 { constructor(name, year) { this.name = name; this.year = year; } age(x) { return x - this.year; } }
JavaScript
class MmkSaturdayService { constructor (boat) { this.boat = boat // Next saturday if (moment.utc().weekday() === 6) { this.saturday = moment.utc().day(13).startOf('day').toDate() // Saturday next week } else { this.saturday = moment.utc().day(6).startOf('day').toDate() // Saturday this week } } async fillDetails () { await this.setupPrice() await this.setupBase() await this.boat.save() } async setupPrice () { // First try to find price for next saturday let price = await this.boat.prices() .where('date_from', '<=', this.saturday) .where('date_to', '>=', this.saturday) .first() if (price !== null) { this.boat.saturday_price = price.price return } // If none found, get the nearest possible price price = await this.boat.prices() .orderBy('date_to', 'asc') .where('date_to', '>', new Date()) .first() // Again, if nothing found, set price to 0 if (price === null) { this.boat.saturday_price = 0.0 } else { this.boat.saturday_price = price.price } } async setupBase () { // If we are not having custom base set for next saturday, use default base ID let location = await this.boat.locations() .where('date_from', '<=', this.saturday) .where('date_to', '>=', this.saturday) .first() if (location === null) { this.boat.saturday_base_id = this.boat.base_id } else { this.boat.saturday_base_id = location.base_id } } }
JavaScript
class FileRegisterView extends Component { constructor() { super(); } render() { /*jshint ignore:start*/ return ( <div className="App"> <header className="App-header"> <h1>IPFS Register</h1> </header> <BrowserAlert /> <GetEtherWalletPanel title="1. Get Ethereum Wallet" /> <PurchaseEtherPanel title="2. Fund Your Wallet with Ethereum" /> <Panel bsStyle="primary" defaultExpanded={true}> <Panel.Heading> <Panel.Title toggle componentClass="h3"> 3. Registering Files </Panel.Title> </Panel.Heading> <Panel.Collapse> <Panel.Body> <FileRegister /> </Panel.Body> </Panel.Collapse> </Panel> <Panel bsStyle="primary" defaultExpanded={!isMobile.any()}> <Panel.Heading> <Panel.Title toggle componentClass="h3"> 4. Have Large Files to upload? </Panel.Title> </Panel.Heading> <Panel.Collapse> <Panel.Body> <Alert bsStyle="warning" style={{ display: isMobile.any() ? 'block' : 'none' }}> <strong>Please use desktop to download the tools. </strong> </Alert> <p>Download our desktop tool to help you upload large files.</p> <p> <Button bsStyle="info" href={CONFIG.desktop_tool.mac} disabled={isMobile.any()}> MacOS </Button>{' '} <Button bsStyle="info" href={CONFIG.desktop_tool.windows} disabled={isMobile.any()}> Window </Button>{' '} <Button bsStyle="info" href={CONFIG.desktop_tool.rpm} disabled={isMobile.any()}> Linux(RPM) </Button>{' '} <Button bsStyle="info" href={CONFIG.desktop_tool.deb} disabled={isMobile.any()}> Linux(Deb) </Button>{' '} </p> </Panel.Body> </Panel.Collapse> </Panel> <ExchangeBMDTokensPanel title="5. Exchange BlockMed(BMD) Tokens" /> </div> ); /*jshint ignore:end*/ } }
JavaScript
class FStatMode { constructor(mode) { this.mode = mode.mode ? mode.mode : mode; this.is_socket = this._is_set(S_IFSOCK); this.is_symbolic = this._is_set(S_IFLNK); this.is_regular = this._is_set(S_IFREG); this.is_block = this._is_set(S_IFBLK); this.is_directory = this._is_set(S_IFDIR); this.is_character = this._is_set(S_IFCHR); this.is_fifo = this._is_set(S_IFIFO); this.is_setuid = this._is_set(S_ISUID); this.is_setgid = this._is_set(S_ISGID); this.is_sticky = this._is_set(S_ISVTX); this.owner = { read: this._is_set(S_IRUSR), write: this._is_set(S_IWUSR), execute: this._is_set(S_IXUSR) }; this.owner.permission = (() => { let rwx = ""; rwx += this.owner.read ? "r" : "-"; rwx += this.owner.write ? "w" : "-"; rwx += this.owner.execute ? "x" : (this.is_setuid ? "S" : "-"); return rwx; })(); this.group = { read: this._is_set(S_IRGRP), write: this._is_set(S_IWGRP), execute: this._is_set(S_IXGRP) }; this.group.permission = (() => { let rwx = ""; rwx += this.group.read ? "r" : "-"; rwx += this.group.write ? "w" : "-"; rwx += this.group.execute ? "x" : (this.is_setgid ? "s" : "-"); return rwx; })(); this.others = { read: this._is_set(S_IROTH), write: this._is_set(S_IWOTH), execute: this._is_set(S_IXOTH) }; this.others.permission = (() => { let rwx = ""; rwx += this.others.read ? "r" : "-"; rwx += this.others.write ? "w" : "-"; rwx += (() => { if (!this.sticky) return this.others.execute ? "x" : "-"; return this.others.execute ? "t" : "T"; })(); return rwx; })(); this.file_type = (() => { if (this.is_regular) return "-"; if (this.is_block) return "b"; if (this.is_character) return "c"; if (this.is_directory) return "d"; if (this.is_symbolic) return "l"; if (this.is_fifo) return "p"; if (this.is_socket) return "s"; })(); this.ll = this.file_type + this.owner.permission + this.group.permission + this.others.permission; } _is_set(flag) { return flag == (this.mode & flag); } }
JavaScript
class MapReducer extends MapReducerCore { static zoomToLayer(state, action) { let alerts = state.get("alerts"); // resolve layer from id if necessary let actionLayer = action.layer; if (typeof actionLayer === "string") { actionLayer = this.findLayerById(state, actionLayer); if (typeof actionLayer === "undefined") { alerts = alerts.push( alert.merge({ title: appStrings.ALERTS.ZOOM_TO_LAYER_FAILED.title, body: appStrings.ALERTS.ZOOM_TO_LAYER_FAILED.formatString .replace("{LAYER}", actionLayer) .replace("{MAP}", "2D & 3D"), severity: appStrings.ALERTS.ZOOM_TO_LAYER_FAILED.severity, time: new Date() }) ); return state.set("alerts", alerts); } } state.get("maps").map(map => { if (!map.zoomToLayer(actionLayer)) { let contextStr = map.is3D ? "3D" : "2D"; alerts = alerts.push( alert.merge({ title: appStrings.ALERTS.ZOOM_TO_LAYER_FAILED.title, body: appStrings.ALERTS.ZOOM_TO_LAYER_FAILED.formatString .replace("{LAYER}", actionLayer) .replace("{MAP}", contextStr), severity: appStrings.ALERTS.ZOOM_TO_LAYER_FAILED.severity, time: new Date() }) ); } }); return state.set("alerts", alerts); } static pixelHover(state, action) { let pixelCoordinate = state.getIn(["view", "pixelHoverCoordinate"]).set("isValid", false); state.get("maps").forEach(map => { if (map.isActive) { let coords = map.getLatLonFromPixelCoordinate(action.pixel); let data = []; if (coords && coords.isValid) { // find data if any data = map.getDataAtPoint(action.pixel); data = data !== false ? data : []; data = Immutable.fromJS( data.map(entry => { entry.layer = this.findLayerById(state, entry.layerId); return entry; }) ); // set the coordinate as valid and store the data pixelCoordinate = pixelCoordinate .set("lat", coords.lat) .set("lon", coords.lon) .set("x", action.pixel[0]) .set("y", action.pixel[1]) .set("data", data) .set("showData", data.size > 0) .set("isValid", true); return false; } else { pixelCoordinate = pixelCoordinate.set("isValid", false); } } return true; }); return state.setIn(["view", "pixelHoverCoordinate"], pixelCoordinate); } static pixelClick(state, action) { let pixelCoordinate = state.getIn(["view", "pixelClickCoordinate"]).set("isValid", false); state.get("maps").forEach(map => { if (map.isActive) { let pixel = map.getPixelFromClickEvent(action.clickEvt); if (pixel) { let coords = map.getLatLonFromPixelCoordinate(pixel); let data = []; if (coords && coords.isValid) { // find data if any data = map.getDataAtPoint(action.clickEvt.pixel); data = data !== false ? data : []; data = Immutable.fromJS( data.map(entry => { entry.layer = this.findLayerById(state, entry.layerId); return entry; }) ); // set the coordinate as valid and store the data pixelCoordinate = pixelCoordinate .set("lat", coords.lat) .set("lon", coords.lon) .set("x", action.clickEvt.pixel[0]) .set("y", action.clickEvt.pixel[1]) .set("data", data) .set("isValid", true); // update the date let dateStr = data.getIn([0, "properties", "dtg"]); if (typeof dateStr !== "undefined") { let date = moment( dateStr, data.getIn([0, "layer", "timeFormat"]) ).toDate(); state = MapReducerCore.setMapDate(state, { date: date }); } return false; } else { pixelCoordinate = pixelCoordinate.set("isValid", false); } } } return true; }); return state.setIn(["view", "pixelClickCoordinate"], pixelCoordinate); } }
JavaScript
class OptionGroup extends React.Component { constructor(props) { super(props); this.handleOptionChange = this.handleOptionChange.bind(this); } handleOptionChange(optValue) { const { onChange, value, type, } = this.props; if (type === 'radio') { onChange(optValue); } else if (type === 'checkbox') { // Clone the array, we're going to mutate it. const valueClone = (value || []).slice(); const optIndex = valueClone.indexOf(optValue); if (valueClone.indexOf(optValue) >= 0) { valueClone.splice(optIndex, 1); } else { valueClone.push(optValue); } onChange(valueClone); } } render() { const { className, id, name, isInline, disabled, cssModule, isHorizontal, type, options, optionsClassName, required, requiredText, label, labelProps, tooltip, tooltipProps, value, onChange, // Don't pass through helpText, error, status, statusMessage, renderOption, ...attrs } = this.props; let _status = status; let _statusMessage = statusMessage; if (error) { _status = 'error'; _statusMessage = error; } const inputClasses = mapToCssModules(classNames( optionsClassName, 'options', { 'is-horizontal': isHorizontal, }, ), cssModule); const inputId = id || name; return ( <Control className={className} name={inputId} isInline={isInline} label={label} labelProps={labelProps} tooltip={tooltip} tooltipProps={tooltipProps} helpText={helpText} required={required} requiredText={requiredText} status={_status} statusMessage={_statusMessage} role="group" aria-labelledby={labelProps && labelProps.id} > <ul className={inputClasses} {...attrs} > {(options || []).map(option => { let checked = false; if (type === 'radio') { checked = value === option.value; } if (type === 'checkbox' && Array.isArray(value)) { checked = value.indexOf(option.value) >= 0; } return renderOption({ ...option, id: `${inputId}__${option.id}`, type, name, checked, disabled, handleOptionChange: e => { this.handleOptionChange(option.value); }, }); })} </ul> </Control> ); } }
JavaScript
class Numbers extends Task { constructor ( rtjs ) { super({ name: "NumbersTask", priority: NUMBERS_PRIO, deadline: NUMBERS_DEADLINE }) this.last = 0; this.div = document.querySelector("#num") this.rtjs = rtjs; } // @rtjs run () { this.last++; this.div.textContent = this.last.toString() } addTask () { if ( this.rtjs != null ) { this.creationTime = performance.now(); this.rtjs.addTask ( this ); } requestAnimationFrame(this.addTask.bind(this)) } onTerminate () { } }
JavaScript
class ProjectFactory { /** * @param {string} markdown The markdown string * @param {ProjectConfiguration} configuration The configuration */ createFromMarkdown (markdown, configuration) { return this.createFromTokens(marked.lexer(markdown), configuration) } /** * @param {object[]} tokens The parsed token object list of `marked` module * @param {ProjectConfiguration} configuration The configuration */ createFromTokens (tokens, configuration) { const todos = [] const dones = [] const STATE_NOTHING = 0 const STATE_TODO = 1 const STATE_DONE = 2 let currentState = STATE_NOTHING tokens.forEach(token => { if (ProjectFactory.tokenIsH1(token)) { if (ProjectFactory.tokenIsTodoStart(token)) { currentState = STATE_TODO } else if (ProjectFactory.tokenIsDoneStart(token)) { currentState = STATE_DONE } else { currentState = STATE_NOTHING } } else { if (currentState === STATE_TODO) { todos.push(token) } else if (currentState === STATE_DONE) { dones.push(token) } } }) return new Project({ title: configuration.title, path: configuration.path, todos: todoFactory.createFromTokens(todos, false), dones: todoFactory.createFromTokens(dones, true), configuration: configuration }) } static tokenIsH1 (token) { return token != null && token.type === 'heading' && token.depth === 1 } static tokenIsTodoStart (token) { return this.tokenIsH1(token) && /^TODO/.test(token.text) } static tokenIsDoneStart (token) { return this.tokenIsH1(token) && /^DONE/.test(token.text) } createFromObject (obj) { const ProjectConfigurationFactory = require('./project-configuration-factory').default obj.todos = todoFactory.createFromObjectList(obj.todos) obj.dones = todoFactory.createFromObjectList(obj.dones) obj.configuration = new ProjectConfigurationFactory().createFromObject(obj.configuration) return new Project(obj) } createCollectionFromArray (arr) { return new ProjectCollection(arr.map(obj => this.createFromObject(obj))) } }
JavaScript
class VarStoragePolyfill { constructor () { this.map = new Map(); } /** * @param {string} key * @param {any} value */ setItem (key, value) { this.map.set(key, value); } /** * @param {string} key */ getItem (key) { return this.map.get(key) } }
JavaScript
class Decoder { /** * @param {Uint8Array} uint8Array Binary data to decode */ constructor (uint8Array) { /** * Decoding target. * * @type {Uint8Array} */ this.arr = uint8Array; /** * Current decoding position. * * @type {number} */ this.pos = 0; } }
JavaScript
class Encoder { constructor () { this.cpos = 0; this.cbuf = new Uint8Array(100); /** * @type {Array<Uint8Array>} */ this.bufs = []; } }
JavaScript
class VConsole { /** * @param {Element} dom */ constructor (dom) { this.dom = dom; /** * @type {Element} */ this.ccontainer = this.dom; this.depth = 0; vconsoles.add(this); } /** * @param {Array<string|Symbol|Object|number>} args * @param {boolean} collapsed */ group (args, collapsed = false) { enqueue(() => { const triangleDown = element('span', [create$3('hidden', collapsed), create$3('style', 'color:grey;font-size:120%;')], [text('▼')]); const triangleRight = element('span', [create$3('hidden', !collapsed), create$3('style', 'color:grey;font-size:125%;')], [text('▶')]); const content = element('div', [create$3('style', `${lineStyle};padding-left:${this.depth * 10}px`)], [triangleDown, triangleRight, text(' ')].concat(_computeLineSpans(args))); const nextContainer = element('div', [create$3('hidden', collapsed)]); const nextLine = element('div', [], [content, nextContainer]); append(this.ccontainer, [nextLine]); this.ccontainer = nextContainer; this.depth++; // when header is clicked, collapse/uncollapse container addEventListener(content, 'click', event => { nextContainer.toggleAttribute('hidden'); triangleDown.toggleAttribute('hidden'); triangleRight.toggleAttribute('hidden'); }); }); } /** * @param {Array<string|Symbol|Object|number>} args */ groupCollapsed (args) { this.group(args, true); } groupEnd () { enqueue(() => { if (this.depth > 0) { this.depth--; // @ts-ignore this.ccontainer = this.ccontainer.parentElement.parentElement; } }); } /** * @param {Array<string|Symbol|Object|number>} args */ print (args) { enqueue(() => { append(this.ccontainer, [element('div', [create$3('style', `${lineStyle};padding-left:${this.depth * 10}px`)], _computeLineSpans(args))]); }); } /** * @param {Error} err */ printError (err) { this.print([RED, BOLD, err.toString()]); } /** * @param {string} url * @param {number} height */ printImg (url, height) { enqueue(() => { append(this.ccontainer, [element('img', [create$3('src', url), create$3('height', `${round(height * 1.5)}px`)])]); }); } /** * @param {Node} node */ printDom (node) { enqueue(() => { append(this.ccontainer, [node]); }); } destroy () { enqueue(() => { vconsoles.delete(this); }); } }
JavaScript
class Xorshift32 { /** * @param {number} seed Unsigned 32 bit number */ constructor (seed) { this.seed = seed; /** * @type {number} */ this._state = seed; } /** * Generate a random signed integer. * * @return {Number} A 32 bit signed integer. */ next () { let x = this._state; x ^= x << 13; x ^= x >> 17; x ^= x << 5; this._state = x; return (x >>> 0) / (BITS32 + 1) } }
JavaScript
class Xoroshiro128plus { /** * @param {number} seed Unsigned 32 bit number */ constructor (seed) { this.seed = seed; // This is a variant of Xoroshiro128plus to fill the initial state const xorshift32 = new Xorshift32(seed); this.state = new Uint32Array(4); for (let i = 0; i < 4; i++) { this.state[i] = xorshift32.next() * BITS32; } this._fresh = true; } /** * @return {number} Float/Double in [0,1) */ next () { const state = this.state; if (this._fresh) { this._fresh = false; return ((state[0] + state[2]) >>> 0) / (BITS32 + 1) } else { this._fresh = true; const s0 = state[0]; const s1 = state[1]; const s2 = state[2] ^ s0; const s3 = state[3] ^ s1; // function js_rotl (x, k) { // k = k - 32 // const x1 = x[0] // const x2 = x[1] // x[0] = x2 << k | x1 >>> (32 - k) // x[1] = x1 << k | x2 >>> (32 - k) // } // rotl(s0, 55) // k = 23 = 55 - 32; j = 9 = 32 - 23 state[0] = (s1 << 23 | s0 >>> 9) ^ s2 ^ (s2 << 14 | s3 >>> 18); state[1] = (s0 << 23 | s1 >>> 9) ^ s3 ^ (s3 << 14); // rol(s1, 36) // k = 4 = 36 - 32; j = 23 = 32 - 9 state[2] = s3 << 4 | s2 >>> 28; state[3] = s2 << 4 | s3 >>> 28; return (((state[1] + state[3]) >>> 0) / (BITS32 + 1)) } } }
JavaScript
class FacebookSocial extends Component { static propTypes = { meta: PropTypes.object } render() { return ( <Helmet meta={getFacebookMeta(this.props.meta)} /> ); } }
JavaScript
class Point { static isValid(point) { const sum = _.reduce(point, function(a,b) { return a + b; }, 0); return !isNaN(sum) && isFinite(sum); } static distanceSquared(p1, p2) { let d2 = 0; if (p1 && p2 && p1.length !== p2.length) { return NaN; } for (let i = 0; i < p1.length; ++i) { const dv = p1[i] - (p2 && p2[i] || 0); d2 += dv*dv; } return d2; } static distance(p1, p2) { return Math.sqrt(Point.distanceSquared(p1, p2)); } static unit(dimensions) { const point = []; for (let i = 0; i<dimensions; ++i) { point.push(1.0); } return point; } static unitDistance(dimensions) { return Math.sqrt(dimensions); } static distanceNormalized(p1, p2) { return Math.sqrt(Point.distanceSquared(p1, p2)) / Point.unitDistance(p1.length); } }
JavaScript
class SyncPromise { constructor() { this.resolved = false; this.callbacks = []; } static all(valuesOrPromises) { const aggrPromise = new SyncPromise(); let resolvedCount = 0; const results = []; const resolve = (idx, value) => { results[idx] = value; if (++resolvedCount === valuesOrPromises.length) aggrPromise.resolve(results); }; valuesOrPromises.forEach((p, idx) => { if (isThenable(p)) { p.then(v => resolve(idx, v)); } else { resolve(idx, p); } }); return aggrPromise; } resolve(value) { // Do nothing, if already resolved. if (this.resolved) return; this.value = value; this.resolved = true; // Run the queued callbacks. this.callbacks.forEach(callback => callback(value)); this.callbacks.length = 0; } then(callback) { if (this.resolved) { callback(this.value); } else { this.callbacks.push(callback); } } }
JavaScript
class GameState { static get PAUSED() { return 1; } static get GAME_OVER() { return 2; } static get GAME_START() { return 4; } static get PLAYING() { return 8; } static get WAVE_START() { return 16; } }
JavaScript
class RestrictedPrompt { /** * Re-prompt the user until their response is not part of the unavailableList. * Will add the unavailable options to the prompt. * @param {ChannelPrompt.single | RolePrompt.single | MemberPrompt.single} promptFunction * @param {PromptInfo} promptInfo * @param {TextChannel[] | Role[] | GuildMember[]} unavailableList - list the response can not be * @returns {Promise<TextChannel | Role | GuildMember>} * @throws Error if the list item type does not match the return item from the prompt function. * @throws {TimeOutError} if the user does not respond within the given time. * @throws {CancelError} if the user cancels the prompt. * @async */ static async single(promptFunction, promptInfo, unavailableList) { let response = await promptFunction({ prompt: `${promptInfo.prompt} \n Unavailable responses: ${unavailableList.join(', ')}`, channel: promptInfo.channel, userId: promptInfo.userId, time: promptInfo.time, cancelable: promptInfo.cancelable, }); // throw error if list items do not match response item if (response.constructor.name != unavailableList[0].constructor.name) throw new Error('List and response items do not match!'); if (unavailableList.includes(response)) { await channelMsgWaitDelete(promptInfo.channel, promptInfo.userId, 'The response is not valid please try again!'); return await RestrictedPrompt.single(promptFunction, promptInfo, unavailableList); } else { return response; } } }
JavaScript
class AlertsMain extends Component { constructor(props) { super(props); let height = 400; this.state = { isLoading: false, alerts: [], tableHeight: height + "px" }; // this.tableStyle = this.tableStyle.bind(this); // this.onAfterInsertRow = this.onAfterInsertRow.bind(this); } selectRow = { mode: 'checkbox', // or checkbox clickToSelectAndEditCell: true }; renderShowsTotal = (start, to, total) => { return ( <p style={ { color: 'blue' } }> From { start } to { to }, totals is { total } </p> ); }; componentDidMount = () => { this.getAlerts(); }; getAlerts() { AlertsApi.getAlerts().then(results => { this.setState({ alerts: results.data, loading: false }); }); } onAfterInsertRow = (row) => { console.log("New record: " + JSON.stringify(row)); console.log("Rows: " + JSON.stringify(this.state)); AlertsApi.createAlert(row).then(data => { this.getAlerts(); }); }; options = { afterInsertRow: this.onAfterInsertRow, // A hook for after insert rows page: 1, // which page you want to show as default sizePerPageList: [ { text: '5', value: 5 }, { text: '10', value: 10 } ], // you can change the dropdown list for size per page sizePerPage: 5, // which size per page you want to locate as default pageStartIndex: 1, // where to start counting the pages paginationSize: 3, // the pagination bar size. alwaysShowAllBtns: true, withFirstAndLast: true, paginationShowsTotal: this.renderShowsTotal, // Accept bool or function }; cellEdit = { mode: 'click' // click cell to edit }; render() { if (this.state.loading) { return ( <div> <h1>Your data is loading</h1> <img src={Images.loadingGif} alt='loading'/> </div> ) } else return ( <div className='home' style={{ backgroundColor: 'white' }}> {/*<BootstrapTable*/} {/*data={this.state.alerts}*/} {/*insertRow={true}*/} {/*deleteRow={true}*/} {/*condensed={true}*/} {/*pagination={true}*/} {/*cellEdit={this.cellEdit}*/} {/*selectRow={this.selectRow}*/} {/*options={this.options}*/} {/*maxHeight={this.state.tableHeight}>*/} {/*<TableHeaderColumn*/} {/*dataField='alertId'*/} {/*isKey visible={false}*/} {/*hiddenOnInsert={true}*/} {/*autoValue={true}*/} {/*hidden={true}*/} {/*width='5%'>Alert ID</TableHeaderColumn>*/} {/*<TableHeaderColumn dataField='alertName'>Alert Name</TableHeaderColumn>*/} {/*<TableHeaderColumn dataField='highValue'>High Value</TableHeaderColumn>*/} {/*<TableHeaderColumn dataField='lowValue'>Low Value</TableHeaderColumn>*/} {/*<TableHeaderColumn dataField='status'>Status</TableHeaderColumn>*/} {/*<TableHeaderColumn dataField='active'>Active</TableHeaderColumn>*/} {/*</BootstrapTable>*/} </div> ); }; }
JavaScript
class TextRendererCanvas extends TextRenderer { /** @inheritDoc */ render(driver, session) { super.render(driver, session); driver.drawTexture(Renderer.getColoredTexture(this.texture, this.gameObject.mColor)); } }
JavaScript
class FormeAbstraite extends PIXI.Container { /** * Constructeur. * * @param {PIXI.Container} stage Scène sur laquelle la forme est affichée. * @param {float} x Position en abscisse sur la scène. * @param {float} y Position en ordonnées sur la scène. * @param {int} taille Epaisseur de la forme. * @param {String} couleur Couleur en héxadécimal de la forme. */ constructor(stage, x, y, taille, couleur) { super(); if(typeof(couleur) == 'undefined') { this.couleur = 0x000000; } else { this.couleur = couleur; } // Largeur d'un trait if(typeof(taille) == 'undefined') { this.taille = 3; } else { this.taille = taille; } this.stage = stage; this.stage.addChild(this); this.x = x+AG.DECALAGE_MAP;; this.y = y-AG.DECALAGE_MAP;; this.mouvement = new Mouvement(this); // A définir dans les sous classes pour obtenir les coordonnées du coin supérieur gauche de la forme. this.minX = null; // La plus petite valeur en x de la forme. this.minY = null; // La plus petite valeur en y de la forme. } /** * Supprime la forme. */ supprimer() { this.stage.removeChild(this); this.destroy(); } /** * @return La plus petite valeur en abscisse de la forme sur la scène. */ getMinX() { return this.minX; } /** * @return La plus petite valeur en ordonnées de la forme sur la scène. */ getMinY() { return this.minY; } /** * @return La largeur de la forme. */ getWidth() { return this.width - this.taille; } /** * @return La hauteur de la forme. */ getHeight() { return this.height - this.taille; } /** * @return La position de la forme en abscisses. */ getX() { return this.x - this.pivot.x; } /** * @return La position de la forme en ordonnées. */ getY() { return this.y - this.pivot.y; } /** * Modifie la position en abscisses de la forme. * * @param {float} x Nouvelle valeur en abscisses de la forme. */ setX(x) { this.x = x + this.pivot.x; } /** * Modifie la position en ordonnées de la forme. * * @param {float} y Nouvelle valeur en ordonnées de la forme. */ setY(y) { this.y = y + this.pivot.y; } /** * Modifie la position du centre de rotation de la forme. * * @param {float} x Nouveau x * @param {float} y Nouveau y */ setPivot(x, y) { let reelX = this.getX(); let reelY = this.getY(); this.pivot.x = x; this.pivot.y = y; // On doit ensuite modifie les coordonnées de la forme // car modifier le pivot affecte également la position de la forme. this.x = reelX + x; this.y = reelY + y; } /** * Applique une rotation sur la forme. * * @param {float} angle Valeur en degrés de la rotation à appliquer. */ rotation(angle) { this.angle = angle; } /** * Déplace la forme de façon relative. * * @param {float} x Déplace la forme de x en abscisses. * @param {float} y Déplace la forme de y en ordonnées. */ deplacer(x, y) { this.x += x; this.y += y; } }
JavaScript
class Plugins extends Component { render() { const { children, passThrough = false } = this.props; return ( <> <Context.Consumer> {context => { const plugins = this.getPlugins(context); const components = Object.entries(plugins).reduce( (cmps, [name, plugin]) => { const { Component, ...pluginProps } = plugin; cmps[name] = props => { return ( Component && ( <Component {...pluginProps} {...props} /> ) ); }; return cmps; }, {}, ); return ( <> {!passThrough ? this.renderPlugins(plugins) : null} {React.Children.map(children, Child => { return React.cloneElement(Child, { components, }); })} </> ); }} </Context.Consumer> </> ); } renderPlugins(plugins) { return Object.values(plugins).map(plugin => { const { Component, ...props } = plugin; return Component && <Component {...props} />; }); } getPlugins({ plugins, filter: providedFilter, mapper: providedMapper, sort: providedSort, }) { const { children, // to discard passThrough, // to discard zone, filter: localFilterOverride, mapper: localMapperOverride, sort: localSortOverride, ...otherProps } = this.props; let pluginFilter = _ => true; if (typeof providedFilter === 'function') { pluginFilter = providedFilter; } if (typeof localFilterOverride === 'function') { pluginFilter = localFilterOverride; } let pluginMapper = _ => _; if (typeof providedMapper === 'function') { pluginMapper = providedMapper; } if (typeof localMapperOverride === 'function') { pluginMapper = localMapperOverride; } let pluginSort = _ => 0; if (typeof providedSort === 'function') { pluginSort = providedSort; } if (typeof localSortOverride === 'function') { pluginSort = localSortOverride; } const PluginComponents = op .get(plugins, zone, []) .filter(pluginFilter) .map(pluginMapper) .sort(pluginSort) .reduce( ( PluginComponents, { id, component, path, paths, ...pluginProps }, ) => { let Component = component; let name = id; if (typeof component === 'string') { name = component; Component = Plugins.findComponent( component, path, paths, ); } PluginComponents[name] = { Component, id, key: id, ...pluginProps, ...otherProps, }; return PluginComponents; }, {}, ); return PluginComponents; } static findComponent(type, path, paths) { let search = [ { type, path: `${path}${type}`, }, ]; if (Array.isArray(paths)) { search = search.concat( paths.map(path => ({ type, path: `${path}${type}`, })), ); } const found = getComponents(search); let Component = null; if (found) { Component = found[type]; } return Component; } }
JavaScript
class ProcessSnapshotDataSource extends DataSource { constructor() { super(5 * 60 * 1000); } setExternalSnapshotData(containerInstanceId, hostName) { snapshotData.container = containerInstanceId; snapshotData['com.instana.plugin.host.name'] = hostName; this._refresh(); } doRefresh(callback) { process.nextTick(() => callback(null, snapshotData)); } }
JavaScript
class SecretDetail extends Component { componentDidMount(){ let paramID = this.props.match.params.id; this.props.getSecret(paramID); //get the secret from the server: // let secret = this.props.secrets.filter( elem => elem.id === paramID) // console.log("hardcoded",this.props.secrets[15]); // console.log("secrets",this.props.secrets.filter(el => el.id === 15)); // this.setState({ // secret: secret // }) } render() { console.log('In Secret detail', this.props) if (!this.props.secret.id){ return( <div className = "loading"> <h3>Loading... </h3> </div> ) } return( <div className = "detail"> <h2>{this.props.secret.title} <Badge variant="secondary"> <Likes secret={this.props.secret}/></Badge></h2> <h3>{this.props.secret.content} </h3> <hr></hr> <Comments commentContent={this.props.secret.comments} theSecret={this.props.secret}/> </div> ) } }
JavaScript
class AddressSearch{ /** * Creates an instance of AddressSearch * and checks for invalid parameters * @param {(Element|String)} target The input targeted by the AddressSearch module * @param {Object} [parameters] Additional optional parameters * @param {Object} [delay] Delay to wait between keypresses before calling the API */ constructor(target, parameters = {}, delay){ /** @private */ this._input = target instanceof Element ? target : document.querySelector(target); /** @private */ this._errors = []; //Errors checking if(!this._input){ this._errors.push('AddressSearch: '+(typeof target == 'string' ? 'The selector `'+target+'` didn\'t match any element.' : 'The element you provided was undefined')); } if(this._input && this._input.classList.contains('address-search-input')){ this._errors.push('AddressSearch: The element has already been initialized.'); } if(!this._errors.length){ // GOOD TO GO ! /** @type {Number} */ this.uniqueId = document.querySelectorAll('.address-search[data-unique-id]').length + 1; /** @private */ this._fetchPredictions = new google.maps.places.AutocompleteService(); /** @private */ this._fetchPlace = new google.maps.places.PlacesService(document.createElement('div')); /** @private */ this._token = ''; /** @private */ this._usedTokens = []; /** @private */ this._economizer = {}; /** @private */ this._lure = this._input.cloneNode(true); /** @private */ this._onSelect = []; /** @private */ this._onPredict = []; /** @private */ this._onError = []; /** @private */ this._parameters = parameters; /** @private */ this._delay = delay; /** @private */ this._lastKeypress = null; /** @private */ this._timeout = null; /** @private */ this._apiFields = ['address_component', 'adr_address', 'alt_id', 'formatted_address', 'geometry', 'icon', 'id', 'name', 'business_status', 'photo', 'place_id', 'plus_code', 'scope', 'type', 'url', 'utc_offset_minutes', 'vicinity']; /** @type {PlaceResult} */ this.value = {}; /** @private */ this._components = Object.entries(this._parameters).reduce((acc, [component, target]) => { const targetElement = document.querySelector(target); if(targetElement){ acc[component] = targetElement; }else{ console.warn('The selector `'+target+'` didn\'t match any element.'); } return acc; }, {}); this._generateToken(); this._build(); this._listen(); }else{ this._errors.forEach(error => { console.warn(error); }); } } /** * Builds the AddressSearch DOM Tree around the element * @private */ _build(){ this._wrapper = document.createElement('div'); this._wrapper.classList.add('address-search'); this._wrapper.setAttribute('data-unique-id', this.uniqueId); this._input.parentNode.insertBefore(this._wrapper, this._input); this._typeahead = document.createElement('input'); this._typeahead.setAttribute('class', this._input.getAttribute('class')); this._typeahead.setAttribute('tabindex', -1); this._typeahead.classList.add('address-search-typeahead'); let typeaheadLure = this._typeahead.cloneNode(true); typeaheadLure.classList.add('lure'); this._wrapper.appendChild(typeaheadLure); this._wrapper.appendChild(this._typeahead); this._lure.classList.add('address-search-lure'); this._lure.setAttribute('tabindex', -1); this._wrapper.appendChild(this._lure); this._input.classList.add('address-search-input'); this._input.removeAttribute('id'); this._input.removeAttribute('name'); this._wrapper.appendChild(this._input); this._predictions = document.createElement('ul'); this._predictions.classList.add('address-search-predictions'); this._wrapper.appendChild(this._predictions); // Add lures to every component Object.values(this._components).forEach(element => { let lure = element.cloneNode(true); lure.removeAttribute('id'); lure.removeAttribute('class'); lure.removeAttribute('name'); lure.classList.add('address-search-lure'); lure.setAttribute('data-refer-to', this.uniqueId); lure.setAttribute('tabindex', -1); element.parentNode.insertBefore(lure, element); }); } /** * Creates event listeners * @private */ _listen(){ this._input.addEventListener('input',() => { clearTimeout(this._timeout); this._lure.value = this._input.value; // Input not empty if(this._input.value.length){ this._input.value = this._capitalize(this._input.value); this._lure.value = this._input.value; // Clean typeahead on delay if(this._delay){ this._typeahead.value = ''; } if(this._economizer[this._input.value]){ this._predictions.innerHTML = this._economizer[this._input.value]; if(this._predictions.firstElementChild.getAttribute('data-place-description').startsWith(this._input.value)){ this._typeahead.value = this._predictions.firstElementChild.getAttribute('data-place-description'); }else{ this._typeahead.value = ''; } this._togglePredictions('on'); for(let callback of this._onPredict) callback.call(this,this._input.value,this._predictions); }else{ if(this._delay){ this._timeout = setTimeout(() => { this._getPredictions(); }, this._delay); }else{ this._getPredictions(); } } }else{ this._typeahead.value = ''; this._togglePredictions('off'); } this.value = {}; }); this._input.addEventListener('keydown', e => { let key = e.keyCode || e.which; if(key == 9 || key == 13){ //TAB || ENTER e.preventDefault(); if(this._input.value.length) this._select(this._predictions.firstElementChild.getAttribute('data-place-id')); else this._input.blur(); } }); this._input.addEventListener('blur',() => { if(Object.keys(this.value).length === 0 && this.value.constructor === Object){ setTimeout(() => { this._input.value = ''; this._lure.value = this._input.value; this._typeahead.value = ''; this._togglePredictions('off'); },1); } }); this._predictions.addEventListener('mousedown', e => { this._predictions.classList.add('clicked'); }); this._predictions.addEventListener('click', e => { this._predictions.classList.remove('clicked'); if(e.target && (e.target.nodeName == 'LI' || e.target.nodeName == 'SPAN')){ let li = e.target.closest('li'); this._select(li.getAttribute('data-place-id')) } }); } /** * Gets the predictions from the API * @private */ _getPredictions(){ this._fetchPredictions.getPlacePredictions({ input: this._input.value, sessiontoken: this._token }, (predictions, status) => { this._resetPredictions(); if(status == google.maps.places.PlacesServiceStatus.OK){ for(let prediction of predictions){ let li = document.createElement('li'); li.setAttribute('data-place-id', prediction.place_id); li.setAttribute('data-place-description', this._capitalize(prediction.description).replace(/"/g,"'")); let mainText = document.createElement('span'); mainText.innerText = prediction.structured_formatting.main_text; li.appendChild(mainText); if(prediction.structured_formatting.secondary_text){ let secondaryText = document.createElement('span'); secondaryText.innerText = prediction.structured_formatting.secondary_text; li.appendChild(secondaryText); } this._predictions.appendChild(li); } this._economizer[this._input.value] = this._predictions.innerHTML; if(this._capitalize(predictions[0].description.substring(0, predictions[0].matched_substrings[0].length)) == this._input.value){ this._typeahead.value = this._capitalize(predictions[0].description); }else{ this._typeahead.value = ''; } this._togglePredictions('on'); //onPredict callbacks for(let callback of this._onPredict) callback.call(this,this._input.value,this._predictions); }else{ if(status == 'ZERO_RESULTS'){ let li = document.createElement('li'); li.classList.add('empty-results'); li.innerText = 'No address found'; this._predictions.appendChild(li); this._typeahead.value = ''; }else{ console.log(status); } } }); } /** * Empty the predictions * @private */ _resetPredictions(){ this._predictions.innerHTML = ''; } /** * Toggles the predictions * @private */ _togglePredictions(state){ if(state){ if(state == 'on') this._predictions.classList.add('shown'); else this._predictions.classList.remove('shown'); }else this._predictions.classList.toggle('shown'); } /** * Capitalize a String * @private */ _capitalize(str){ return str.charAt(0).toUpperCase() + str.slice(1); } /** * Handles a place selection * @param {String} placeId The place ID * @param {Boolean} [triggerCallbacks=true] Should the method trigger the select callbacks? * @returns {Promise} - Resolves when the place has been selected * @private */ _select(placeId, triggerCallbacks = true){ return new Promise((resolve, reject) => { this._fetchPlace.getDetails({placeId: placeId, fields: this._apiFields, sessiontoken: this._token}, (place, status) => { if(status == google.maps.places.PlacesServiceStatus.OK){ this._generateToken(); this._togglePredictions('off'); this._resetPredictions(); this.value = place; this._input.value = place.formatted_address; this._lure.value = this._input.value; this._typeahead.value = ''; Object.entries(this._components).forEach(([component, element]) => { let value = component.endsWith('_short') ? this._getPlaceComponent(component.slice(0, -6), true) : this._getPlaceComponent(component); element.value = value; element.previousElementSibling.value = value; element.readOnly = !!element.value.length; }); this._input.blur(); //onSelect callbacks if(triggerCallbacks){ for(let callback of this._onSelect) callback.call(this,this.value); } resolve(); }else{ console.log(status); for(let callback of this._onError) callback.call(this,status); reject(status); } }); }); } /** * Get a component for the current place. * @private */ _getPlaceComponent(component,isShort){ let target = this.value.address_components.filter(c => c.types.includes(component)); if(target.length){ return isShort ? target[0].short_name : target[0].long_name }else return ''; } /** * Generate a new unique token for Google Places API * @private */ _generateToken(){ let newToken = this._token; while(newToken == '' || this._usedTokens.includes(newToken)){ newToken = (Math.random() + 1).toString(36).substring(7); } this._token = newToken; this._usedTokens.push(this._token); } /** * Function called after a selection. * Using <code>this</code> inside it will return the current {@link AddressSearch} * * @callback onSelectCallback * @param {PlaceResult} address The selected address */ /** * Adds a callback to be used when the user selects an address * @param {onSelectCallback} callback Function to call after the user's selection * @returns {AddressSearch} The current {@link AddressSearch} */ onSelect(callback){ if(!this._errors.length) this._onSelect.push(callback); return this; } /** * Removes every callback previously added with {@link AddressSearch#onSelect} * @returns {AddressSearch} The current {@link AddressSearch} */ offSelect(){ if(!this._errors.length) this._onSelect = []; return this; } /** * Function called after a prediction. * Using <code>this</code> inside it will return the current {@link AddressSearch} * * @callback onPredictCallback * @param {String} value The user's input * @param {HTMLUListElement} predictions The predictions UL element */ /** * Adds a callback to be used when predictions are displayed * @param {onPredictCallback} callback Function to call after predictions * @returns {AddressSearch} The current {@link AddressSearch} */ onPredict(callback){ if(!this._errors.length) this._onPredict.push(callback); return this; } /** * Removes every callback previously added with {@link AddressSearch#onPredict} * @returns {AddressSearch} The current {@link AddressSearch} */ offPredict(){ if(!this._errors.length) this._onPredict = []; return this; } /** * Function called after an error. * Using <code>this</code> inside it will return the current {@link AddressSearch} * * @callback onErrorCallback * @param {Object} error The error */ /** * Adds a callback to be used when an error occurs * @param {onErrorCallback} callback Function to call after an error * @returns {AddressSearch} The current {@link AddressSearch} */ onError(callback){ if(!this._errors.length) this._onError.push(callback); return this; } /** * Removes every callback previously added with {@link AddressSearch#onError} * @returns {AddressSearch} The current {@link AddressSearch} */ offError(){ if(!this._errors.length) this._onError = []; return this; } /** * Manually sets the AddressSearch value * @param {String|PlaceResult} value New value * @param {Boolean} [triggerCallbacks=true] Should the method trigger the select callbacks? */ setValue(value, triggerCallbacks = true){ if(!this._errors.length){ if(typeof value === 'string'){ this._fetchPredictions.getPlacePredictions({ input: value }, (predictions, status) => { if(status == google.maps.places.PlacesServiceStatus.OK){ let prediction = predictions[0]; this._select(prediction.place_id, triggerCallbacks); }else{ console.log(status); for(let callback of this._onError) callback.call(this,status); } }); }else{ this.value = value; this._input.value = value.formatted_address; this._lure.value = this._input.value; this._typeahead.value = ''; } } } /** * Manually sets the AddressSearch value via a `place_id` * @param {Integer} place_id New place_id * @param {Boolean} [triggerCallbacks=true] Should the method trigger the select callbacks? * @returns {Promise} - Resolves when the place has been set */ setPlace(place_id, triggerCallbacks = true){ if(!this._errors.length){ return this._select(place_id, triggerCallbacks); }else{ return Promise.resolve(); } } /** * Resets the AddressSearch * @returns {AddressSearch} The current {@link AddressSearch} */ reset(){ if(!this._errors.length){ this.value = {}; this._input.value = ''; this._lure.value = ''; this._typeahead.value = ''; } return this; } /** * Refreshes the Google API fetchers * @returns {AddressSearch} The current {@link AddressSearch} */ refreshService(){ if(!this._errors.length){ this._fetchPredictions = new google.maps.places.AutocompleteService(); this._fetchPlace = new google.maps.places.PlacesService(document.createElement('div')); this._economizer = {}; } return this; } /** * Use a different 'google' object to fetch data * @param {Object} googleService - The service to use * @returns {AddressSearch} The current {@link AddressSearch} */ useService(googleService){ if(!this._errors.length){ this._fetchPredictions = googleService.maps.places.AutocompleteService(); this._fetchPlace = googleService.maps.places.PlacesService(document.createElement('div')); this._economizer = {}; } return this; } /** * Manually set which fields should be returned by the Google Places API * @param {String[]} fieldList List of field names * @returns {AddressSearch} The current {@link AddressSearch} */ setFields(fieldList){ this._apiFields = fieldList; return this; } /** * Removes any AddressSearch mutation from the DOM */ destroy(){ if(!this._errors.length){ if(this._lure.id) this._input.setAttribute('id',this._lure.id); if(this._lure.getAttribute('name')) this._input.setAttribute('name',this._lure.getAttribute('name')); this._input.parentNode.parentNode.insertBefore(this._input, this._wrapper); this._wrapper.remove(); this._input.classList.remove('address-search-input'); document.querySelectorAll('.address-search-lure[data-refer-to="'+this.uniqueId+'"]').forEach(lure => lure.remove()); //Remove event listeners let cleanInput = this._input.cloneNode(true); this._input.parentNode.replaceChild(cleanInput, this._input); } } /** * Removes any AddressSearch mutation from the DOM * @param {String} selector The AddressSearch input selector * @static */ static destroy(selector){ let lure = document.querySelector(selector); // If it exists if(lure){ let element = lure.nextElementSibling; // If it has been initialized as an AddressSearch if(element && element.matches('.address-search-input')){ // Remove outside lures let id = element.closest('.address-search[data-unique-id]').getAttribute('data-unique-id'); document.querySelectorAll('.address-search-lure[data-refer-to="'+id+'"]').forEach(lure => lure.remove()); if(lure.id) element.setAttribute('id',lure.id); if(lure.getAttribute('name')) element.setAttribute('name',lure.getAttribute('name')); element.parentNode.parentNode.insertBefore(element, element.parentNode); element.nextElementSibling.remove(); element.classList.remove('address-search-input'); //Remove event listeners let cleanInput = element.cloneNode(true); element.parentNode.replaceChild(cleanInput, element); } } } }
JavaScript
class DesktopMenu { constructor () { this.dateFormat = {year: 'numeric', month: 'numeric', day: 'numeric'} this.timeFormat = {hour: '2-digit', minute: '2-digit'} } /** * Initilize the class * @memberof DesktopMenu */ init () { setInterval(() => { this.updateClock() }, 1000) let li = document.querySelectorAll('ul li') li.forEach(current => { current.addEventListener('click', event => this.handleClick(event)) }) } /** * Updates clock * @memberof DesktopMenu */ updateClock () { let date = new Date() let currentDate = date.toLocaleDateString('sv-se', this.dateFormat) let currentTime = date.toLocaleTimeString('sv-se', this.timeFormat) let dateElem = document.querySelector('.date') let timeElem = document.querySelector('.time') dateElem.textContent = currentDate timeElem.textContent = currentTime } /** * Handels click and opens right app depending on click target * @param {object} event mouse event * @memberof DesktopMenu */ handleClick (event) { switch (event.target.getAttribute('value')) { case 'Memory': // Creats the window this.win = document.createElement('basic-window') document.querySelector('#container').appendChild(this.win) // Creates the application to appen to window this.app = document.createElement('memory-board') this.win.shadowRoot.querySelector('#content').appendChild(this.app) this.win.setAttribute('value', 'win') // Adds icon and title this.img = this.win.shadowRoot.querySelector('.window-top').childNodes[1] this.img.innerHTML = '<img src="image/memory-mini.png" alt="memory">' this.title = this.img.nextSibling this.title.textContent = 'Memory' break case 'Chat': this.win = document.createElement('basic-window') document.querySelector('#container').appendChild(this.win) this.app = document.createElement('chat-element') this.win.shadowRoot.querySelector('#content').appendChild(this.app) this.win.setAttribute('value', 'win') this.img = this.win.shadowRoot.querySelector('.window-top').childNodes[1] this.img.innerHTML = '<img src="image/chat_icon-mini.png" alt="memory">' this.title = this.img.nextSibling this.title.textContent = 'Chat' break case 'Canvas': this.win = document.createElement('basic-window') document.querySelector('#container').appendChild(this.win) this.app = document.createElement('drawing-canvas') this.win.shadowRoot.querySelector('#content').appendChild(this.app) this.win.setAttribute('value', 'win') this.img = this.win.shadowRoot.querySelector('.window-top').childNodes[1] this.img.innerHTML = '<img src="image/canvas-mini.png" alt="memory">' this.title = this.img.nextSibling this.title.textContent = 'Canvas' } } }
JavaScript
class CircleToCirclePair extends Pair { /** * Creates new instance of CircleToCirclePair. */ constructor() { super(); /** * Collider from body a. * @public * @type {black-engine~CircleCollider|null} */ this.a = null; /** * Collider from body b. * @public * @type {black-engine~CircleCollider|null} */ this.b = null; } /** * Setter * * @public * * @param {black-engine~CircleCollider} a Pair circle collider * @param {black-engine~CircleCollider} b Pair circle collider * @param {black-engine~RigidBody} bodyA Pair body * @param {black-engine~RigidBody} bodyB Pair body * * @return {Pair} This */ set(a, b, bodyA, bodyB) { this.a = a; this.b = b; this.bodyA = bodyA; this.bodyB = bodyB; return this; } /** * @inheritDoc */ test() { const a = this.a; const b = this.b; const offsetX = b.mCenter.x - a.mCenter.x; const offsetY = b.mCenter.y - a.mCenter.y; const totalRadius = a.mRadius + b.mRadius; if (offsetX === 0 && offsetY === 0) { this.mOverlap = totalRadius; this.mNormal.set(1, 0); return this.mInCollision = true; } const totalRadiusSq = totalRadius * totalRadius; const distanceSq = offsetX * offsetX + offsetY * offsetY; if (distanceSq > totalRadiusSq) { return this.mInCollision = false; } const dist = Math.sqrt(distanceSq); this.mOverlap = totalRadius - dist; this.mNormal.set(offsetX / dist, offsetY / dist); return this.mInCollision = true; } static get pool() { if (pool === null) pool = new ObjectPool(CircleToCirclePair, 100); return pool; } }
JavaScript
class Utils { /** * typeOf * * @example * // returns string * Utils.typeOf('hello'); * @example * // returns number * Utils.typeOf(123); * * @static * @return string */ static typeOf (value) { return this.rawType(value).replace(/^\[object (\w+)]$/, '$1').toLowerCase() } /** * isString * * @example * // returns true * Utils.isString('hello'); * @example * // returns false * Utils.isString(123); * * @static * @return boolean */ static isString (value) { return typeof value === 'string' } /** * hasValue * * @static * @param {string} params - A string. */ static hasValue (params) { return params.length === 2 } /** * rawType * * @static */ static rawType (value) { return Object.prototype.toString.call(value) } /** * is * * @example * // returns true * Utils.is('object', {}); * @example * // returns false * Utils.is('object', []); * * @static * @return {Boolean} */ static is (...params) { const [typeToTest, value] = params if (!this.isString(typeToTest)) { throw new TypeError('typeToTest must be a string') } if (!this.hasValue(params)) { return (value) => this.is(typeToTest, value) } const type = typeToTest.replace(/^\w/, (l) => l.toUpperCase()) return this.rawType(value) === `[object ${type}]` } }
JavaScript
class ListView { constructor(superview) { this.superview = superview; } // BUILDER /** * Constructs a HTML div with the given text. * @public * @method ListView#listItemDiv */ listItemDiv(text, opts = {}) { var css = (opts && opts.class ? opts.class : null); var help = (opts && opts.help ? opts.help : null); var d = ViewUtils.div(css, text, opts); if (help) { this.addHelp(help, d); } return d; } /** * Constructs a HTML list item with the given text. * @public * @method ListView#listItem */ listItem(text, opts) { return $('<li>').append(this.listItemDiv(text, opts)); } /** * Constructs a HTML list item with both of the given texts. * @public * @method ListView#listItem2 */ listItem2(text1, opts1, text2, opts2) { return $('<li>').append(this.listItemDiv(text1, opts1)).append(this.listItemDiv(text2, opts2)); } /** * Constructs a HTML div with the given key and value. * @public * @method ListView#listKeyValueDiv */ listKeyValueDiv(key, value, opts) { var css = (opts && opts.class ? opts.class : null); var help = (opts && opts.help ? opts.help : null); var d = ViewUtils.div2(css, key, value, opts); if (help) { this.addHelp(help, d); } return d; } /** * Constructs a HTML list item with the key and value. * @public * @method ListView#listKeyValue */ listKeyValue(key, value, opts) { return $('<li>').append(this.listKeyValueDiv(key, value, opts)); } // HELP addHelp(key, container) { let a = $('<a>', {'class': 'help'}); a.fastClick(this.superview.showListHelp.bind(this.superview, key)); container.append(a); return a; } }
JavaScript
class RequestTracker { /** * Invoked each time a query or batch request succeeds. * @param {Host} host The node that acted as coordinator of the request. * @param {String|Array} query In the case of prepared or unprepared query executions, the provided * query string. For batch requests, an Array containing the queries and parameters provided. * @param {Array|Object|null} parameters In the case of prepared or unprepared query executions, the provided * parameters. * @param {ExecutionOptions} executionOptions The information related to the execution of the request. * @param {Number} requestLength Length of the body of the request. * @param {Number} responseLength Length of the body of the response. * @param {Array<Number>} latency An array containing [seconds, nanoseconds] tuple, where nanoseconds is the * remaining part of the real time that can't be represented in second precision (see <code>process.hrtime()</code>). */ onSuccess(host, query, parameters, executionOptions, requestLength, responseLength, latency) { } /** * Invoked each time a query or batch request fails. * @param {Host} host The node that acted as coordinator of the request. * @param {String|Array} query In the case of prepared or unprepared query executions, the provided * query string. For batch requests, an Array containing the queries and parameters provided. * @param {Array|Object|null} parameters In the case of prepared or unprepared query executions, the provided * parameters. * @param {ExecutionOptions} executionOptions The information related to the execution of the request. * @param {Number} requestLength Length of the body of the request. When the failure occurred before the request was * written to the wire, the length will be <code>0</code>. * @param {Error} err The error that caused that caused the request to fail. * @param {Array<Number>} latency An array containing [seconds, nanoseconds] tuple, where nanoseconds is the * remaining part of the real time that can't be represented in second precision (see <code>process.hrtime()</code>). */ onError(host, query, parameters, executionOptions, requestLength, err, latency) { } /** * Invoked when the Client is being shutdown. */ shutdown() { } }
JavaScript
class TaskDependency { /** * @param {Task} depender * @param {Dependee} dependee * @param {string} [name] */ constructor(depender, dependee, name = null) { this._depender = InvalidType.check(depender, Task) this._dependee = InvalidType.check(dependee, Task, Promise, 'function', 'string'); if (name === null) { if (dependee instanceof Task) this._name = dependee.displayName; else if (typeof dependee === 'string') this._name = dependee; else this._name = ''; } else this._name = String(name); this._resol = local.INITIAL; this._error = local.INITIAL; } /** * The name of this dependency * @type {string} * @readonly */ get name() { return this._name; } /** * Whether this dependency has been resolved * @type {boolean} * @readonly */ get isResolved() { return this._resol !== local.INITIAL; } /** * Whether this dependency has encountered an error while resolving itself * @type {boolean} * @readonly */ get hasError() { return this._error !== local.INITIAL; } /** * The resolution of the dependency * @type {any} * @readonly */ get resol() { if (this.hasError) throw new Exception(`${this.expr} has an error`); if (!this.isResolved) throw new Exception(`${this.expr} is not resolved`); return this._resol; } /** * The error that this dependency encountered while resolving itself * @type {any} * @readonly */ get error() { return this.hasError ? this._error : null; } /** * @ignore */ get expr() { return this.name ? `the dependency '${this.name}'` : `an anonymous dependency`; } /** * Tries to resolve the dependency and returns a `Promise` object * @return {Promise} */ resolve() { let r; if (this._dependee instanceof Task) r = this._dependee(); else if (this._dependee instanceof Promise) r = this._dependee; else if (typeof this._dependee === 'function') r = new Promise(this._dependee); else if (typeof this._dependee === 'string') { let manager = this._depender.manager; if (!manager) throw new Exception(`the task ${this._depender.label} is not registered`); let task = manager.get(this._dependee); if (!task) throw new Exception(`no such task as '${this._dependee}'`); r = task(); } else throw new InvalidType.failed(this._dependee, Task, Promise, 'function', 'string'); return r.then(resol => { this._resol = resol; return resol; }, err => { this._error = err; throw err; }); } }
JavaScript
class LinkedListNode { /** * @description class constructor */ constructor(value, next = null) { this.value = value; this.next = next; } /** * @public method * @description convert linked list node to string * @param {function} [callback] * @return {LinkedListNode} */ toString(callback) { return callback ? callback(this.value) : `${this.value}`; } }
JavaScript
class Alert { /** * Creates a new Alert instance with the specified message and title. * * @param message The message to show on the alert * @param title The title to show on the alert * @param type Can be 'success', 'info', 'warning', 'error' or '' */ constructor(message, title = '', type = '') { this.type = type; this.message = message; this.title = title; this.dangerMode = type === 'error' || type === 'warning'; } /** * Shows a simple self-disappearing alert message. Does not automatically disappear if a button text is set. * * @param buttonText * @param timer * @returns {Promise} */ show(buttonText = false, timer = 3000) { if (this.type === 'error') { timer = null; buttonText = "Ok"; } return new Promise((resolve) => { swal({ title: this.title, text: this.message, icon: this.type, dangerMode: this.dangerMode, timer: timer, button: buttonText }).then(() => { resolve(); }); }); } /** * Shows a confirm alert with the specified confirm and cancel button texts. * * @param buttonText * @param cancelButtonText */ confirm(buttonText = true, cancelButtonText = true) { return new Promise((resolve) => { swal({ title: this.title, text: this.message, icon: this.type, dangerMode: this.dangerMode, buttons: [cancelButtonText, buttonText], }).then((value) => { swal.close(); resolve(value); }); }); } /** * Shows an input alert with the specified confirm and cancel button texts. * * @param buttonText * @param cancelButtonText * @param placeholder * @param type * @param value */ ask(buttonText = true, cancelButtonText = true, placeholder = null, type = "text", value = null) { return new Promise((resolve) => { swal({ title: this.title, text: this.message, icon: this.type, content: { element: "input", attributes: { placeholder: placeholder, value: value, type: type } }, dangerMode: this.dangerMode, buttons: [cancelButtonText, buttonText], }).then((value) => { swal.close(); resolve(value); }); }); } /** * Shows a select input alert with the specified options, confirm and cancel button texts. * * @param options * @param buttonText * @param cancelButtonText * @param value * @param placeholder */ select(options, buttonText = true, cancelButtonText = true, value = null, placeholder = null) { let selectElement = document.createElement("select"); selectElement.className = "form-control"; if (placeholder !== null) { let option = document.createElement("option"); option.value = ''; option.selected = true; option.disabled = true; option.text = placeholder; selectElement.appendChild(option); } for (let key in options) { if (options.hasOwnProperty(key)) { let option = document.createElement("option"); option.value = key; option.text = options[key]; if (key === value) { option.selected = true; swal.setActionValue(key); } selectElement.appendChild(option); } } selectElement.addEventListener("change", function () { swal.setActionValue(selectElement.value); }); return new Promise((resolve) => { swal({ title: this.title, text: this.message, icon: this.type, content: selectElement, dangerMode: this.dangerMode, buttons: [cancelButtonText, buttonText], }).then((value) => { swal.close(); resolve(value); }); }); } /** * Shows a confirm alert with the specified confirm and cancel button texts. * If the confirm button is clicked, an ajax request to the specified url with the specified method and data will be sent. * * @param url * @param method * @param data * @param buttonText * @param cancelButtonText */ send(url, method, data, buttonText = 'Ok', cancelButtonText = true) { return new Promise((resolve, reject) => { swal({ title: this.title, text: this.message, icon: this.type, dangerMode: this.dangerMode, buttons: { cancel: cancelButtonText, confirm: { text: buttonText, closeModal: false } }, }).then((value) => { if (value) { $.ajax({ type: method.toLowerCase(), url: url, data: data, success: response => { this.showAlert(response, true).then(() => { resolve(response); }); }, error: error => { this.showAlert(error.responseJSON, false).then(() => { reject(error.responseJSON); }); } }).always(() => { swal.stopLoading(); }); } else { swal.close(); reject(value); } }); }); } /** * Shows an alert based on the specified server response and success field. * * @param response * @param success * @returns {Promise} */ showAlert(response, success = true) { return new Promise((resolve) => { let serverKeys = { showAlert: 'alert', alert: { title: 'title', message: 'message', accept: 'accept', duration: 'duration' }, redirect: 'redirect', reload: 'reload', data: 'data', error: 'error' }; let message = null; let title = ''; let accept = false; let duration = 3000; if (response && response.hasOwnProperty(serverKeys.showAlert) && response[serverKeys.showAlert].hasOwnProperty(serverKeys.alert.message)) { let alertInfo = response[serverKeys.showAlert]; message = alertInfo[serverKeys.alert.message]; if (alertInfo.hasOwnProperty(serverKeys.alert.title)) { title = alertInfo[serverKeys.alert.title]; } if (alertInfo.hasOwnProperty(serverKeys.alert.accept)) { accept = alertInfo[serverKeys.alert.accept]; } if (alertInfo.hasOwnProperty(serverKeys.alert.duration)) { duration = alertInfo[serverKeys.alert.duration]; } } else if (!success) { title = 'Sorry!'; message = 'An unknown error occurred! Please try again later.'; accept = 'Ok!'; // Check for Laravel >= 5.5 validation errors if (response && response.hasOwnProperty('errors')) { // Get the first validation error to show on the alert message = response.errors[Object.keys(response.errors)[0]]; // Check for custom error message from server } else if (response && response.hasOwnProperty(serverKeys.error)) { message = response[serverKeys.error]; // Check for Laravel HTTP Exception error message } else if (response && response.hasOwnProperty('message')) { message = response['message']; } } if (message) { new Alert(message, title, success ? 'success' : 'error').show(accept, accept ? null : duration).then(() => { resolve(); }); } else { resolve(); } }); } }
JavaScript
class Client extends abstract_client_1.AbstractClient { constructor(clientConfig) { super("bri.tencentcloudapi.com", "2019-03-28", clientConfig); } /** * 输入业务名 (bri_num, bri_dev, bri_ip, bri_apk, bri_url, bri_social 六种之一) 及其 相应字段, 获取业务风险分数和标签。 当业务名为bri_num时,必须填PhoneNumber字段. 当业务名为bri_dev时, 必须填Imei字段. 当业务名为bri_ip时,必须填IP字段. 当业务名为bri_apk时,必须填 (PackageName,CertMd5,FileSize) 三个字段 或者 FileMd5一个字段. 当业务名为bri_url时,必须填Url字段. 当业务名为bri_social时,必须填QQ和Wechat字段两者其中一个或者两个. */ async DescribeBRI(req, cb) { return this.request("DescribeBRI", req, cb); } }
JavaScript
class PageTree { /** * Create a new Tree page object. * @constructor * @param {string} rootElement - The selector of the Tree root element. */ constructor(rootElement) { this.rootElement = rootElement; } /** * Returns a new Node page object of the element in item position. * @method * @param {number} itemPosition - The base 0 index of the Node. */ getNode(itemPosition) { const items = $(this.rootElement).$$('[data-id="node-element-li"]'); if (items[itemPosition]) { return new PageNodeItem( `${this.rootElement} [data-id="node-element-li"]:nth-child(${itemPosition + 1})`, ); } return null; } }
JavaScript
class Handler { /** * Constructor for a new Handler instance. * * @param {Object} input * @param {boolean} [input.waitOnCache] For handlers that write to the cache, * `true` means the method should wait for the `cache.put()` call to * complete before returning. The default value of `false` means * return without waiting. It this value is true and the response * can't be cached, an error will be thrown. * @param {module:workbox-runtime-caching.RequestWrapper} * [input.requestWrapper] An optional `RequestWrapper` that is used to * configure the cache name and request plugins. If not provided, a * new `RequestWrapper` using the [default cache name](#getDefaultCacheName) * will be used. */ constructor({requestWrapper, waitOnCache} = {}) { if (requestWrapper) { this.requestWrapper = requestWrapper; } else { this.requestWrapper = new RequestWrapper(); } this.waitOnCache = Boolean(waitOnCache); } /** * An abstract method that each subclass must implement. * * @abstract * @param {Object} input * @param {FetchEvent} input.event The event that triggered the service * worker's fetch handler. * @param {Object} [input.params] Additional parameters that might be passed * in to the method. If used in conjunction with the * {@link module:workbox-routing.Route|Route} class, then the return * value from the `match` function in the Route constructor * will be passed in as the `params` value. * @return {Promise.<Response>} A promise resolving with a response. */ handle({event, params} = {}) { throw Error('This abstract method must be implemented in a subclass.'); } }
JavaScript
class CashOut extends Component { constructor() { super(); this.state = { formOpen: false, resultsMessage: '' }; } async componentWillMount() { await this.props.getUserBalance(); } componentWillReceiveProps(nextProps) { if (nextProps.unlistOrderError !== 'null') { this.setState({ resultsMessage: `Error: ${this.props.cashOutError}`, formOpen: false }); } else if (this.props.unlistOrderTx) { this.setState({ resultsMessage: `Tx receipt: ${this.props.cashOutTx}`, formOpen: false }); } } // Toggle form visibility on button click toggleFormVisibility() { this.setState({ collapse: !this.state.collapse }); } render() { return ( <div className="container"> <div className="user-balance"> Your Balance: {this.props.userBalance} </div> <div id="cashout-button"> <button className="btn btn-info" onClick={this.toggleFormVisibility}> Cash Out </button> </div> <Collapse isOpen={this.state.collapse}> <div id="cashout-form"> <h4 className="center-text">Cash Out Request</h4> <CashOutFormContainer /> </div> </Collapse> {this.state.resultsMessage && ( <div id="results-message" className="text-center"> {this.state.resultsMessage} </div> )} </div> ); } }
JavaScript
class MotionCorrectionModule extends BaseModule { constructor() { super(); this.name = 'motionCorrection'; this.JSOnly=true; this.useworker=true; } getDescription() { let des={ "name": "Motion Correction", "description": "Runs motion correction", "author": "Michelle Lim", "version": "1.0", "buttonName": "Execute", "shortname" : "mot", "inputs": baseutils.getRegistrationInputs(), "outputs" : baseutils.getRegistrationOutputs(), "params": baseutils.getRegistrationParams() }; des.params.push({ "name": "Reference Frame Number", "description": "Frame number of reference image used for linear registration", "priority": 12, "advanced": false, "gui": "slider", "type": "int", "varname": "refno", "default" : 0, }); baseutils.setParamDefaultValue(des.params,'metric','CC'); baseutils.setParamDefaultValue(des.params,'numbins',1024); baseutils.setParamDefaultValue(des.params,'steps',4); baseutils.setParamDefaultValue(des.params,'resolution',1.01); baseutils.setParamDefaultValue(des.params,'iterations',32); baseutils.setParamDefaultValue(des.params,'levels',3); baseutils.setParamDefaultValue(des.params,'stepsize',0.125); baseutils.setParamDefaultValue(des.params,'optimization',"HillClimb"); des.outputs[0].type="collection"; des.outputs[1].required=true; return des; } directInvokeAlgorithm(vals) { console.log('MotionCorrection invoking with vals', JSON.stringify(vals)); return new Promise( (resolve, reject) => { let target = this.inputs['target']; let reference = this.inputs['reference'] || 0; if (reference===0) reference=target; if (!reference.hasSameOrientation(target,'reference image','target image',true)) { reject('Failed'); return; } biswrap.initialize().then(() => { //Open input file this.outputs['output'] = this.run_registrations(vals, reference, target, parseInt(vals.refno)); //Run Reslicing on InputImage using matrices this.outputs['resliced'] = this.runReslice(target, this.outputs['output']); resolve(); }).catch( (e) => { reject(e.stack); }); }); } // Get a Single Frame getFrame(InputImage,frame) { return smoothreslice.imageExtractFrame(InputImage,frame); } run_registrations(vals, ReferenceImage, InputImage, refno = 0) { let RefFrameImage = smoothreslice.imageExtractFrame(ReferenceImage,refno); let dimensions = InputImage.getDimensions(); let numframes = dimensions[3]; let matrices=new BisWebDataObjectCollection(); for (let frame = 0; frame < numframes; frame++) { let debug=false; if (frame===1) debug=true; let InputFrame = this.getFrame(InputImage,frame); let xform = biswrap.runLinearRegistrationWASM(RefFrameImage, InputFrame, 0, { 'intscale' : parseInt(vals.intscale), 'numbins' : parseInt(vals.numbins), 'levels' : parseInt(vals.levels), 'smoothing' : parseFloat(vals.imagesmoothing), 'optimization' : baseutils.getOptimizationCode(vals.optimization), 'stepsize' : parseFloat(vals.stepsize), 'metric' : baseutils.getMetricCode(vals.metric), 'normalize' : this.parseBoolean(vals.norm), 'steps' : parseInt(vals.steps), 'iterations' : parseInt(vals.iterations), 'mode' : baseutils.getLinearModeCode(vals.mode), 'resolution' : parseFloat(vals.resolution), 'return_vector' : "true", 'debug' : debug, }, debug); if (frame%25 ===0) console.log('++++ Done with frame',frame,' p=('+xform.getParameterVector({scale:true}).join(" ")+')'); matrices.addItem(xform, { "frame": frame}); } return matrices; } runReslice(inputimage, matrices ) { let output_image = new BisWebImage(); let dimensions = inputimage.getDimensions(); let spacing = inputimage.getSpacing(); let numframes=matrices.getNumberOfItems(); output_image.cloneImage(inputimage, { dimensions : dimensions, spacing : spacing, }); let volumesize = dimensions[0] * dimensions[1] * dimensions[2]; let outdata = output_image.getImageData(); for (let frame = 0; frame < numframes; frame++) { let InputFrame = this.getFrame(inputimage,frame); let resliceW = biswrap.resliceImageWASM(InputFrame, matrices.getItemData(frame), { "interpolation": 3, "dimensions": dimensions, "spacing": spacing }, 0); let inp_data = resliceW.getImageData(); let offset = frame * volumesize; for (let i = 0; i < volumesize; i++) outdata[i + offset] = inp_data[i]; if (frame%25 ===0) console.log('++++ Resliced frame',frame); } return output_image; } }
JavaScript
class StraightAttackAI extends AI { // eslint-disable-line no-unused-vars /** * Straight attack AI Constructor * @constructor * @param {number} maxVeocityX Maximum speed x vector * @param {number} maxVeocityY Maximum speed y vector * @param {number} movePowerX Force of x direction applied when moving * @param {number} movePowerY Force of y direction applied when moving */ constructor(maxVelocityX, maxVelocityY, movePowerX, movePowerY) { super(); /** * Maximum speed x vector * @protected * @type {number} */ this.maxVelocityX = maxVelocityX; /** * Maximum speed y vector * @protected * @type {number} */ this.maxVelocityY = maxVelocityY; /** * Force of x direction applied when moving * @protected * @type {number} */ this.movePowerX = movePowerX; /** * Force of x direction applied when moving * @protected * @type {number} */ this.movePowerY = movePowerY; /** * Owned entity * @protected * @type {Entity} */ this.actor = null; } /** * Initialize * @override */ init() { if (BaseUtil.implementsOf(this.entity, IOwned)) { this.actor = this.entity.getOwner(); } } /** * Apply AI and decide action * @override * @param {number} dt Delta time * @return {boolean} Whether decided on action */ apply(dt) { // move to actor if (this.entity.body.velocityX * this.entity.directionX < 0 || Math.abs(this.entity.body.velocityX) < Math.abs(this.maxVelocityX)) { this.entity.body.enforce(this.movePowerX * this.entity.material.mass * this.entity.directionX / dt, 0); } if (this.entity.body.velocityY * this.entity.directionY < 0 || Math.abs(this.entity.body.velocityY) < Math.abs(this.maxVelocityY)) { this.entity.body.enforce(0, this.movePowerY * this.entity.material.mass * this.entity.directionY / dt); } // If damageable object is collided, damage for (const it of this.entity.collider.collisions) { const entity = Util.getCollidedEntity(this.entity, it); if (this.actor === entity) { continue; } if (BaseUtil.implementsOf(entity, IDamagable)) { entity.damage(1); } // destroy if it is collided if (BaseUtil.implementsOf(this.entity, IBreakable)) { this.entity.destroy(); } } return true; } }
JavaScript
class Base { /** * @constructor */ constructor() { /** * @property Base.ts * @type {LibDateTime} */ this.ts = new LibDateTime(); /** * @property Base.gen * @type {LibGenerator} */ this.gen = new LibGenerator(); /** * @property Base.str * @type {LibString} */ this.str = new LibString(); /** * @property Base.num * @type {LibNumber} */ this.num = new LibNumber(); /** * @property Base.ua * @type {LibUserAgent} */ this.ua = new LibUserAgent(); /** * @property Base.hash * @type {LibHash} */ this.hash = new LibHash(); /** * @property Base.fn * @type {LibFunction} */ this.fn = new LibFunction(); /** * @property Base.array * @type {LibArray} */ this.array = new LibArray(); /** * @property Base.event * @type {LibEvent} */ this.event = new LibEvent(); /** * @property Base.css * @type {LibCss} */ this.css = new LibCss(); } /** * Get static method * @memberOf Base * @param {string|array} component * @return {boolean} */ getStatic(component) { /** * @property Base * @type {getType|*} */ const method = this.constructor[component]; if (!method) { return false; } return method; } /** * @method setBoolean * @memberOf Base * @param {boolean} instanceValue * @param {boolean} defaultValue * @return {boolean} */ setBoolean(instanceValue, defaultValue) { return typeof instanceValue === 'undefined' ? defaultValue : instanceValue; } /** * Get object type * @memberOf Base * @param obj * @returns {string} */ getType(obj) { return Object.prototype.toString.call(obj).match(/^\[object (.*)]$/)[1]; } /** * Check if uuid has uuid format * @memberOf Base * @param {string} uuid * @returns {Array|{index: number, input: string}|*} */ isUUID(uuid) { return uuid.match(/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i); } /** * Check if url * @memberOf Base * @param {string} [url] * @returns {Array|{index: number, input: string}|*} */ isUrl(url) { /** * Define regex * @type {RegExp} * https://gist.github.com/dperini/729294 */ this.isUrl.regex = new RegExp([ '^', // protocol identifier '(?:(?:https?|ftp)://)', // user:pass authentication '(?:\\S+(?::\\S*)?@)?', '(?:', // IP address exclusion // private & local networks '(?!(?:10|127)(?:\\.\\d{1,3}){3})', '(?!(?:169\\.254|192\\.168)(?:\\.\\d{1,3}){2})', '(?!172\\.(?:1[6-9]|2\\d|3[0-1])(?:\\.\\d{1,3}){2})', // IP address dotted notation octets // excludes loopback network 0.0.0.0 // excludes reserved space >= 224.0.0.0 // excludes network & broadcast addresses // (first & last IP address of each class) '(?:[1-9]\\d?|1\\d\\d|2[01]\\d|22[0-3])', '(?:\\.(?:1?\\d{1,2}|2[0-4]\\d|25[0-5])){2}', '(?:\\.(?:[1-9]\\d?|1\\d\\d|2[0-4]\\d|25[0-4]))', '|', // host name '(?:(?:[a-z\\u00a1-\\uffff0-9]-*)*[a-z\\u00a1-\\uffff0-9]+)', // domain name '(?:\\.(?:[a-z\\u00a1-\\uffff0-9]-*)*[a-z\\u00a1-\\uffff0-9]+)*', // TLD identifier '(?:\\.(?:[a-z\\u00a1-\\uffff]{2,}))', ')', // port number '(?::\\d{2,5})?', // resource path '(?:/\\S*)?', '$' ].join(''), 'i'); return url ? url.match(this.isUrl.regex) : url; } /** * Define isBase64 matcher * @memberOf Base * @param {string} s * @returns {boolean} */ isBase64(s) { /** * Define Base64 matcher * @type {RegExp} */ this.isBase64.regex = /^@(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/; return s ? !!this.isBase64.regex.test(s) : s; } /** * Detecting data URLs * data URI - MDN https://developer.mozilla.org/en-US/docs/data_URIs * The "data" URL scheme: http://tools.ietf.org/html/rfc2397 * Valid URL Characters: http://tools.ietf.org/html/rfc2396#section2 * @memberOf Base * @param {string} [s] * @returns {boolean} */ isDataURL(s) { /** * Define regex * @type {RegExp} */ this.isDataURL.regex = /^data:.+\/(.+);base64,(.*)$/; return s ? !!s.match(this.isDataURL.regex) : s; } /** * Define wait for condition * @memberOf Base * @param {function} conditionFn * @param {function} callbackFn * @param {function} [fallbackFn] * @param {number} [timeout] */ waitFor(conditionFn, callbackFn, fallbackFn, timeout) { // Init timeout timeout = timeout || 100; let wait; /** * @constant _poll * @private */ const _poll = () => { // Define timeout instance wait = setTimeout(() => { timeout--; if (conditionFn()) { // External file loaded callbackFn(); clearTimeout(wait); } else if (timeout > 0) { _poll(); } else { // External library failed to load if (typeof (fallbackFn) === 'function') { fallbackFn(); } } }, 100); }; // Call timer _poll(); } }
JavaScript
class ContentController { /** * Show a list of all contents. * GET contents * * @param {object} ctx * @param {Request} ctx.request * @param {Response} ctx.response * @param {View} ctx.view */ async index({params, response}) { if(params.type == null){ const contents = await Content.all() return response.json({ error: false, content: contents }) } console.log(params.content) const contents = await Content.query() .where('type', params.type) .fetch() return response.json({ error: false, content: contents }) } /** * Render a form to be used for creating a new content. * GET contents/create * * @param {object} ctx * @param {Request} ctx.request * @param {Response} ctx.response * @param {View} ctx.view */ /** * Create/save a new content. * POST contents * * @param {object} ctx * @param {Request} ctx.request * @param {Response} ctx.response */ async store({ request, response, auth }) { const data = request.only(["title", "subtitle", "type", "likes", "content"]) const contents = await Content.create(data) return response.json({ error: false, request: contents }) /* else{ return response.status(401).json({ error: true }) } */ } /** * Display a single content. * GET contents/:id * * @param {object} ctx * @param {Request} ctx.request * @param {Response} ctx.response * @param {View} ctx.view */ async show({ params }) { const contents = await Content.findOrFail(params.id) await contents.load("images") return contents } /** * Render a form to update an existing content. * GET contents/:id/edit * * @param {object} ctx * @param {Request} ctx.request * @param {Response} ctx.response * @param {View} ctx.view */ /** * Update content details. * PUT or PATCH contents/:id * * @param {object} ctx * @param {Request} ctx.request * @param {Response} ctx.response */ async update({ params, request, response }) { const content = await Content.findOrFail(params.id) if (content) { const contentMerged = content.merge(request.body) if (await content.save()) { return response.json({ error: false }) } return response.status(400).json({ error: true, message: 'You must change any field' }) } return response.status(400).json({ error: true, message: 'You solicitation was not completed' }) } /** * Delete a content with id. * DELETE contents/:id * * @param {object} ctx * @param {Request} ctx.request * @param {Response} ctx.response */ async destroy({ params, request, response }) { } async index_img({ request, response, params }) { const oneID = params.id || false if (oneID) { const content = await Content.query() .with('images') .where('id', params.id) .fetch() if(content){ return response.json({ error: false, data: content }) } return response.status(400).json({ error: true, message: 'Not founded images related to this content id' }) } else { return response.send('falsiane') } } }
JavaScript
class DiscordInteractionError extends Error { constructor(...args) { super(...args); } }
JavaScript
class DatabaseLokiMuseria extends (Parent || DatabaseLokiStoracle) { /** * @see DatabaseMuseria.prototype.getMusicByPk */ async getMusicByPk(title, options = {}) { title = utils.prepareComparisonSongTitle(title); options = Object.assign({ similarity: this.node.options.music.similarity }, options); const fullName = this.createCollectionName('music'); const documents = this.col[fullName].find(); let max = null; for(let i = 0; i < documents.length; i++) { const doc = documents[i]; let score = doc.compTitle === title? 1: 0; if(!score) { score = utils.getSongSimilarity(doc.compTitle, title, { beautify: false, min: options.similarity }); } if(score === 1) { max = { score, doc }; break; } if(!max || score > max.score) { max = { score, doc }; continue; } if(score == max.score && Math.random() > 0.5) { max = { score, doc }; } } if(max && max.score >= options.similarity) { return this.prepareDocumentToGet(max.doc); } return null; } /** * Add music document * * @async * @param {object} doc * @returns {object} */ async addMusicDocument(doc, options = {}) { options.beautify !== false && (doc.title = utils.beautifySongTitle(doc.title)); doc.compTitle = utils.prepareComparisonSongTitle(doc.title, { beautify: options.beautify }); return await this.addDocument('music', doc); } /** * Add music document * * @async * @param {object} doc * @param {object} options * @param {object} options.beautify * @returns {object} */ async updateMusicDocument(doc, options = {}) { options.beautify !== false && (doc.title = utils.beautifySongTitle(doc.title)); doc.compTitle = utils.prepareComparisonSongTitle(doc.title, { beautify: options.beautify }); return await this.updateDocument(doc); } /** * @see DatabaseMuseria.prototype.getMusicByFileHash */ async getMusicByFileHash(hash) { const fullName = this.createCollectionName('music'); const document = this.col[fullName].by('fileHash', hash); return document? this.prepareDocumentToGet(document): null; } /** * @see DatabaseMuseria.prototype.removeMusicByFileHash */ async removeMusicByFileHash(hash) { const fullName = this.createCollectionName('music'); this.col[fullName].chain().find({ fileHash: hash }).remove(); } }
JavaScript
class App { constructor(_context, params, baseUrl) { this._context = _context; this.params = params; this.baseUrl = baseUrl; this._connectedUsers = new Map(); this.testResults = {}; this.activeTest = null; this.runPromise = null; this.menu = new menu_1.Menu(this); this.assets = new MRE.AssetContainer(_context); this.context.onStarted(() => { this.setupShared(); if (this.params.test === undefined) { this.menu.show(); } else { this.activeTestName = this.params.test; this.activeTestFactory = tests_1.Factories[this.activeTestName]; this.setupRunner(); } }); this.context.onUserJoined((user) => this.userJoined(user)); this.context.onUserLeft((user) => this.userLeft(user)); this.backgroundMaterial = this.assets.createMaterial('background', { color: exports.BackgroundColor }); this.menu.onSelection((name, factory, user) => { this.menu.hide(); this.activeTestName = name; this.activeTestFactory = factory; this.runTest(user); }); } get context() { return this._context; } get connectedUsers() { return this._connectedUsers; } userJoined(user) { this.connectedUsers.set(user.id, user); if (!this.firstUser) { this.firstUser = user; if (this.params.autorun === 'true' || this.params.nomenu === 'true') { this.runTest(user); } } } userLeft(user) { this.connectedUsers.delete(user.id); if (user === this.firstUser) { this.firstUser = this.context.users[0] || null; if (!this.firstUser) { this.stopTest().catch(() => { }); } } } runTest(user) { // finish setting up runner if (!this.contextLabel) { this.setupRunner(); } // halt the previous test if there is one (this.activeTest !== null ? this.stopTest() : Promise.resolve()) // start the new test, and save the stop handle .then(() => { if (this.playPauseButton) { this.playPauseButton.appearance.material.color.set(1, 0, 0, 1); this.playPauseText.text.contents = "Stop"; } return this.runPromise = this.runTestHelper(user); }) // and log unexpected errors .catch(err => console.log(err)); } async runTestHelper(user) { this.context.rpc.send({ procName: 'functional-test:test-starting' }, this.activeTestName); console.log(`Test starting: '${this.activeTestName}'`); const test = this.activeTest = this.activeTestFactory(this, this.baseUrl, user); this.setOverrideText(test.expectedResultDescription); this.testRoot = MRE.Actor.Create(this.context, { actor: { name: 'testRoot', exclusiveToUser: this.exclusiveUser && this.exclusiveUser.id || undefined } }); let success; try { test.checkPermission(user); success = await test.run(this.testRoot); if (!success) { this.setOverrideText("Test Failed: '${testName}'", exports.FailureColor); } } catch (e) { console.log(e); this.setOverrideText(e.toString(), exports.FailureColor); success = false; } console.log(`Test complete: '${this.activeTestName}'. Success: ${success}`); this.context.rpc.send({ procName: 'functional-test:test-complete' }, this.activeTestName, success); this.testResults[this.activeTestName] = success; if (success) { this.setOverrideText(null); } } async stopTest() { var _a; if (this.activeTest !== null) { this.activeTest.stop(); await this.runPromise; this.activeTest.cleanup(); this.activeTest = null; this.runPromise = null; // Delete all actors (_a = this.testRoot) === null || _a === void 0 ? void 0 : _a.destroy(); this.testRoot = null; if (this.playPauseButton) { this.playPauseButton.appearance.material.color.set(0, 1, 0, 1); this.playPauseText.text.contents = "Start"; } } } setOverrideText(text, color = exports.NeutralColor) { if (text) { this.contextLabel.text.color = color; this.contextLabel.text.contents = text; } else { if (this.testResults[this.activeTestName] === true) { this.contextLabel.text.color = exports.SuccessColor; } else if (this.testResults[this.activeTestName] === false) { this.contextLabel.text.color = exports.FailureColor; } else { this.contextLabel.text.color = exports.NeutralColor; } this.contextLabel.text.contents = this.activeTest.expectedResultDescription; } } async toggleExclusiveUser(user) { if (this.exclusiveUser || !user) { this.exclusiveUser = null; this.exclusiveUserLabel.contents = "Inclusive"; } else { this.exclusiveUser = user; this.exclusiveUserLabel.contents = `Exclusive to:\n${user.name}`; } const wasRunning = !!this.activeTest; await this.stopTest(); if (wasRunning) { this.runTest(user); } } setupShared() { // change the exclusive user if (this.params.exclusive) { this.exclusiveUser = this.firstUser; } this.exclusiveUserToggle = MRE.Actor.Create(this.context, { actor: { appearance: { meshId: this.assets.createBoxMesh('button', 0.25, 0.25, 0.1).id }, transform: { local: { position: { x: -0.875, y: 2.3 } } }, collider: { geometry: { shape: MRE.ColliderType.Auto } } } }); const label = MRE.Actor.Create(this.context, { actor: { parentId: this.exclusiveUserToggle.id, transform: { local: { position: { x: 0.3 } } }, text: { contents: this.exclusiveUser ? `Exclusive to:\n${this.exclusiveUser.name}` : "Inclusive", height: 0.2, anchor: MRE.TextAnchorLocation.MiddleLeft } } }); this.exclusiveUserLabel = label.text; this.exclusiveUserToggle.setBehavior(MRE.ButtonBehavior) .onButton('released', user => this.toggleExclusiveUser(user)); MRE.Actor.Create(this.context, { actor: { name: 'floor', appearance: { meshId: this.assets.createBoxMesh('floor', 2, 0.1, 2.1).id, materialId: this.backgroundMaterial.id }, transform: { local: { position: { x: 0, y: -0.05, z: -1 } } }, collider: { geometry: { shape: MRE.ColliderType.Auto } } } }); MRE.Actor.Create(this.context, { actor: { name: 'wall', appearance: { meshId: this.assets.createBoxMesh('wall', 2, 2, 0.1).id, materialId: this.backgroundMaterial.id }, transform: { local: { position: { x: 0, y: 1, z: 0.1 } } }, collider: { geometry: { shape: MRE.ColliderType.Auto } } } }); } setupRunner() { // Main label at the top of the stage this.contextLabel = MRE.Actor.Create(this.context, { actor: { name: 'contextLabel', text: { contents: this.activeTestName, height: 0.2, anchor: MRE.TextAnchorLocation.MiddleCenter, justify: MRE.TextJustify.Center, color: exports.NeutralColor }, transform: { local: { position: { y: 1.8 } } } } }); if (this.params.nomenu === 'true') { this.runnerActors = [this.contextLabel]; return; } // start or stop the active test const ppMat = this.assets.materials.find(m => m.name === 'ppMat') || this.assets.createMaterial('ppMat', { color: MRE.Color3.Green() }); const ppMesh = this.assets.materials.find(m => m.name === 'ppMesh') || this.assets.createBoxMesh('ppMesh', 0.7, 0.3, 0.1); this.playPauseButton = MRE.Actor.Create(this.context, { actor: { name: 'playpause', appearance: { meshId: ppMesh.id, materialId: ppMat.id }, transform: { local: { position: { x: -0.65, y: 0.15, z: -1.95 } } }, collider: { geometry: { shape: MRE.ColliderType.Auto } } } }); this.playPauseText = MRE.Actor.Create(this.context, { actor: { parentId: this.playPauseButton.id, transform: { local: { position: { z: -0.1 } } }, text: { contents: "Start", height: 0.15, anchor: MRE.TextAnchorLocation.MiddleCenter, justify: MRE.TextJustify.Center, color: exports.NeutralColor } } }); this.playPauseButton.setBehavior(MRE.ButtonBehavior) .onButton("released", user => { if (this.activeTest === null) { this.runTest(user); } else { this.stopTest().catch(err => MRE.log.error('app', err)); } }); const menuButton = MRE.Actor.Create(this.context, { actor: { name: 'menu', appearance: { meshId: ppMesh.id }, transform: { local: { position: { x: 0.65, y: 0.15, z: -1.95 } } }, collider: { geometry: { shape: MRE.ColliderType.Auto } } } }); const menuText = MRE.Actor.Create(this.context, { actor: { parentId: menuButton.id, transform: { local: { position: { z: -0.1 } } }, text: { contents: "Return", height: 0.15, anchor: MRE.TextAnchorLocation.MiddleCenter, justify: MRE.TextJustify.Center, color: MRE.Color3.Black() } } }); menuButton.setBehavior(MRE.ButtonBehavior) .onButton("released", async () => { await this.stopTest(); [this.contextLabel, this.playPauseButton, this.playPauseText] = this.runnerActors = destroyActors_1.default(this.runnerActors); this.menu.show(); }); this.runnerActors = [ this.contextLabel, this.testRoot, this.playPauseButton, this.playPauseText, menuButton, menuText ]; } }
JavaScript
class MediaPlayer { constructor({ element, plugins = [] }) { this.player = element this.plugins = plugins this.#initPlugins() } #initPlugins() { this.plugins.forEach((item) => item.run(this)) } play() { this.player.play() } mute() { this.player.muted = true } unmute() { this.player.muted = false } decreaseVolumen() { if (this.player.volume <= 0.1) return this.player.volume -= 0.1 } increaseVolumen() { if (this.player.volume === 1) return this.player.volume += 0.1 } pause() { this.player.pause() } toggleMute() { // eslint-disable-next-line no-unused-expressions this.player.muted ? this.unmute() : this.mute() } togglePlay() { // eslint-disable-next-line no-unused-expressions this.player.paused ? this.play() : this.pause() } }
JavaScript
class Practitioner extends DomainResource { /** An identifier that applies to this person in this role. @returns {Array} an array of {@link Identifier} objects */ identifier () { if (this.json['identifier']) { return this.json['identifier'].map(item => new Identifier(item)) } } /** A name associated with the person. @returns {HumanName} */ name () { if (this.json['name']) { return new HumanName(this.json['name']) } } /** A contact detail for the practitioner, e.g. a telephone number or an email address. @returns {Array} an array of {@link ContactPoint} objects */ telecom () { if (this.json['telecom']) { return this.json['telecom'].map(item => new ContactPoint(item)) } } /** The postal address where the practitioner can be found or visited or to which mail can be delivered. @returns {Array} an array of {@link Address} objects */ address () { if (this.json['address']) { return this.json['address'].map(item => new Address(item)) } } /** Administrative Gender - the gender that the person is considered to have for administration and record keeping purposes. @returns {Array} an array of {@link String} objects */ gender () { return this.json['gender'] } /** The date and time of birth for the practitioner. @returns {Array} an array of {@link Date} objects */ birthDate () { if (this.json['birthDate']) { return DT.DateTime.parse(this.json['birthDate']) } } /** Image of the person. @returns {Array} an array of {@link Attachment} objects */ photo () { if (this.json['photo']) { return this.json['photo'].map(item => new Attachment(item)) } } /** The organization that the practitioner represents. @returns {Reference} */ organization () { if (this.json['organization']) { return new Reference(this.json['organization']) } } /** Roles which this practitioner is authorized to perform for the organization. @returns {Array} an array of {@link CodeableConcept} objects */ role () { if (this.json['role']) { return this.json['role'].map(item => new CodeableConcept(item)) } } /** Specific specialty of the practitioner. @returns {Array} an array of {@link CodeableConcept} objects */ specialty () { if (this.json['specialty']) { return this.json['specialty'].map(item => new CodeableConcept(item)) } } /** The period during which the person is authorized to act as a practitioner in these role(s) for the organization. @returns {Period} */ period () { if (this.json['period']) { return new Period(this.json['period']) } } /** The location(s) at which this practitioner provides care. @returns {Array} an array of {@link Reference} objects */ location () { if (this.json['location']) { return this.json['location'].map(item => new Reference(item)) } } /** Qualifications obtained by training and certification. @returns {Array} an array of {@link PractitionerQualificationComponent} objects */ qualification () { if (this.json['qualification']) { return this.json['qualification'].map(item => new PractitionerQualificationComponent(item)) } } /** A language the practitioner is able to use in patient communication. @returns {Array} an array of {@link CodeableConcept} objects */ communication () { if (this.json['communication']) { return this.json['communication'].map(item => new CodeableConcept(item)) } } }
JavaScript
class M20eChatMessage extends ChatMessage { constructor(data, context) { super(data, context); } /** * Updates message with the 'stealthroll' flag set to true * todo : check if await is needed ? * @override */ applyRollMode(rollMode) { if (rollMode === 'stealthroll') { this.data.update({['flags.stealthroll']: true}); rollMode = "blindroll"; } super.applyRollMode(rollMode); } /** * Don't display stealth rolls unless user isGM * @override */ async getHTML() { if ( this.data.flags.stealthroll && this.data.blind && this.data.whisper.length) { if ( game.user.isGM ) { return super.getHTML(); } } else { return super.getHTML(); } } }
JavaScript
class SimpleHandler extends Handler { /* TODO limit the scope of suggestions using the current contexts. * Determine whether or not to delegate to the successor. */ perform(request) { let { editor, bufferPosition, scopeDescriptor, prefix, activatedManually, completions, suggestions, contexts } = request completions.simple.forEach((item) => { suggestions.push({ snippet: item, displayText: item, type: 'keyword', description: item, descriptionMoreURL: 'http://web.cecs.pdx.edu/~len/sql1999.pdf' }) }) } }
JavaScript
class CLIGenerator extends Generator { constructor (args, opts) { super(args, opts); this.bail = false; this.out = require('../index').generator_output(this); this.answerOverrides = {}; } setupArgumentsAndOptions (prompts) { prompts.forEach(prompt => { if (prompt.hasOwnProperty('argument')) { debug('Adding argument %s with config %j', prompt.argument.name, prompt.argument.config); this.argument(prompt.argument.name, prompt.argument.config); } if (prompt.hasOwnProperty('option')) { debug('Adding option %s with config %j', prompt.option.name, prompt.option.config); this.option(prompt.option.name, prompt.option.config); } }); } subgeneratorPrompt (prompts, desc, donePromptingFunc) { // ==== PROMPT EXTENSIONS ==== this.processedPrompts = prompts.map(prompt => { const newPrompt = _.assign({}, prompt); const oldWhen = prompt.when; newPrompt.when = props => { debug('Synthetic when() logic'); if (this.bail) return false; if (prompt.hasOwnProperty('commonFilter') && _.isFunction(prompt.commonFilter) && prompt.hasOwnProperty('name') && ( (prompt.hasOwnProperty('option') && prompt.option.hasOwnProperty('name')) || (prompt.hasOwnProperty('argument') && prompt.argument.hasOwnProperty('name')) ) ) { let cliName; let cliValue; if (prompt.hasOwnProperty('option') && prompt.option.hasOwnProperty('name')) { cliName = prompt.option.name; cliValue = this.options[prompt.option.name]; debug('Calling commonFilter(%s) for option: %s', cliValue, cliName); } else { cliName = prompt.argument.name; cliValue = this.options[prompt.argument.name]; debug('Calling commonFilter(%s) for argument: %s', cliValue, cliName); } const v = prompt.commonFilter.call(this, cliValue); if (undefined !== v) { this.answerOverrides[prompt.name] = v; this.out.info('Value for ' + cliName + ' set from command line: ' + chalk.reset.dim.cyan(v)); return false; } } if (_.isBoolean(oldWhen)) { debug('Returning when=%s via value provided in prompt %s', oldWhen, prompt.name); return oldWhen; } if (_.isFunction(oldWhen)) { const retv = oldWhen.call(this, props); debug('Returning when(%s)=%s via function provided in prompt: %s', JSON.stringify(props), retv, prompt.name); return retv; } return true; }; if (prompt.hasOwnProperty('commonFilter') && _.isFunction(prompt.commonFilter)) { if (!prompt.hasOwnProperty('filter')) { newPrompt.filter = input => { debug('Using commonFilter(%s) for filter', input); return prompt.commonFilter.call(this, input); }; } if (!prompt.hasOwnProperty('validate') && prompt.hasOwnProperty('name')) { newPrompt.validate = input => { debug('Using commonFilter(%s) for validate', input); const required = prompt.valueRequired; let msg = 'The ' + (required ? 'required ' : '') + chalk.yellow(prompt.name) + ' value ' + (required ? 'is missing or invalid' : 'is invalid'); if (prompt.hasOwnProperty('invalidMessage')) { if (_.isFunction(prompt.invalidMessage)) { msg = prompt.invalidMessage.call(this, input); } if (_.isString(prompt.invalidMessage)) { msg = prompt.invalidMessage; } } return (prompt.commonFilter.call(this, input) !== undefined ? true : msg); }; } } return newPrompt; }); // ==== NOW DO THE ACTUAL PROMPTING ==== return this.prompt(this.processedPrompts).then(props => { const combinedProps = {}; if (!this.bail) { _.assign(combinedProps, this.answerOverrides); _.assign(combinedProps, props); this.processedPrompts.forEach(promptItem => { const name = promptItem.name; const required = promptItem.valueRequired; if (name && required) { debug('Required check for %s which is %s and has value %s', name, (required ? 'required' : 'not required'), combinedProps[name]); if (undefined === combinedProps[name]) { this.out.error('At least one required properties not set: ' + name); this.bail = true; } } }); } if (!this.bail && donePromptingFunc) { debug('calling user supplied done prompting function'); donePromptingFunc.call(this, combinedProps); debug('completed user supplied done prompting function'); } }); } }
JavaScript
class HelpDefault extends TestCase { /** * Executes the test case * @return {Promise} nothing (in case of failure - an exception will be thrown) */ async execute() { super.execute(); const discordClient = this.processor.discordClient; this.assertNotNull(discordClient); const guild = discordClient.guilds.cache.get(this.processor.prefsManager.test_discord_guild_id); this.assertNotNull(guild); const channel = guild.channels.cache.get(this.processor.prefsManager.test_discord_text_channel_1_id); this.assertNotNull(channel); channel.send('!help'); const receivedMessages = await this.getAllReplies(channel); this.assertNotNull(receivedMessages); let totalText = ''; for (const message of receivedMessages) { this.assertNotNull(message.content); totalText += message.content; } this.assertTrue(totalText.startsWith( 'Available commands are below. Use !help <command name> to get more details about the command')); this.assertTrue(totalText.indexOf('!help : Prints the bot\'s help. If you are not an admin, then by' + ' default prints only non-admin commands. Type \'all\' as the argument to get help on all commands.') >= 0); } }
JavaScript
class MetroHashWrapper { constructor(size) { if (!metrohash) { throw new Error("Unable to find metrohash module") } if (size !== 128 && size !== 64) { throw new Error(`Invalid metrohash size: ${size}`) } const MetroHash = size === 128 ? metrohash.MetroHash128 : metrohash.MetroHash64 this.hasher = new MetroHash() } update(data) { this.hasher.update(data) return this } digest(encoding) { if (encoding === "hex") { return this.hasher.digest() } const hex = this.hasher.digest() const buffer = Buffer.from(hex, "hex") return encoding === "buffer" ? buffer : buffer.toString(encoding) } }
JavaScript
class CSSVariableTarget extends AnimationTarget { /** * @param {string} variable The CSS variable name prefix to use. * It doesn't have to be unique, as each CSSVariableTarget automatically * gets a random extra few characters on the end. * @param {CSSVariablesAreAlsoStrings<T>} value The initial value. * This also sets the type of the interpolator, so you can't use * a bare string as the value if you intend to use a certain CSS type: * e.g. <code>value = "0px"</code> won't do what you want, you have to * use <code>value = CSSPixels(0)</code> instead. * @param {HTMLElement} anchor The element to use to put the CSS variable on. * This defaults to document.body, but you can substitute another HTML element * here to place the variable on something else. */ constructor(variable, value, anchor = document.body) { super(value); /** @private */ this._variable = variable + rnda(); this._anchor = anchor; /** @type {CSSVariablesAreAlsoStrings<T>} */ this._value = value; this.value = value; } get var() { return `var(${this._variable})`; } get value() { return this._value; } /** @param {CSSVariablesAreAlsoStrings<T>} v */ set value(v) { this._value = v; if (this._variable) { this._anchor.style.setProperty(this._variable, `${this._value}`); } } }
JavaScript
class SharingService { /** * Returns the unhashed sharing URL for the current state. * * @returns {String} - The unhashed sharing URL. */ getSharedUrl() { const urlWithHashes = $location.absUrl(); let url = urlWithHashes; if (config.get('state:storeInSessionStorage')) { url = unhashUrl(urlWithHashes, getUnhashableStates()); } return url; } /** * Generates a short URL for the current state. * * @returns {Promise} - Resolved with the short URL. */ async generateShortUrl() { return urlShortener.shortenUrl(this.getSharedUrl()); } /** * Adds parameters to the URL * * @param {String} url - URL to modify * @param {Boolean} shareAsEmbed - Set to true to enable embedding in the URL. * @param {Boolean} displayNavBar - Set to true to display the Kibi navigation bar when embedding is enabled in the URL. */ addParamsToUrl(url, shareAsEmbed, displayNavBar) { if (shareAsEmbed) { if (displayNavBar) { url += '?embed=true&kibiNavbarVisible=true'; } else { url += '?embed=true'; } } return url; } }
JavaScript
class CodeBlockView { constructor(node) { this.dom = document.createElement('div'); this.language = 'lel'; this.dom.innerHTML = ` <div class="CodeBlockLanguageSelector" contenteditable=false> <span>${this.language}</span> </div> <pre><code class="content-dom"></code></pre> `; this.contentDOM = this.dom.querySelector('.content-dom'); } update(node) { const rawLanguage = 'lelz'; if (this.language !== rawLanguage) { this.dom.querySelector('.CodeBlockLanguageSelector span').textContent = rawLanguage; this.language = rawLanguage; } return true; } }
JavaScript
class NieuwsPage { // constructor for used components constructor () { this.compPostsList = new PostsList(); } // render the content async render () { return ` <div class="page page--nieuws container"> <h1>Nieuws</h1> ${await this.compPostsList.render()} </div> `; } async afterRender () { // afterRender all components on the page this.compPostsList.afterRender(); // Connect the listeners return this; } async mount () { // Before the rendering of the page // scroll to the top window.scrollTo(0, 0); return this; } async unmount () { // After leaving the page return this; } }
JavaScript
class DisableBackupDescription { /** * Create a DisableBackupDescription. * @property {boolean} cleanBackup Boolean flag to delete backups. It can be * set to true for deleting all the backups which were created for the backup * entity that is getting disabled for backup. */ constructor() { } /** * Defines the metadata of DisableBackupDescription * * @returns {object} metadata of DisableBackupDescription * */ mapper() { return { required: false, serializedName: 'DisableBackupDescription', type: { name: 'Composite', className: 'DisableBackupDescription', modelProperties: { cleanBackup: { required: true, serializedName: 'CleanBackup', type: { name: 'Boolean' } } } } }; } }
JavaScript
class TTTGame { constructor(state) { this._state = Immutable(state); } get state() { return this._state; } clone() { return new TTTGame(this._state); } getCurrentPlayer() { const { currentPlayerId } = this._state; return this._state.playerInstances[currentPlayerId]; } getPossibleMoves() { const { board } = this._state; const currentPlayer = this.getCurrentPlayer(); const answer = []; for (let i = 0; i < 9; i += 1) { if (!board[i]) { answer.push({ index: i, token: currentPlayer.team }); } } return answer; } getWinner() { const { board } = this._state; let token; // Rows. for (let i = 0; i < 9 && !token; i += 3) { if ( board[i] && board[i] === board[i + 1] && board[i + 1] === board[i + 2] ) { token = board[i]; } } // Columns. for (let i = 0; i < 3 && !token; i += 1) { if ( board[i] && board[i] === board[i + 3] && board[i + 3] === board[i + 6] ) { token = board[i]; } } // Diagonals. if (!token && board[0] && board[0] === board[4] && board[4] === board[8]) { token = board[0]; } if (!token && board[2] && board[2] === board[4] && board[4] === board[6]) { token = board[2]; } let answer; if (token === "X") { answer = this._state.playerInstances[1]; } else if (token === "O") { answer = this._state.playerInstances[2]; } return answer; } isGameOver() { return this.getWinner() || this.getPossibleMoves().length === 0; } performMove(move) { const { board } = this._state; const newBoard = [...board]; newBoard[move.index] = move.token; const playerIds = Object.keys(this._state.playerInstances); const index0 = playerIds.indexOf(`${this._state.currentPlayerId}`); const index = index0 < playerIds.length - 1 ? index0 + 1 : 0; const nextPlayerId = playerIds[index]; const newState = Immutable({ ...this._state, board: newBoard, currentPlayerId: nextPlayerId, }); this._state = newState; } }