language
stringclasses
6 values
original_string
stringlengths
25
887k
text
stringlengths
25
887k
JavaScript
async function refreshAccessToken(token) { try { const url = "https://accounts.spotify.com/api/token?" + new URLSearchParams({ client_id: process.env.SPOTIFY_CLIENT_ID, client_secret: process.env.SPOTIFY_CLIENT_SECRET, grant_type: "refresh_token", refresh_token: token.refreshToken, }); const response = await fetch(url, { headers: { "Content-Type": "application/x-www-form-urlencoded", }, method: "POST", }); const refreshedTokens = await response.json(); if (!response.ok) { throw refreshedTokens; } return { ...token, accessToken: refreshedTokens.access_token, accessTokenExpires: Date.now() + refreshedTokens.expires_in * 1000, refreshToken: refreshedTokens.refresh_token ?? token.refreshToken, // Fall back to old refresh token }; } catch (error) { console.log(error); return { ...token, error: "RefreshAccessTokenError", }; } }
async function refreshAccessToken(token) { try { const url = "https://accounts.spotify.com/api/token?" + new URLSearchParams({ client_id: process.env.SPOTIFY_CLIENT_ID, client_secret: process.env.SPOTIFY_CLIENT_SECRET, grant_type: "refresh_token", refresh_token: token.refreshToken, }); const response = await fetch(url, { headers: { "Content-Type": "application/x-www-form-urlencoded", }, method: "POST", }); const refreshedTokens = await response.json(); if (!response.ok) { throw refreshedTokens; } return { ...token, accessToken: refreshedTokens.access_token, accessTokenExpires: Date.now() + refreshedTokens.expires_in * 1000, refreshToken: refreshedTokens.refresh_token ?? token.refreshToken, // Fall back to old refresh token }; } catch (error) { console.log(error); return { ...token, error: "RefreshAccessTokenError", }; } }
JavaScript
function prepareAll(renderer, prepare) { // Right thing is prepare.add, but that does't seem to work. // Possibly related to https://github.com/pixijs/pixi.js/issues/3829 // Workaround: https://stackoverflow.com/a/42762277 if (!renderer.bindTexture) return; SHEETS.forEach( sheet => Object.keys(sheet.data.frames) .forEach(frame => renderer.bindTexture(PIXI.Texture.from(frame).baseTexture))); }
function prepareAll(renderer, prepare) { // Right thing is prepare.add, but that does't seem to work. // Possibly related to https://github.com/pixijs/pixi.js/issues/3829 // Workaround: https://stackoverflow.com/a/42762277 if (!renderer.bindTexture) return; SHEETS.forEach( sheet => Object.keys(sheet.data.frames) .forEach(frame => renderer.bindTexture(PIXI.Texture.from(frame).baseTexture))); }
JavaScript
function generateBrowserBot(ships, shipyard) { const rawCode = ` (INPUT_BUFFER) => { const hlt = {}; hlt.constants = { /** * The maximum number of map cells to consider in navigation. */ MAX_BFS_STEPS: 1024, // search an entire 32x32 region /** * Load constants from JSON given by the game engine. */ loadConstants: function loadConstants(constants) { /** The cost to build a single ship. */ this.SHIP_COST = constants['NEW_ENTITY_ENERGY_COST']; /** The cost to build a dropoff. */ this.DROPOFF_COST = constants['DROPOFF_COST']; /** The maximum amount of halite a ship can carry. */ this.MAX_HALITE = constants['MAX_ENERGY']; /** * The maximum number of turns a game can last. This reflects * the fact that smaller maps play for fewer turns. */ this.MAX_TURNS = constants['MAX_TURNS']; /** 1/EXTRACT_RATIO halite (truncated) is collected from a square per turn. */ this.EXTRACT_RATIO = constants['EXTRACT_RATIO']; /** 1/MOVE_COST_RATIO halite (truncated) is needed to move off a cell. */ this.MOVE_COST_RATIO = constants['MOVE_COST_RATIO']; /** Whether inspiration is enabled. */ this.INSPIRATION_ENABLED = constants['INSPIRATION_ENABLED']; /** * A ship is inspired if at least INSPIRATION_SHIP_COUNT * opponent ships are within this Manhattan distance. */ this.INSPIRATION_RADIUS = constants['INSPIRATION_RADIUS']; /** * A ship is inspired if at least this many opponent ships are * within INSPIRATION_RADIUS distance. */ this.INSPIRATION_SHIP_COUNT = constants['INSPIRATION_SHIP_COUNT']; /** An inspired ship mines 1/X halite from a cell per turn instead. */ this.INSPIRED_EXTRACT_RATIO = constants['INSPIRED_EXTRACT_RATIO']; /** An inspired ship that removes Y halite from a cell collects X*Y additional halite. */ this.INSPIRED_BONUS_MULTIPLIER = constants['INSPIRED_BONUS_MULTIPLIER']; /** An inspired ship instead spends 1/X% halite to move. */ this.INSPIRED_MOVE_COST_RATIO = constants['INSPIRED_MOVE_COST_RATIO']; }, }; hlt.commands = (function() { const NORTH = 'n'; const SOUTH = 's'; const EAST = 'e'; const WEST = 'w'; const STAY_STILL = 'o'; const GENERATE = 'g'; const CONSTRUCT = 'c'; const MOVE = 'm'; return { NORTH, SOUTH, EAST, WEST, STAY_STILL, GENERATE, CONSTRUCT, MOVE, }; })(); hlt.positionals = (function(commands) { class Direction { constructor(dx, dy) { this.dx = dx; this.dy = dy; } equals(other) { return this.dx === other.dx && this.dy === other.dy; } toString() { return \`$\{this.constructor.name}($\{this.dx}, $\{this.dy})\`; } static getAllCardinals() { return [ Direction.North, Direction.South, Direction.East, Direction.West ]; } toWireFormat() { if (this.equals(Direction.North)) { return commands.NORTH; } else if (this.equals(Direction.South)) { return commands.SOUTH; } else if (this.equals(Direction.East)) { return commands.EAST; } else if (this.equals(Direction.West)) { return commands.WEST; } else if (this.equals(Direction.Still)) { return commands.STAY_STILL; } throw new Error(\`Non-cardinal direction cannot be converted to wire format: $\{this}\`); } invert() { if (this.equals(Direction.North)) { return Direction.South; } else if (this.equals(Direction.South)) { return Direction.North; } else if (this.equals(Direction.East)) { return Direction.West; } else if (this.equals(Direction.West)) { return Direction.East; } else if (this.equals(Direction.Still)) { return Direction.Still; } throw new Error(\`Non-cardinal direction cannot be inverted: $\{this}\`); } } Direction.North = new Direction(0, -1); Direction.South = new Direction(0, 1); Direction.East = new Direction(1, 0); Direction.West = new Direction(-1, 0); Direction.Still = new Direction(0, 0); class Position { constructor(x, y) { this.x = x; this.y = y; } directionalOffset(direction) { return this.add(new Position(direction.dx, direction.dy)); } getSurroundingCardinals() { return Direction.getAllCardinals() .map(currentDirection => this.directionalOffset(currentDirection)); } add(other) { return new Position(this.x + other.x, this.y + other.y); } sub(other) { return new Position(this.x - other.x, this.y - other.y); } addMut(other) { this.x += other.x; this.y += other.y; } subMut(other) { this.x -= other.x; this.y -= other.y; } abs() { return new Position(Math.abs(this.x), Math.abs(this.y)); } equals(other) { return this.x === other.x && this.y === other.y; } toString() { return \`$\{this.constructor.name}($\{this.x}, $\{this.y})\`; } } return { Direction, Position, }; })(hlt.commands); hlt.entity = (function(positionals, commands, constants) { const { Direction, Position } = positionals; /** Base entity class for Ships, Dropoffs, and Shipyards. */ class Entity { constructor(owner, id, position) { this.owner = owner; this.id = id; this.position = position; } toString() { return \`$\{this.constructor.name}(id=$\{this.id}, $\{this.position})\`; } } /** Represents a dropoff. */ class Dropoff extends Entity { /** * Create a Dropoff for a specific player from the engine input. * @private * @param playerId the player that owns this dropoff * @param {Function} getLine function to read a line of input * @returns {Dropoff} */ static async _generate(playerId, getLine) { const [ id, xPos, yPos ] = (await getLine()) .split(/\\s+/) .map(x => parseInt(x, 10)); return [ id, new Dropoff(playerId, id, new Position(xPos, yPos)) ]; } } /** Represents a shipyard. */ class Shipyard extends Entity { /** Return a move to spawn a new ship at your shipyard. */ spawn() { return commands.GENERATE; } } /** Represents a ship. */ class Ship extends Entity { constructor(owner, id, position, haliteAmount) { super(owner, id, position); this.haliteAmount = haliteAmount; } /** Is this ship at max halite capacity? */ get isFull() { return this.haliteAmount >= constants.MAX_HALITE; } /** Return a move to turn this ship into a dropoff. */ makeDropoff() { return \`$\{commands.CONSTRUCT} $\{this.id}\`; } /** * Return a command to move this ship in a direction without * checking for collisions. * @param {String|Direction} direction the direction to move in * @returns {String} the command */ move(direction) { if (direction.toWireFormat) { direction = direction.toWireFormat(); } return \`$\{commands.MOVE} $\{this.id} $\{direction}\`; } /** * Return a command to not move this ship. * * Not strictly needed, since ships do nothing by default. */ stayStill() { return \`$\{commands.MOVE} $\{this.id} $\{commands.STAY_STILL}\`; } /** * Create a Ship instance for a player using the engine input. * @param playerId the owner * @return The ship ID and ship object. * @private */ static async _generate(playerId, getLine) { const [ shipId, xPos, yPos, halite ] = (await getLine()) .split(/\\s+/) .map(x => parseInt(x, 10)); return [ shipId, new Ship(playerId, shipId, new Position(xPos, yPos), halite) ]; } toString() { return \`$\{this.constructor.name}(id=$\{this.id}, $\{this.position}, cargo=$\{this.haliteAmount} halite)\`; } } return { Entity, Ship, Dropoff, Shipyard, }; })(hlt.positionals, hlt.commands, hlt.constants); hlt.gameMap = (function(constants, entity, positionals) { const { Ship, Dropoff, Shipyard } = entity; const { Direction, Position } = positionals; /** Player object, containing all entities/metadata for the player. */ class Player { constructor(playerId, shipyard, halite=0) { this.id = playerId; this.shipyard = shipyard; this.haliteAmount = halite; this._ships = new Map(); this._dropoffs = new Map(); } /** Get a single ship by its ID. */ getShip(shipId) { return this._ships.get(shipId); } /** Get a list of the player's ships. */ getShips() { const result = []; for (const ship of this._ships.values()) { result.push(ship); } return result; } /** Get a single dropoff by its ID. */ getDropoff(dropoffId) { return this._dropoffs.get(dropoffId); } /** Get a list of the player's dropoffs. */ getDropoffs() { const result = []; for (const dropoff of this._dropoffs.values()) { result.push(dropoff); } return result; } /** Check whether a ship with a given ID exists. */ hasShip(shipId) { return this._ships.has(shipId); } /** * Create a player object using input from the game engine. * @private */ static async _generate(getLine) { const line = await getLine(); const [ playerId, shipyardX, shipyardY ] = line .split(/\\s+/) .map(x => parseInt(x, 10)); return new Player(playerId, new Shipyard(playerId, -1, new Position(shipyardX, shipyardY))); } /** * Update the player object for the current turn using input from * the game engine. * @private */ async _update(numShips, numDropoffs, halite, getLine) { this.haliteAmount = halite; this._ships = new Map(); for (let i = 0; i < numShips; i++) { const [ shipId, ship ] = await Ship._generate(this.id, getLine); this._ships.set(shipId, ship); } this._dropoffs = new Map(); for (let i = 0; i < numDropoffs; i++) { const [ dropoffId, dropoff ] = await Dropoff._generate(this.id, getLine); this._dropoffs.set(dropoffId, dropoff); } } } /** A cell on the game map. */ class MapCell { constructor(position, halite) { this.position = position; this.haliteAmount = halite; this.ship = null; this.structure = null; } /** * @returns {Boolean} whether this cell has no ships or structures. */ get isEmpty() { return !this.isOccupied && !this.hasStructure; } /** * @returns {Boolean} whether this cell has any ships. */ get isOccupied() { return this.ship !== null; } /** * @returns {Boolean} whether this cell has any structures. */ get hasStructure() { return this.structure !== null; } /** * @returns The type of the structure in this cell, or null. */ get structureType() { if (this.hasStructure) { return this.structure.constructor; } return null; } /** * Mark this cell as unsafe (occupied) for navigation. * * Use in conjunction with {@link GameMap#getSafeMove}. * * @param {Ship} ship The ship occupying this cell. */ markUnsafe(ship) { this.ship = ship; } equals(other) { return this.position.equals(other.position); } toString() { return \`MapCell($\{this.position}, halite=$\{this.haliteAmount})\`; } } /** * The game map. * * Can be indexed by a position, or by a contained entity. * Coordinates start at 0. Coordinates are normalized for you. */ class GameMap { constructor(cells, width, height) { this.width = width; this.height = height; this._cells = cells; } /** * Getter for position object or entity objects within the game map * @param location the position or entity to access in this map * @returns the contents housing that cell or entity */ get(...args) { if (args.length === 2) { return this._cells[args[1]][args[0]]; } let [ location ] = args; if (location instanceof Position) { location = this.normalize(location); return this._cells[location.y][location.x]; } else if (location.position) { return this.get(location.position); } return null; } /** * Compute the Manhattan distance between two locations. * Accounts for wrap-around. * @param source The source from where to calculate * @param target The target to where calculate * @returns The distance between these items */ calculateDistance(source, target) { source = this.normalize(source); target = this.normalize(target); const delta = source.sub(target).abs(); return Math.min(delta.x, this.width - delta.x) + Math.min(delta.y, this.height - delta.y); } /** * Normalized the position within the bounds of the toroidal map. * i.e.: Takes a point which may or may not be within width and * height bounds, and places it within those bounds considering * wraparound. * @param {Position} position A position object. * @returns A normalized position object fitting within the bounds of the map */ normalize(position) { let x = ((position.x % this.width) + this.width) % this.width; let y = ((position.y % this.height) + this.height) % this.height; return new Position(x, y); } /** * Determine the relative direction of the target compared to the * source (i.e. is the target north, south, east, or west of the * source). Does not account for wraparound. * @param {Position} source The source position * @param {Position} target The target position * @returns {[Direction | null, Direction | null]} A 2-tuple whose * elements are: the relative direction for each of the Y and X * coordinates (note the inversion), or null if the coordinates * are the same. */ static _getTargetDirection(source, target) { return [ target.y > source.y ? Direction.South : (target.y < source.y ? Direction.North : null), target.x > source.x ? Direction.East : (target.x < source.x ? Direction.West : null), ]; } /** * Return a list of Direction(s) that move closer to the * destination, if any. * * This does not account for collisions. Multiple directions may * be returned if movement in both coordinates is viable. * * @param {Position} source The (normalized) source position * @param {Position} destination The (normalized) target position * @returns A list of Directions moving towards the target (if * any) */ getUnsafeMoves(source, destination) { if (!(source instanceof Position && destination instanceof Position)) { throw new Error("source and destination must be of type Position"); } source = this.normalize(source); destination = this.normalize(destination); const possibleMoves = []; const distance = destination.sub(source).abs(); const [ yDir, xDir ] = GameMap._getTargetDirection(source, destination); if (distance.x !== 0) { possibleMoves.push(distance.x < (this.width / 2) ? xDir : xDir.invert()); } if (distance.y !== 0) { possibleMoves.push(distance.y < (this.height / 2) ? yDir : yDir.invert()); } return possibleMoves; } /** * Returns a singular safe move towards the destination. * @param {Ship} ship - the ship to move * @param {Position} destination - the location to move towards * @return {Direction} */ naiveNavigate(ship, destination) { // No need to normalize destination since getUnsafeMoves does // that for (const direction of this.getUnsafeMoves(ship.position, destination)) { const targetPos = ship.position.directionalOffset(direction); if (!this.get(targetPos).isOccupied) { this.get(targetPos).markUnsafe(ship); return direction; } } return Direction.Still; } static async _generate(getLine) { const [ mapWidth, mapHeight ] = (await getLine()) .split(/\\s+/) .map(x => parseInt(x, 10)); const gameMap = []; for (let i = 0; i < mapHeight; i++) { const row = []; row.fill(null, 0, mapWidth); gameMap.push(row); } for (let y = 0; y < mapHeight; y++) { const cells = (await getLine()).split(/\\s+/); for (let x = 0; x < mapWidth; x++) { gameMap[y][x] = new MapCell(new Position(x, y), parseInt(cells[x], 10)); } } return new GameMap(gameMap, mapWidth, mapHeight); } /** * Update this map object from the input given by the game * engine. */ async _update(getLine) { // Mark cells as safe for navigation (re-mark unsafe cells // later) for (let y = 0; y < this.height; y++) { for (let x = 0; x < this.width; x++) { this.get(x, y).ship = null; } } const numChangedCells = parseInt(await getLine(), 10); for (let i = 0; i < numChangedCells; i++) { const line = (await getLine()); const [ cellX, cellY, cellEnergy ] = line .split(/\\s+/) .map(x => parseInt(x, 10)); this.get(cellX, cellY).haliteAmount = cellEnergy; } } } return { Player, GameMap, MapCell, }; })(hlt.constants, hlt.entity, hlt.positionals); hlt.logging = ({ log(...args) {}, setup(filename) { }, format(args) { return args.map(x => typeof x !== 'string' ? x.toString() : x).join(' '); }, debug(...args) { this.log(\`DEBUG: $\{this.format(args)}\n\`); }, info(...args) { this.log(\`INFO: $\{this.format(args)}\n\`); }, warn(...args) { this.log(\`WARN: $\{this.format(args)}\n\`); }, error(...args) { this.log(\`ERROR: $\{this.format(args)}\n\`); }, }); hlt.networking = (function(constants, logging, gameMap) { const { GameMap, Player } = gameMap; class Game { constructor() { this.turnNumber = 0; const getLine = function() { return new Promise(async (resolve) => { resolve(INPUT_BUFFER.shift()); }); }; this._getLine = getLine; } /** * Initialize a game object collecting all the start-state * instances for pre-game. Also sets up a log file in * "bot-<bot_id>.log". */ async initialize() { const rawConstants = await this._getLine(); constants.loadConstants(JSON.parse(rawConstants)); const [ numPlayers, myId ] = (await this._getLine()) .split(/\\s+/) .map(tok => parseInt(tok, 10)); this.myId = myId; this.players = new Map(); for (let i = 0; i < numPlayers; i++) { this.players.set(i, await Player._generate(this._getLine)); } this.me = this.players.get(this.myId); this.gameMap = await GameMap._generate(this._getLine); } /** Indicate that your bot is ready to play. */ async ready(name) { await sendCommands(this.myId, [ name ]); } /** * Updates the game object's state. */ async updateFrame() { this.turnNumber = parseInt(await this._getLine(), 10); logging.info(\`================ TURN $\{this.turnNumber.toString().padStart(3, '0')} ================\`); for (let i = 0; i < this.players.size; i++) { const [ player, numShips, numDropoffs, halite ] = (await this._getLine()) .split(/\\s+/) .map(x => parseInt(x, 10)); await this.players.get(player)._update(numShips, numDropoffs, halite, this._getLine); } await this.gameMap._update(this._getLine); // Mark cells with ships as unsafe for navigation for (const player of this.players.values()) { for (const ship of player.getShips()) { this.gameMap.get(ship.position).markUnsafe(ship); } this.gameMap.get(player.shipyard.position).structure = player.shipyard; for (const dropoff of player.getDropoffs()) { this.gameMap.get(dropoff.position).structure = dropoff; } } } /** * Send all commands to the game engine, effectively ending your * turn. * @param {Array} commands */ async endTurn(commands) { await sendCommands(this.myId, commands); } } /** * Sends a list of commands to the engine. * @param commands The list of commands to send. * @returns a Promise fulfilled once stdout is drained. */ function sendCommands(botId, commands) { return new Promise((resolve) => { SEND_COMMANDS(botId, commands); resolve(); }); } return { Player, Game, sendCommands, }; })(hlt.constants, hlt.logging, hlt.gameMap); hlt.Direction = hlt.positionals.Direction; hlt.Position = hlt.positionals.Position; hlt.Entity = hlt.entity.Entity; hlt.Dropoff = hlt.entity.Dropoff; hlt.Shipyard = hlt.entity.Shipyard; hlt.Ship = hlt.entity.Ship; hlt.Game = hlt.networking.Game; hlt.Player = hlt.networking.Player; hlt.MapCell = hlt.gameMap.MapCell; hlt.GameMap = hlt.gameMap.GameMap; const { Direction, Position } = hlt.positionals; const logging = hlt.logging; ${utils} const shipState = new Map(); const game = new hlt.Game(); return [ async function(log) { logging.log = log; return game.initialize().then(async () => { // At this point "game" variable is populated with initial map data. // This is a good place to do computationally expensive start-up pre-processing. // As soon as you call "ready" function below, the 2 second per turn timer will start. return "MyJavaScriptBot"; }); }, async function() { await game.updateFrame(); const { gameMap, me } = game; analyzeMap(gameMap, me); const commandQueue = []; numBlocks = 0; ${ships} ${shipyard} return commandQueue; }, ]; } `; const code = prettier.format(rawCode, { parser: "babylon", plugins: prettierPlugins, }); return code; }
function generateBrowserBot(ships, shipyard) { const rawCode = ` (INPUT_BUFFER) => { const hlt = {}; hlt.constants = { /** * The maximum number of map cells to consider in navigation. */ MAX_BFS_STEPS: 1024, // search an entire 32x32 region /** * Load constants from JSON given by the game engine. */ loadConstants: function loadConstants(constants) { /** The cost to build a single ship. */ this.SHIP_COST = constants['NEW_ENTITY_ENERGY_COST']; /** The cost to build a dropoff. */ this.DROPOFF_COST = constants['DROPOFF_COST']; /** The maximum amount of halite a ship can carry. */ this.MAX_HALITE = constants['MAX_ENERGY']; /** * The maximum number of turns a game can last. This reflects * the fact that smaller maps play for fewer turns. */ this.MAX_TURNS = constants['MAX_TURNS']; /** 1/EXTRACT_RATIO halite (truncated) is collected from a square per turn. */ this.EXTRACT_RATIO = constants['EXTRACT_RATIO']; /** 1/MOVE_COST_RATIO halite (truncated) is needed to move off a cell. */ this.MOVE_COST_RATIO = constants['MOVE_COST_RATIO']; /** Whether inspiration is enabled. */ this.INSPIRATION_ENABLED = constants['INSPIRATION_ENABLED']; /** * A ship is inspired if at least INSPIRATION_SHIP_COUNT * opponent ships are within this Manhattan distance. */ this.INSPIRATION_RADIUS = constants['INSPIRATION_RADIUS']; /** * A ship is inspired if at least this many opponent ships are * within INSPIRATION_RADIUS distance. */ this.INSPIRATION_SHIP_COUNT = constants['INSPIRATION_SHIP_COUNT']; /** An inspired ship mines 1/X halite from a cell per turn instead. */ this.INSPIRED_EXTRACT_RATIO = constants['INSPIRED_EXTRACT_RATIO']; /** An inspired ship that removes Y halite from a cell collects X*Y additional halite. */ this.INSPIRED_BONUS_MULTIPLIER = constants['INSPIRED_BONUS_MULTIPLIER']; /** An inspired ship instead spends 1/X% halite to move. */ this.INSPIRED_MOVE_COST_RATIO = constants['INSPIRED_MOVE_COST_RATIO']; }, }; hlt.commands = (function() { const NORTH = 'n'; const SOUTH = 's'; const EAST = 'e'; const WEST = 'w'; const STAY_STILL = 'o'; const GENERATE = 'g'; const CONSTRUCT = 'c'; const MOVE = 'm'; return { NORTH, SOUTH, EAST, WEST, STAY_STILL, GENERATE, CONSTRUCT, MOVE, }; })(); hlt.positionals = (function(commands) { class Direction { constructor(dx, dy) { this.dx = dx; this.dy = dy; } equals(other) { return this.dx === other.dx && this.dy === other.dy; } toString() { return \`$\{this.constructor.name}($\{this.dx}, $\{this.dy})\`; } static getAllCardinals() { return [ Direction.North, Direction.South, Direction.East, Direction.West ]; } toWireFormat() { if (this.equals(Direction.North)) { return commands.NORTH; } else if (this.equals(Direction.South)) { return commands.SOUTH; } else if (this.equals(Direction.East)) { return commands.EAST; } else if (this.equals(Direction.West)) { return commands.WEST; } else if (this.equals(Direction.Still)) { return commands.STAY_STILL; } throw new Error(\`Non-cardinal direction cannot be converted to wire format: $\{this}\`); } invert() { if (this.equals(Direction.North)) { return Direction.South; } else if (this.equals(Direction.South)) { return Direction.North; } else if (this.equals(Direction.East)) { return Direction.West; } else if (this.equals(Direction.West)) { return Direction.East; } else if (this.equals(Direction.Still)) { return Direction.Still; } throw new Error(\`Non-cardinal direction cannot be inverted: $\{this}\`); } } Direction.North = new Direction(0, -1); Direction.South = new Direction(0, 1); Direction.East = new Direction(1, 0); Direction.West = new Direction(-1, 0); Direction.Still = new Direction(0, 0); class Position { constructor(x, y) { this.x = x; this.y = y; } directionalOffset(direction) { return this.add(new Position(direction.dx, direction.dy)); } getSurroundingCardinals() { return Direction.getAllCardinals() .map(currentDirection => this.directionalOffset(currentDirection)); } add(other) { return new Position(this.x + other.x, this.y + other.y); } sub(other) { return new Position(this.x - other.x, this.y - other.y); } addMut(other) { this.x += other.x; this.y += other.y; } subMut(other) { this.x -= other.x; this.y -= other.y; } abs() { return new Position(Math.abs(this.x), Math.abs(this.y)); } equals(other) { return this.x === other.x && this.y === other.y; } toString() { return \`$\{this.constructor.name}($\{this.x}, $\{this.y})\`; } } return { Direction, Position, }; })(hlt.commands); hlt.entity = (function(positionals, commands, constants) { const { Direction, Position } = positionals; /** Base entity class for Ships, Dropoffs, and Shipyards. */ class Entity { constructor(owner, id, position) { this.owner = owner; this.id = id; this.position = position; } toString() { return \`$\{this.constructor.name}(id=$\{this.id}, $\{this.position})\`; } } /** Represents a dropoff. */ class Dropoff extends Entity { /** * Create a Dropoff for a specific player from the engine input. * @private * @param playerId the player that owns this dropoff * @param {Function} getLine function to read a line of input * @returns {Dropoff} */ static async _generate(playerId, getLine) { const [ id, xPos, yPos ] = (await getLine()) .split(/\\s+/) .map(x => parseInt(x, 10)); return [ id, new Dropoff(playerId, id, new Position(xPos, yPos)) ]; } } /** Represents a shipyard. */ class Shipyard extends Entity { /** Return a move to spawn a new ship at your shipyard. */ spawn() { return commands.GENERATE; } } /** Represents a ship. */ class Ship extends Entity { constructor(owner, id, position, haliteAmount) { super(owner, id, position); this.haliteAmount = haliteAmount; } /** Is this ship at max halite capacity? */ get isFull() { return this.haliteAmount >= constants.MAX_HALITE; } /** Return a move to turn this ship into a dropoff. */ makeDropoff() { return \`$\{commands.CONSTRUCT} $\{this.id}\`; } /** * Return a command to move this ship in a direction without * checking for collisions. * @param {String|Direction} direction the direction to move in * @returns {String} the command */ move(direction) { if (direction.toWireFormat) { direction = direction.toWireFormat(); } return \`$\{commands.MOVE} $\{this.id} $\{direction}\`; } /** * Return a command to not move this ship. * * Not strictly needed, since ships do nothing by default. */ stayStill() { return \`$\{commands.MOVE} $\{this.id} $\{commands.STAY_STILL}\`; } /** * Create a Ship instance for a player using the engine input. * @param playerId the owner * @return The ship ID and ship object. * @private */ static async _generate(playerId, getLine) { const [ shipId, xPos, yPos, halite ] = (await getLine()) .split(/\\s+/) .map(x => parseInt(x, 10)); return [ shipId, new Ship(playerId, shipId, new Position(xPos, yPos), halite) ]; } toString() { return \`$\{this.constructor.name}(id=$\{this.id}, $\{this.position}, cargo=$\{this.haliteAmount} halite)\`; } } return { Entity, Ship, Dropoff, Shipyard, }; })(hlt.positionals, hlt.commands, hlt.constants); hlt.gameMap = (function(constants, entity, positionals) { const { Ship, Dropoff, Shipyard } = entity; const { Direction, Position } = positionals; /** Player object, containing all entities/metadata for the player. */ class Player { constructor(playerId, shipyard, halite=0) { this.id = playerId; this.shipyard = shipyard; this.haliteAmount = halite; this._ships = new Map(); this._dropoffs = new Map(); } /** Get a single ship by its ID. */ getShip(shipId) { return this._ships.get(shipId); } /** Get a list of the player's ships. */ getShips() { const result = []; for (const ship of this._ships.values()) { result.push(ship); } return result; } /** Get a single dropoff by its ID. */ getDropoff(dropoffId) { return this._dropoffs.get(dropoffId); } /** Get a list of the player's dropoffs. */ getDropoffs() { const result = []; for (const dropoff of this._dropoffs.values()) { result.push(dropoff); } return result; } /** Check whether a ship with a given ID exists. */ hasShip(shipId) { return this._ships.has(shipId); } /** * Create a player object using input from the game engine. * @private */ static async _generate(getLine) { const line = await getLine(); const [ playerId, shipyardX, shipyardY ] = line .split(/\\s+/) .map(x => parseInt(x, 10)); return new Player(playerId, new Shipyard(playerId, -1, new Position(shipyardX, shipyardY))); } /** * Update the player object for the current turn using input from * the game engine. * @private */ async _update(numShips, numDropoffs, halite, getLine) { this.haliteAmount = halite; this._ships = new Map(); for (let i = 0; i < numShips; i++) { const [ shipId, ship ] = await Ship._generate(this.id, getLine); this._ships.set(shipId, ship); } this._dropoffs = new Map(); for (let i = 0; i < numDropoffs; i++) { const [ dropoffId, dropoff ] = await Dropoff._generate(this.id, getLine); this._dropoffs.set(dropoffId, dropoff); } } } /** A cell on the game map. */ class MapCell { constructor(position, halite) { this.position = position; this.haliteAmount = halite; this.ship = null; this.structure = null; } /** * @returns {Boolean} whether this cell has no ships or structures. */ get isEmpty() { return !this.isOccupied && !this.hasStructure; } /** * @returns {Boolean} whether this cell has any ships. */ get isOccupied() { return this.ship !== null; } /** * @returns {Boolean} whether this cell has any structures. */ get hasStructure() { return this.structure !== null; } /** * @returns The type of the structure in this cell, or null. */ get structureType() { if (this.hasStructure) { return this.structure.constructor; } return null; } /** * Mark this cell as unsafe (occupied) for navigation. * * Use in conjunction with {@link GameMap#getSafeMove}. * * @param {Ship} ship The ship occupying this cell. */ markUnsafe(ship) { this.ship = ship; } equals(other) { return this.position.equals(other.position); } toString() { return \`MapCell($\{this.position}, halite=$\{this.haliteAmount})\`; } } /** * The game map. * * Can be indexed by a position, or by a contained entity. * Coordinates start at 0. Coordinates are normalized for you. */ class GameMap { constructor(cells, width, height) { this.width = width; this.height = height; this._cells = cells; } /** * Getter for position object or entity objects within the game map * @param location the position or entity to access in this map * @returns the contents housing that cell or entity */ get(...args) { if (args.length === 2) { return this._cells[args[1]][args[0]]; } let [ location ] = args; if (location instanceof Position) { location = this.normalize(location); return this._cells[location.y][location.x]; } else if (location.position) { return this.get(location.position); } return null; } /** * Compute the Manhattan distance between two locations. * Accounts for wrap-around. * @param source The source from where to calculate * @param target The target to where calculate * @returns The distance between these items */ calculateDistance(source, target) { source = this.normalize(source); target = this.normalize(target); const delta = source.sub(target).abs(); return Math.min(delta.x, this.width - delta.x) + Math.min(delta.y, this.height - delta.y); } /** * Normalized the position within the bounds of the toroidal map. * i.e.: Takes a point which may or may not be within width and * height bounds, and places it within those bounds considering * wraparound. * @param {Position} position A position object. * @returns A normalized position object fitting within the bounds of the map */ normalize(position) { let x = ((position.x % this.width) + this.width) % this.width; let y = ((position.y % this.height) + this.height) % this.height; return new Position(x, y); } /** * Determine the relative direction of the target compared to the * source (i.e. is the target north, south, east, or west of the * source). Does not account for wraparound. * @param {Position} source The source position * @param {Position} target The target position * @returns {[Direction | null, Direction | null]} A 2-tuple whose * elements are: the relative direction for each of the Y and X * coordinates (note the inversion), or null if the coordinates * are the same. */ static _getTargetDirection(source, target) { return [ target.y > source.y ? Direction.South : (target.y < source.y ? Direction.North : null), target.x > source.x ? Direction.East : (target.x < source.x ? Direction.West : null), ]; } /** * Return a list of Direction(s) that move closer to the * destination, if any. * * This does not account for collisions. Multiple directions may * be returned if movement in both coordinates is viable. * * @param {Position} source The (normalized) source position * @param {Position} destination The (normalized) target position * @returns A list of Directions moving towards the target (if * any) */ getUnsafeMoves(source, destination) { if (!(source instanceof Position && destination instanceof Position)) { throw new Error("source and destination must be of type Position"); } source = this.normalize(source); destination = this.normalize(destination); const possibleMoves = []; const distance = destination.sub(source).abs(); const [ yDir, xDir ] = GameMap._getTargetDirection(source, destination); if (distance.x !== 0) { possibleMoves.push(distance.x < (this.width / 2) ? xDir : xDir.invert()); } if (distance.y !== 0) { possibleMoves.push(distance.y < (this.height / 2) ? yDir : yDir.invert()); } return possibleMoves; } /** * Returns a singular safe move towards the destination. * @param {Ship} ship - the ship to move * @param {Position} destination - the location to move towards * @return {Direction} */ naiveNavigate(ship, destination) { // No need to normalize destination since getUnsafeMoves does // that for (const direction of this.getUnsafeMoves(ship.position, destination)) { const targetPos = ship.position.directionalOffset(direction); if (!this.get(targetPos).isOccupied) { this.get(targetPos).markUnsafe(ship); return direction; } } return Direction.Still; } static async _generate(getLine) { const [ mapWidth, mapHeight ] = (await getLine()) .split(/\\s+/) .map(x => parseInt(x, 10)); const gameMap = []; for (let i = 0; i < mapHeight; i++) { const row = []; row.fill(null, 0, mapWidth); gameMap.push(row); } for (let y = 0; y < mapHeight; y++) { const cells = (await getLine()).split(/\\s+/); for (let x = 0; x < mapWidth; x++) { gameMap[y][x] = new MapCell(new Position(x, y), parseInt(cells[x], 10)); } } return new GameMap(gameMap, mapWidth, mapHeight); } /** * Update this map object from the input given by the game * engine. */ async _update(getLine) { // Mark cells as safe for navigation (re-mark unsafe cells // later) for (let y = 0; y < this.height; y++) { for (let x = 0; x < this.width; x++) { this.get(x, y).ship = null; } } const numChangedCells = parseInt(await getLine(), 10); for (let i = 0; i < numChangedCells; i++) { const line = (await getLine()); const [ cellX, cellY, cellEnergy ] = line .split(/\\s+/) .map(x => parseInt(x, 10)); this.get(cellX, cellY).haliteAmount = cellEnergy; } } } return { Player, GameMap, MapCell, }; })(hlt.constants, hlt.entity, hlt.positionals); hlt.logging = ({ log(...args) {}, setup(filename) { }, format(args) { return args.map(x => typeof x !== 'string' ? x.toString() : x).join(' '); }, debug(...args) { this.log(\`DEBUG: $\{this.format(args)}\n\`); }, info(...args) { this.log(\`INFO: $\{this.format(args)}\n\`); }, warn(...args) { this.log(\`WARN: $\{this.format(args)}\n\`); }, error(...args) { this.log(\`ERROR: $\{this.format(args)}\n\`); }, }); hlt.networking = (function(constants, logging, gameMap) { const { GameMap, Player } = gameMap; class Game { constructor() { this.turnNumber = 0; const getLine = function() { return new Promise(async (resolve) => { resolve(INPUT_BUFFER.shift()); }); }; this._getLine = getLine; } /** * Initialize a game object collecting all the start-state * instances for pre-game. Also sets up a log file in * "bot-<bot_id>.log". */ async initialize() { const rawConstants = await this._getLine(); constants.loadConstants(JSON.parse(rawConstants)); const [ numPlayers, myId ] = (await this._getLine()) .split(/\\s+/) .map(tok => parseInt(tok, 10)); this.myId = myId; this.players = new Map(); for (let i = 0; i < numPlayers; i++) { this.players.set(i, await Player._generate(this._getLine)); } this.me = this.players.get(this.myId); this.gameMap = await GameMap._generate(this._getLine); } /** Indicate that your bot is ready to play. */ async ready(name) { await sendCommands(this.myId, [ name ]); } /** * Updates the game object's state. */ async updateFrame() { this.turnNumber = parseInt(await this._getLine(), 10); logging.info(\`================ TURN $\{this.turnNumber.toString().padStart(3, '0')} ================\`); for (let i = 0; i < this.players.size; i++) { const [ player, numShips, numDropoffs, halite ] = (await this._getLine()) .split(/\\s+/) .map(x => parseInt(x, 10)); await this.players.get(player)._update(numShips, numDropoffs, halite, this._getLine); } await this.gameMap._update(this._getLine); // Mark cells with ships as unsafe for navigation for (const player of this.players.values()) { for (const ship of player.getShips()) { this.gameMap.get(ship.position).markUnsafe(ship); } this.gameMap.get(player.shipyard.position).structure = player.shipyard; for (const dropoff of player.getDropoffs()) { this.gameMap.get(dropoff.position).structure = dropoff; } } } /** * Send all commands to the game engine, effectively ending your * turn. * @param {Array} commands */ async endTurn(commands) { await sendCommands(this.myId, commands); } } /** * Sends a list of commands to the engine. * @param commands The list of commands to send. * @returns a Promise fulfilled once stdout is drained. */ function sendCommands(botId, commands) { return new Promise((resolve) => { SEND_COMMANDS(botId, commands); resolve(); }); } return { Player, Game, sendCommands, }; })(hlt.constants, hlt.logging, hlt.gameMap); hlt.Direction = hlt.positionals.Direction; hlt.Position = hlt.positionals.Position; hlt.Entity = hlt.entity.Entity; hlt.Dropoff = hlt.entity.Dropoff; hlt.Shipyard = hlt.entity.Shipyard; hlt.Ship = hlt.entity.Ship; hlt.Game = hlt.networking.Game; hlt.Player = hlt.networking.Player; hlt.MapCell = hlt.gameMap.MapCell; hlt.GameMap = hlt.gameMap.GameMap; const { Direction, Position } = hlt.positionals; const logging = hlt.logging; ${utils} const shipState = new Map(); const game = new hlt.Game(); return [ async function(log) { logging.log = log; return game.initialize().then(async () => { // At this point "game" variable is populated with initial map data. // This is a good place to do computationally expensive start-up pre-processing. // As soon as you call "ready" function below, the 2 second per turn timer will start. return "MyJavaScriptBot"; }); }, async function() { await game.updateFrame(); const { gameMap, me } = game; analyzeMap(gameMap, me); const commandQueue = []; numBlocks = 0; ${ships} ${shipyard} return commandQueue; }, ]; } `; const code = prettier.format(rawCode, { parser: "babylon", plugins: prettierPlugins, }); return code; }
JavaScript
function generateStandardBot(ships, shipyard) { const rawCode = ` const hlt = require('./hlt'); const { Direction, Position } = require('./hlt/positionals'); const logging = require('./hlt/logging'); ${utils} const game = new hlt.Game(); game.initialize().then(async () => { // At this point "game" variable is populated with initial map data. // This is a good place to do computationally expensive start-up pre-processing. // As soon as you call "ready" function below, the 2 second per turn timer will start. await game.ready('MyJavaScriptBot'); logging.info(\`My Player ID is $\{game.myId}.\`); const shipState = new Map(); while (true) { await game.updateFrame(); const { gameMap, me } = game; analyzeMap(gameMap, me); const commandQueue = []; ${ships} ${shipyard} await game.endTurn(commandQueue); } }); `; const code = prettier.format(rawCode, { parser: "babylon", plugins: prettierPlugins, }); return code; }
function generateStandardBot(ships, shipyard) { const rawCode = ` const hlt = require('./hlt'); const { Direction, Position } = require('./hlt/positionals'); const logging = require('./hlt/logging'); ${utils} const game = new hlt.Game(); game.initialize().then(async () => { // At this point "game" variable is populated with initial map data. // This is a good place to do computationally expensive start-up pre-processing. // As soon as you call "ready" function below, the 2 second per turn timer will start. await game.ready('MyJavaScriptBot'); logging.info(\`My Player ID is $\{game.myId}.\`); const shipState = new Map(); while (true) { await game.updateFrame(); const { gameMap, me } = game; analyzeMap(gameMap, me); const commandQueue = []; ${ships} ${shipyard} await game.endTurn(commandQueue); } }); `; const code = prettier.format(rawCode, { parser: "babylon", plugins: prettierPlugins, }); return code; }
JavaScript
function onComplete(tween) { //this tween goes backwards this.tweens.add({ targets: [this.wheelContainer], angle: this.wheelContainer.angle - backDegrees, duration: Phaser.Math.Between(gameOptions.rotationTimeRange.min, gameOptions.rotationTimeRange.max), ease: "Cubic.easeIn", callbackScope: this, onComplete: function onComplete(tween) { this.canSpin = true; gameOptions.isSpinning = false; } }); }
function onComplete(tween) { //this tween goes backwards this.tweens.add({ targets: [this.wheelContainer], angle: this.wheelContainer.angle - backDegrees, duration: Phaser.Math.Between(gameOptions.rotationTimeRange.min, gameOptions.rotationTimeRange.max), ease: "Cubic.easeIn", callbackScope: this, onComplete: function onComplete(tween) { this.canSpin = true; gameOptions.isSpinning = false; } }); }
JavaScript
async function processTrigger(msg, cfg, snapshot = {}) { try { // Authenticate and get the token from Snazzy Contacts const { applicationUid } = cfg; // const token = cfg.API_KEY; const token = await getToken(cfg); // Set the snapshot if it is not provided snapshot.lastUpdated = snapshot.lastUpdated || (new Date(0)).getTime(); const startSnapshot = snapshot.lastUpdated; /** Create an OIH meta object which is required * to make the Hub and Spoke architecture work properly */ const oihMeta = { applicationUid: applicationUid || 'snazzy', }; const persons = await getEntries(token, snapshot, 'person', cfg.devMode, cfg.searchTerm); console.error(`Found ${persons.result.length} new records.`); if (persons.result.length > 0) { persons.result.forEach((elem) => { const newElement = {}; if (!cfg.targetApp || (cfg.snazzyFlowVersion && cfg.snazzyFlowVersion > 1)) oihMeta.recordUid = elem.uid; if (cfg.targetApp) { // If using Snazzy reference handling, add target reference if (elem.contactData) { let index; if (cfg.metaUserId) { index = elem.contactData.findIndex(cd => cd.type === `reference:${cfg.targetApp}_${cfg.metaUserId}`); } else { index = elem.contactData.findIndex(cd => cd.type === `reference:${cfg.targetApp}`); } if (index !== -1) { oihMeta.recordUid = elem.contactData[index].value; oihMeta.applicationUid = cfg.targetApp; } } } delete elem.uid; newElement.metadata = oihMeta; newElement.data = elem; const transformedElement = transform(newElement, cfg, personToOih); // Emit the object with meta and data properties this.emit('data', transformedElement); }); // Get the lastUpdate property from the last object and attach it to snapshot if ( cfg.searchTerm && persons && persons.result && persons.result[persons.result.length - 1].lastUpdate ) { snapshot.lastUpdated = persons.result[persons.result.length - 1].lastUpdate; } else { snapshot.lastUpdated = Date.parse(persons.result[persons.result.length - 1].updatedAt); } console.error(`New snapshot: ${JSON.stringify(snapshot, undefined, 2)}`); } this.emit('snapshot', snapshot); if (cfg.deletes && startSnapshot > 0) { const result = await getAllDeletedSince(startSnapshot, token, cfg, 'Person', cfg.devMode); if (result && Array.isArray(result)) { const { length } = result; console.log(`Found ${length} deleted entries since ${startSnapshot}`); for (let i = 0; i < length; i += 1) { this.emit('data', result[i]); } } } } catch (e) { console.log(`ERROR: ${e}`); this.emit('error', e); } }
async function processTrigger(msg, cfg, snapshot = {}) { try { // Authenticate and get the token from Snazzy Contacts const { applicationUid } = cfg; // const token = cfg.API_KEY; const token = await getToken(cfg); // Set the snapshot if it is not provided snapshot.lastUpdated = snapshot.lastUpdated || (new Date(0)).getTime(); const startSnapshot = snapshot.lastUpdated; /** Create an OIH meta object which is required * to make the Hub and Spoke architecture work properly */ const oihMeta = { applicationUid: applicationUid || 'snazzy', }; const persons = await getEntries(token, snapshot, 'person', cfg.devMode, cfg.searchTerm); console.error(`Found ${persons.result.length} new records.`); if (persons.result.length > 0) { persons.result.forEach((elem) => { const newElement = {}; if (!cfg.targetApp || (cfg.snazzyFlowVersion && cfg.snazzyFlowVersion > 1)) oihMeta.recordUid = elem.uid; if (cfg.targetApp) { // If using Snazzy reference handling, add target reference if (elem.contactData) { let index; if (cfg.metaUserId) { index = elem.contactData.findIndex(cd => cd.type === `reference:${cfg.targetApp}_${cfg.metaUserId}`); } else { index = elem.contactData.findIndex(cd => cd.type === `reference:${cfg.targetApp}`); } if (index !== -1) { oihMeta.recordUid = elem.contactData[index].value; oihMeta.applicationUid = cfg.targetApp; } } } delete elem.uid; newElement.metadata = oihMeta; newElement.data = elem; const transformedElement = transform(newElement, cfg, personToOih); // Emit the object with meta and data properties this.emit('data', transformedElement); }); // Get the lastUpdate property from the last object and attach it to snapshot if ( cfg.searchTerm && persons && persons.result && persons.result[persons.result.length - 1].lastUpdate ) { snapshot.lastUpdated = persons.result[persons.result.length - 1].lastUpdate; } else { snapshot.lastUpdated = Date.parse(persons.result[persons.result.length - 1].updatedAt); } console.error(`New snapshot: ${JSON.stringify(snapshot, undefined, 2)}`); } this.emit('snapshot', snapshot); if (cfg.deletes && startSnapshot > 0) { const result = await getAllDeletedSince(startSnapshot, token, cfg, 'Person', cfg.devMode); if (result && Array.isArray(result)) { const { length } = result; console.log(`Found ${length} deleted entries since ${startSnapshot}`); for (let i = 0; i < length; i += 1) { this.emit('data', result[i]); } } } } catch (e) { console.log(`ERROR: ${e}`); this.emit('error', e); } }
JavaScript
async function fetchAll(options, snapshot) { try { const entries = await request.get(options); if (Object.entries(entries.body).length === 0 && entries.body.constructor === Object) { return false; } const result = (entries.body.data) ? entries.body.data : []; // Sort the objects by lastUpdate ASC result.sort((a, b) => Date.parse(a.updatedAt) - Date.parse(b.updatedAt)); const newEntries = []; const { length } = result; for (let i = 0; i < length; i += 1) { const timestamp = Date.parse(result[i].updatedAt); if (timestamp > snapshot.lastUpdated) { newEntries.push(result[i]); } } // console.log('newEntries', newEntries); return { result: newEntries, count: newEntries.length, }; } catch (e) { throw new Error(e); } }
async function fetchAll(options, snapshot) { try { const entries = await request.get(options); if (Object.entries(entries.body).length === 0 && entries.body.constructor === Object) { return false; } const result = (entries.body.data) ? entries.body.data : []; // Sort the objects by lastUpdate ASC result.sort((a, b) => Date.parse(a.updatedAt) - Date.parse(b.updatedAt)); const newEntries = []; const { length } = result; for (let i = 0; i < length; i += 1) { const timestamp = Date.parse(result[i].updatedAt); if (timestamp > snapshot.lastUpdated) { newEntries.push(result[i]); } } // console.log('newEntries', newEntries); return { result: newEntries, count: newEntries.length, }; } catch (e) { throw new Error(e); } }
JavaScript
async function upsertObject(msg, token, objectExists, type, recordUid, devMode) { if (!type) { return false; } const BASE_URI = devMode === true ? 'https://dev-api.snazzyapps.de/api' : 'https://api.snazzycontacts.com/api'; let newObject; let uri; let method; if (objectExists) { // Update the object if it already exists method = 'PUT'; uri = `${BASE_URI}/operation/${type}`; newObject = msg; newObject.uid = recordUid; } else { // Create the object if it does not exist method = 'POST'; uri = `${BASE_URI}/operation`; newObject = msg; delete newObject.uid; } try { const options = { method, uri, json: true, headers: { Authorization: `Bearer ${token}`, }, body: newObject, qs: { type, }, }; const response = await request(options); if (response.statusCode !== 200) { console.log('Could not upsert object!'); console.log('Body: ', JSON.stringify(options.body)); console.log('Status: ', response.statusCode); console.log(JSON.stringify(response.body)); } return response; } catch (e) { return e; } }
async function upsertObject(msg, token, objectExists, type, recordUid, devMode) { if (!type) { return false; } const BASE_URI = devMode === true ? 'https://dev-api.snazzyapps.de/api' : 'https://api.snazzycontacts.com/api'; let newObject; let uri; let method; if (objectExists) { // Update the object if it already exists method = 'PUT'; uri = `${BASE_URI}/operation/${type}`; newObject = msg; newObject.uid = recordUid; } else { // Create the object if it does not exist method = 'POST'; uri = `${BASE_URI}/operation`; newObject = msg; delete newObject.uid; } try { const options = { method, uri, json: true, headers: { Authorization: `Bearer ${token}`, }, body: newObject, qs: { type, }, }; const response = await request(options); if (response.statusCode !== 200) { console.log('Could not upsert object!'); console.log('Body: ', JSON.stringify(options.body)); console.log('Status: ', response.statusCode); console.log(JSON.stringify(response.body)); } return response; } catch (e) { return e; } }
JavaScript
async function upsertObjectAdvanced(msg, token, objectExists, type, recordUid, appId, metaUserId, devMode) { if (!type) { return false; } const BASE_URI = devMode === true ? 'https://dev-api.snazzyapps.de/api' : 'https://api.snazzycontacts.com/api'; const newObject = msg; const uri = `${BASE_URI}/operation/integration/${type}`; const qs = { appId, recordUid, metaUserId, }; delete newObject.uid; try { const options = { method: 'PUT', uri, json: true, headers: { Authorization: `Bearer ${token}`, }, body: newObject, qs, }; const response = await request(options); if (response.statusCode !== 200) { console.log('Could not upsert object!'); console.log('Body: ', JSON.stringify(options.body)); console.log('Status: ', response.statusCode); console.log(JSON.stringify(response.body)); } return response; } catch (e) { return e; } }
async function upsertObjectAdvanced(msg, token, objectExists, type, recordUid, appId, metaUserId, devMode) { if (!type) { return false; } const BASE_URI = devMode === true ? 'https://dev-api.snazzyapps.de/api' : 'https://api.snazzycontacts.com/api'; const newObject = msg; const uri = `${BASE_URI}/operation/integration/${type}`; const qs = { appId, recordUid, metaUserId, }; delete newObject.uid; try { const options = { method: 'PUT', uri, json: true, headers: { Authorization: `Bearer ${token}`, }, body: newObject, qs, }; const response = await request(options); if (response.statusCode !== 200) { console.log('Could not upsert object!'); console.log('Body: ', JSON.stringify(options.body)); console.log('Status: ', response.statusCode); console.log(JSON.stringify(response.body)); } return response; } catch (e) { return e; } }
JavaScript
function formatSearchResult(contact) { const formattedObject = { uid: contact.uid, lastUpdate: contact.timestamp, contactData: [], addresses: [], categories: [], }; if (contact.name) { formattedObject.name = contact.name; formattedObject.logo = contact.logo; } else { formattedObject.firstName = contact.firstName; formattedObject.lastName = contact.lastName; formattedObject.middleName = contact.middleName; formattedObject.title = contact.title; formattedObject.photo = contact.photo; formattedObject.salutation = contact.salutation; formattedObject.gender = contact.gender; formattedObject.birthday = contact.birthday; formattedObject.displayName = contact.displayName; formattedObject.nickname = contact.nickname; } for (let i = 0; `contactData.${i}.type` in contact; i += 1) { const cd = { type: contact[`contactData.${i}.type`], value: contact[`contactData.${i}.value`], }; formattedObject.contactData.push(cd); } for (let i = 0; `addresses.${i}.street` in contact || `addresses.${i}.streetNumber` in contact || `addresses.${i}.city` in contact || `addresses.${i}.zipcode` in contact || `addresses.${i}.country` in contact; i += 1) { const adr = { street: contact[`addresses.${i}.street`] || '', streetNumber: contact[`addresses.${i}.streetNumber`] || '', city: contact[`addresses.${i}.city`] || '', zipcode: contact[`addresses.${i}.zipcode`] || '', country: contact[`addresses.${i}.country`] || '', }; formattedObject.addresses.push(adr); } for (let i = 0; `categories.${i}.label` in contact; i += 1) { const cat = { label: contact[`categories.${i}.label`], uid: contact[`categories.${i}.uid`], }; formattedObject.categories.push(cat); } return formattedObject; }
function formatSearchResult(contact) { const formattedObject = { uid: contact.uid, lastUpdate: contact.timestamp, contactData: [], addresses: [], categories: [], }; if (contact.name) { formattedObject.name = contact.name; formattedObject.logo = contact.logo; } else { formattedObject.firstName = contact.firstName; formattedObject.lastName = contact.lastName; formattedObject.middleName = contact.middleName; formattedObject.title = contact.title; formattedObject.photo = contact.photo; formattedObject.salutation = contact.salutation; formattedObject.gender = contact.gender; formattedObject.birthday = contact.birthday; formattedObject.displayName = contact.displayName; formattedObject.nickname = contact.nickname; } for (let i = 0; `contactData.${i}.type` in contact; i += 1) { const cd = { type: contact[`contactData.${i}.type`], value: contact[`contactData.${i}.value`], }; formattedObject.contactData.push(cd); } for (let i = 0; `addresses.${i}.street` in contact || `addresses.${i}.streetNumber` in contact || `addresses.${i}.city` in contact || `addresses.${i}.zipcode` in contact || `addresses.${i}.country` in contact; i += 1) { const adr = { street: contact[`addresses.${i}.street`] || '', streetNumber: contact[`addresses.${i}.streetNumber`] || '', city: contact[`addresses.${i}.city`] || '', zipcode: contact[`addresses.${i}.zipcode`] || '', country: contact[`addresses.${i}.country`] || '', }; formattedObject.addresses.push(adr); } for (let i = 0; `categories.${i}.label` in contact; i += 1) { const cat = { label: contact[`categories.${i}.label`], uid: contact[`categories.${i}.uid`], }; formattedObject.categories.push(cat); } return formattedObject; }
JavaScript
async function executeSearch(options, type, snapshot) { const response = await request(options); if (response.statusCode !== 200) { console.error('Search failed!'); console.error('Status: ', response.statusCode); console.error(JSON.stringify(response.body)); return false; } const objects = response.body[1]; const result = []; for (let i = 0; i < objects.length; i += 1) { const currentObject = objects[i]; if (currentObject.timestamp > snapshot.lastUpdated) { if ( (type === 'organization' && currentObject.name) || (type === 'person' && (currentObject.firstName || currentObject.lastName)) ) result.push(formatSearchResult(currentObject)); } } result.sort((a, b) => parseInt(a.lastUpdate, 10) - parseInt(b.lastUpdate, 10)); return { result, count: result.length, }; }
async function executeSearch(options, type, snapshot) { const response = await request(options); if (response.statusCode !== 200) { console.error('Search failed!'); console.error('Status: ', response.statusCode); console.error(JSON.stringify(response.body)); return false; } const objects = response.body[1]; const result = []; for (let i = 0; i < objects.length; i += 1) { const currentObject = objects[i]; if (currentObject.timestamp > snapshot.lastUpdated) { if ( (type === 'organization' && currentObject.name) || (type === 'person' && (currentObject.firstName || currentObject.lastName)) ) result.push(formatSearchResult(currentObject)); } } result.sort((a, b) => parseInt(a.lastUpdate, 10) - parseInt(b.lastUpdate, 10)); return { result, count: result.length, }; }
JavaScript
async function deleteObject(token, type, recordUid, devMode) { if (!type) { return false; } const BASE_URI = devMode === true ? 'https://dev-api.snazzyapps.de/api' : 'https://api.snazzycontacts.com/api'; const method = 'DELETE'; const uri = `${BASE_URI}/${type}`; const newObject = { signature: '', }; try { const options = { method, uri, json: true, headers: { Authorization: `Bearer ${token}`, }, body: { uid: recordUid, }, }; console.log('Options:', options); const response = await request(options); if (response.statusCode !== 200) { console.log('Could not delete object!'); console.log('Body: ', JSON.stringify(options.body)); console.log('Status: ', response.statusCode); console.log(JSON.stringify(response.body)); newObject.delete = 'failed'; if (response.statusCode !== 404) { newObject.comment = 'Not found'; } else if (response.statusCode !== 401 || response.statusCode !== 403) { newObject.delete = 'denied'; newObject.comment = `${response.statusCode}`; } } else { newObject.delete = 'confirmed'; } newObject.timestamp = `${Date.now()}`; return newObject; } catch (e) { console.log(e); return false; } }
async function deleteObject(token, type, recordUid, devMode) { if (!type) { return false; } const BASE_URI = devMode === true ? 'https://dev-api.snazzyapps.de/api' : 'https://api.snazzycontacts.com/api'; const method = 'DELETE'; const uri = `${BASE_URI}/${type}`; const newObject = { signature: '', }; try { const options = { method, uri, json: true, headers: { Authorization: `Bearer ${token}`, }, body: { uid: recordUid, }, }; console.log('Options:', options); const response = await request(options); if (response.statusCode !== 200) { console.log('Could not delete object!'); console.log('Body: ', JSON.stringify(options.body)); console.log('Status: ', response.statusCode); console.log(JSON.stringify(response.body)); newObject.delete = 'failed'; if (response.statusCode !== 404) { newObject.comment = 'Not found'; } else if (response.statusCode !== 401 || response.statusCode !== 403) { newObject.delete = 'denied'; newObject.comment = `${response.statusCode}`; } } else { newObject.delete = 'confirmed'; } newObject.timestamp = `${Date.now()}`; return newObject; } catch (e) { console.log(e); return false; } }
JavaScript
function upToDate(local, remote) { if (!local || !remote || local.length === 0 || remote.length === 0) return false; if (local == remote) return true; if (VPAT.test(local) && VPAT.test(remote)) { var lparts = local.split('.'); while (lparts.length < 3) lparts.push('0'); var rparts = remote.split('.'); while (rparts.length < 3) rparts.push('0'); for (var i = 0; i < 3; i++) { var l = parseInt(lparts[i], 10); var r = parseInt(rparts[i], 10); if (l === r) continue; return l > r; } return true; } else { return local >= remote; } }
function upToDate(local, remote) { if (!local || !remote || local.length === 0 || remote.length === 0) return false; if (local == remote) return true; if (VPAT.test(local) && VPAT.test(remote)) { var lparts = local.split('.'); while (lparts.length < 3) lparts.push('0'); var rparts = remote.split('.'); while (rparts.length < 3) rparts.push('0'); for (var i = 0; i < 3; i++) { var l = parseInt(lparts[i], 10); var r = parseInt(rparts[i], 10); if (l === r) continue; return l > r; } return true; } else { return local >= remote; } }
JavaScript
async function run() { try { woocommerce(); } catch ( error ) { core.setFailed( error.message ); } }
async function run() { try { woocommerce(); } catch ( error ) { core.setFailed( error.message ); } }
JavaScript
function isElementVisible(el) { // see https://stackoverflow.com/a/21627295 var rect = el.getBoundingClientRect(); var top = rect.top; var height = rect.height; var el = el.parentNode; if (rect.bottom < 0) return false; if (top > document.documentElement.clientHeight) return false; do { rect = el.getBoundingClientRect(); if (top <= rect.bottom === false) return false; if ((top + height) <= rect.top) return false; el = el.parentNode; } while (el != document.body) return true; }
function isElementVisible(el) { // see https://stackoverflow.com/a/21627295 var rect = el.getBoundingClientRect(); var top = rect.top; var height = rect.height; var el = el.parentNode; if (rect.bottom < 0) return false; if (top > document.documentElement.clientHeight) return false; do { rect = el.getBoundingClientRect(); if (top <= rect.bottom === false) return false; if ((top + height) <= rect.top) return false; el = el.parentNode; } while (el != document.body) return true; }
JavaScript
Gamertag(gt) { let regex = /[a-z0-9_-]{5,16}/i; if (!this.token) { throw new TypeError("API token not provided"); } if (!regex.test(gt)) { throw new TypeError("GamerTag must be Alpha-Numerical"); } return new Promise(async (resolve, reject) => { try { const res = await wump(`${this.baseurl}${this.version}/xbox?gamertag=${gt}`, { method: "POST", headers: { "User-Agent": this.useragent, "Authorization": this.token } }).send(); resolve(res.json()); } catch (err) { reject(new Error(err)); } }); }
Gamertag(gt) { let regex = /[a-z0-9_-]{5,16}/i; if (!this.token) { throw new TypeError("API token not provided"); } if (!regex.test(gt)) { throw new TypeError("GamerTag must be Alpha-Numerical"); } return new Promise(async (resolve, reject) => { try { const res = await wump(`${this.baseurl}${this.version}/xbox?gamertag=${gt}`, { method: "POST", headers: { "User-Agent": this.useragent, "Authorization": this.token } }).send(); resolve(res.json()); } catch (err) { reject(new Error(err)); } }); }
JavaScript
PSN(psn) { let regex = /[a-z0-9_-]{5,16}/i; if (!this.token) { throw new TypeError("API token not provided"); } if (!regex.test(psn)) { throw new TypeError("PSN must be Alpha-Numerical"); } return new Promise(async (resolve, reject) => { try { const res = await wump(`${this.baseurl}${this.version}/psn?psn=${psn}`, { method: "POST", headers: { "User-Agent": this.useragent, "Authorization": this.token } }).send(); resolve(res.json()); } catch (err) { reject(new Error(err)); } }); }
PSN(psn) { let regex = /[a-z0-9_-]{5,16}/i; if (!this.token) { throw new TypeError("API token not provided"); } if (!regex.test(psn)) { throw new TypeError("PSN must be Alpha-Numerical"); } return new Promise(async (resolve, reject) => { try { const res = await wump(`${this.baseurl}${this.version}/psn?psn=${psn}`, { method: "POST", headers: { "User-Agent": this.useragent, "Authorization": this.token } }).send(); resolve(res.json()); } catch (err) { reject(new Error(err)); } }); }
JavaScript
function arrangeRows() { var fullRowIndex = 0; for (var row = 0; row < TOTAL_ROWS-1; row++) { if (isRowFull(row)) { moveRowsDown(row); lines = lines + 1; score += 10; //bases++; levelLines = levelLines+1; increaseLevel(); } // end if } // end for } // end arrangeRows
function arrangeRows() { var fullRowIndex = 0; for (var row = 0; row < TOTAL_ROWS-1; row++) { if (isRowFull(row)) { moveRowsDown(row); lines = lines + 1; score += 10; //bases++; levelLines = levelLines+1; increaseLevel(); } // end if } // end for } // end arrangeRows
JavaScript
function renderCal() { for (var i = 0; i < hourArr.length; i++) { //create div for each row var row = $("<div>"); row.addClass("row row1 time-block"); row.attr("time-hour", hourArr[i].hour) row.attr("id", hourArr[i].military); $(".container").append(row); //create col 1 of 3 for hr var hourCol = $("<div>"); hourCol.addClass("col col-2 justify-content-center hour row time-block ml-2 py-4"); hourCol.text($(row).attr("time-hour")); $(row).append(hourCol); //create col 2 of 3 for appt text var inputCol = $("<input>"); inputCol.addClass("col col-8 input row time-block ml-3"); inputCol.attr("input-key", hourArr[i].military); $(row).append(inputCol); //create col 3 of 3 to hold saveBtn var saveCol = $("<div>"); saveCol.addClass("col col-2 justify-content-center hour save row time-block ml-3"); $(row).append(saveCol); }}
function renderCal() { for (var i = 0; i < hourArr.length; i++) { //create div for each row var row = $("<div>"); row.addClass("row row1 time-block"); row.attr("time-hour", hourArr[i].hour) row.attr("id", hourArr[i].military); $(".container").append(row); //create col 1 of 3 for hr var hourCol = $("<div>"); hourCol.addClass("col col-2 justify-content-center hour row time-block ml-2 py-4"); hourCol.text($(row).attr("time-hour")); $(row).append(hourCol); //create col 2 of 3 for appt text var inputCol = $("<input>"); inputCol.addClass("col col-8 input row time-block ml-3"); inputCol.attr("input-key", hourArr[i].military); $(row).append(inputCol); //create col 3 of 3 to hold saveBtn var saveCol = $("<div>"); saveCol.addClass("col col-2 justify-content-center hour save row time-block ml-3"); $(row).append(saveCol); }}
JavaScript
function displayAppt() { hourArr.forEach(function (_thisHour) { $(".input").eq(_thisHour.military-8).val(_thisHour.appt); console.log(_thisHour.appt); }) }
function displayAppt() { hourArr.forEach(function (_thisHour) { $(".input").eq(_thisHour.military-8).val(_thisHour.appt); console.log(_thisHour.appt); }) }
JavaScript
function initCal () { var storedAppt = JSON.parse(localStorage.getItem("hourArr")); console.log(storedAppt); if (storedAppt !== null) { hourArr = storedAppt; } displayAppt(); }
function initCal () { var storedAppt = JSON.parse(localStorage.getItem("hourArr")); console.log(storedAppt); if (storedAppt !== null) { hourArr = storedAppt; } displayAppt(); }
JavaScript
function doTestSignedValue(readValue, writeValue, epsilon, lowerLimit, upperLimit, filter) { var encoder = new jspb.BinaryEncoder(); // Encode zero and limits. writeValue.call(encoder, filter(lowerLimit)); writeValue.call(encoder, filter(-epsilon)); writeValue.call(encoder, filter(0)); writeValue.call(encoder, filter(epsilon)); writeValue.call(encoder, filter(upperLimit)); var inputValues = []; // Encode negative values. for (var cursor = lowerLimit; cursor < -epsilon; cursor /= 1.1) { var val = filter(cursor); writeValue.call(encoder, val); inputValues.push(val); } // Encode positive values. for (var cursor = epsilon; cursor < upperLimit; cursor *= 1.1) { var val = filter(cursor); writeValue.call(encoder, val); inputValues.push(val); } var decoder = jspb.BinaryDecoder.alloc(encoder.end()); // Check zero and limits. assertEquals(filter(lowerLimit), readValue.call(decoder)); assertEquals(filter(-epsilon), readValue.call(decoder)); assertEquals(filter(0), readValue.call(decoder)); assertEquals(filter(epsilon), readValue.call(decoder)); assertEquals(filter(upperLimit), readValue.call(decoder)); // Verify decoded values. for (var i = 0; i < inputValues.length; i++) { assertEquals(inputValues[i], readValue.call(decoder)); } // Encoding values outside the valid range should assert. assertThrows(function() {writeValue.call(encoder, lowerLimit * 1.1);}); assertThrows(function() {writeValue.call(encoder, upperLimit * 1.1);}); }
function doTestSignedValue(readValue, writeValue, epsilon, lowerLimit, upperLimit, filter) { var encoder = new jspb.BinaryEncoder(); // Encode zero and limits. writeValue.call(encoder, filter(lowerLimit)); writeValue.call(encoder, filter(-epsilon)); writeValue.call(encoder, filter(0)); writeValue.call(encoder, filter(epsilon)); writeValue.call(encoder, filter(upperLimit)); var inputValues = []; // Encode negative values. for (var cursor = lowerLimit; cursor < -epsilon; cursor /= 1.1) { var val = filter(cursor); writeValue.call(encoder, val); inputValues.push(val); } // Encode positive values. for (var cursor = epsilon; cursor < upperLimit; cursor *= 1.1) { var val = filter(cursor); writeValue.call(encoder, val); inputValues.push(val); } var decoder = jspb.BinaryDecoder.alloc(encoder.end()); // Check zero and limits. assertEquals(filter(lowerLimit), readValue.call(decoder)); assertEquals(filter(-epsilon), readValue.call(decoder)); assertEquals(filter(0), readValue.call(decoder)); assertEquals(filter(epsilon), readValue.call(decoder)); assertEquals(filter(upperLimit), readValue.call(decoder)); // Verify decoded values. for (var i = 0; i < inputValues.length; i++) { assertEquals(inputValues[i], readValue.call(decoder)); } // Encoding values outside the valid range should assert. assertThrows(function() {writeValue.call(encoder, lowerLimit * 1.1);}); assertThrows(function() {writeValue.call(encoder, upperLimit * 1.1);}); }
JavaScript
function parserOnHeadersComplete(info) { var parser = this; var headers = info.headers; if (!headers) { headers = parser._headers; parser.incoming.addHeaders(headers); parser._headers = {}; } else { parser.incoming.addHeaders(headers); } // add header fields of headers to incoming.headers parser.incoming.addHeaders(headers); parser.incoming.statusCode = info.status; parser.incoming.statusMessage = info.status_msg; parser.incoming.started = true; // For client side, if response to 'HEAD' request, we will skip parsing body if (parser.incoming.statusCode == 100) { return false; } return parser.incoming.clientRequest.headersComplete(); }
function parserOnHeadersComplete(info) { var parser = this; var headers = info.headers; if (!headers) { headers = parser._headers; parser.incoming.addHeaders(headers); parser._headers = {}; } else { parser.incoming.addHeaders(headers); } // add header fields of headers to incoming.headers parser.incoming.addHeaders(headers); parser.incoming.statusCode = info.status; parser.incoming.statusMessage = info.status_msg; parser.incoming.started = true; // For client side, if response to 'HEAD' request, we will skip parsing body if (parser.incoming.statusCode == 100) { return false; } return parser.incoming.clientRequest.headersComplete(); }
JavaScript
function parserOnBody(buf, start, len) { var parser = this; var incoming = parser.incoming; if (!incoming) { return; } // Push body part into incoming stream, which will emit 'data' event var body = buf.slice(start, start + len); incoming.push(body); }
function parserOnBody(buf, start, len) { var parser = this; var incoming = parser.incoming; if (!incoming) { return; } // Push body part into incoming stream, which will emit 'data' event var body = buf.slice(start, start + len); incoming.push(body); }
JavaScript
function parserOnMessageComplete() { var parser = this; var incoming = parser.incoming; if (incoming) { if (incoming.statusCode == 100) { incoming.headers = {}; incoming.statusCode = null; incoming.statusMessage = null; incoming.started = false; } else { incoming.completed = true; // no more data from incoming, stream will emit 'end' event incoming.push(null); } } }
function parserOnMessageComplete() { var parser = this; var incoming = parser.incoming; if (incoming) { if (incoming.statusCode == 100) { incoming.headers = {}; incoming.statusCode = null; incoming.statusMessage = null; incoming.started = false; } else { incoming.completed = true; // no more data from incoming, stream will emit 'end' event incoming.push(null); } } }
JavaScript
function cbOnEnd() { var incoming = this; var parser = incoming.parser; if (parser) { // Unref all links to parser, make parser GCed parser.finish(); parser = null; incoming.parser = null; } }
function cbOnEnd() { var incoming = this; var parser = incoming.parser; if (parser) { // Unref all links to parser, make parser GCed parser.finish(); parser = null; incoming.parser = null; } }
JavaScript
function cbOnData(chunk) { var incoming = this; if (!incoming) { return false; } var parser = incoming.parser; var clientRequest = incoming.clientRequest; chunk = new Buffer(chunk); var ret = parser.execute(chunk); if (ret instanceof Error) { parser.finish(); // Unref all links to parser, make parser GCed parser = null; clientRequest.onError(ret); return false; } return true; }
function cbOnData(chunk) { var incoming = this; if (!incoming) { return false; } var parser = incoming.parser; var clientRequest = incoming.clientRequest; chunk = new Buffer(chunk); var ret = parser.execute(chunk); if (ret instanceof Error) { parser.finish(); // Unref all links to parser, make parser GCed parser = null; clientRequest.onError(ret); return false; } return true; }
JavaScript
function randomTraceId() { var digits = '0123456789abcdef'; var n = ''; for (var i = 0; i < 16; i += 1) { var rand = Math.floor(Math.random() * 16); n += digits[rand]; } return n; }
function randomTraceId() { var digits = '0123456789abcdef'; var n = ''; for (var i = 0; i < 16; i += 1) { var rand = Math.floor(Math.random() * 16); n += digits[rand]; } return n; }
JavaScript
function PartialSpan(traceId, timeoutTimestamp) { _classCallCheck(this, PartialSpan); this.traceId = traceId; this.timeoutTimestamp = timeoutTimestamp; this.delegate = new Span$1(traceId); this.localEndpoint = new Endpoint$2({}); this.shouldFlush = false; }
function PartialSpan(traceId, timeoutTimestamp) { _classCallCheck(this, PartialSpan); this.traceId = traceId; this.timeoutTimestamp = timeoutTimestamp; this.delegate = new Span$1(traceId); this.localEndpoint = new Endpoint$2({}); this.shouldFlush = false; }
JavaScript
function BatchRecorder(_ref) { var _this = this; var logger = _ref.logger, _ref$timeout = _ref.timeout, timeout = _ref$timeout === void 0 ? defaultTimeout : _ref$timeout; _classCallCheck(this, BatchRecorder); this.logger = logger; this.timeout = timeout; /** * @type Map<string, PartialSpan> */ this.partialSpans = new Map(); this[defaultTagsSymbol] = {}; // read through the partials spans regularly // and collect any timed-out ones var timer = setInterval(function () { _this.partialSpans.forEach(function (span, id) { if (_timedOut(span)) { // the zipkin-js.flush annotation makes it explicit that // the span has been reported because of a timeout, even // when it is not finished yet (and thus enqueued for reporting) span.delegate.addAnnotation(now$2(), 'zipkin-js.flush'); _this._writeSpan(id, span); } }); }, 1000); // every second, this will flush to zipkin any spans that have timed out if (timer.unref) { // unref might not be available in browsers timer.unref(); // Allows Node to terminate instead of blocking on timer } }
function BatchRecorder(_ref) { var _this = this; var logger = _ref.logger, _ref$timeout = _ref.timeout, timeout = _ref$timeout === void 0 ? defaultTimeout : _ref$timeout; _classCallCheck(this, BatchRecorder); this.logger = logger; this.timeout = timeout; /** * @type Map<string, PartialSpan> */ this.partialSpans = new Map(); this[defaultTagsSymbol] = {}; // read through the partials spans regularly // and collect any timed-out ones var timer = setInterval(function () { _this.partialSpans.forEach(function (span, id) { if (_timedOut(span)) { // the zipkin-js.flush annotation makes it explicit that // the span has been reported because of a timeout, even // when it is not finished yet (and thus enqueued for reporting) span.delegate.addAnnotation(now$2(), 'zipkin-js.flush'); _this._writeSpan(id, span); } }); }, 1000); // every second, this will flush to zipkin any spans that have timed out if (timer.unref) { // unref might not be available in browsers timer.unref(); // Allows Node to terminate instead of blocking on timer } }
JavaScript
function encode(input) { var n, delta, handledCPCount, basicLength, bias, j, m, q, k, t, currentValue, output = [], /** `inputLength` will hold the number of code points in `input`. */ inputLength, /** Cached calculation results */ handledCPCountPlusOne, baseMinusT, qMinusT; // Convert the input in UCS-2 to Unicode input = ucs2decode(input); // Cache the length inputLength = input.length; // Initialize the state n = initialN; delta = 0; bias = initialBias; // Handle the basic code points for (j = 0; j < inputLength; ++j) { currentValue = input[j]; if (currentValue < 0x80) { output.push(stringFromCharCode(currentValue)); } } handledCPCount = basicLength = output.length; // `handledCPCount` is the number of code points that have been handled; // `basicLength` is the number of basic code points. // Finish the basic string - if it is not empty - with a delimiter if (basicLength) { output.push(delimiter); } // Main encoding loop: while (handledCPCount < inputLength) { // All non-basic code points < n have been handled already. Find the next // larger one: for (m = maxInt, j = 0; j < inputLength; ++j) { currentValue = input[j]; if (currentValue >= n && currentValue < m) { m = currentValue; } } // Increase `delta` enough to advance the decoder's <n,i> state to <m,0>, // but guard against overflow handledCPCountPlusOne = handledCPCount + 1; if (m - n > floor((maxInt - delta) / handledCPCountPlusOne)) { error('overflow'); } delta += (m - n) * handledCPCountPlusOne; n = m; for (j = 0; j < inputLength; ++j) { currentValue = input[j]; if (currentValue < n && ++delta > maxInt) { error('overflow'); } if (currentValue == n) { // Represent delta as a generalized variable-length integer for (q = delta, k = base;; /* no condition */ k += base) { t = k <= bias ? tMin : k >= bias + tMax ? tMax : k - bias; if (q < t) { break; } qMinusT = q - t; baseMinusT = base - t; output.push(stringFromCharCode(digitToBasic(t + qMinusT % baseMinusT, 0))); q = floor(qMinusT / baseMinusT); } output.push(stringFromCharCode(digitToBasic(q, 0))); bias = adapt(delta, handledCPCountPlusOne, handledCPCount == basicLength); delta = 0; ++handledCPCount; } } ++delta; ++n; } return output.join(''); }
function encode(input) { var n, delta, handledCPCount, basicLength, bias, j, m, q, k, t, currentValue, output = [], /** `inputLength` will hold the number of code points in `input`. */ inputLength, /** Cached calculation results */ handledCPCountPlusOne, baseMinusT, qMinusT; // Convert the input in UCS-2 to Unicode input = ucs2decode(input); // Cache the length inputLength = input.length; // Initialize the state n = initialN; delta = 0; bias = initialBias; // Handle the basic code points for (j = 0; j < inputLength; ++j) { currentValue = input[j]; if (currentValue < 0x80) { output.push(stringFromCharCode(currentValue)); } } handledCPCount = basicLength = output.length; // `handledCPCount` is the number of code points that have been handled; // `basicLength` is the number of basic code points. // Finish the basic string - if it is not empty - with a delimiter if (basicLength) { output.push(delimiter); } // Main encoding loop: while (handledCPCount < inputLength) { // All non-basic code points < n have been handled already. Find the next // larger one: for (m = maxInt, j = 0; j < inputLength; ++j) { currentValue = input[j]; if (currentValue >= n && currentValue < m) { m = currentValue; } } // Increase `delta` enough to advance the decoder's <n,i> state to <m,0>, // but guard against overflow handledCPCountPlusOne = handledCPCount + 1; if (m - n > floor((maxInt - delta) / handledCPCountPlusOne)) { error('overflow'); } delta += (m - n) * handledCPCountPlusOne; n = m; for (j = 0; j < inputLength; ++j) { currentValue = input[j]; if (currentValue < n && ++delta > maxInt) { error('overflow'); } if (currentValue == n) { // Represent delta as a generalized variable-length integer for (q = delta, k = base;; /* no condition */ k += base) { t = k <= bias ? tMin : k >= bias + tMax ? tMax : k - bias; if (q < t) { break; } qMinusT = q - t; baseMinusT = base - t; output.push(stringFromCharCode(digitToBasic(t + qMinusT % baseMinusT, 0))); q = floor(qMinusT / baseMinusT); } output.push(stringFromCharCode(digitToBasic(q, 0))); bias = adapt(delta, handledCPCountPlusOne, handledCPCount == basicLength); delta = 0; ++handledCPCount; } } ++delta; ++n; } return output.join(''); }
JavaScript
function Buffer(arg, encodingOrOffset, length) { if (!Buffer.TYPED_ARRAY_SUPPORT && !(this instanceof Buffer)) { return new Buffer(arg, encodingOrOffset, length); } // Common case. if (typeof arg === 'number') { if (typeof encodingOrOffset === 'string') { throw new Error('If encoding is specified then the first argument must be a string'); } return allocUnsafe(this, arg); } return from(this, arg, encodingOrOffset, length); }
function Buffer(arg, encodingOrOffset, length) { if (!Buffer.TYPED_ARRAY_SUPPORT && !(this instanceof Buffer)) { return new Buffer(arg, encodingOrOffset, length); } // Common case. if (typeof arg === 'number') { if (typeof encodingOrOffset === 'string') { throw new Error('If encoding is specified then the first argument must be a string'); } return allocUnsafe(this, arg); } return from(this, arg, encodingOrOffset, length); }
JavaScript
function bidirectionalIndexOf(buffer, val, byteOffset, encoding, dir) { // Empty buffer means no match if (buffer.length === 0) return -1; // Normalize byteOffset if (typeof byteOffset === 'string') { encoding = byteOffset; byteOffset = 0; } else if (byteOffset > 0x7fffffff) { byteOffset = 0x7fffffff; } else if (byteOffset < -0x80000000) { byteOffset = -0x80000000; } byteOffset = +byteOffset; // Coerce to Number. if (isNaN(byteOffset)) { // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer byteOffset = dir ? 0 : buffer.length - 1; } // Normalize byteOffset: negative offsets start from the end of the buffer if (byteOffset < 0) byteOffset = buffer.length + byteOffset; if (byteOffset >= buffer.length) { if (dir) return -1;else byteOffset = buffer.length - 1; } else if (byteOffset < 0) { if (dir) byteOffset = 0;else return -1; } // Normalize val if (typeof val === 'string') { val = Buffer.from(val, encoding); } // Finally, search either indexOf (if dir is true) or lastIndexOf if (internalIsBuffer(val)) { // Special case: looking for empty string/buffer always fails if (val.length === 0) { return -1; } return arrayIndexOf(buffer, val, byteOffset, encoding, dir); } else if (typeof val === 'number') { val = val & 0xFF; // Search for a byte value [0-255] if (Buffer.TYPED_ARRAY_SUPPORT && typeof Uint8Array.prototype.indexOf === 'function') { if (dir) { return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset); } else { return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset); } } return arrayIndexOf(buffer, [val], byteOffset, encoding, dir); } throw new TypeError('val must be string, number or Buffer'); }
function bidirectionalIndexOf(buffer, val, byteOffset, encoding, dir) { // Empty buffer means no match if (buffer.length === 0) return -1; // Normalize byteOffset if (typeof byteOffset === 'string') { encoding = byteOffset; byteOffset = 0; } else if (byteOffset > 0x7fffffff) { byteOffset = 0x7fffffff; } else if (byteOffset < -0x80000000) { byteOffset = -0x80000000; } byteOffset = +byteOffset; // Coerce to Number. if (isNaN(byteOffset)) { // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer byteOffset = dir ? 0 : buffer.length - 1; } // Normalize byteOffset: negative offsets start from the end of the buffer if (byteOffset < 0) byteOffset = buffer.length + byteOffset; if (byteOffset >= buffer.length) { if (dir) return -1;else byteOffset = buffer.length - 1; } else if (byteOffset < 0) { if (dir) byteOffset = 0;else return -1; } // Normalize val if (typeof val === 'string') { val = Buffer.from(val, encoding); } // Finally, search either indexOf (if dir is true) or lastIndexOf if (internalIsBuffer(val)) { // Special case: looking for empty string/buffer always fails if (val.length === 0) { return -1; } return arrayIndexOf(buffer, val, byteOffset, encoding, dir); } else if (typeof val === 'number') { val = val & 0xFF; // Search for a byte value [0-255] if (Buffer.TYPED_ARRAY_SUPPORT && typeof Uint8Array.prototype.indexOf === 'function') { if (dir) { return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset); } else { return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset); } } return arrayIndexOf(buffer, [val], byteOffset, encoding, dir); } throw new TypeError('val must be string, number or Buffer'); }
JavaScript
function _spawn(mvn, args) { const spawn = require('child_process').spawn; // Command to be executed. let cmd = mvn.options.cmd || mvnw(mvn.options.cwd) || 'mvn'; return new Promise((resolve, reject) => { if (isWin) { args.unshift(cmd); args.unshift('/c'), args.unshift('/s'); cmd = process.env.COMSPEC || 'cmd.exe'; } const proc = spawn(cmd, args, { 'cwd': mvn.options.cwd, stdio: [process.stdin, process.stdout, process.stderr] }); proc.on('error', reject); proc.on('exit', (code, signal) => { if (code !== 0) { reject({ 'code': code, 'signal': signal }); } else { resolve(); } }); }); }
function _spawn(mvn, args) { const spawn = require('child_process').spawn; // Command to be executed. let cmd = mvn.options.cmd || mvnw(mvn.options.cwd) || 'mvn'; return new Promise((resolve, reject) => { if (isWin) { args.unshift(cmd); args.unshift('/c'), args.unshift('/s'); cmd = process.env.COMSPEC || 'cmd.exe'; } const proc = spawn(cmd, args, { 'cwd': mvn.options.cwd, stdio: [process.stdin, process.stdout, process.stderr] }); proc.on('error', reject); proc.on('exit', (code, signal) => { if (code !== 0) { reject({ 'code': code, 'signal': signal }); } else { resolve(); } }); }); }
JavaScript
fromHeaders() { if (this.hasHeaders()) { // nginx (if configured), load balancers (AWS ELB), and other proxies if (this.hasIpInForwardedFor()) { return this.getFromForwardedFor(); } // Heroku, AWS EC2, nginx (if configured), and others if (this.hasIpInHeader('x-client-ip')) { return this.ipInHeader('x-client-ip'); } // used by some proxies, like nginx if (this.hasIpInHeader('x-real-ip')) { return this.header('x-real-ip'); } // Cloudflare if (this.hasIpInHeader('cf-connecting-ip')) { return this.header('cf-connecting-ip'); } // Fastly and Firebase if (this.hasIpInHeader('fastly-client-ip')) { return this.header('fastly-client-ip'); } // Akamai, Cloudflare if (this.hasIpInHeader('true-client-ip')) { return this.header('true-client-ip'); } // Rackspace if (this.hasIpInHeader('x-cluster-client-ip')) { return this.header('x-cluster-client-ip'); } } }
fromHeaders() { if (this.hasHeaders()) { // nginx (if configured), load balancers (AWS ELB), and other proxies if (this.hasIpInForwardedFor()) { return this.getFromForwardedFor(); } // Heroku, AWS EC2, nginx (if configured), and others if (this.hasIpInHeader('x-client-ip')) { return this.ipInHeader('x-client-ip'); } // used by some proxies, like nginx if (this.hasIpInHeader('x-real-ip')) { return this.header('x-real-ip'); } // Cloudflare if (this.hasIpInHeader('cf-connecting-ip')) { return this.header('cf-connecting-ip'); } // Fastly and Firebase if (this.hasIpInHeader('fastly-client-ip')) { return this.header('fastly-client-ip'); } // Akamai, Cloudflare if (this.hasIpInHeader('true-client-ip')) { return this.header('true-client-ip'); } // Rackspace if (this.hasIpInHeader('x-cluster-client-ip')) { return this.header('x-cluster-client-ip'); } } }
JavaScript
fromConnection() { if (!this.hasConnection()) { return; } if (this.isIp(this.request.connection.remoteAddress)) { return this.request.connection.remoteAddress; } if (!this.request.connection.socket) { return; } if (this.isIp(this.request.connection.socket.remoteAddress)) { return this.request.connection.socket.remoteAddress; } }
fromConnection() { if (!this.hasConnection()) { return; } if (this.isIp(this.request.connection.remoteAddress)) { return this.request.connection.remoteAddress; } if (!this.request.connection.socket) { return; } if (this.isIp(this.request.connection.socket.remoteAddress)) { return this.request.connection.socket.remoteAddress; } }
JavaScript
fromSocket() { if (!this.hasSocket()) { return; } if (this.isIp(this.request.socket.remoteAddress)) { return this.request.socket.remoteAddress; } }
fromSocket() { if (!this.hasSocket()) { return; } if (this.isIp(this.request.socket.remoteAddress)) { return this.request.socket.remoteAddress; } }
JavaScript
fromInfo() { if (!this.hasInfo()) { return; } if (this.isIp(this.request.info.remoteAddress)) { return this.request.info.remoteAddress; } }
fromInfo() { if (!this.hasInfo()) { return; } if (this.isIp(this.request.info.remoteAddress)) { return this.request.info.remoteAddress; } }
JavaScript
fromRaw() { if (this.hasRaw()) { return new Request(this.request.raw).getClientIp(); } }
fromRaw() { if (this.hasRaw()) { return new Request(this.request.raw).getClientIp(); } }
JavaScript
fromRequestContext() { // AWS API Gateway/Lambda if (!this.hasRequestContext()) { return; } if (!this.requestContext().identity) { return; } if (this.isIp(this.requestContext().identity.sourceIp)) { return this.requestContext().identity.sourceIp; } }
fromRequestContext() { // AWS API Gateway/Lambda if (!this.hasRequestContext()) { return; } if (!this.requestContext().identity) { return; } if (this.isIp(this.requestContext().identity.sourceIp)) { return this.requestContext().identity.sourceIp; } }
JavaScript
function listfiles() { myfilestable = $('#myfiles>table>tbody'); $.ajax({ method: "GET", url: '/getfiles.php', dataType: 'json', success: function(response){ $('#myfiles>.no-files').remove(); myfilestable.html(''); if (response.status && response.status == 'error') { toastr[response.status](response.message); } if (response && response.files) { Object.values(response.files).forEach((file) => { let html = ''; html += '<tr id="' + file.id + '">'; html += '<td>'; html += file.type == 'mp3' ? '<i class="far fa-file-audio text-muted fa-2x"></i>' : '<i class="far fa-file-archive text-muted fa-2x"></i>'; html += '</td>'; html += '<td>'; html += '<a href="' + response.relative_user_dir + file.name + '" target="_blank">' + file.name + '</a>'; html += '</td>'; html += '<td class="text-muted">' + file.date + '</td>'; html += '<td class="actions text-right">'; html += file.type == 'mp3' ? '<button type="button" data-action="listen" data-file="' + response.relative_user_dir + file.name + '" class="btn btn-link pb-0 pt-0 action-btn listen"><i class="fas fa-play"></i></button>' : '<button type="button" data-action="listen" data-file="" class="btn btn-link pb-0 pt-0 action-btn listen disabled"><i class="fas fa-play"></i></button>'; html += '<button type="button" data-action="download" data-file="' + response.relative_user_dir + file.name + '" class="btn btn-link pb-0 pt-0 action-btn download" download><i class="fas fa-download"></i></button>'; html += '<button type="button" data-action="remove" data-file="' + response.relative_user_dir + file.name + '" class="btn btn-link pb-0 pt-0 action-btn remove"><i class="far fa-trash-alt" aria-hidden="true"></i></button>'; html += '</td>'; html += '</tr>'; myfilestable.append(html); }); if(response.files.length == 0){ $('#myfiles>.no-files').remove(); $('#myfiles>table').before('<div class="no-files text-center p-4 text-muted">Aucun fichier récent</div>'); } initActions(); } }, error: function(response){ console.log(response); toastr['error']('Erreur lors de la requête Ajax'); } }); }
function listfiles() { myfilestable = $('#myfiles>table>tbody'); $.ajax({ method: "GET", url: '/getfiles.php', dataType: 'json', success: function(response){ $('#myfiles>.no-files').remove(); myfilestable.html(''); if (response.status && response.status == 'error') { toastr[response.status](response.message); } if (response && response.files) { Object.values(response.files).forEach((file) => { let html = ''; html += '<tr id="' + file.id + '">'; html += '<td>'; html += file.type == 'mp3' ? '<i class="far fa-file-audio text-muted fa-2x"></i>' : '<i class="far fa-file-archive text-muted fa-2x"></i>'; html += '</td>'; html += '<td>'; html += '<a href="' + response.relative_user_dir + file.name + '" target="_blank">' + file.name + '</a>'; html += '</td>'; html += '<td class="text-muted">' + file.date + '</td>'; html += '<td class="actions text-right">'; html += file.type == 'mp3' ? '<button type="button" data-action="listen" data-file="' + response.relative_user_dir + file.name + '" class="btn btn-link pb-0 pt-0 action-btn listen"><i class="fas fa-play"></i></button>' : '<button type="button" data-action="listen" data-file="" class="btn btn-link pb-0 pt-0 action-btn listen disabled"><i class="fas fa-play"></i></button>'; html += '<button type="button" data-action="download" data-file="' + response.relative_user_dir + file.name + '" class="btn btn-link pb-0 pt-0 action-btn download" download><i class="fas fa-download"></i></button>'; html += '<button type="button" data-action="remove" data-file="' + response.relative_user_dir + file.name + '" class="btn btn-link pb-0 pt-0 action-btn remove"><i class="far fa-trash-alt" aria-hidden="true"></i></button>'; html += '</td>'; html += '</tr>'; myfilestable.append(html); }); if(response.files.length == 0){ $('#myfiles>.no-files').remove(); $('#myfiles>table').before('<div class="no-files text-center p-4 text-muted">Aucun fichier récent</div>'); } initActions(); } }, error: function(response){ console.log(response); toastr['error']('Erreur lors de la requête Ajax'); } }); }
JavaScript
function style_to_code() { let code = quill.root.innerHTML; code = code.replaceAll('<p><br></p>', ''); code = code.replaceAll('&nbsp;', ' '); //Changing Hourglass to Break tags code = code.replaceAll('⌛⌛⌛⌛', '<break strength="x-strong"/>'); code = code.replaceAll('⌛⌛⌛', '<break strength="strong"/>'); code = code.replaceAll('⌛⌛', '<break strength="weak"/>'); code = code.replaceAll('⌛', '<break strength="x-weak"/>'); return(code); }
function style_to_code() { let code = quill.root.innerHTML; code = code.replaceAll('<p><br></p>', ''); code = code.replaceAll('&nbsp;', ' '); //Changing Hourglass to Break tags code = code.replaceAll('⌛⌛⌛⌛', '<break strength="x-strong"/>'); code = code.replaceAll('⌛⌛⌛', '<break strength="strong"/>'); code = code.replaceAll('⌛⌛', '<break strength="weak"/>'); code = code.replaceAll('⌛', '<break strength="x-weak"/>'); return(code); }
JavaScript
function updateButtons(){ let format = quill.getFormat(quill.getSelection()); if (format.emphasis == "strong"){ document.getElementById("emphasis").classList.add("active"); } else{ document.getElementById("emphasis").classList.remove("active"); } if (format.spellout == "spell-out"){ document.getElementById("spellout").classList.add("active"); } else { document.getElementById("spellout").classList.remove("active"); } if (format.prosody != undefined){ if (quill.getFormat(quill.getSelection()).prosody.pitch!=null) { document.getElementsByClassName("fa-wave-square")[0].classList.add("active"); } else { document.getElementsByClassName("fa-wave-square")[0].classList.remove("active"); } if (quill.getFormat(quill.getSelection()).prosody.rate!=null) { document.getElementsByClassName("fa-tachometer-alt")[0].classList.add("active"); } else { document.getElementsByClassName("fa-tachometer-alt")[0].classList.remove("active"); } } else { document.getElementsByClassName("fa-wave-square")[0].classList.remove("active"); document.getElementsByClassName("fa-tachometer-alt")[0].classList.remove("active"); } }
function updateButtons(){ let format = quill.getFormat(quill.getSelection()); if (format.emphasis == "strong"){ document.getElementById("emphasis").classList.add("active"); } else{ document.getElementById("emphasis").classList.remove("active"); } if (format.spellout == "spell-out"){ document.getElementById("spellout").classList.add("active"); } else { document.getElementById("spellout").classList.remove("active"); } if (format.prosody != undefined){ if (quill.getFormat(quill.getSelection()).prosody.pitch!=null) { document.getElementsByClassName("fa-wave-square")[0].classList.add("active"); } else { document.getElementsByClassName("fa-wave-square")[0].classList.remove("active"); } if (quill.getFormat(quill.getSelection()).prosody.rate!=null) { document.getElementsByClassName("fa-tachometer-alt")[0].classList.add("active"); } else { document.getElementsByClassName("fa-tachometer-alt")[0].classList.remove("active"); } } else { document.getElementsByClassName("fa-wave-square")[0].classList.remove("active"); document.getElementsByClassName("fa-tachometer-alt")[0].classList.remove("active"); } }
JavaScript
stopCapture() { if (this._orig_stdout_write) { process.stdout.write = this._orig_stdout_write; } }
stopCapture() { if (this._orig_stdout_write) { process.stdout.write = this._orig_stdout_write; } }
JavaScript
mineBlock(difficulty) { while (this.hash.substring(0, difficulty) !== Array(difficulty + 1).join('0')) { this.nonce++; this.hash = this.calculateHash(); console.log(this.hash) } console.log(`Block mined: ${this.hash}`); }
mineBlock(difficulty) { while (this.hash.substring(0, difficulty) !== Array(difficulty + 1).join('0')) { this.nonce++; this.hash = this.calculateHash(); console.log(this.hash) } console.log(`Block mined: ${this.hash}`); }
JavaScript
signTransaction(signingKey) { // You can only send a transaction from the wallet that is linked to your // key. So here we check if the fromAddress matches your publicKey let pubk = Buffer.from(signingKey.getPublic('hex')) let key = signingKey.getPublic('hex') console.log('PUBLIC KEY BUFFER : ',pubk.toString()) console.log('PUBLIC KEY : ',key) if (key !== this.fromAddress) { console.log('FROM :',address) console.log('From : ', this.fromAddress) throw new Error('You cannot sign transactions for other wallets!'); } // Calculate the hash of this transaction, sign it with the key // and store it inside the transaction obect const hashTx = this.calculateHash(); const sig = signingKey.sign(hashTx).toHex(); this.signature = sig console.log('SIGNATURE : ',sig) }
signTransaction(signingKey) { // You can only send a transaction from the wallet that is linked to your // key. So here we check if the fromAddress matches your publicKey let pubk = Buffer.from(signingKey.getPublic('hex')) let key = signingKey.getPublic('hex') console.log('PUBLIC KEY BUFFER : ',pubk.toString()) console.log('PUBLIC KEY : ',key) if (key !== this.fromAddress) { console.log('FROM :',address) console.log('From : ', this.fromAddress) throw new Error('You cannot sign transactions for other wallets!'); } // Calculate the hash of this transaction, sign it with the key // and store it inside the transaction obect const hashTx = this.calculateHash(); const sig = signingKey.sign(hashTx).toHex(); this.signature = sig console.log('SIGNATURE : ',sig) }
JavaScript
isValid() { // If the transaction doesn't have a from address we assume it's a // mining reward and that it's valid. You could verify this in a // different way (special field for instance) if (this.fromAddress === null) return true; if (!this.signature || this.signature.length === 0) { throw new Error('No signature in this transaction'); } console.log('THIS FROM ADDRESS : ',this.fromAddress) const publicKey = ec.keyFromPublic(this.fromAddress, 'hex'); return publicKey.verify(this.calculateHash(), this.signature); }
isValid() { // If the transaction doesn't have a from address we assume it's a // mining reward and that it's valid. You could verify this in a // different way (special field for instance) if (this.fromAddress === null) return true; if (!this.signature || this.signature.length === 0) { throw new Error('No signature in this transaction'); } console.log('THIS FROM ADDRESS : ',this.fromAddress) const publicKey = ec.keyFromPublic(this.fromAddress, 'hex'); return publicKey.verify(this.calculateHash(), this.signature); }
JavaScript
minePendingTransactions(miningRewardAddress) { const rewardTx = new Transaction(null, miningRewardAddress, this.miningReward); this.pendingTransactions.push(rewardTx); const block = new Block(Date.now(), this.pendingTransactions, this.getLatestBlock().hash); block.mineBlock(this.difficulty); console.log('Block successfully mined!'); this.chain.push(block); this.pendingTransactions = []; }
minePendingTransactions(miningRewardAddress) { const rewardTx = new Transaction(null, miningRewardAddress, this.miningReward); this.pendingTransactions.push(rewardTx); const block = new Block(Date.now(), this.pendingTransactions, this.getLatestBlock().hash); block.mineBlock(this.difficulty); console.log('Block successfully mined!'); this.chain.push(block); this.pendingTransactions = []; }
JavaScript
addTransaction(transaction) { if (!transaction.fromAddress || !transaction.toAddress) { throw new Error('Transaction must include from and to address'); } // Verify the transactiion if (!transaction.isValid()) { throw new Error('Cannot add invalid transaction to chain'); } if (transaction.amount <= 0) { throw new Error('Transaction amount should be higher than 0'); } // Making sure that the amount sent is not greater than existing balance if (this.getBalanceOfAddress(transaction.fromAddress) < transaction.amount) { throw new Error('Not enough balance'); } this.pendingTransactions.push(transaction); console.log('transaction added: ', transaction); }
addTransaction(transaction) { if (!transaction.fromAddress || !transaction.toAddress) { throw new Error('Transaction must include from and to address'); } // Verify the transactiion if (!transaction.isValid()) { throw new Error('Cannot add invalid transaction to chain'); } if (transaction.amount <= 0) { throw new Error('Transaction amount should be higher than 0'); } // Making sure that the amount sent is not greater than existing balance if (this.getBalanceOfAddress(transaction.fromAddress) < transaction.amount) { throw new Error('Not enough balance'); } this.pendingTransactions.push(transaction); console.log('transaction added: ', transaction); }
JavaScript
isChainValid() { // Check if the Genesis block hasn't been tampered with by comparing // the output of createGenesisBlock with the first block on our chain const realGenesis = JSON.stringify(this.createGenesisBlock()); if (realGenesis !== JSON.stringify(this.chain[0])) { return false; } // Check the remaining blocks on the chain to see if there hashes and // signatures are correct for (let i = 1; i < this.chain.length; i++) { const currentBlock = this.chain[i]; if (!currentBlock.hasValidTransactions()) { return false; } if (currentBlock.hash !== currentBlock.calculateHash()) { return false; } } return true; }
isChainValid() { // Check if the Genesis block hasn't been tampered with by comparing // the output of createGenesisBlock with the first block on our chain const realGenesis = JSON.stringify(this.createGenesisBlock()); if (realGenesis !== JSON.stringify(this.chain[0])) { return false; } // Check the remaining blocks on the chain to see if there hashes and // signatures are correct for (let i = 1; i < this.chain.length; i++) { const currentBlock = this.chain[i]; if (!currentBlock.hasValidTransactions()) { return false; } if (currentBlock.hash !== currentBlock.calculateHash()) { return false; } } return true; }
JavaScript
function normalSliderVideoInit( wrapper, play ) { wrapper.find( '.uix-video__slider' ).each( function() { const $this = $( this ); const videoWrapperW = $this.closest( '.uix-advanced-slider__outline' ).width(), curVideoID = $this.find( 'video' ).attr( 'id' ) + '-slider-videopush', coverPlayBtnID = 'videocover-' + curVideoID, $replayBtn = $( '#'+curVideoID+'-replay-btn' ); let dataControls = $this.data( 'embed-video-controls' ), dataAuto = $this.data( 'embed-video-autoplay' ), dataLoop = $this.data( 'embed-video-loop' ), dataW = $this.data( 'embed-video-width' ), dataH = $this.data( 'embed-video-height' ); //Push a new ID to video //Solve the problem that ajax asynchronous loading does not play $this.find( '.video-js' ).attr( 'id', curVideoID ); if ( typeof dataAuto === typeof undefined ) { dataAuto = true; } if ( typeof dataLoop === typeof undefined ) { dataLoop = true; } if ( typeof dataControls === typeof undefined ) { dataControls = false; } if ( typeof dataW === typeof undefined || dataW == 'auto' ) { dataW = videoWrapperW; } if ( typeof dataH === typeof undefined || dataH == 'auto' ) { dataH = videoWrapperW/1.77777777777778; } //Display cover and play buttons when some mobile device browsers cannot automatically play video if ( $( '#' + coverPlayBtnID ).length == 0 ) { $( '<div id="'+coverPlayBtnID+'" class="uix-video__cover"><span class="uix-video__cover__placeholder" style="background-image:url('+$this.find( 'video' ).attr( 'poster' )+')"></span><span class="uix-video__cover__playbtn"></span></div>' ).insertBefore( $this ); const btnEv = ( Modernizr.touchevents ) ? 'touchstart' : 'click'; $( '#' + coverPlayBtnID + ' .uix-video__cover__playbtn' ).on( btnEv, function( e ) { e.preventDefault(); myPlayer.play(); $( '#' + coverPlayBtnID ).hide(); }); } //Add replay button to video if ( $replayBtn.length == 0 ) { $this.after( '<span class="uix-video__btn-play" id="'+curVideoID+'-replay-btn"></span>' ); } //HTML5 video autoplay on mobile revisited if ( dataAuto && windowWidth <= 768 ) { $this.find( '.video-js' ).attr({ 'autoplay' : 'true', 'muted' : 'true', 'playsinline' : 'true' }); } const myPlayer = videojs( curVideoID, { width : dataW, height : dataH, loop : dataLoop, autoplay : dataAuto }, function onPlayerReady() { const initVideo = function( obj ) { //Get Video Dimensions let curW = obj.videoWidth(), curH = obj.videoHeight(), newW = curW, newH = curH; newW = videoWrapperW; //Scaled/Proportional Content newH = curH*(newW/curW); if ( !isNaN( newW ) && !isNaN( newH ) ) { obj.height( newH ); obj.width( newW ); $this.css( 'height', newH ); } //Show this video wrapper $this.css( 'visibility', 'visible' ); //Hide loading effect $this.find( '.vjs-loading-spinner, .vjs-big-play-button' ).hide(); } /* --------- Video initialize */ this.on( 'loadedmetadata', function() { initVideo( this ); }); /* --------- Display the play button */ if ( ! dataAuto ) $this.find( '.vjs-big-play-button' ).show(); $this.find( '.vjs-big-play-button' ).off( 'click' ).on( 'click', function() { $( this ).hide(); }); /* --------- Set, tell the player it's in fullscreen */ if ( dataAuto ) { //Fix an error of Video auto play is not working in browser this.muted( true ); //Prevent autoplay error: Uncaught (in promise) DOMException const promise = this.play(); if ( promise !== undefined ) { promise.then( function() { // Autoplay started! }).catch( function( error ) { // Autoplay was prevented. $( '#' + coverPlayBtnID ).show(); $( '#' + coverPlayBtnID + ' .uix-video__cover__playbtn' ).show(); console.log( 'Autoplay was prevented.' ); }); } } /* --------- Disable control bar play button click */ if ( !dataControls ) { this.controls( false ); } /* --------- Determine if the video is auto played from mobile devices */ let autoPlayOK = false; this.on( 'timeupdate', function() { let duration = this.duration(); if ( duration > 0 ) { autoPlayOK = true; if ( this.currentTime() > 0 ) { autoPlayOK = true; this.off( 'timeupdate' ); //Hide cover and play buttons when the video automatically played $( '#' + coverPlayBtnID ).hide(); } } }); /* --------- Pause the video when it is not current slider */ if ( !play ) { this.pause(); this.currentTime(0); } else { //Unmute, because there is interaction, you can turn on the audio. this.muted( false ); if ( dataAuto ) { this.currentTime(0); //Prevent autoplay error: Uncaught (in promise) DOMException const promise = this.play(); if ( promise !== undefined ) { promise.then( function() { // Autoplay started! }).catch( function( error ) { // Autoplay was prevented. $( '#' + coverPlayBtnID ).show(); $( '#' + coverPlayBtnID + ' .uix-video__cover__playbtn' ).show(); console.log( 'Autoplay was prevented.' ); }); } //Hidden replay button $replayBtn.hide(); //Should the video go to the beginning when it ends this.on( 'ended', function () { if ( dataLoop ) { this.currentTime(0); this.play(); } else { //Replay this video this.currentTime(0); $replayBtn .show() .off( 'click' ) .on( 'click', function( e ) { e.preventDefault(); this.play(); $replayBtn.hide(); }); } }); } } }); }); }
function normalSliderVideoInit( wrapper, play ) { wrapper.find( '.uix-video__slider' ).each( function() { const $this = $( this ); const videoWrapperW = $this.closest( '.uix-advanced-slider__outline' ).width(), curVideoID = $this.find( 'video' ).attr( 'id' ) + '-slider-videopush', coverPlayBtnID = 'videocover-' + curVideoID, $replayBtn = $( '#'+curVideoID+'-replay-btn' ); let dataControls = $this.data( 'embed-video-controls' ), dataAuto = $this.data( 'embed-video-autoplay' ), dataLoop = $this.data( 'embed-video-loop' ), dataW = $this.data( 'embed-video-width' ), dataH = $this.data( 'embed-video-height' ); //Push a new ID to video //Solve the problem that ajax asynchronous loading does not play $this.find( '.video-js' ).attr( 'id', curVideoID ); if ( typeof dataAuto === typeof undefined ) { dataAuto = true; } if ( typeof dataLoop === typeof undefined ) { dataLoop = true; } if ( typeof dataControls === typeof undefined ) { dataControls = false; } if ( typeof dataW === typeof undefined || dataW == 'auto' ) { dataW = videoWrapperW; } if ( typeof dataH === typeof undefined || dataH == 'auto' ) { dataH = videoWrapperW/1.77777777777778; } //Display cover and play buttons when some mobile device browsers cannot automatically play video if ( $( '#' + coverPlayBtnID ).length == 0 ) { $( '<div id="'+coverPlayBtnID+'" class="uix-video__cover"><span class="uix-video__cover__placeholder" style="background-image:url('+$this.find( 'video' ).attr( 'poster' )+')"></span><span class="uix-video__cover__playbtn"></span></div>' ).insertBefore( $this ); const btnEv = ( Modernizr.touchevents ) ? 'touchstart' : 'click'; $( '#' + coverPlayBtnID + ' .uix-video__cover__playbtn' ).on( btnEv, function( e ) { e.preventDefault(); myPlayer.play(); $( '#' + coverPlayBtnID ).hide(); }); } //Add replay button to video if ( $replayBtn.length == 0 ) { $this.after( '<span class="uix-video__btn-play" id="'+curVideoID+'-replay-btn"></span>' ); } //HTML5 video autoplay on mobile revisited if ( dataAuto && windowWidth <= 768 ) { $this.find( '.video-js' ).attr({ 'autoplay' : 'true', 'muted' : 'true', 'playsinline' : 'true' }); } const myPlayer = videojs( curVideoID, { width : dataW, height : dataH, loop : dataLoop, autoplay : dataAuto }, function onPlayerReady() { const initVideo = function( obj ) { //Get Video Dimensions let curW = obj.videoWidth(), curH = obj.videoHeight(), newW = curW, newH = curH; newW = videoWrapperW; //Scaled/Proportional Content newH = curH*(newW/curW); if ( !isNaN( newW ) && !isNaN( newH ) ) { obj.height( newH ); obj.width( newW ); $this.css( 'height', newH ); } //Show this video wrapper $this.css( 'visibility', 'visible' ); //Hide loading effect $this.find( '.vjs-loading-spinner, .vjs-big-play-button' ).hide(); } /* --------- Video initialize */ this.on( 'loadedmetadata', function() { initVideo( this ); }); /* --------- Display the play button */ if ( ! dataAuto ) $this.find( '.vjs-big-play-button' ).show(); $this.find( '.vjs-big-play-button' ).off( 'click' ).on( 'click', function() { $( this ).hide(); }); /* --------- Set, tell the player it's in fullscreen */ if ( dataAuto ) { //Fix an error of Video auto play is not working in browser this.muted( true ); //Prevent autoplay error: Uncaught (in promise) DOMException const promise = this.play(); if ( promise !== undefined ) { promise.then( function() { // Autoplay started! }).catch( function( error ) { // Autoplay was prevented. $( '#' + coverPlayBtnID ).show(); $( '#' + coverPlayBtnID + ' .uix-video__cover__playbtn' ).show(); console.log( 'Autoplay was prevented.' ); }); } } /* --------- Disable control bar play button click */ if ( !dataControls ) { this.controls( false ); } /* --------- Determine if the video is auto played from mobile devices */ let autoPlayOK = false; this.on( 'timeupdate', function() { let duration = this.duration(); if ( duration > 0 ) { autoPlayOK = true; if ( this.currentTime() > 0 ) { autoPlayOK = true; this.off( 'timeupdate' ); //Hide cover and play buttons when the video automatically played $( '#' + coverPlayBtnID ).hide(); } } }); /* --------- Pause the video when it is not current slider */ if ( !play ) { this.pause(); this.currentTime(0); } else { //Unmute, because there is interaction, you can turn on the audio. this.muted( false ); if ( dataAuto ) { this.currentTime(0); //Prevent autoplay error: Uncaught (in promise) DOMException const promise = this.play(); if ( promise !== undefined ) { promise.then( function() { // Autoplay started! }).catch( function( error ) { // Autoplay was prevented. $( '#' + coverPlayBtnID ).show(); $( '#' + coverPlayBtnID + ' .uix-video__cover__playbtn' ).show(); console.log( 'Autoplay was prevented.' ); }); } //Hidden replay button $replayBtn.hide(); //Should the video go to the beginning when it ends this.on( 'ended', function () { if ( dataLoop ) { this.currentTime(0); this.play(); } else { //Replay this video this.currentTime(0); $replayBtn .show() .off( 'click' ) .on( 'click', function( e ) { e.preventDefault(); this.play(); $replayBtn.hide(); }); } }); } } }); }); }
JavaScript
function extend() { var length = arguments.length, obj = arguments[0]; if (length < 2) { return obj; } for (var index = 1; index < length; index++) { var source = arguments[index], keys = Object.keys(source || {}), l = keys.length; for (var i = 0; i < l; i++) { var key = keys[i]; obj[key] = source[key]; } } return obj; }
function extend() { var length = arguments.length, obj = arguments[0]; if (length < 2) { return obj; } for (var index = 1; index < length; index++) { var source = arguments[index], keys = Object.keys(source || {}), l = keys.length; for (var i = 0; i < l; i++) { var key = keys[i]; obj[key] = source[key]; } } return obj; }
JavaScript
function CameraScroller(options) { this.targetPosition = 0; this.targetPositionOnMouseDown = 0; this.mouseY = 0; this.mouseYOnMouseDown = 0; this.scrollPosY = 0; this.domElem = undefined; this.init = function(domEl) { this.domElem = domEl; this.domElem.addEventListener('mousedown', this.onDocumentMouseDown, false); this.domElem.addEventListener('touchstart', this.onDocumentTouchStart, browser.supportsPassive ? { passive: true } : false); this.domElem.addEventListener('touchmove', this.onDocumentTouchMove, browser.supportsPassive ? { passive: true } : false); this.domElem.addEventListener('wheel', this.onDocumentMousewheel, browser.supportsPassive ? { passive: true } : false); }; this.onDocumentMouseDown = function(event) { event.preventDefault(); this.domElem.addEventListener('mousemove', this.onDocumentMouseMove, false); this.domElem.addEventListener('mouseup', this.onDocumentMouseUp, false); this.domElem.addEventListener('mouseout', this.onDocumentMouseOut, false); this.mouseYOnMouseDown = event.clientY; this.targetPositionOnMouseDown = this.targetPosition; }.bind(this); this.onDocumentMouseMove = function(event) { this.mouseY = event.clientY; this.targetPosition = this.targetPositionOnMouseDown + (this.mouseY - this.mouseYOnMouseDown) * 0.02; }.bind(this); this.onDocumentMouseUp = function(event) { this.domElem.removeEventListener('mousemove', this.onDocumentMouseMove, false); this.domElem.removeEventListener('mouseup', this.onDocumentMouseUp, false); this.domElem.removeEventListener('mouseout', this.onDocumentMouseOut, false); }.bind(this); this.onDocumentMouseOut = function(event) { this.domElem.removeEventListener('mousemove', this.onDocumentMouseMove, false); this.domElem.removeEventListener('mouseup', this.onDocumentMouseUp, false); this.domElem.removeEventListener('mouseout', this.onDocumentMouseOut, false); }.bind(this); this.onDocumentTouchStart = function(event) { if (event.touches.length == 1) { event.preventDefault(); this.mouseYOnMouseDown = event.touches[0].pageY; this.targetPositionOnMouseDown = this.targetPosition; } }.bind(this); this.onDocumentTouchMove = function(event) { if (event.touches.length == 1) { event.preventDefault(); this.mouseY = event.touches[0].pageY; this.targetPosition = this.targetPositionOnMouseDown + (this.mouseY - this.mouseYOnMouseDown) * 0.02; } }.bind(this); this.onDocumentMousewheel = function(event) { this.targetPosition = this.targetPosition + event.wheelDeltaY * 0.005; }.bind(this); this.getScrollPosY = function() { this.scrollPosY = this.scrollPosY + (this.targetPosition - this.scrollPosY) * 0.05; // 0.05=long scroll delay, 0.15=short delay return this.scrollPosY }.bind(this); }
function CameraScroller(options) { this.targetPosition = 0; this.targetPositionOnMouseDown = 0; this.mouseY = 0; this.mouseYOnMouseDown = 0; this.scrollPosY = 0; this.domElem = undefined; this.init = function(domEl) { this.domElem = domEl; this.domElem.addEventListener('mousedown', this.onDocumentMouseDown, false); this.domElem.addEventListener('touchstart', this.onDocumentTouchStart, browser.supportsPassive ? { passive: true } : false); this.domElem.addEventListener('touchmove', this.onDocumentTouchMove, browser.supportsPassive ? { passive: true } : false); this.domElem.addEventListener('wheel', this.onDocumentMousewheel, browser.supportsPassive ? { passive: true } : false); }; this.onDocumentMouseDown = function(event) { event.preventDefault(); this.domElem.addEventListener('mousemove', this.onDocumentMouseMove, false); this.domElem.addEventListener('mouseup', this.onDocumentMouseUp, false); this.domElem.addEventListener('mouseout', this.onDocumentMouseOut, false); this.mouseYOnMouseDown = event.clientY; this.targetPositionOnMouseDown = this.targetPosition; }.bind(this); this.onDocumentMouseMove = function(event) { this.mouseY = event.clientY; this.targetPosition = this.targetPositionOnMouseDown + (this.mouseY - this.mouseYOnMouseDown) * 0.02; }.bind(this); this.onDocumentMouseUp = function(event) { this.domElem.removeEventListener('mousemove', this.onDocumentMouseMove, false); this.domElem.removeEventListener('mouseup', this.onDocumentMouseUp, false); this.domElem.removeEventListener('mouseout', this.onDocumentMouseOut, false); }.bind(this); this.onDocumentMouseOut = function(event) { this.domElem.removeEventListener('mousemove', this.onDocumentMouseMove, false); this.domElem.removeEventListener('mouseup', this.onDocumentMouseUp, false); this.domElem.removeEventListener('mouseout', this.onDocumentMouseOut, false); }.bind(this); this.onDocumentTouchStart = function(event) { if (event.touches.length == 1) { event.preventDefault(); this.mouseYOnMouseDown = event.touches[0].pageY; this.targetPositionOnMouseDown = this.targetPosition; } }.bind(this); this.onDocumentTouchMove = function(event) { if (event.touches.length == 1) { event.preventDefault(); this.mouseY = event.touches[0].pageY; this.targetPosition = this.targetPositionOnMouseDown + (this.mouseY - this.mouseYOnMouseDown) * 0.02; } }.bind(this); this.onDocumentMousewheel = function(event) { this.targetPosition = this.targetPosition + event.wheelDeltaY * 0.005; }.bind(this); this.getScrollPosY = function() { this.scrollPosY = this.scrollPosY + (this.targetPosition - this.scrollPosY) * 0.05; // 0.05=long scroll delay, 0.15=short delay return this.scrollPosY }.bind(this); }
JavaScript
function saveStyles() { var styleAttr = $html.attr( 'style' ), styleStrs = [], styleHash = {}; if( !styleAttr ){ return; } styleStrs = styleAttr.split( /;\s/ ); $.each( styleStrs, function serializeStyleProp( styleString ){ if( !styleString ) { return; } var keyValue = styleString.split( /\s:\s/ ); if( keyValue.length < 2 ) { return; } styleHash[ keyValue[ 0 ] ] = keyValue[ 1 ]; } ); $.extend( prevStyles, styleHash ); }
function saveStyles() { var styleAttr = $html.attr( 'style' ), styleStrs = [], styleHash = {}; if( !styleAttr ){ return; } styleStrs = styleAttr.split( /;\s/ ); $.each( styleStrs, function serializeStyleProp( styleString ){ if( !styleString ) { return; } var keyValue = styleString.split( /\s:\s/ ); if( keyValue.length < 2 ) { return; } styleHash[ keyValue[ 0 ] ] = keyValue[ 1 ]; } ); $.extend( prevStyles, styleHash ); }
JavaScript
function ajaxInit() { if ( windowWidth <= 768 ) { $( AJAXPageLinks ).data( 'mobile-running', true ); } else { $( AJAXPageLinks ).data( 'mobile-running', false ); } }
function ajaxInit() { if ( windowWidth <= 768 ) { $( AJAXPageLinks ).data( 'mobile-running', true ); } else { $( AJAXPageLinks ).data( 'mobile-running', false ); } }
JavaScript
function scrollMoveInit( event, dir ) { const timeNow = new Date().getTime(); // Cancel scroll if currently animating or within quiet period if( timeNow - lastAnimation < quietPeriod + animationTime) { return; } if ( dir == 'down' ) { //scroll down moveTo( $( ajaxContainer ), false, 'down', false, true ); } else { //scroll up moveTo( $( ajaxContainer ), false, 'up', false, true ); } lastAnimation = timeNow; }
function scrollMoveInit( event, dir ) { const timeNow = new Date().getTime(); // Cancel scroll if currently animating or within quiet period if( timeNow - lastAnimation < quietPeriod + animationTime) { return; } if ( dir == 'down' ) { //scroll down moveTo( $( ajaxContainer ), false, 'down', false, true ); } else { //scroll up moveTo( $( ajaxContainer ), false, 'up', false, true ); } lastAnimation = timeNow; }
JavaScript
function ajaxSucceeds( dir, container, content, title ) { //If the page resource is not loaded, then the following code is not executed if ( loadedProgress < 100 ) return false; //Remove loader const oldContent = container.html(); hideLoader(container, title, dir, oldContent, content); }
function ajaxSucceeds( dir, container, content, title ) { //If the page resource is not loaded, then the following code is not executed if ( loadedProgress < 100 ) return false; //Remove loader const oldContent = container.html(); hideLoader(container, title, dir, oldContent, content); }
JavaScript
function hideLoader( container, title, dir, oldContent, content ) { TweenMax.to( '.uix-ajax-load__loader', 0.5, { alpha : 0, onComplete : function() { TweenMax.set( this.target, { css : { 'display' : 'none' } }); //The data returned from the server container.html( content ).promise().done( function() { //Transition effect between two elements. eleTransitionEff( dir, oldContent, content ); //Change the page title if ( title ) { document.title = title; } //Prevent multiple request on click $( AJAXPageLinks ).data( 'request-running', false ); }); }, delay : loaderRemoveDelay/1000 }); }
function hideLoader( container, title, dir, oldContent, content ) { TweenMax.to( '.uix-ajax-load__loader', 0.5, { alpha : 0, onComplete : function() { TweenMax.set( this.target, { css : { 'display' : 'none' } }); //The data returned from the server container.html( content ).promise().done( function() { //Transition effect between two elements. eleTransitionEff( dir, oldContent, content ); //Change the page title if ( title ) { document.title = title; } //Prevent multiple request on click $( AJAXPageLinks ).data( 'request-running', false ); }); }, delay : loaderRemoveDelay/1000 }); }
JavaScript
function eleTransitionEff( dir, oldContent, newContent ) { const $originalItem = $sectionsContainer.find( '> section' ), $cloneItem = $originalItem.clone(); //Reset the original element $originalItem.css( { 'z-index': 1 } ); //Clone the last element to the first position $cloneItem .prependTo( $sectionsContainer ) .css( { 'z-index': 2, 'transform': 'translateY('+( ( dir == 'down' || dir === false ) ? windowHeight : -windowHeight )+'px)' } ) //Add the latest content to the new container .find( ajaxContainer ) .html( newContent ); $originalItem.first().find( ajaxContainer ).html( oldContent ).promise().done( function() { TweenMax.to( $originalItem.first(), animationTime/1000, { y : ( dir == 'down' || dir === false ) ? -windowHeight/2 : windowHeight/2, ease : Power2.easeOut }); TweenMax.to( $cloneItem, animationTime/1000, { y : 0, ease : Power2.easeOut, onComplete : function() { //Remove duplicate elements $originalItem .first() .remove(); // Apply some asynchronism scripts $( document ).UixApplyAsyncScripts(); } }); }); }
function eleTransitionEff( dir, oldContent, newContent ) { const $originalItem = $sectionsContainer.find( '> section' ), $cloneItem = $originalItem.clone(); //Reset the original element $originalItem.css( { 'z-index': 1 } ); //Clone the last element to the first position $cloneItem .prependTo( $sectionsContainer ) .css( { 'z-index': 2, 'transform': 'translateY('+( ( dir == 'down' || dir === false ) ? windowHeight : -windowHeight )+'px)' } ) //Add the latest content to the new container .find( ajaxContainer ) .html( newContent ); $originalItem.first().find( ajaxContainer ).html( oldContent ).promise().done( function() { TweenMax.to( $originalItem.first(), animationTime/1000, { y : ( dir == 'down' || dir === false ) ? -windowHeight/2 : windowHeight/2, ease : Power2.easeOut }); TweenMax.to( $cloneItem, animationTime/1000, { y : 0, ease : Power2.easeOut, onComplete : function() { //Remove duplicate elements $originalItem .first() .remove(); // Apply some asynchronism scripts $( document ).UixApplyAsyncScripts(); } }); }); }
JavaScript
function scrollMoveInit( event, dir ) { const timeNow = new Date().getTime(); // Cancel scroll if currently animating or within quiet period if( timeNow - lastAnimation < quietPeriod + animationTime) { return; } if ( dir == 'down' ) { //scroll down $( '#demo-mousewheel-interaction-status' ).html( 'Direction: down, Total: ' + scrollCount ); scrollCount++; } else { //scroll up $( '#demo-mousewheel-interaction-status' ).html( 'Direction: up, Total: ' + scrollCount ); scrollCount++; } lastAnimation = timeNow; }
function scrollMoveInit( event, dir ) { const timeNow = new Date().getTime(); // Cancel scroll if currently animating or within quiet period if( timeNow - lastAnimation < quietPeriod + animationTime) { return; } if ( dir == 'down' ) { //scroll down $( '#demo-mousewheel-interaction-status' ).html( 'Direction: down, Total: ' + scrollCount ); scrollCount++; } else { //scroll up $( '#demo-mousewheel-interaction-status' ).html( 'Direction: up, Total: ' + scrollCount ); scrollCount++; } lastAnimation = timeNow; }
JavaScript
function scrollMoveInit( event, dir ) { const timeNow = new Date().getTime(); // Cancel scroll if currently animating or within quiet period if( timeNow - lastAnimation < quietPeriod + animationTime) { return; } if ( dir == 'down' ) { //scroll down moveTo( $sectionsContainer, 'down', false ); } else { //scroll up moveTo( $sectionsContainer, 'up', false ); } lastAnimation = timeNow; }
function scrollMoveInit( event, dir ) { const timeNow = new Date().getTime(); // Cancel scroll if currently animating or within quiet period if( timeNow - lastAnimation < quietPeriod + animationTime) { return; } if ( dir == 'down' ) { //scroll down moveTo( $sectionsContainer, 'down', false ); } else { //scroll up moveTo( $sectionsContainer, 'up', false ); } lastAnimation = timeNow; }
JavaScript
function handleClickOutside(event) { if ( event.target.className != '' && ( event.target.className.indexOf( 'uix-cascading-dropdown-list__trigger' ) < 0 && event.target.className.indexOf( 'uix-cascading-dropdown-list__items' ) < 0 && event.target.className.indexOf( 'uix-cascading-dropdown-list__opt' ) < 0 ) ) { $control.data({ 'isShow': false }); } }
function handleClickOutside(event) { if ( event.target.className != '' && ( event.target.className.indexOf( 'uix-cascading-dropdown-list__trigger' ) < 0 && event.target.className.indexOf( 'uix-cascading-dropdown-list__items' ) < 0 && event.target.className.indexOf( 'uix-cascading-dropdown-list__opt' ) < 0 ) ) { $control.data({ 'isShow': false }); } }
JavaScript
function itemInit() { if ( dir == 'verticle' ) { $li.removeClass( 'is-active active-sub' ).css( 'height', 100/total + '%' ); } else { $li.removeClass( 'is-active active-sub' ).css( 'width', 100/total + '%' ); } }
function itemInit() { if ( dir == 'verticle' ) { $li.removeClass( 'is-active active-sub' ).css( 'height', 100/total + '%' ); } else { $li.removeClass( 'is-active active-sub' ).css( 'width', 100/total + '%' ); } }
JavaScript
function lerp( object, prop, destination ) { if (object && object[prop] !== destination) { object[prop] += (destination - object[prop]) * 0.1; if (Math.abs(destination - object[prop]) < 0.001) { object[prop] = destination; } } }
function lerp( object, prop, destination ) { if (object && object[prop] !== destination) { object[prop] += (destination - object[prop]) * 0.1; if (Math.abs(destination - object[prop]) < 0.001) { object[prop] = destination; } } }
JavaScript
function menuWrapInit( h ) { const $menuWrap = $( '.uix-v-menu__container:not(.is-mobile)' ), vMenuTop = 0; //This value is equal to the $vertical-menu-top variable in the SCSS let winHeight = h - vMenuTop; //WoedPress spy if ( $( '.admin-bar' ).length > 0 ) { winHeight = h - 132; } $menuWrap.css({ position : 'fixed', height : winHeight + 'px', marginTop : 0 }); function scrollUpdate() { const curULHeight = $( 'ul.uix-menu' ).height(), scrolled = $( window ).scrollTop(); if ( curULHeight > winHeight ) { $menuWrap.css({ position : 'absolute', height : curULHeight + 'px' }); if ( scrolled >= ( curULHeight - winHeight ) ) { $menuWrap.css({ position : 'fixed', marginTop : -( curULHeight - winHeight ) + 'px' }); } else { $menuWrap.css({ position : 'absolute', marginTop : 0 }); } } if ( $menuWrap.height() < winHeight ) { $menuWrap.css({ position : 'fixed', height : winHeight + 'px', marginTop : 0 }); } } // Add function to the element that should be used as the scrollable area. const throttleFunc = UixThrottle(scrollUpdate, 5); window.removeEventListener('scroll', throttleFunc); window.removeEventListener('touchmove', throttleFunc); window.addEventListener('scroll', throttleFunc); window.addEventListener('touchmove', throttleFunc); throttleFunc(); }
function menuWrapInit( h ) { const $menuWrap = $( '.uix-v-menu__container:not(.is-mobile)' ), vMenuTop = 0; //This value is equal to the $vertical-menu-top variable in the SCSS let winHeight = h - vMenuTop; //WoedPress spy if ( $( '.admin-bar' ).length > 0 ) { winHeight = h - 132; } $menuWrap.css({ position : 'fixed', height : winHeight + 'px', marginTop : 0 }); function scrollUpdate() { const curULHeight = $( 'ul.uix-menu' ).height(), scrolled = $( window ).scrollTop(); if ( curULHeight > winHeight ) { $menuWrap.css({ position : 'absolute', height : curULHeight + 'px' }); if ( scrolled >= ( curULHeight - winHeight ) ) { $menuWrap.css({ position : 'fixed', marginTop : -( curULHeight - winHeight ) + 'px' }); } else { $menuWrap.css({ position : 'absolute', marginTop : 0 }); } } if ( $menuWrap.height() < winHeight ) { $menuWrap.css({ position : 'fixed', height : winHeight + 'px', marginTop : 0 }); } } // Add function to the element that should be used as the scrollable area. const throttleFunc = UixThrottle(scrollUpdate, 5); window.removeEventListener('scroll', throttleFunc); window.removeEventListener('touchmove', throttleFunc); window.addEventListener('scroll', throttleFunc); window.addEventListener('touchmove', throttleFunc); throttleFunc(); }
JavaScript
function movePositionWithButton( paginationEnabled, $btn, type ) { const //Protection button is not triggered multiple times. btnDisabled = $btn.data( 'disabled' ), //Get current button index tIndex = parseFloat( $btn.attr( 'data-target-index' ) ); // Retrieve the position (X,Y) of an element let moveX = eachItemNewWidth, moveY = ( typeof eachItemNewHeight[tIndex-1] === typeof undefined ) ? 0 : eachItemNewHeight[tIndex-1]; if ( paginationEnabled ) { //-- moveX = eachItemNewWidth * tIndex; //-- let moveYIncrement = 0; for (let k = 0; k < eachItemNewHeight.length; k++ ) { const tempY = ( typeof eachItemNewHeight[k-1] === typeof undefined ) ? 0 : eachItemNewHeight[k-1]; moveYIncrement += tempY; if ( k == tIndex ) break; } moveY = moveYIncrement; } // let delta; if ( type == 'next' ) { delta = ( sliderDir === 'horizontal' ) ? -moveX : -moveY; } else { delta = ( sliderDir === 'horizontal' ) ? moveX : moveY; } if ( typeof btnDisabled === typeof undefined ) { itemUpdates( $sliderWrapper, $btn, delta, null, false, tIndex, eachItemNewHeight ); } }
function movePositionWithButton( paginationEnabled, $btn, type ) { const //Protection button is not triggered multiple times. btnDisabled = $btn.data( 'disabled' ), //Get current button index tIndex = parseFloat( $btn.attr( 'data-target-index' ) ); // Retrieve the position (X,Y) of an element let moveX = eachItemNewWidth, moveY = ( typeof eachItemNewHeight[tIndex-1] === typeof undefined ) ? 0 : eachItemNewHeight[tIndex-1]; if ( paginationEnabled ) { //-- moveX = eachItemNewWidth * tIndex; //-- let moveYIncrement = 0; for (let k = 0; k < eachItemNewHeight.length; k++ ) { const tempY = ( typeof eachItemNewHeight[k-1] === typeof undefined ) ? 0 : eachItemNewHeight[k-1]; moveYIncrement += tempY; if ( k == tIndex ) break; } moveY = moveYIncrement; } // let delta; if ( type == 'next' ) { delta = ( sliderDir === 'horizontal' ) ? -moveX : -moveY; } else { delta = ( sliderDir === 'horizontal' ) ? moveX : moveY; } if ( typeof btnDisabled === typeof undefined ) { itemUpdates( $sliderWrapper, $btn, delta, null, false, tIndex, eachItemNewHeight ); } }
JavaScript
function videoEmbedInit( wrapper, play ) { wrapper.find( '.uix-video__slider' ).each( function() { const $this = $( this ); const videoWrapperW = $this.closest( '[data-embed-video-wrapper]' ).width(), curVideoID = $this.find( 'video' ).attr( 'id' ) + '-slider-videopush', coverPlayBtnID = 'videocover-' + curVideoID, $replayBtn = $( '#'+curVideoID+'-replay-btn' ); let dataControls = $this.data( 'embed-video-controls' ), dataAuto = $this.data( 'embed-video-autoplay' ), dataLoop = $this.data( 'embed-video-loop' ), dataW = $this.data( 'embed-video-width' ), dataH = $this.data( 'embed-video-height' ); //Push a new ID to video //Solve the problem that ajax asynchronous loading does not play $this.find( '.video-js' ).attr( 'id', curVideoID ); if ( typeof dataAuto === typeof undefined ) { dataAuto = true; } if ( typeof dataLoop === typeof undefined ) { dataLoop = true; } if ( typeof dataControls === typeof undefined ) { dataControls = false; } if ( typeof dataW === typeof undefined || dataW == 'auto' ) { dataW = videoWrapperW; } if ( typeof dataH === typeof undefined || dataH == 'auto' ) { dataH = videoWrapperW/1.77777777777778; } //Display cover and play buttons when some mobile device browsers cannot automatically play video if ( $( '#' + coverPlayBtnID ).length == 0 ) { $( '<div id="'+coverPlayBtnID+'" class="uix-video__cover"><span class="uix-video__cover__placeholder" style="background-image:url('+$this.find( 'video' ).attr( 'poster' )+')"></span><span class="uix-video__cover__playbtn"></span></div>' ).insertBefore( $this ); const btnEv = ( Modernizr.touchevents ) ? 'touchstart' : 'click'; $( '#' + coverPlayBtnID + ' .uix-video__cover__playbtn' ).on( btnEv, function( e ) { e.preventDefault(); myPlayer.play(); $( '#' + coverPlayBtnID ).hide(); }); } //Add replay button to video if ( $replayBtn.length == 0 ) { $this.after( '<span class="uix-video__btn-play" id="'+curVideoID+'-replay-btn"></span>' ); } //HTML5 video autoplay on mobile revisited if ( dataAuto && windowWidth <= 768 ) { $this.find( '.video-js' ).attr({ 'autoplay' : 'true', 'muted' : 'true', 'playsinline' : 'true' }); } const myPlayer = videojs( curVideoID, { width : dataW, height : dataH, loop : dataLoop, autoplay : dataAuto }, function onPlayerReady() { const initVideo = function( obj ) { //Get Video Dimensions let curW = obj.videoWidth(), curH = obj.videoHeight(), newW = curW, newH = curH; newW = videoWrapperW; //Scaled/Proportional Content newH = curH*(newW/curW); if ( !isNaN( newW ) && !isNaN( newH ) ) { obj.height( newH ); obj.width( newW ); $this.css( 'height', newH ); } //Show this video wrapper $this.css( 'visibility', 'visible' ); //Hide loading effect $this.find( '.vjs-loading-spinner, .vjs-big-play-button' ).hide(); } /* --------- Video initialize */ this.on( 'loadedmetadata', function() { initVideo( this ); }); /* --------- Display the play button */ if ( ! dataAuto ) $this.find( '.vjs-big-play-button' ).show(); $this.find( '.vjs-big-play-button' ).off( 'click' ).on( 'click', function() { $( this ).hide(); }); /* --------- Set, tell the player it's in fullscreen */ if ( dataAuto ) { //Fix an error of Video auto play is not working in browser //this.muted( true ); //Prevent autoplay error: Uncaught (in promise) DOMException const promise = this.play(); if ( promise !== undefined ) { promise.then( function() { // Autoplay started! }).catch( function( error ) { // Autoplay was prevented. $( '#' + coverPlayBtnID ).show(); $( '#' + coverPlayBtnID + ' .uix-video__cover__playbtn' ).show(); console.log( 'Autoplay was prevented.' ); }); } } /* --------- Disable control bar play button click */ if ( !dataControls ) { this.controls( false ); } /* --------- Determine if the video is auto played from mobile devices */ let autoPlayOK = false; this.on( 'timeupdate', function() { let duration = this.duration(); if ( duration > 0 ) { autoPlayOK = true; if ( this.currentTime() > 0 ) { autoPlayOK = true; this.off( 'timeupdate' ); //Hide cover and play buttons when the video automatically played $( '#' + coverPlayBtnID ).hide(); } } }); /* --------- Pause the video when it is not current slider */ if ( !play ) { this.pause(); this.currentTime(0); } else { if ( dataAuto ) { this.currentTime(0); //Prevent autoplay error: Uncaught (in promise) DOMException const promise = this.play(); if ( promise !== undefined ) { promise.then( function() { // Autoplay started! }).catch( function( error ) { // Autoplay was prevented. $( '#' + coverPlayBtnID ).show(); $( '#' + coverPlayBtnID + ' .uix-video__cover__playbtn' ).show(); console.log( 'Autoplay was prevented.' ); }); } //Hidden replay button $replayBtn.hide(); //Should the video go to the beginning when it ends this.on( 'ended', function () { if ( dataLoop ) { this.currentTime(0); this.play(); } else { //Replay this video this.currentTime(0); $replayBtn .show() .off( 'click' ) .on( 'click', function( e ) { e.preventDefault(); this.play(); $replayBtn.hide(); }); } }); } } }); }); }
function videoEmbedInit( wrapper, play ) { wrapper.find( '.uix-video__slider' ).each( function() { const $this = $( this ); const videoWrapperW = $this.closest( '[data-embed-video-wrapper]' ).width(), curVideoID = $this.find( 'video' ).attr( 'id' ) + '-slider-videopush', coverPlayBtnID = 'videocover-' + curVideoID, $replayBtn = $( '#'+curVideoID+'-replay-btn' ); let dataControls = $this.data( 'embed-video-controls' ), dataAuto = $this.data( 'embed-video-autoplay' ), dataLoop = $this.data( 'embed-video-loop' ), dataW = $this.data( 'embed-video-width' ), dataH = $this.data( 'embed-video-height' ); //Push a new ID to video //Solve the problem that ajax asynchronous loading does not play $this.find( '.video-js' ).attr( 'id', curVideoID ); if ( typeof dataAuto === typeof undefined ) { dataAuto = true; } if ( typeof dataLoop === typeof undefined ) { dataLoop = true; } if ( typeof dataControls === typeof undefined ) { dataControls = false; } if ( typeof dataW === typeof undefined || dataW == 'auto' ) { dataW = videoWrapperW; } if ( typeof dataH === typeof undefined || dataH == 'auto' ) { dataH = videoWrapperW/1.77777777777778; } //Display cover and play buttons when some mobile device browsers cannot automatically play video if ( $( '#' + coverPlayBtnID ).length == 0 ) { $( '<div id="'+coverPlayBtnID+'" class="uix-video__cover"><span class="uix-video__cover__placeholder" style="background-image:url('+$this.find( 'video' ).attr( 'poster' )+')"></span><span class="uix-video__cover__playbtn"></span></div>' ).insertBefore( $this ); const btnEv = ( Modernizr.touchevents ) ? 'touchstart' : 'click'; $( '#' + coverPlayBtnID + ' .uix-video__cover__playbtn' ).on( btnEv, function( e ) { e.preventDefault(); myPlayer.play(); $( '#' + coverPlayBtnID ).hide(); }); } //Add replay button to video if ( $replayBtn.length == 0 ) { $this.after( '<span class="uix-video__btn-play" id="'+curVideoID+'-replay-btn"></span>' ); } //HTML5 video autoplay on mobile revisited if ( dataAuto && windowWidth <= 768 ) { $this.find( '.video-js' ).attr({ 'autoplay' : 'true', 'muted' : 'true', 'playsinline' : 'true' }); } const myPlayer = videojs( curVideoID, { width : dataW, height : dataH, loop : dataLoop, autoplay : dataAuto }, function onPlayerReady() { const initVideo = function( obj ) { //Get Video Dimensions let curW = obj.videoWidth(), curH = obj.videoHeight(), newW = curW, newH = curH; newW = videoWrapperW; //Scaled/Proportional Content newH = curH*(newW/curW); if ( !isNaN( newW ) && !isNaN( newH ) ) { obj.height( newH ); obj.width( newW ); $this.css( 'height', newH ); } //Show this video wrapper $this.css( 'visibility', 'visible' ); //Hide loading effect $this.find( '.vjs-loading-spinner, .vjs-big-play-button' ).hide(); } /* --------- Video initialize */ this.on( 'loadedmetadata', function() { initVideo( this ); }); /* --------- Display the play button */ if ( ! dataAuto ) $this.find( '.vjs-big-play-button' ).show(); $this.find( '.vjs-big-play-button' ).off( 'click' ).on( 'click', function() { $( this ).hide(); }); /* --------- Set, tell the player it's in fullscreen */ if ( dataAuto ) { //Fix an error of Video auto play is not working in browser //this.muted( true ); //Prevent autoplay error: Uncaught (in promise) DOMException const promise = this.play(); if ( promise !== undefined ) { promise.then( function() { // Autoplay started! }).catch( function( error ) { // Autoplay was prevented. $( '#' + coverPlayBtnID ).show(); $( '#' + coverPlayBtnID + ' .uix-video__cover__playbtn' ).show(); console.log( 'Autoplay was prevented.' ); }); } } /* --------- Disable control bar play button click */ if ( !dataControls ) { this.controls( false ); } /* --------- Determine if the video is auto played from mobile devices */ let autoPlayOK = false; this.on( 'timeupdate', function() { let duration = this.duration(); if ( duration > 0 ) { autoPlayOK = true; if ( this.currentTime() > 0 ) { autoPlayOK = true; this.off( 'timeupdate' ); //Hide cover and play buttons when the video automatically played $( '#' + coverPlayBtnID ).hide(); } } }); /* --------- Pause the video when it is not current slider */ if ( !play ) { this.pause(); this.currentTime(0); } else { if ( dataAuto ) { this.currentTime(0); //Prevent autoplay error: Uncaught (in promise) DOMException const promise = this.play(); if ( promise !== undefined ) { promise.then( function() { // Autoplay started! }).catch( function( error ) { // Autoplay was prevented. $( '#' + coverPlayBtnID ).show(); $( '#' + coverPlayBtnID + ' .uix-video__cover__playbtn' ).show(); console.log( 'Autoplay was prevented.' ); }); } //Hidden replay button $replayBtn.hide(); //Should the video go to the beginning when it ends this.on( 'ended', function () { if ( dataLoop ) { this.currentTime(0); this.play(); } else { //Replay this video this.currentTime(0); $replayBtn .show() .off( 'click' ) .on( 'click', function( e ) { e.preventDefault(); this.play(); $replayBtn.hide(); }); } }); } } }); }); }
JavaScript
function updateChildrenSlides( slideNumber, childrenSlidesObj, loop, speed, timing ) { /** * Create the children flexsliders. Must be array of jquery objects with the * flexslider data. Easiest way is to place selector group in a var. */ let childrenSlides = $( childrenSlidesObj ).flexslider({ slideshow : false, // Remove the animations controlNav : false, // Remove the controls animationLoop : loop, animationSpeed : speed, slideshowSpeed : timing }); // Iterate through the children slides but not past the max for ( let i=0; i < childrenSlides.length; i++ ) { // Run the animate method on the child slide $( childrenSlides[i] ).data( 'flexslider' ).flexAnimate( slideNumber ); } }
function updateChildrenSlides( slideNumber, childrenSlidesObj, loop, speed, timing ) { /** * Create the children flexsliders. Must be array of jquery objects with the * flexslider data. Easiest way is to place selector group in a var. */ let childrenSlides = $( childrenSlidesObj ).flexslider({ slideshow : false, // Remove the animations controlNav : false, // Remove the controls animationLoop : loop, animationSpeed : speed, slideshowSpeed : timing }); // Iterate through the children slides but not past the max for ( let i=0; i < childrenSlides.length; i++ ) { // Run the animate method on the child slide $( childrenSlides[i] ).data( 'flexslider' ).flexAnimate( slideNumber ); } }
JavaScript
function windowUpdate() { // Check window width has actually changed and it's not just iOS triggering a resize event on scroll if ( window.innerWidth != windowWidth ) { // Update the window width for next time windowWidth = window.innerWidth; // Do stuff here $sliderDefault.each( function() { if ( $( this ).length > 0 ) { // check grid size on resize event const dataShowItems = $( this ).data( 'my-multiple-items' ); if ( typeof dataShowItems != typeof undefined && dataShowItems != '' && dataShowItems != 0 ) { const gridSize = getGridSize( dataShowItems ); flexslider.vars.minItems = gridSize; flexslider.vars.maxItems = gridSize; } $( this ).data( 'flexslider' ).setup(); } }); } }
function windowUpdate() { // Check window width has actually changed and it's not just iOS triggering a resize event on scroll if ( window.innerWidth != windowWidth ) { // Update the window width for next time windowWidth = window.innerWidth; // Do stuff here $sliderDefault.each( function() { if ( $( this ).length > 0 ) { // check grid size on resize event const dataShowItems = $( this ).data( 'my-multiple-items' ); if ( typeof dataShowItems != typeof undefined && dataShowItems != '' && dataShowItems != 0 ) { const gridSize = getGridSize( dataShowItems ); flexslider.vars.minItems = gridSize; flexslider.vars.maxItems = gridSize; } $( this ).data( 'flexslider' ).setup(); } }); } }
JavaScript
function listFiles(client, container) { client.getFiles(container, function(err, files) { if (err) { console.log("Error fetching files from {0}: {1}".format(container.name, err)); return; } console.log(container.name.concat(":")); files.forEach(function(file, index, array) { console.log(" {name} ({size} bytes)".format(file)); }); }); }
function listFiles(client, container) { client.getFiles(container, function(err, files) { if (err) { console.log("Error fetching files from {0}: {1}".format(container.name, err)); return; } console.log(container.name.concat(":")); files.forEach(function(file, index, array) { console.log(" {name} ({size} bytes)".format(file)); }); }); }
JavaScript
function flatten(data) { const json = JSON.parse(data); const user = json.results[0]; return { title: user.name.title, firstname: user.name.first, lastname: user.name.last, gender: user.gender, age: user.dob.age, birth: user.dob.date, streetName: user.location.street.name, streetNumber: user.location.street.number, city: user.location.city, state: user.location.state, country: user.location.country, postcode: user.location.postcode, longitude: user.location.coordinates.longitude, latitude: user.location.coordinates.latitude, email: user.email, uuid: user.login.uuid, username: user.login.username, password: user.login.password, passwordSha256: user.login.sha256, registered: user.registered.date, phone: user.phone, cell: user.cell, largePicture: user.picture.large, mediumPicture: user.picture.medium, thumbnail: user.picture.thumbnail, nationality: user.nat, }; }
function flatten(data) { const json = JSON.parse(data); const user = json.results[0]; return { title: user.name.title, firstname: user.name.first, lastname: user.name.last, gender: user.gender, age: user.dob.age, birth: user.dob.date, streetName: user.location.street.name, streetNumber: user.location.street.number, city: user.location.city, state: user.location.state, country: user.location.country, postcode: user.location.postcode, longitude: user.location.coordinates.longitude, latitude: user.location.coordinates.latitude, email: user.email, uuid: user.login.uuid, username: user.login.username, password: user.login.password, passwordSha256: user.login.sha256, registered: user.registered.date, phone: user.phone, cell: user.cell, largePicture: user.picture.large, mediumPicture: user.picture.medium, thumbnail: user.picture.thumbnail, nationality: user.nat, }; }
JavaScript
function auth(req, res, next) { // Ensure at least that we got a u/p if(!req.body.username || !req.body.password) { return res.end(JSON.stringify({ error: 'Bad Credentials' }), 401); } next(); }
function auth(req, res, next) { // Ensure at least that we got a u/p if(!req.body.username || !req.body.password) { return res.end(JSON.stringify({ error: 'Bad Credentials' }), 401); } next(); }
JavaScript
function createWindow() { mainWindow = new BrowserWindow({width: 800, height: 800}); mainWindow.loadURL(url.format({ pathname: path.join(__dirname, 'index.html'), protocol: 'file:', slashes: true })); mainWindow.webContents.openDevTools(); mainWindow.on('closed', () => { mainWindow = null; }); }
function createWindow() { mainWindow = new BrowserWindow({width: 800, height: 800}); mainWindow.loadURL(url.format({ pathname: path.join(__dirname, 'index.html'), protocol: 'file:', slashes: true })); mainWindow.webContents.openDevTools(); mainWindow.on('closed', () => { mainWindow = null; }); }
JavaScript
async function sendEmail(recipients, subject = '', htmlBody = '') { let dotenv = require("dotenv").config(); // create reusable transporter object using the default SMTP transport let transporter = nodemailer.createTransport({ host: "smtp.gmail.com", port: 587, secure: false, // true for 465, false for other ports requireTLS: true, auth: { user: `${process.env.GMAIL_USER}`, // generated ethereal user pass: `${process.env.GMAIL_PASS}`, // generated ethereal password }, }); transporter.use('compile', htmlToText()); let mailOptions = { from: `Pro Event Planner 🌦" <${process.env.GMAIL_USER}>'`, // sender address to: `${recipients}`, // list of receivers subject: `${subject}`, // Subject line html: `${htmlBody || body}`, // html body }; // send mail with defined transport object transporter.sendMail(mailOptions, (error, info) => { if (error) { return console.log(error.message); } // Message sent: <[email protected]> console.log("Message sent: %s", info.messageId); }); }
async function sendEmail(recipients, subject = '', htmlBody = '') { let dotenv = require("dotenv").config(); // create reusable transporter object using the default SMTP transport let transporter = nodemailer.createTransport({ host: "smtp.gmail.com", port: 587, secure: false, // true for 465, false for other ports requireTLS: true, auth: { user: `${process.env.GMAIL_USER}`, // generated ethereal user pass: `${process.env.GMAIL_PASS}`, // generated ethereal password }, }); transporter.use('compile', htmlToText()); let mailOptions = { from: `Pro Event Planner 🌦" <${process.env.GMAIL_USER}>'`, // sender address to: `${recipients}`, // list of receivers subject: `${subject}`, // Subject line html: `${htmlBody || body}`, // html body }; // send mail with defined transport object transporter.sendMail(mailOptions, (error, info) => { if (error) { return console.log(error.message); } // Message sent: <[email protected]> console.log("Message sent: %s", info.messageId); }); }
JavaScript
function handle_pyout(cell) { var el = d.createElement('div'); if (cell.hasOwnProperty('prompt_number')) el.appendChild(excount(cell, false)); // var ks = Object.keys(cell) // text, png, jpeg, html -- supported // svg, latex, javascript, json, pdf, metadata -- not yet Object.keys(cell).forEach(function(k) { // TODO: are metadata in any way useful? if (['output_type', 'prompt_number', 'metadata'].indexOf(k) > -1) return; var p = d.createElement('span'); // if errs switch (k) { case 'text': p = d.createElement('pre'); p.style.margin = 0; p.textContent = handle_multiline_strings(cell[k]); break; case 'html': case 'svg': p = d.createElement('div'); // guessing here, haven't seen a v3 HTML element (TODO: remove it and test against our big dataset) p.innerHTML = handle_multiline_strings(cell[k]); break; case 'png': case 'jpeg': p = d.createElement('img'); p.setAttribute('src', 'data:' + k + ';base64,' + cell[k]); p.setAttribute('style', 'max-width: 100%'); // avoid overflow break; default: throw new Error('unsupported pyout format: ' + k); } el.appendChild(p); }); return el; }
function handle_pyout(cell) { var el = d.createElement('div'); if (cell.hasOwnProperty('prompt_number')) el.appendChild(excount(cell, false)); // var ks = Object.keys(cell) // text, png, jpeg, html -- supported // svg, latex, javascript, json, pdf, metadata -- not yet Object.keys(cell).forEach(function(k) { // TODO: are metadata in any way useful? if (['output_type', 'prompt_number', 'metadata'].indexOf(k) > -1) return; var p = d.createElement('span'); // if errs switch (k) { case 'text': p = d.createElement('pre'); p.style.margin = 0; p.textContent = handle_multiline_strings(cell[k]); break; case 'html': case 'svg': p = d.createElement('div'); // guessing here, haven't seen a v3 HTML element (TODO: remove it and test against our big dataset) p.innerHTML = handle_multiline_strings(cell[k]); break; case 'png': case 'jpeg': p = d.createElement('img'); p.setAttribute('src', 'data:' + k + ';base64,' + cell[k]); p.setAttribute('style', 'max-width: 100%'); // avoid overflow break; default: throw new Error('unsupported pyout format: ' + k); } el.appendChild(p); }); return el; }
JavaScript
function openPDF(im){ initRoundTableSurface(); pdfSource = im; roundTableData[currentSurface].pdfSource = im; var d = document.getElementById("slidespace").getElementsByClassName('slide')[0]; d.innerHTML +='<canvas id="pdf-canvas"></canvas>' ; canvasPDF = document.getElementById('pdf-canvas'); ctxPDF = canvasPDF.getContext('2d'); /** * Asynchronously downloads PDF. */ pdfjsLib.getDocument(URL.createObjectURL(im)).promise.then(function(pdfDoc_) { pdfDoc = pdfDoc_; if (pdfDoc.numPages > 1){ var d = document.getElementById("slidespace").getElementsByClassName('slide')[0]; var nd = document.createElement("div"); nd.classList.add("pdfcontrol"); nd.innerHTML = '<button id="prev">&nbsp;&lt;&nbsp;&lt;&nbsp;</button> ' +'<span><span id="textpdfpage">1</span><input type="range" id="pdfpage" name="pdfPage" min="1" max="1"><span>' +' <button id="next">&nbsp;&gt;&nbsp;&gt;&nbsp;</button>'; d.append(nd); document.getElementById('pdfpage').max = pdfDoc.numPages; document.getElementById("pdfpage").addEventListener("change",function(e){ var num = parseInt(document.getElementById("pdfpage").value, 10); collectAnnotationPage(pageNum); pageNum = num; queueRenderPage(num); }); document.getElementById('prev').addEventListener('click', onPrevPage); document.getElementById('next').addEventListener('click', onNextPage); } // Initial/first page rendering renderPage(pageNum); }); }
function openPDF(im){ initRoundTableSurface(); pdfSource = im; roundTableData[currentSurface].pdfSource = im; var d = document.getElementById("slidespace").getElementsByClassName('slide')[0]; d.innerHTML +='<canvas id="pdf-canvas"></canvas>' ; canvasPDF = document.getElementById('pdf-canvas'); ctxPDF = canvasPDF.getContext('2d'); /** * Asynchronously downloads PDF. */ pdfjsLib.getDocument(URL.createObjectURL(im)).promise.then(function(pdfDoc_) { pdfDoc = pdfDoc_; if (pdfDoc.numPages > 1){ var d = document.getElementById("slidespace").getElementsByClassName('slide')[0]; var nd = document.createElement("div"); nd.classList.add("pdfcontrol"); nd.innerHTML = '<button id="prev">&nbsp;&lt;&nbsp;&lt;&nbsp;</button> ' +'<span><span id="textpdfpage">1</span><input type="range" id="pdfpage" name="pdfPage" min="1" max="1"><span>' +' <button id="next">&nbsp;&gt;&nbsp;&gt;&nbsp;</button>'; d.append(nd); document.getElementById('pdfpage').max = pdfDoc.numPages; document.getElementById("pdfpage").addEventListener("change",function(e){ var num = parseInt(document.getElementById("pdfpage").value, 10); collectAnnotationPage(pageNum); pageNum = num; queueRenderPage(num); }); document.getElementById('prev').addEventListener('click', onPrevPage); document.getElementById('next').addEventListener('click', onNextPage); } // Initial/first page rendering renderPage(pageNum); }); }
JavaScript
function renderPage(num) { roundTableData[currentSurface].pageNum = pageNum; pageRendering = true; // Using promise to fetch the page pdfDoc.getPage(num).then(function(page) { var viewport = page.getViewport({"scale":1}); var scale = Math.min(tableWidth / viewport.width, tableHeight/viewport.height) viewport = page.getViewport({"scale": scale}); canvasPDF.height = viewport.height; canvasPDF.width = viewport.width; canvasPDF.style.height = viewport.height + "px"; canvasPDF.style.width = viewport.width+ "px"; canvasPDF.style.marginLeft = (tableWidth - viewport.width)/2+ "px"; canvasPDF.style.marginTop = (tableHeight - viewport.height)/2+ "px"; // Render PDF page into canvas context var renderContext = { "canvasContext": ctxPDF, "viewport": viewport }; var renderTask = page.render(renderContext); // Wait for rendering to finish renderTask.promise.then(function() { pageRendering = false; if (pageNumPending !== null) { // New page rendering is pending renderPage(pageNumPending); pageNumPending = null; } else{ setAnnotationPage(pageNum); } }); }); // Update page counters var pageCounterIndicator = document.getElementById('pdfpage'); if (pageCounterIndicator !=null){ pageCounterIndicator.value = num; } }
function renderPage(num) { roundTableData[currentSurface].pageNum = pageNum; pageRendering = true; // Using promise to fetch the page pdfDoc.getPage(num).then(function(page) { var viewport = page.getViewport({"scale":1}); var scale = Math.min(tableWidth / viewport.width, tableHeight/viewport.height) viewport = page.getViewport({"scale": scale}); canvasPDF.height = viewport.height; canvasPDF.width = viewport.width; canvasPDF.style.height = viewport.height + "px"; canvasPDF.style.width = viewport.width+ "px"; canvasPDF.style.marginLeft = (tableWidth - viewport.width)/2+ "px"; canvasPDF.style.marginTop = (tableHeight - viewport.height)/2+ "px"; // Render PDF page into canvas context var renderContext = { "canvasContext": ctxPDF, "viewport": viewport }; var renderTask = page.render(renderContext); // Wait for rendering to finish renderTask.promise.then(function() { pageRendering = false; if (pageNumPending !== null) { // New page rendering is pending renderPage(pageNumPending); pageNumPending = null; } else{ setAnnotationPage(pageNum); } }); }); // Update page counters var pageCounterIndicator = document.getElementById('pdfpage'); if (pageCounterIndicator !=null){ pageCounterIndicator.value = num; } }
JavaScript
function queueRenderPage(num) { queueRenderPage_nosend(num); socket.emit('send_room', {"action":"pdf_page", "page":num, "username": username, "room": room}, function (timestamp){ roundTableData[currentSurface].timestamp = timestamp; }); }
function queueRenderPage(num) { queueRenderPage_nosend(num); socket.emit('send_room', {"action":"pdf_page", "page":num, "username": username, "room": room}, function (timestamp){ roundTableData[currentSurface].timestamp = timestamp; }); }
JavaScript
function drawLineRaster(ctx,x,y,size) { // If lastX is not set, set lastX and lastY to the current position if (lastX==-1) { lastX=x; lastY=y; firstSegment = true; return; } else if (firstSegment && (Math.abs(lastX-x)>maxLine || Math.abs(lastY-y)>maxLine)){ lastX=x; lastY=y; return; } else{ firstSegment = false; } // Select a fill style ctx.strokeStyle = "rgba("+penColor[0]+","+penColor[1]+","+penColor[2]+","+(penColor[3]/255)+")"; // Set the line "cap" style to round, so lines at different angles can join into each other ctx.lineCap = "round"; //ctx.lineJoin = "round"; // Draw a filled line ctx.beginPath(); // First, move to the old (previous) position ctx.moveTo(lastX,lastY); // Now draw a line to the current touch/pointer position ctx.lineTo(x,y); // Set the line thickness and draw the line ctx.lineWidth = size; ctx.stroke(); ctx.closePath(); // Update the last position to reference the current position lastX=x; lastY=y; }
function drawLineRaster(ctx,x,y,size) { // If lastX is not set, set lastX and lastY to the current position if (lastX==-1) { lastX=x; lastY=y; firstSegment = true; return; } else if (firstSegment && (Math.abs(lastX-x)>maxLine || Math.abs(lastY-y)>maxLine)){ lastX=x; lastY=y; return; } else{ firstSegment = false; } // Select a fill style ctx.strokeStyle = "rgba("+penColor[0]+","+penColor[1]+","+penColor[2]+","+(penColor[3]/255)+")"; // Set the line "cap" style to round, so lines at different angles can join into each other ctx.lineCap = "round"; //ctx.lineJoin = "round"; // Draw a filled line ctx.beginPath(); // First, move to the old (previous) position ctx.moveTo(lastX,lastY); // Now draw a line to the current touch/pointer position ctx.lineTo(x,y); // Set the line thickness and draw the line ctx.lineWidth = size; ctx.stroke(); ctx.closePath(); // Update the last position to reference the current position lastX=x; lastY=y; }
JavaScript
function sketchpad_mouseUp(e) { if (mouseDown==0){ return; } mouseDown=0; if (firstSegment){ getMousePos(e); if (mouseX == lastX && mouseY == lastY){ drawLine(ctx,mouseX,mouseY,penSize); } } // Reset lastX and lastY to -1 to indicate that they are now invalid, since we have lifted the "pen" lastX=-1; lastY=-1; if (useSVG && !firstSegment){ var lineID = "l"+lineCount+"-"+username; if (roundTable){ var l = document.getElementById(lineID); if (l===null || l.getAttribute("points")===null) return; socket.emit('send_room', {"action":"line", "points":l.getAttribute("points"), "style":l.getAttribute("style"), "id":lineCount, "username": username, "room": room}, function (timestamp){ roundTableData[currentSurface].timestamp = timestamp; }); } smoothLine(lineID); } }
function sketchpad_mouseUp(e) { if (mouseDown==0){ return; } mouseDown=0; if (firstSegment){ getMousePos(e); if (mouseX == lastX && mouseY == lastY){ drawLine(ctx,mouseX,mouseY,penSize); } } // Reset lastX and lastY to -1 to indicate that they are now invalid, since we have lifted the "pen" lastX=-1; lastY=-1; if (useSVG && !firstSegment){ var lineID = "l"+lineCount+"-"+username; if (roundTable){ var l = document.getElementById(lineID); if (l===null || l.getAttribute("points")===null) return; socket.emit('send_room', {"action":"line", "points":l.getAttribute("points"), "style":l.getAttribute("style"), "id":lineCount, "username": username, "room": room}, function (timestamp){ roundTableData[currentSurface].timestamp = timestamp; }); } smoothLine(lineID); } }
JavaScript
function sketchpad_mouseMove(e) { // Update the mouse co-ordinates when moved getMousePos(e); // Draw a dot if the mouse button is currently being pressed if (mouseDown==1) { drawLine(ctx,mouseX,mouseY,penSize); } }
function sketchpad_mouseMove(e) { // Update the mouse co-ordinates when moved getMousePos(e); // Draw a dot if the mouse button is currently being pressed if (mouseDown==1) { drawLine(ctx,mouseX,mouseY,penSize); } }
JavaScript
function sketchpad_touchStart(e) { // Update the touch co-ordinates getTouchPos(e); drawLine(ctx,touchX/roundTableScale,touchY/roundTableScale,penSize); // Prevents an additional mousedown event being triggered event.preventDefault(); }
function sketchpad_touchStart(e) { // Update the touch co-ordinates getTouchPos(e); drawLine(ctx,touchX/roundTableScale,touchY/roundTableScale,penSize); // Prevents an additional mousedown event being triggered event.preventDefault(); }
JavaScript
function initRoundTable(){ var h = window.location.hash.substr(1) if ((h=="") || (h.indexOf("slide")==0)){ document.getElementById("gettable").value = 'Get my roundtable'; } else{ document.getElementById("gettable").value = 'Join roundtable'; } // document.getElementsByTagName("h1")[0].onclick = function(){ // window.location = roundTableServer; // } var e = document.getElementById("uname"); e.focus(); document.getElementById("gettable").addEventListener("click",function(){ if (document.getElementById("uname").value.match(/^\s+$/) == null && document.getElementById("uname").value.length>0){ username = document.getElementById("uname").value; username = username.replace("=",""); document.getElementById("intro1").style.display="none"; document.getElementById("intro2").style.display="block"; document.getElementById("about").style.display="none"; } else{ document.getElementById("uname").focus(); } }); document.getElementById("uname").addEventListener("keyup", function(e){ var x = e.which || e.keyCode; if (x==13){ if (document.getElementById("uname").value.match(/^\s+$/) == null && document.getElementById("uname").value.length>0 ){ username = document.getElementById("uname").value; username = username.replace("=",""); document.getElementById("intro1").style.display="none"; document.getElementById("intro2").style.display="block"; } else{ document.getElementById("uname").focus(); } } }) window.addEventListener('hashchange', function() { if (room != window.location.hash.substr(1)){ window.location.reload(); } }, false); document.getElementById("bproceed").disabled = true; document.getElementById("bproceed").addEventListener("click",function(){ document.getElementById("intro2").style.display="none"; document.getElementById("intro3").style.display="block"; roundTableExit = function(){ confirmChoice("Do you want to exit this roundtable?", "Cancel", function (){return; }, "Yes, leave this roundtable", function (){window.location = roundTableServer; } ); }; roundTable=true; roundTableAuth = grecaptcha.getResponse(); roundTableCallBack = afterConnection; initApp(); // overwrite default clear all to add confirmation var d = document.getElementById("controlspace").children[19]; d.onclick = function(e){ confirmChoice("Do you want to delete everything from the table (including annotations of other people)?", "Cancel", function (){return; }, "Yes, clear roundtable", function (){ socket.emit('send_room', {action:"clearAll", username: username, room: room}) cleanRoundtable(); } ); e.preventDefault(); } // add proper notification if moderator cannot be reached roundtableModeratorTimout = function(){ confirmChoice("It seems you joined a roundtable where moderator already left, or lost connection.<br> Would you like to navigate to homepage and set up your own roundable?", "No, continue waiting", function (){return; }, "Yes, set up my own roundtable", function (){ window.location = roundTableServer; } ); }; }); var s = document.getElementsByClassName('rselect'); for (var i=0; i<s.length; i += 1){ s[i].addEventListener("click",function(e){ if (e.target.innerHTML == "left hand use"){ leftHanded = true; } else{ leftHanded = false; } var s = document.getElementsByClassName('rselect'); for (var i=0; i<s.length; i += 1){ s[i].classList.remove('rselected'); } e.target.classList.add('rselected'); }) } }
function initRoundTable(){ var h = window.location.hash.substr(1) if ((h=="") || (h.indexOf("slide")==0)){ document.getElementById("gettable").value = 'Get my roundtable'; } else{ document.getElementById("gettable").value = 'Join roundtable'; } // document.getElementsByTagName("h1")[0].onclick = function(){ // window.location = roundTableServer; // } var e = document.getElementById("uname"); e.focus(); document.getElementById("gettable").addEventListener("click",function(){ if (document.getElementById("uname").value.match(/^\s+$/) == null && document.getElementById("uname").value.length>0){ username = document.getElementById("uname").value; username = username.replace("=",""); document.getElementById("intro1").style.display="none"; document.getElementById("intro2").style.display="block"; document.getElementById("about").style.display="none"; } else{ document.getElementById("uname").focus(); } }); document.getElementById("uname").addEventListener("keyup", function(e){ var x = e.which || e.keyCode; if (x==13){ if (document.getElementById("uname").value.match(/^\s+$/) == null && document.getElementById("uname").value.length>0 ){ username = document.getElementById("uname").value; username = username.replace("=",""); document.getElementById("intro1").style.display="none"; document.getElementById("intro2").style.display="block"; } else{ document.getElementById("uname").focus(); } } }) window.addEventListener('hashchange', function() { if (room != window.location.hash.substr(1)){ window.location.reload(); } }, false); document.getElementById("bproceed").disabled = true; document.getElementById("bproceed").addEventListener("click",function(){ document.getElementById("intro2").style.display="none"; document.getElementById("intro3").style.display="block"; roundTableExit = function(){ confirmChoice("Do you want to exit this roundtable?", "Cancel", function (){return; }, "Yes, leave this roundtable", function (){window.location = roundTableServer; } ); }; roundTable=true; roundTableAuth = grecaptcha.getResponse(); roundTableCallBack = afterConnection; initApp(); // overwrite default clear all to add confirmation var d = document.getElementById("controlspace").children[19]; d.onclick = function(e){ confirmChoice("Do you want to delete everything from the table (including annotations of other people)?", "Cancel", function (){return; }, "Yes, clear roundtable", function (){ socket.emit('send_room', {action:"clearAll", username: username, room: room}) cleanRoundtable(); } ); e.preventDefault(); } // add proper notification if moderator cannot be reached roundtableModeratorTimout = function(){ confirmChoice("It seems you joined a roundtable where moderator already left, or lost connection.<br> Would you like to navigate to homepage and set up your own roundable?", "No, continue waiting", function (){return; }, "Yes, set up my own roundtable", function (){ window.location = roundTableServer; } ); }; }); var s = document.getElementsByClassName('rselect'); for (var i=0; i<s.length; i += 1){ s[i].addEventListener("click",function(e){ if (e.target.innerHTML == "left hand use"){ leftHanded = true; } else{ leftHanded = false; } var s = document.getElementsByClassName('rselect'); for (var i=0; i<s.length; i += 1){ s[i].classList.remove('rselected'); } e.target.classList.add('rselected'); }) } }
JavaScript
async function walkCheckpoints () { if (checkpoints.length === 0) { bot.chat('There are no checkpoints') return } // Remove all checkpoints when starting to walking const checkPointCopy = [...checkpoints] checkpoints = [] for (const checkpoint of checkPointCopy) { // Make a new goal to goto. GoalBlock will make the bot walk to the // block position off checkpoint. const goal = new GoalBlock(checkpoint.x, checkpoint.y, checkpoint.z) try { // Use await to make sure the bot is at the checkpoint before moving on await bot.pathfinder.goto(goal) } catch (error) { console.log('Got error from goto', error.message) // If we get an error we quit the loop return } } }
async function walkCheckpoints () { if (checkpoints.length === 0) { bot.chat('There are no checkpoints') return } // Remove all checkpoints when starting to walking const checkPointCopy = [...checkpoints] checkpoints = [] for (const checkpoint of checkPointCopy) { // Make a new goal to goto. GoalBlock will make the bot walk to the // block position off checkpoint. const goal = new GoalBlock(checkpoint.x, checkpoint.y, checkpoint.z) try { // Use await to make sure the bot is at the checkpoint before moving on await bot.pathfinder.goto(goal) } catch (error) { console.log('Got error from goto', error.message) // If we get an error we quit the loop return } } }
JavaScript
async function parkourMap (Version) { const pwd = path.join(__dirname, './schematics/parkour1.schem') // parkour1.schem is a version 1.12 schematic. If other schematics are used the version has to change here too. const readSchem = await Schematic.read(await fs.readFile(pwd), '1.12.2') const Block = require('prismarine-block')(Version) const Chunk = require('prismarine-chunk')(Version) const mcData = require('minecraft-data')(Version) const chunk = new Chunk() chunk.initialize((x, y, z) => { const block = readSchem.getBlock(new Vec3(x, y, z)) if (block.name === 'air') return null // Different versions off schematic are not compatible with each other. Assumes block names between versions stay the same. const blockVersion = mcData.blocksByName[block.name] if (!blockVersion) return null return new Block(blockVersion.id, 1, 0) }) return chunk }
async function parkourMap (Version) { const pwd = path.join(__dirname, './schematics/parkour1.schem') // parkour1.schem is a version 1.12 schematic. If other schematics are used the version has to change here too. const readSchem = await Schematic.read(await fs.readFile(pwd), '1.12.2') const Block = require('prismarine-block')(Version) const Chunk = require('prismarine-chunk')(Version) const mcData = require('minecraft-data')(Version) const chunk = new Chunk() chunk.initialize((x, y, z) => { const block = readSchem.getBlock(new Vec3(x, y, z)) if (block.name === 'air') return null // Different versions off schematic are not compatible with each other. Assumes block names between versions stay the same. const blockVersion = mcData.blocksByName[block.name] if (!blockVersion) return null return new Block(blockVersion.id, 1, 0) }) return chunk }
JavaScript
async function newServer (server, chunk, spawnPos, Version, useLoginPacket) { const mcData = require('minecraft-data')(Version) server = mc.createServer({ 'online-mode': false, version: Version, // 25565 - local server, 25566 - proxy server port: ServerPort }) server.on('login', (client) => { let loginPacket if (useLoginPacket) { loginPacket = mcData.loginPacket } else { loginPacket = { entityId: 0, levelType: 'fogetaboutit', gameMode: 0, previousGameMode: 255, worldNames: ['minecraft:overworld'], dimension: 0, worldName: 'minecraft:overworld', hashedSeed: [0, 0], difficulty: 0, maxPlayers: 20, reducedDebugInfo: 1, enableRespawnScreen: true } } client.write('login', loginPacket) client.write('map_chunk', { x: 0, z: 0, groundUp: true, biomes: chunk.dumpBiomes !== undefined ? chunk.dumpBiomes() : undefined, heightmaps: { type: 'compound', name: '', value: { MOTION_BLOCKING: { type: 'longArray', value: new Array(36).fill([0, 0]) } } }, // send fake heightmap bitMap: chunk.getMask(), chunkData: chunk.dump(), blockEntities: [] }) client.write('position', { x: spawnPos.x, y: spawnPos.y, z: spawnPos.z, yaw: 0, pitch: 0, flags: 0x00 }) }) await once(server, 'listening') return server }
async function newServer (server, chunk, spawnPos, Version, useLoginPacket) { const mcData = require('minecraft-data')(Version) server = mc.createServer({ 'online-mode': false, version: Version, // 25565 - local server, 25566 - proxy server port: ServerPort }) server.on('login', (client) => { let loginPacket if (useLoginPacket) { loginPacket = mcData.loginPacket } else { loginPacket = { entityId: 0, levelType: 'fogetaboutit', gameMode: 0, previousGameMode: 255, worldNames: ['minecraft:overworld'], dimension: 0, worldName: 'minecraft:overworld', hashedSeed: [0, 0], difficulty: 0, maxPlayers: 20, reducedDebugInfo: 1, enableRespawnScreen: true } } client.write('login', loginPacket) client.write('map_chunk', { x: 0, z: 0, groundUp: true, biomes: chunk.dumpBiomes !== undefined ? chunk.dumpBiomes() : undefined, heightmaps: { type: 'compound', name: '', value: { MOTION_BLOCKING: { type: 'longArray', value: new Array(36).fill([0, 0]) } } }, // send fake heightmap bitMap: chunk.getMask(), chunkData: chunk.dump(), blockEntities: [] }) client.write('position', { x: spawnPos.x, y: spawnPos.y, z: spawnPos.z, yaw: 0, pitch: 0, flags: 0x00 }) }) await once(server, 'listening') return server }
JavaScript
function bufferToStream(binary) { const readableInstanceStream = new Readable({ read() { this.push(binary); this.push(null); } }); return readableInstanceStream; }
function bufferToStream(binary) { const readableInstanceStream = new Readable({ read() { this.push(binary); this.push(null); } }); return readableInstanceStream; }
JavaScript
function install(items, callback) { var item = items[next], command = item.command, args = item.args, admin = item.admin, spawnopt = (item.spawnopt || {}), print; // set the spawn object according to the passed admin argument admin = setSpawnObject(admin); // run the command if (isLinux) { if (admin) { // use sudo args.unshift(command); print = args.join(" "); logger.console.log("[package-script] Running Installer command: " + print); sudoopt.spawnOptions = {}; jsutils.Object.copy(spawnopt, sudoopt.spawnOptions); cprocess = spawn(args, sudoopt); } else { //use child_process print = args.join(" "); logger.console.log("[package-script] Running Installer command: " + command + " " + print); cprocess = spawn(command, args, spawnopt); } } else { args.unshift(command); args.unshift("/c"); command = "cmd"; print = [command, args.join(" ")].join(" "); logger.console.log("[package-script] Running Installer command: " + print); cprocess = spawn(command, args, spawnopt); } // -- Spawn Listeners cprocess.stdout.on('data', function (data) { var log = 'CAT Installer: ' + data; logger.logall(log); }); cprocess.stderr.on('data', function (data) { if (data && (new String(data)).indexOf("npm ERR") != -1) { logger.logall('Package Script : ' + data); } else { logger.log2file('Package Script : ' + data); } }); cprocess.on('close', function (code) { logger.log2file('Package Script Complete ' + code); next++; if (next < size) { install(items, callback); } else { // callback if (callback && _.isFunction(callback)) { callback.call(this, code); } } }); }
function install(items, callback) { var item = items[next], command = item.command, args = item.args, admin = item.admin, spawnopt = (item.spawnopt || {}), print; // set the spawn object according to the passed admin argument admin = setSpawnObject(admin); // run the command if (isLinux) { if (admin) { // use sudo args.unshift(command); print = args.join(" "); logger.console.log("[package-script] Running Installer command: " + print); sudoopt.spawnOptions = {}; jsutils.Object.copy(spawnopt, sudoopt.spawnOptions); cprocess = spawn(args, sudoopt); } else { //use child_process print = args.join(" "); logger.console.log("[package-script] Running Installer command: " + command + " " + print); cprocess = spawn(command, args, spawnopt); } } else { args.unshift(command); args.unshift("/c"); command = "cmd"; print = [command, args.join(" ")].join(" "); logger.console.log("[package-script] Running Installer command: " + print); cprocess = spawn(command, args, spawnopt); } // -- Spawn Listeners cprocess.stdout.on('data', function (data) { var log = 'CAT Installer: ' + data; logger.logall(log); }); cprocess.stderr.on('data', function (data) { if (data && (new String(data)).indexOf("npm ERR") != -1) { logger.logall('Package Script : ' + data); } else { logger.log2file('Package Script : ' + data); } }); cprocess.on('close', function (code) { logger.log2file('Package Script Complete ' + code); next++; if (next < size) { install(items, callback); } else { // callback if (callback && _.isFunction(callback)) { callback.call(this, code); } } }); }
JavaScript
function loadDisplay() { if (screenState === "lock-screen") { unlockPhone(); fadeInP.classList.toggle("animate-text"); } else if (screenState === "home-screen") { lockPhone(); fadeInP.classList.toggle("animate-text"); } else if (screenState === "open-app") { closeApp(); } }
function loadDisplay() { if (screenState === "lock-screen") { unlockPhone(); fadeInP.classList.toggle("animate-text"); } else if (screenState === "home-screen") { lockPhone(); fadeInP.classList.toggle("animate-text"); } else if (screenState === "open-app") { closeApp(); } }
JavaScript
function unlockPhone() { timeP.classList.add("animate-time"); setTimeout(() => { lock.classList.toggle("fa-lock"); lock.innerText = timeP.innerText; home.classList.toggle("on-display"); display.classList.toggle("on-display"); timeP.style.animationPlayState = "paused"; }, 195); screenState = "home-screen"; }
function unlockPhone() { timeP.classList.add("animate-time"); setTimeout(() => { lock.classList.toggle("fa-lock"); lock.innerText = timeP.innerText; home.classList.toggle("on-display"); display.classList.toggle("on-display"); timeP.style.animationPlayState = "paused"; }, 195); screenState = "home-screen"; }
JavaScript
function lockPhone() { home.classList.toggle("on-display"); display.classList.toggle("on-display"); audio.play(); timeP.style.animationPlayState = "running"; lock.classList.toggle("fa-lock"); lock.innerText = ""; setTimeout(() => { timeP.classList.remove("animate-time"); }, 195); screenState = "lock-screen"; }
function lockPhone() { home.classList.toggle("on-display"); display.classList.toggle("on-display"); audio.play(); timeP.style.animationPlayState = "running"; lock.classList.toggle("fa-lock"); lock.innerText = ""; setTimeout(() => { timeP.classList.remove("animate-time"); }, 195); screenState = "lock-screen"; }
JavaScript
function openApp() { const app = document.querySelector("." + this.dataset.name); app.classList.toggle("on-display"); display.classList.toggle("on-display"); screen.style.backgroundImage = "none"; screenState = "open-app"; }
function openApp() { const app = document.querySelector("." + this.dataset.name); app.classList.toggle("on-display"); display.classList.toggle("on-display"); screen.style.backgroundImage = "none"; screenState = "open-app"; }
JavaScript
function closeApp() { if ([...cameraApp.classList].includes("on-display")) { stopStreamedVideo(camVideo); //defined in camera-app.js } if ([...player.classList].includes("on-display")) { video.pause(); //defined in video-player.js rotatePortrait(); //defined in video-player.js } apps.forEach(app => app.classList.remove("on-display")); display.classList.toggle("on-display"); screen.style.backgroundImage = `url(${cuteCat})`; screenState = "home-screen"; }
function closeApp() { if ([...cameraApp.classList].includes("on-display")) { stopStreamedVideo(camVideo); //defined in camera-app.js } if ([...player.classList].includes("on-display")) { video.pause(); //defined in video-player.js rotatePortrait(); //defined in video-player.js } apps.forEach(app => app.classList.remove("on-display")); display.classList.toggle("on-display"); screen.style.backgroundImage = `url(${cuteCat})`; screenState = "home-screen"; }
JavaScript
function generateRandomColors(num) { const arr = []; for (let x = 0; x < num; x++) { arr.push(randomColor()); }; return (arr); }
function generateRandomColors(num) { const arr = []; for (let x = 0; x < num; x++) { arr.push(randomColor()); }; return (arr); }
JavaScript
function stopStreamedVideo(videoElem) { let stream = videoElem.srcObject; let tracks = stream.getTracks(); tracks.forEach(function (track) { track.stop(); }); videoElem.srcObject = null; }
function stopStreamedVideo(videoElem) { let stream = videoElem.srcObject; let tracks = stream.getTracks(); tracks.forEach(function (track) { track.stop(); }); videoElem.srcObject = null; }
JavaScript
function paintToCanvas() { // sets dimensions of canvas based off dimensions of video const width = camVideo.videoWidth; const height = camVideo.videoHeight; camCanvas.width = width; camCanvas.height = height; setInterval(() => { //draw camVideo to camCanvas ctx.drawImage(camVideo, 0, 0, width, height); //get pixels from camCanvas (left, top, right, bottom) let pixels = ctx.getImageData(0, 0, width, height); //add effect to pixels // pixels = redEffect(pixels); //put pixels back into camCanvas ctx.putImageData(pixels, 0, 0); }, 50); }
function paintToCanvas() { // sets dimensions of canvas based off dimensions of video const width = camVideo.videoWidth; const height = camVideo.videoHeight; camCanvas.width = width; camCanvas.height = height; setInterval(() => { //draw camVideo to camCanvas ctx.drawImage(camVideo, 0, 0, width, height); //get pixels from camCanvas (left, top, right, bottom) let pixels = ctx.getImageData(0, 0, width, height); //add effect to pixels // pixels = redEffect(pixels); //put pixels back into camCanvas ctx.putImageData(pixels, 0, 0); }, 50); }
JavaScript
function takePhoto() { snap.currentTime = 0; snap.play(); const data = camCanvas.toDataURL("image/jpeg"); const link = document.createElement("a"); link.href = data; link.className = "cam-image"; link.setAttribute("download", "selfie"); link.innerHTML = `<img src="${data}" alt="selfie" />`; camPhotos.insertBefore(link, camPhotos.firstChild); }
function takePhoto() { snap.currentTime = 0; snap.play(); const data = camCanvas.toDataURL("image/jpeg"); const link = document.createElement("a"); link.href = data; link.className = "cam-image"; link.setAttribute("download", "selfie"); link.innerHTML = `<img src="${data}" alt="selfie" />`; camPhotos.insertBefore(link, camPhotos.firstChild); }
JavaScript
delStory(id) { console.log("del story"); API.deleteStory(id) .then(res => this.loadStories()) .catch(err => console.log(err)); }
delStory(id) { console.log("del story"); API.deleteStory(id) .then(res => this.loadStories()) .catch(err => console.log(err)); }
JavaScript
gdUploadStory(title, words) { console.log("Google Drive Upload clicked"); googleApi.init() .then(() => { googleApi.saveFile(title, words) .then(() => { console.log('File uploaded'); }) }) .catch(err => { console.log('error uploading to google drive ' + err); }); }
gdUploadStory(title, words) { console.log("Google Drive Upload clicked"); googleApi.init() .then(() => { googleApi.saveFile(title, words) .then(() => { console.log('File uploaded'); }) }) .catch(err => { console.log('error uploading to google drive ' + err); }); }
JavaScript
mailStory() { const msg = { to: '[email protected]', from: '[email protected]', subject: 'Sending with SendGrid is Fun', text: 'and easy to do anywhere, even with Node.js', }; API.mail(msg) .then(res => console.log(res)) .catch(err => console.log(err)); }
mailStory() { const msg = { to: '[email protected]', from: '[email protected]', subject: 'Sending with SendGrid is Fun', text: 'and easy to do anywhere, even with Node.js', }; API.mail(msg) .then(res => console.log(res)) .catch(err => console.log(err)); }