file_name
stringlengths
3
137
prefix
stringlengths
0
918k
suffix
stringlengths
0
962k
middle
stringlengths
0
812k
bundle.js
(function webpackUniversalModuleDefinition(root, factory) { if(typeof exports === 'object' && typeof module === 'object') module.exports = factory(); else if(typeof define === 'function' && define.amd) define("Debugger", [], factory); else if(typeof exports === 'object') exports["Debugger"] = factory(); else root["Debugger"] = factory(); })(typeof self !== 'undefined' ? self : this, function() { return /******/ (function(modules) { // webpackBootstrap /******/ // The module cache /******/ var installedModules = {}; /******/ /******/ // The require function /******/ function __webpack_require__(moduleId) { /******/ /******/ // Check if module is in cache /******/ if(installedModules[moduleId]) { /******/ return installedModules[moduleId].exports; /******/ } /******/ // Create a new module (and put it into the cache) /******/ var module = installedModules[moduleId] = { /******/ i: moduleId, /******/ l: false, /******/ exports: {} /******/ }; /******/ /******/ // Execute the module function /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); /******/ /******/ // Flag the module as loaded /******/ module.l = true; /******/ /******/ // Return the exports of the module /******/ return module.exports; /******/ } /******/ /******/ /******/ // expose the modules object (__webpack_modules__) /******/ __webpack_require__.m = modules; /******/ /******/ // expose the module cache /******/ __webpack_require__.c = installedModules; /******/ /******/ // define getter function for harmony exports /******/ __webpack_require__.d = function(exports, name, getter) { /******/ if(!__webpack_require__.o(exports, name)) { /******/ Object.defineProperty(exports, name, { /******/ configurable: false, /******/ enumerable: true, /******/ get: getter /******/ }); /******/ } /******/ }; /******/ /******/ // getDefaultExport function for compatibility with non-harmony modules /******/ __webpack_require__.n = function(module) { /******/ var getter = module && module.__esModule ? /******/ function getDefault() { return module['default']; } : /******/ function getModuleExports() { return module; }; /******/ __webpack_require__.d(getter, 'a', getter); /******/ return getter; /******/ }; /******/ /******/ // Object.prototype.hasOwnProperty.call /******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); }; /******/ /******/ // __webpack_public_path__ /******/ __webpack_require__.p = ""; /******/ /******/ // Load entry module and return exports /******/ return __webpack_require__(__webpack_require__.s = 37); /******/ }) /************************************************************************/ /******/ ([ /* 0 */ /***/ (function(module, exports) { module.exports = require("debug"); /***/ }), /* 1 */ /***/ (function(module, exports) { module.exports = require("babel-runtime/core-js/object/entries"); /***/ }), /* 2 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _extends2 = __webpack_require__(3); var _extends3 = _interopRequireDefault(_extends2); var _entries = __webpack_require__(1); var _entries2 = _interopRequireDefault(_entries); var _assign = __webpack_require__(4); var _assign2 = _interopRequireDefault(_assign); var _debug = __webpack_require__(0); var _debug2 = _interopRequireDefault(_debug); var _reselectTree = __webpack_require__(9); var _selectors = __webpack_require__(19); var _selectors2 = _interopRequireDefault(_selectors); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } const debug = (0, _debug2.default)("debugger:evm:selectors"); const WORD_SIZE = 0x20; /** * create EVM-level selectors for a given trace step selector * may specify additional selectors to include */ function createStepSelectors(step, state = null) { let base = { /** * .trace * * trace step info related to operation */ trace: (0, _reselectTree.createLeaf)([step], ({ gasCost, op, pc }) => ({ gasCost, op, pc })), /** * .programCounter */ programCounter: (0, _reselectTree.createLeaf)(["./trace"], step => step.pc), /** * .isJump */ isJump: (0, _reselectTree.createLeaf)(["./trace"], step => step.op != "JUMPDEST" && step.op.indexOf("JUMP") == 0), /** * .isCall * * whether the opcode will switch to another calling context */ isCall: (0, _reselectTree.createLeaf)(["./trace"], step => step.op == "CALL" || step.op == "DELEGATECALL"), /** * .isCreate */ isCreate: (0, _reselectTree.createLeaf)(["./trace"], step => step.op == "CREATE"), /** * .isHalting * * whether the instruction halts or returns from a calling context */ isHalting: (0, _reselectTree.createLeaf)(["./trace"], step => step.op == "STOP" || step.op == "RETURN") }; if (state) { const isRelative = path => typeof path == "string" && (path.startsWith("./") || path.startsWith("../")); if (isRelative(state)) { state = `../${state}`; } (0, _assign2.default)(base, { /** * .callAddress * * address transferred to by call operation */ callAddress: (0, _reselectTree.createLeaf)(["./isCall", "./trace", state], (matches, step, { stack }) => { if (!matches) return null; let address = stack[stack.length - 2]; address = "0x" + address.substring(24); return address; }), /** * .createBinary * * binary code to execute via create operation */ createBinary: (0, _reselectTree.createLeaf)(["./isCreate", "./trace", state], (matches, step, { stack, memory }) => { if (!matches) return null; // Get the code that's going to be created from memory. // Note we multiply by 2 because these offsets are in bytes. const offset = parseInt(stack[stack.length - 2], 16) * 2; const length = parseInt(stack[stack.length - 3], 16) * 2; return "0x" + memory.join("").substring(offset, offset + length); }) }); } return base; } const evm = (0, _reselectTree.createSelectorTree)({ /** * evm.state */ state: state => state.evm, /** * evm.info */ info: { /** * evm.info.contexts */ contexts: (0, _reselectTree.createLeaf)(['/state'], state => state.info.contexts.byContext), /** * evm.info.instances */ instances: (0, _reselectTree.createLeaf)(['/state'], state => state.info.instances.byAddress), /** * evm.info.binaries */ binaries: { _: (0, _reselectTree.createLeaf)(['/state'], state => state.info.contexts.byBinary), /** * evm.info.binaries.search * * returns function (binary) => context */ search: (0, _reselectTree.createLeaf)(['./_'], binaries => { // HACK ignore link references for search // link references come in two forms: with underscores or all zeroes // the underscore format is used by Truffle to reference links by name // zeroes are used by solc directly, as libraries inject their own // address at CREATE-time const toRegExp = binary => new RegExp(`^${binary.replace(/__.{38}|0{40}/g, ".{40}")}`); let matchers = (0, _entries2.default)(binaries).map(([binary, { context }]) => ({ context, regex: toRegExp(binary) })); return binary => matchers.filter(({ context, regex }) => binary.match(regex)).map(({ context }) => ({ context }))[0] || null; }) } }, /** * evm.current */ current: { /** * evm.current.callstack */ callstack: state => state.evm.proc.callstack, /** * evm.current.call */ call: (0, _reselectTree.createLeaf)(["./callstack"], stack => stack.length ? stack[stack.length - 1] : {}), /** * evm.current.context */ context: (0, _reselectTree.createLeaf)(["./call", "/info/instances", "/info/binaries/search", "/info/contexts"], ({ address, binary }, instances, search, contexts) => { let record; if (address) { record = instances[address]; binary = record.binary; } else { record = search(binary); } let context = contexts[(record || {}).context]; return (0, _extends3.default)({}, context, { binary }); }), /** * evm.current.state * * evm state info: as of last operation, before op defined in step */ state: (0, _assign2.default)({}, ...["depth", "error", "gas", "memory", "stack", "storage"].map(param => ({ [param]: (0, _reselectTree.createLeaf)([_selectors2.default.step], step => step[param]) }))), /** * evm.current.step */ step: createStepSelectors(_selectors2.default.step, "./state") }, /** * evm.next */ next: { /** * evm.next.state * * evm state as a result of next step operation */ state: (0, _assign2.default)({}, ...["depth", "error", "gas", "memory", "stack", "storage"].map(param => ({ [param]: (0, _reselectTree.createLeaf)([_selectors2.default.next], step => step[param]) }))), step: createStepSelectors(_selectors2.default.next, "./state") } }); exports.default = evm; /***/ }), /* 3 */ /***/ (function(module, exports) { module.exports = require("babel-runtime/helpers/extends"); /***/ }), /* 4 */ /***/ (function(module, exports) { module.exports = require("babel-runtime/core-js/object/assign"); /***/ }), /* 5 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.prefixName = prefixName; exports.keccak256 = keccak256; var _utils = __webpack_require__(11); function prefixName(prefix, fn) { Object.defineProperty(fn, 'name', { value: `${prefix}.${fn.name}`, configurable: true }); return fn; } /** * @return 0x-prefix string of keccak256 hash */ function keccak256(...args) { return (0, _utils.toHexString)((0, _utils.keccak256)(...args)); } /***/ }), /* 6 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _extends2 = __webpack_require__(3); var _extends3 = _interopRequireDefault(_extends2); var _entries = __webpack_require__(1); var _entries2 = _interopRequireDefault(_entries); var _assign = __webpack_require__(4); var _assign2 = _interopRequireDefault(_assign); var _debug = __webpack_require__(0); var _debug2 = _interopRequireDefault(_debug); var _reselectTree = __webpack_require__(9); var _truffleSolidityUtils = __webpack_require__(50); var _truffleSolidityUtils2 = _interopRequireDefault(_truffleSolidityUtils); var _truffleCodeUtils = __webpack_require__(51); var _truffleCodeUtils2 = _interopRequireDefault(_truffleCodeUtils); var _selectors = __webpack_require__(2); var _selectors2 = _interopRequireDefault(_selectors); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } const debug = (0, _debug2.default)("debugger:solidity:selectors"); function getSourceRange(instruction = {}) { return { start: instruction.start || 0, length: instruction.length || 0, lines: instruction.range || { start: { line: 0, column: 0 }, end: { line: 0, column: 0 } } }; } let solidity = (0, _reselectTree.createSelectorTree)({ /** * solidity.state */ state: state => state.solidity, /** * solidity.info */ info: { /** * solidity.info.sources */ sources: (0, _reselectTree.createLeaf)(['/state'], state => state.info.sources.byId), /** * solidity.info.sourceMaps */ sourceMaps: (0, _reselectTree.createLeaf)(['/state'], state => state.info.sourceMaps.byContext) }, /** * solidity.current */ current: { /** * solidity.current.sourceMap */ sourceMap: (0, _reselectTree.createLeaf)([_selectors2.default.current.context, "/info/sourceMaps"], ({ context }, sourceMaps) => sourceMaps[context] || {}), /** * solidity.current.functionDepth */ functionDepth: state => state.solidity.proc.functionDepth, /** * solidity.current.instructions */ instructions: (0, _reselectTree.createLeaf)(["/info/sources", _selectors2.default.current.context, "./sourceMap"], (sources, { binary }, { sourceMap }) => { let instructions = _truffleCodeUtils2.default.parseCode(binary); if (!sourceMap) { // Let's create a source map to use since none exists. This source map // maps just as many ranges as there are instructions, and ensures every // instruction is marked as "jumping out". This will ensure all // available debugger commands step one instruction at a time. // // This is kindof a hack; perhaps this should be broken out into separate // context types. TODO sourceMap = ""; for (var i = 0; i < instructions.length; i++) { sourceMap += i + ":" + i + ":1:-1;"; } } var lineAndColumnMappings = (0, _assign2.default)({}, ...(0, _entries2.default)(sources).map(([id, { source }]) => ({ [id]: _truffleSolidityUtils2.default.getCharacterOffsetToLineAndColumnMapping(source || "") }))); var humanReadableSourceMap = _truffleSolidityUtils2.default.getHumanReadableSourceMap(sourceMap); let primaryFile = humanReadableSourceMap[0].file; debug("primaryFile %o", primaryFile); return instructions.map((instruction, index) => { // lookup source map by index and add `index` property to // instruction // const sourceMap = humanReadableSourceMap[index] || {}; return { instruction: (0, _extends3.default)({}, instruction, { index }), sourceMap }; }).map(({ instruction, sourceMap }) => { // add source map information to instruction, or defaults // const { jump, start = 0, length = 0, file = primaryFile } = sourceMap; const lineAndColumnMapping = lineAndColumnMappings[file] || {}; const range = { start: lineAndColumnMapping[start] || { line: null, column: null }, end: lineAndColumnMapping[start + length] || { line: null, column: null } }; if (range.start.line === null) { debug("sourceMap %o", sourceMap); } return (0, _extends3.default)({}, instruction, { jump, start, length, file, range }); }); }), /** * solidity.current.instructionAtProgramCounter */ instructionAtProgramCounter: (0, _reselectTree.createLeaf)(["./instructions"], instructions => { let map = []; instructions.forEach(function (instruction) { map[instruction.pc] = instruction; }); // fill in gaps in map by defaulting to the last known instruction let lastSeen = null; for (let [pc, instruction] of map.entries()) { if (instruction) { lastSeen = instruction; } else { map[pc] = lastSeen; } } return map; }), /** * solidity.current.instruction */ instruction: (0, _reselectTree.createLeaf)(["./instructionAtProgramCounter", _selectors2.default.current.step.programCounter], (map, pc) => map[pc] || {}), /** * solidity.current.source */ source: (0, _reselectTree.createLeaf)(["/info/sources", "./instruction"], (sources, { file: id }) => sources[id] || {}), /** * solidity.current.sourceRange */ sourceRange: (0, _reselectTree.createLeaf)(["./instruction"], getSourceRange), /** * solidity.current.isSourceRangeFinal */ isSourceRangeFinal: (0, _reselectTree.createLeaf)(["./instructionAtProgramCounter", _selectors2.default.current.step.programCounter, _selectors2.default.next.step.programCounter], (map, current, next) => { if (!map[next]) { return true; } current = map[current]; next = map[next]; return current.start != next.start || current.length != next.length || current.file != next.file; }), /** * solidity.current.isMultiline */ isMultiline: (0, _reselectTree.createLeaf)(["./sourceRange"], ({ lines }) => lines.start.line != lines.end.line), /** * solidity.current.willJump */ willJump: (0, _reselectTree.createLeaf)([_selectors2.default.current.step.isJump], isJump => isJump), /** * solidity.current.jumpDirection */ jumpDirection: (0, _reselectTree.createLeaf)(["./instruction"], (i = {}) => i.jump || "-") } }); exports.default = solidity; /***/ }), /* 7 */ /***/ (function(module, exports) { module.exports = require("babel-runtime/helpers/asyncToGenerator"); /***/ }), /* 8 */ /***/ (function(module, exports) { module.exports = require("web3"); /***/ }), /* 9 */ /***/ (function(module, exports) { module.exports = require("reselect-tree"); /***/ }), /* 10 */ /***/ (function(module, exports) { module.exports = require("redux-saga/effects"); /***/ }), /* 11 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.MAX_WORD = exports.WORD_SIZE = undefined; var _entries = __webpack_require__(1); var _entries2 = _interopRequireDefault(_entries); var _assign = __webpack_require__(4); var _assign2 = _interopRequireDefault(_assign); exports.cleanBigNumbers = cleanBigNumbers; exports.typeIdentifier = typeIdentifier; exports.typeClass = typeClass; exports.allocateDeclarations = allocateDeclarations; exports.specifiedSize = specifiedSize; exports.storageSize = storageSize; exports.isMapping = isMapping; exports.isReference = isReference; exports.referenceType = referenceType; exports.baseDefinition = baseDefinition; exports.toBigNumber = toBigNumber; exports.toSignedBigNumber = toSignedBigNumber; exports.toHexString = toHexString; exports.toBytes = toBytes; exports.keccak256 = keccak256; var _debug = __webpack_require__(0); var _debug2 = _interopRequireDefault(_debug); var _bignumber = __webpack_require__(20); var _web = __webpack_require__(8); var _web2 = _interopRequireDefault(_web); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } const debug = (0, _debug2.default)("debugger:data:decode:utils"); const WORD_SIZE = exports.WORD_SIZE = 0x20; const MAX_WORD = exports.MAX_WORD = new _bignumber.BigNumber(2).pow(256).minus(1); /** * recursively converts big numbers into something nicer to look at */ function cleanBigNumbers(value) { if (_bignumber.BigNumber.isBigNumber(value)) { return value.toNumber(); } else if (value && value.map != undefined) { return value.map(inner => cleanBigNumbers(inner)); } else if (value && typeof value == "object") { return (0, _assign2.default)({}, ...(0, _entries2.default)(value).map(([key, inner]) => ({ [key]: cleanBigNumbers(inner) }))); } else { return value; } } function typeIdentifier(definition) { return definition.typeDescriptions.typeIdentifier; } /** * returns basic type class for a variable definition node * e.g.: * `t_uint256` becomes `uint` * `t_struct$_Thing_$20_memory_ptr` becomes `struct` */ function typeClass(definition) { return typeIdentifier(definition).match(/t_([^$_0-9]+)/)[1]; } /** * Allocate storage for given variable declarations * * Postcondition: starts a new slot and occupies whole slots */ function allocateDeclarations(declarations, refs, slot = 0, index = WORD_SIZE - 1, path = []) { if (index < WORD_SIZE - 1) { // starts a new slot slot++; index = WORD_SIZE - 1; } let parentFrom = { slot, index: 0 }; var parentTo = { slot, index: WORD_SIZE - 1 }; let mapping = {}; for (let declaration of declarations) { let { from, to, next, children } = allocateDeclaration(declaration, refs, slot, index); mapping[declaration.id] = { from, to, name: declaration.name }; if (children !== undefined) { mapping[declaration.id].children = children; } slot = next.slot; index = next.index; parentTo = { slot: to.slot, index: WORD_SIZE - 1 }; } if (index < WORD_SIZE - 1) { slot++; index = WORD_SIZE - 1; } return { from: parentFrom, to: parentTo, next: { slot, index }, children: mapping }; } function allocateValue(slot, index, bytes) { let from = index - bytes + 1 >= 0 ? { slot, index: index - bytes + 1 } : { slot: slot + 1, index: WORD_SIZE - bytes }; let to = { slot: from.slot, index: from.index + bytes - 1 }; let next = from.index == 0 ? { slot: from.slot + 1, index: WORD_SIZE - 1 } : { slot: from.slot, index: from.index - 1 }; return { from, to, next }; } function allocateDeclaration(declaration, refs, slot, index) { let definition = refs[declaration.id].definition; var byteSize = storageSize(definition); // yum if (typeClass(definition) == "struct") { let struct = refs[definition.typeName.referencedDeclaration]; debug("struct: %O", struct); let result = allocateDeclarations(struct.variables || [], refs, slot, index); debug("struct result %o", result); return result; } if (typeClass(definition) == "mapping") {} return allocateValue(slot, index, byteSize); } /** * e.g. uint48 -> 6 * @return size in bytes for explicit type size, or `null` if not stated */ function specifiedSize(definition) { let specified = typeIdentifier(definition).match(/t_[a-z]+([0-9]+)/); if (!specified) { return null; } let num = specified[1]; switch (typeClass(definition)) { case "int": case "uint": return num / 8; case "bytes": return num; default: debug("Unknown type for size specification: %s", typeIdentifier(definition)); } } function storageSize(definition) { switch (typeClass(definition)) { case "bool": return 1; case "address": return 20; case "int": case "uint": // is this a HACK? ("256" / 8) return typeIdentifier(definition).match(/t_[a-z]+([0-9]+)/)[1] / 8; case "string": case "bytes": case "array": return WORD_SIZE; case "mapping": // HACK just to reserve slot. mappings have no size as such return WORD_SIZE; } } function isMapping(definition) { return typeIdentifier(definition).match(/^t_mapping/) != null; } function isReference(definition) { return typeIdentifier(definition).match(/_(memory|storage)(_ptr)?$/) != null; } function referenceType(definition) { return typeIdentifier(definition).match(/_([^_]+)(_ptr)?$/)[1]; } function baseDefinition(definition) { let baseIdentifier = typeIdentifier(definition) // first dollar sign last dollar sign // `---------. ,---' .match(/^[^$]+\$_(.+)_\$[^$]+$/)[1]; // `----' greedy match // HACK - internal types for memory or storage also seem to be pointers if (baseIdentifier.match(/_(memory|storage)$/) != null) { baseIdentifier = `${baseIdentifier}_ptr`; } // another HACK - we get away with it becausewe're only using that one property return { typeDescriptions: { typeIdentifier: baseIdentifier } }; } function toBigNumber(bytes) { if (bytes == undefined) { return undefined; } else if (typeof bytes == "string") { return new _bignumber.BigNumber(bytes, 16); } else if (typeof bytes == "number" || _bignumber.BigNumber.isBigNumber(bytes)) { return new _bignumber.BigNumber(bytes); } else if (bytes.reduce) { return bytes.reduce((num, byte) => num.times(0x100).plus(byte), new _bignumber.BigNumber(0)); } } function toSignedBigNumber(bytes) { if (bytes[0] < 0b10000000) { // first bit is 0 return toBigNumber(bytes); } else { return toBigNumber(bytes.map(b => 0xff - b)).plus(1).negated(); } } /** * @param bytes - Uint8Array * @param length - desired byte length (pad with zeroes) * @param trim - omit leading zeroes */ function toHexString(bytes, length = 0, trim = false) { if (typeof length == "boolean") { trim = length; length = 0; } if (_bignumber.BigNumber.isBigNumber(bytes)) { bytes = toBytes(bytes); } const pad = s => `${"00".slice(0, 2 - s.length)}${s}`; // 0 1 2 3 4 // 0 1 2 3 4 5 6 7 // bytes.length: 5 - 0x( e5 c2 aa 09 11 ) // length (preferred): 8 - 0x( 00 00 00 e5 c2 aa 09 11 ) // `--.---' // offset 3 if (bytes.length < length) { let prior = bytes; bytes = new Uint8Array(length); bytes.set(prior, length - prior.length); } debug("bytes: %o", bytes); let string = bytes.reduce((str, byte) => `${str}${pad(byte.toString(16))}`, ""); if (trim) { string = string.replace(/^(00)+/, ""); } if (string.length == 0) { string = "00"; } return `0x${string}`; } function toBytes(number, length = 0) { if (number < 0) { return []; } let hex = number.toString(16); if (hex.length % 2 == 1) { hex = `0${hex}`; } let bytes = new Uint8Array(hex.match(/.{2}/g).map(byte => parseInt(byte, 16))); if (bytes.length < length) { let prior = bytes; bytes = new Uint8Array(length); bytes.set(prior, length - prior.length); } return bytes; } function keccak256(...args) { let web3 = new _web2.default(); debug("args %o", args); // args = args.map( (arg) => { // if (typeof arg == "number" || BigNumber.isBigNumber(arg)) { // return toHexString(toBytes(arg, WORD_SIZE)).slice(2) // } else if (typeof arg == "string") { // return web3.utils.toHex(arg).slice(2); // } else { // return ""; // } // }); // debug("processed args %o", args); let sha = web3.utils.soliditySha3(...args); debug("sha %o", sha); return toBigNumber(sha); } /***/ }), /* 12 */ /***/ (function(module, exports) { module.exports = require("chai"); /***/ }), /* 13 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.gatherArtifacts = exports.migrate = exports.compile = exports.defaultMigrations = exports.addMigrations = exports.addContracts = exports.createSandbox = exports.prepareContracts = undefined; var _promise = __webpack_require__(23); var _promise2 = _interopRequireDefault(_promise); var _keys = __webpack_require__(17); var _keys2 = _interopRequireDefault(_keys); var _asyncToGenerator2 = __webpack_require__(7); var _asyncToGenerator3 = _interopRequireDefault(_asyncToGenerator2); let prepareContracts = exports.prepareContracts = (() => { var _ref = (0, _asyncToGenerator3.default)(function* (provider, sources = {}, migrations) { let config = yield createSandbox(); let accounts = yield getAccounts(provider); config.networks["debugger"] = { provider: provider, network_id: "*", from: accounts[0] }; config.network = "debugger"; yield addContracts(config, sources); let { contracts, files } = yield compile(config); let contractNames = (0, _keys2.default)(contracts); if (!migrations) { migrations = yield defaultMigrations(contractNames); } yield addMigrations(config, migrations); yield migrate(config); let artifacts = yield gatherArtifacts(config); debug("artifacts: %o", artifacts.map(function (a) { return a.contractName; })); let abstractions = {}; contractNames.forEach(function (name) { abstractions[name] = config.resolver.require(name); }); return { files, abstractions, artifacts, config }; }); return function prepareContracts(_x) { return _ref.apply(this, arguments); }; })(); let createSandbox = exports.createSandbox = (() => { var _ref2 = (0, _asyncToGenerator3.default)(function* () { let config = yield new _promise2.default(function (accept, reject) { _truffleBox2.default.sandbox(function (err, result) { if (err) return reject(err); result.resolver = new _truffleResolver2.default(result); result.artifactor = new _truffleArtifactor2.default(result.contracts_build_directory); result.networks = {}; accept(result); }); }); yield _fsExtra2.default.remove(_path2.default.join(config.contracts_directory, "MetaCoin.sol")); yield _fsExtra2.default.remove(_path2.default.join(config.contracts_directory, "ConvertLib.sol")); yield _fsExtra2.default.remove(_path2.default.join(config.migrations_directory, "2_deploy_contracts.js")); return config; }); return function createSandbox() { return _ref2.apply(this, arguments); }; })(); let addContracts = exports.addContracts = (() => { var _ref3 = (0, _asyncToGenerator3.default)(function* (config, sources = {}) { let promises = []; for (let filename of (0, _keys2.default)(sources)) { let source = sources[filename]; promises.push(_fsExtra2.default.outputFile(_path2.default.join(config.contracts_directory, filename), source)); } return yield _promise2.default.all(promises); }); return function addContracts(_x2) { return _ref3.apply(this, arguments); }; })(); let addMigrations = exports.addMigrations = (() => { var _ref4 = (0, _asyncToGenerator3.default)(function* (config, migrations = {}) { let promises = []; for (let filename of (0, _keys2.default)(migrations)) { let source = migrations[filename]; promises.push(_fsExtra2.default.outputFile(_path2.default.join(config.migrations_directory, filename), source)); } return yield _promise2.default.all(promises); }); return function addMigrations(_x3) { return _ref4.apply(this, arguments); }; })(); let defaultMigrations = exports.defaultMigrations = (() => { var _ref5 = (0, _asyncToGenerator3.default)(function* (contractNames) { contractNames = contractNames.filter(function (name) { return name != "Migrations"; }); let migrations = {}; contractNames.forEach(function (contractName, i) { let index = i + 2; // start at 2 cause Migrations migration let filename = `${index}_migrate_${contractName}.js`; let source = ` var ${contractName} = artifacts.require("${contractName}"); module.exports = function(deployer) { deployer.deploy(${contractName}); }; `; migrations[filename] = source; }); return migrations; }); return function defaultMigrations(_x4) { return _ref5.apply(this, arguments); }; })(); let compile = exports.compile = (() => { var _ref6 = (0, _asyncToGenerator3.default)(function* (config) { return new _promise2.default(function (accept, reject) { _truffleWorkflowCompile2.default.compile(config.with({ all: true, quiet: true }), function (err, contracts, files) { if (err) return reject(err); return accept({ contracts, files }); }); }); }); return function compile(_x5) { return _ref6.apply(this, arguments); }; })(); let migrate = exports.migrate = (() => { var _ref7 = (0, _asyncToGenerator3.default)(function* (config) { return new _promise2.default(function (accept, reject) { _truffleMigrate2.default.run(config.with({ quiet: true }), function (err, contracts) { if (err) return reject(err); accept(contracts); }); }); }); return function migrate(_x6) { return _ref7.apply(this, arguments); }; })(); let gatherArtifacts = exports.gatherArtifacts = (() => { var _ref8 = (0, _asyncToGenerator3.default)(function* (config) { return _truffleDebugUtils2.default.gatherArtifacts(config); }); return function gatherArtifacts(_x7) { return _ref8.apply(this, arguments); }; })(); exports.getAccounts = getAccounts; var _debug = __webpack_require__(0); var _debug2 = _interopRequireDefault(_debug); var _path = __webpack_require__(39); var _path2 = _interopRequireDefault(_path); var _fsExtra = __webpack_require__(40); var _fsExtra2 = _interopRequireDefault(_fsExtra); var _async = __webpack_require__(41); var _async2 = _interopRequireDefault(_async); var _truffleWorkflowCompile = __webpack_require__(42); var _truffleWorkflowCompile2 = _interopRequireDefault(_truffleWorkflowCompile); var _truffleDebugUtils = __webpack_require__(43); var _truffleDebugUtils2 = _interopRequireDefault(_truffleDebugUtils); var _truffleArtifactor = __webpack_require__(44); var _truffleArtifactor2 = _interopRequireDefault(_truffleArtifactor); var _web = __webpack_require__(8); var _web2 = _interopRequireDefault(_web); var _truffleMigrate = __webpack_require__(45); var _truffleMigrate2 = _interopRequireDefault(_truffleMigrate); var _truffleBox = __webpack_require__(46); var _truffleBox2 = _interopRequireDefault(_truffleBox); var _truffleResolver = __webpack_require__(47); var _truffleResolver2 = _interopRequireDefault(_truffleResolver); var _truffleExpect = __webpack_require__(27); var _truffleExpect2 = _interopRequireDefault(_truffleExpect); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } const debug = (0, _debug2.default)("test:helpers"); function getAccounts(provider) { let web3 = new _web2.default(provider); return new _promise2.default(function (accept, reject) { web3.eth.getAccounts(function (err, accounts) { if (err) return reject(err); accept(accounts); }); }); } /***/ }), /* 14 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _debug = __webpack_require__(0); var _debug2 = _interopRequireDefault(_debug); var _reselectTree = __webpack_require__(9); var _jsonPointer = __webpack_require__(24); var _jsonPointer2 = _interopRequireDefault(_jsonPointer); var _selectors = __webpack_require__(6); var _selectors2 = _interopRequireDefault(_selectors); var _map = __webpack_require__(28); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } const debug = (0, _debug2.default)("debugger:ast:selectors"); /** * ast */ const ast = (0, _reselectTree.createSelectorTree)({ /** * ast.views */ views: { /** * ast.views.sources */ sources: (0, _reselectTree.createLeaf)([_selectors2.default.info.sources], sources => sources) }, /** * ast.current */ current: { /** * ast.current.tree * * ast for current source */ tree: (0, _reselectTree.createLeaf)([_selectors2.default.current.source], ({ ast }) => ast), /** * ast.current.index * * source ID */ index: (0, _reselectTree.createLeaf)([_selectors2.default.current.source], ({ id }) => id), /** * ast.current.pointer * * jsonpointer for current ast node */ pointer: (0, _reselectTree.createLeaf)(["./tree", _selectors2.default.current.sourceRange], (ast, range) => (0, _map.findRange)(ast, range.start, range.length)), /** * ast.current.node * * current ast node to execute */ node: (0, _reselectTree.createLeaf)(["./tree", "./pointer"], (ast, pointer) => pointer ? _jsonPointer2.default.get(ast, pointer) : _jsonPointer2.default.get(ast, "")) } }); exports.default = ast; /***/ }), /* 15 */ /***/ (function(module, exports) { module.exports = require("redux"); /***/ }), /* 16 */ /***/ (function(module, exports) { module.exports = require("ganache-cli"); /***/ }), /* 17 */ /***/ (function(module, exports) { module.exports = require("babel-runtime/core-js/object/keys"); /***/ }), /* 18 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _asyncToGenerator2 = __webpack_require__(7); var _asyncToGenerator3 = _interopRequireDefault(_asyncToGenerator2); var _debug = __webpack_require__(0); var _debug2 = _interopRequireDefault(_debug); var _truffleExpect = __webpack_require__(27); var _truffleExpect2 = _interopRequireDefault(_truffleExpect); var _session = __webpack_require__(48); var _session2 = _interopRequireDefault(_session); var _reselectTree = __webpack_require__(9); var _selectors = __webpack_require__(26); var _selectors2 = _interopRequireDefault(_selectors); var _selectors3 = __webpack_require__(14); var _selectors4 = _interopRequireDefault(_selectors3); var _selectors5 = __webpack_require__(19); var _selectors6 = _interopRequireDefault(_selectors5); var _selectors7 = __webpack_require__(2); var _selectors8 = _interopRequireDefault(_selectors7); var _selectors9 = __webpack_require__(6); var _selectors10 = _interopRequireDefault(_selectors9); var _selectors11 = __webpack_require__(35); var _selectors12 = _interopRequireDefault(_selectors11); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } const debug = (0, _debug2.default)("debugger"); /** * @example * let session = Debugger * .forTx(<txHash>, { * contracts: [<contract obj>, ...], * provider: <provider instance> * }) * .connect(); */ class Debugger { /** * @param {Session} session - debugger session * @private */ constructor(session) { /** * @private */ this._session = session; } /** * Instantiates a Debugger for a given transaction hash. * * @param {String} txHash - transaction hash with leading "0x" * @param {{contracts: Array<Contract>, files: Array<String>, provider: Web3Provider}} options - * @return {Debugger} instance */ static forTx(txHash, options = {}) { var _this = this; return (0, _asyncToGenerator3.default)(function* () { _truffleExpect2.default.options(options, ["contracts", "provider"]); let session = new _session2.default(options.contracts, options.files, txHash, options.provider); try { yield session.ready(); } catch (e) { throw e; } return new _this(session); })(); } /** * Connects to the instantiated Debugger. * * @return {Session} session instance */ connect() { return this._session; } /** * Exported selectors * * See individual selector docs for full listing * * @example * Debugger.selectors.ast.current.tree * * @example * Debugger.selectors.solidity.current.instruction * * @example * Debugger.selectors.trace.steps */ static get selectors() { return (0, _reselectTree.createNestedSelector)({ ast: _selectors4.default, data: _selectors2.default, trace: _selectors6.default, evm: _selectors8.default, solidity: _selectors10.default, session: _selectors12.default }); } } exports.default = Debugger; /** * @typedef {Object} Contract * @property {string} contractName contract name * @property {string} source solidity source code * @property {string} sourcePath path to source file * @property {string} binary 0x-prefixed hex string with create bytecode * @property {string} sourceMap solidity source map for create bytecode * @property {Object} ast Abstract Syntax Tree from Solidity * @property {string} deployedBinary 0x-prefixed compiled binary (on chain) * @property {string} deployedSourceMap solidity source map for on-chain bytecode */ /***/ }), /* 19 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _reselectTree = __webpack_require__(9); let trace = (0, _reselectTree.createSelectorTree)({ /** * trace.index * * current step index */ index: state => state.trace.proc.index, /** * trace.steps * * all trace steps */ steps: state => state.trace.info.steps, /** * trace.stepsRemaining * * number of steps remaining in trace */ stepsRemaining: (0, _reselectTree.createLeaf)(["./steps", "./index"], (steps, index) => steps.length - index), /** * trace.step * * current trace step */ step: (0, _reselectTree.createLeaf)(["./steps", "./index"], (steps, index) => steps[index]), /** * trace.next * * next trace step or {} */ next: (0, _reselectTree.createLeaf)(["./steps", "./index"], (steps, index) => index < steps.length - 1 ? steps[index + 1] : {}) }); exports.default = trace; /***/ }), /* 20 */ /***/ (function(module, exports) { module.exports = require("bignumber.js"); /***/ }), /* 21 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.saveSteps = saveSteps; exports.receiveAddresses = receiveAddresses; exports.next = next; exports.tick = tick; exports.tock = tock; exports.endTrace = endTrace; const SAVE_STEPS = exports.SAVE_STEPS = "SAVE_STEPS"; function saveSteps(steps) { return { type: SAVE_STEPS, steps }; } const RECEIVE_ADDRESSES = exports.RECEIVE_ADDRESSES = "RECEIVE_ADDRESSES"; function receiveAddresses(addresses) { return { type: RECEIVE_ADDRESSES, addresses }; } const NEXT = exports.NEXT = "NEXT"; function next() { return { type: NEXT }; } const TICK = exports.TICK = "TICK"; function tick() { return { type: TICK }; } const TOCK = exports.TOCK = "TOCK"; function tock() { return { type: TOCK }; } const END_OF_TRACE = exports.END_OF_TRACE = "EOT"; function endTrace() { return { type: END_OF_TRACE }; } /***/ }), /* 22 */ /***/ (function(module, exports) { module.exports = require("babel-runtime/core-js/set"); /***/ }), /* 23 */ /***/ (function(module, exports) { module.exports = require("babel-runtime/core-js/promise"); /***/ }), /* 24 */ /***/ (function(module, exports) { module.exports = require("json-pointer"); /***/ }), /* 25 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.start = start; exports.ready = ready; exports.error = error; exports.finish = finish; exports.recordContracts = recordContracts; const START = exports.START = "SESSION_START"; function start(txHash, provider) { return { type: START, txHash, provider }; } const READY = exports.READY = "SESSION_READY"; function ready() { return { type: READY }; } const ERROR = exports.ERROR = "SESSION_ERROR"; function error(error) { return { type: ERROR, error }; } const FINISH = exports.FINISH = "SESSION_FINISH"; function finish() { return { type: FINISH }; } const RECORD_CONTRACTS = exports.RECORD_CONTRACTS = "RECORD_CONTRACTS"; function recordContracts(contexts, sources) { return { type: RECORD_CONTRACTS, contexts, sources }; } /***/ }), /* 26 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _extends2 = __webpack_require__(3); var _extends3 = _interopRequireDefault(_extends2); var _entries = __webpack_require__(1); var _entries2 = _interopRequireDefault(_entries); var _assign = __webpack_require__(4); var _assign2 = _interopRequireDefault(_assign); var _debug = __webpack_require__(0); var _debug2 = _interopRequireDefault(_debug); var _reselectTree = __webpack_require__(9); var _jsonPointer = __webpack_require__(24); var _jsonPointer2 = _interopRequireDefault(_jsonPointer); var _selectors = __webpack_require__(14); var _selectors2 = _interopRequireDefault(_selectors); var _selectors3 = __webpack_require__(2); var _selectors4 = _interopRequireDefault(_selectors3); var _selectors5 = __webpack_require__(6); var _selectors6 = _interopRequireDefault(_selectors5); var _decode = __webpack_require__(61); var _decode2 = _interopRequireDefault(_decode); var _utils = __webpack_require__(11); var decodeUtils = _interopRequireWildcard(_utils); var _bignumber = __webpack_require__(20); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {};if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } }newObj.default = obj;return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } const debug = (0, _debug2.default)("debugger:data:selectors"); function createStateSelectors({ stack, memory, storage }) { return { /** * .stack */ stack: (0, _reselectTree.createLeaf)([stack], words => (words || []).map(word => decodeUtils.toBytes(decodeUtils.toBigNumber(word, decodeUtils.WORD_SIZE)))), /** * .memory */ memory: (0, _reselectTree.createLeaf)([memory], words => new Uint8Array((words.join("").match(/.{1,2}/g) || []).map(byte => parseInt(byte, 16)))), /** * .storage */ storage: (0, _reselectTree.createLeaf)([storage], mapping => (0, _assign2.default)({}, ...(0, _entries2.default)(mapping).map(([address, word]) => ({ [`0x${address}`]: new Uint8Array((word.match(/.{1,2}/g) || []).map(byte => parseInt(byte, 16))) })))) }; } const data = (0, _reselectTree.createSelectorTree)({ state: state => state.data, /** * data.views */ views: { ast: (0, _reselectTree.createLeaf)([_selectors2.default.current], tree => tree), atLastInstructionForSourceRange: (0, _reselectTree.createLeaf)([_selectors6.default.current.isSourceRangeFinal], final => final), /** * data.views.scopes */ scopes: { /** * data.views.scopes.inlined */ inlined: (0, _reselectTree.createLeaf)(["/info/scopes", _selectors6.default.info.sources], (scopes, sources) => (0, _assign2.default)({}, ...(0, _entries2.default)(scopes).map(([id, entry]) => ({ [id]: (0, _extends3.default)({}, entry, { definition: _jsonPointer2.default.get(sources[entry.sourceId].ast, entry.pointer) }) })))) }, /** * data.views.decoder * * selector returns (ast node definition, data reference) => value */ decoder: (0, _reselectTree.createLeaf)(["/views/scopes/inlined", "/next/state"], (scopes, state) => { return (definition, ref) => (0, _decode2.default)(definition, ref, state, scopes); }) }, /** * data.info */ info: { /** * data.info.scopes */ scopes: (0, _reselectTree.createLeaf)(["/state"], state => state.info.scopes.byId) }, /** * data.proc */ proc: { /** * data.proc.assignments */ assignments: (0, _reselectTree.createLeaf)(["/state"], state => state.proc.assignments.byId) }, /** * data.current */ current: { /** * * data.current.scope */ scope: { /** * data.current.scope.id */ id: (0, _reselectTree.createLeaf)([_selectors2.default.current.node], node => node.id) }, /** * data.current.state */ state: createStateSelectors(_selectors4.default.current.state), /** * data.current.identifiers (namespace) */ identifiers: { /** * data.current.identifiers (selector) * * returns identifers and corresponding definition node ID */ _: (0, _reselectTree.createLeaf)(["/views/scopes/inlined", "/current/scope"], (scopes, scope) => { let cur = scope.id; let variables = {}; do { variables = (0, _assign2.default)(variables, ...(scopes[cur].variables || []).filter(v => variables[v.name] == undefined).map(v => ({ [v.name]: v.id }))); cur = scopes[cur].parentId; } while (cur != null); return variables; }), /** * data.current.identifiers.definitions * * current variable definitions */ definitions: (0, _reselectTree.createLeaf)(["/views/scopes/inlined", "./_"], (scopes, identifiers) => (0, _assign2.default)({}, ...(0, _entries2.default)(identifiers).map(([identifier, id]) => { let { definition } = scopes[id]; return { [identifier]: definition }; }))), /** * data.current.identifiers.refs * * current variables' value refs */ refs: (0, _reselectTree.createLeaf)(["/proc/assignments", "./_"], (assignments, identifiers) => (0, _assign2.default)({}, ...(0, _entries2.default)(identifiers).map(([identifier, id]) => { let { ref } = assignments[id] || {}; if (!ref) { return undefined; }; return { [identifier]: ref }; }))), decoded: (0, _reselectTree.createLeaf)(["/views/decoder", "./definitions", "./refs"], (decode, definitions, refs) => (0, _assign2.default)({}, ...(0, _entries2.default)(refs).map(([identifier, ref]) => ({ [identifier]: decode(definitions[identifier], ref) })))), native: (0, _reselectTree.createLeaf)(['./decoded'], decodeUtils.cleanBigNumbers) } }, /** * data.next */ next: { /** * data.next.state */ state: createStateSelectors(_selectors4.default.next.state) } }); exports.default = data; /***/ }), /* 27 */ /***/ (function(module, exports) { module.exports = require("truffle-expect"); /***/ }), /* 28 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _keys = __webpack_require__(17); var _keys2 = _interopRequireDefault(_keys); exports.getRange = getRange; exports.rangeNodes = rangeNodes; exports.findRange = findRange; var _debug = __webpack_require__(0); var _debug2 = _interopRequireDefault(_debug); var _nodeIntervalTree = __webpack_require__(52); var _nodeIntervalTree2 = _interopRequireDefault(_nodeIntervalTree); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } const debug = (0, _debug2.default)("debugger:ast:map"); /** * @private */ function getRange(node) { // src: "<start>:<length>:<_>" // returns [start, end] let [start, length] = node.src.split(":").slice(0, 2).map(i => parseInt(i)); return [start, start + length]; } /** * @private */ function rangeNodes(node, pointer = "") { if (node instanceof Array) { return [].concat(...node.map((sub, i) => rangeNodes(sub, `${pointer}/${i}`))); } else if (node instanceof Object) { let results = []; if (node.src) { results.push({ pointer, range: getRange(node) }); } return results.concat(...(0, _keys2.default)(node).map(key => rangeNodes(node[key], `${pointer}/${key}`))); } else { return []; } } /** * @private */ function findRange(node, sourceStart, sourceLength) { let ranges = rangeNodes(node); let tree = new _nodeIntervalTree2.default(); ranges.forEach(({ range, pointer }) => { let [start, end] = range; tree.insert(start, end, { range, pointer }); }); let sourceEnd = sourceStart + sourceLength; let overlapping = tree.search(sourceStart, sourceEnd); // find nodes that fully contain requested range, // return longest pointer return overlapping.filter(({ range }) => sourceStart >= range[0] && sourceEnd <= range[1]).map(({ pointer }) => pointer).reduce((a, b) => a.length > b.length ? a : b, ""); } /***/ }), /* 29 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.beginStep = beginStep; exports.advance = advance; exports.stepNext = stepNext; exports.stepOver = stepOver; exports.stepInto = stepInto; exports.stepOut = stepOut; exports.interrupt = interrupt; exports.continueUntil = continueUntil; const BEGIN_STEP = exports.BEGIN_STEP = "BEGIN_STEP"; function beginStep(type) { return { type: BEGIN_STEP, stepType: type }; } const ADVANCE = exports.ADVANCE = "ADVANCE"; function advance() { return { type: ADVANCE }; } const STEP_NEXT = exports.STEP_NEXT = "STEP_NEXT"; function stepNext() { return { type: STEP_NEXT }; } const STEP_OVER = exports.STEP_OVER = "STEP_OVER"; function stepOver() { return { type: STEP_OVER }; } const STEP_INTO = exports.STEP_INTO = "STEP_INTO"; function stepInto() { return { type: STEP_INTO }; } const STEP_OUT = exports.STEP_OUT = "STEP_OUT"; function stepOut() { return { type: STEP_OUT }; } const INTERRUPT = exports.INTERRUPT = "INTERRUPT"; function interrupt() { return { type: INTERRUPT }; } const CONTINUE_UNTIL = exports.CONTINUE_UNTIL = "CONTINUE_UNTIL"; function continueUntil(...breakpoints) { return { type: CONTINUE_UNTIL, breakpoints }; } /***/ }), /* 30 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _set = __webpack_require__(22); var _set2 = _interopRequireDefault(_set); var _extends2 = __webpack_require__(3); var _extends3 = _interopRequireDefault(_extends2); var _entries = __webpack_require__(1); var _entries2 = _interopRequireDefault(_entries); var _assign = __webpack_require__(4); var _assign2 = _interopRequireDefault(_assign); exports.scope = scope; exports.declare = declare; exports.saga = saga; var _debug = __webpack_require__(0); var _debug2 = _interopRequireDefault(_debug); var _effects = __webpack_require__(10); var _jsonPointer = __webpack_require__(24); var _jsonPointer2 = _interopRequireDefault(_jsonPointer); var _helpers = __webpack_require__(5); var _actions = __webpack_require__(21); var _actions2 = __webpack_require__(31); var actions = _interopRequireWildcard(_actions2); var _selectors = __webpack_require__(26); var _selectors2 = _interopRequireDefault(_selectors); var _utils = __webpack_require__(11); var utils = _interopRequireWildcard(_utils); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {};if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } }newObj.default = obj;return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } const debug = (0, _debug2.default)("debugger:data:sagas"); function* scope(nodeId, pointer, parentId, sourceId) { yield (0, _effects.put)(actions.scope(nodeId, pointer, parentId, sourceId)); } function* declare(node) { yield (0, _effects.put)(actions.declare(node)); } function* tickSaga() { let { tree, id: treeId, node, pointer } = yield (0, _effects.select)(_selectors2.default.views.ast); let decode = yield (0, _effects.select)(_selectors2.default.views.decoder); let scopes = yield (0, _effects.select)(_selectors2.default.info.scopes); let definitions = yield (0, _effects.select)(_selectors2.default.views.scopes.inlined); let currentAssignments = yield (0, _effects.select)(_selectors2.default.proc.assignments); let stack = yield (0, _effects.select)(_selectors2.default.next.state.stack); if (!stack) { return; } let top = stack.length - 1; var parameters, returnParameters, assignments, storageVars; if (!node) { return; } // stack is only ready for interpretation after the last step of each // source range // // the data module always looks at the result of a particular opcode // (i.e., the following trace step's stack/memory/storage), so this // asserts that the _current_ operation is the final one before // proceeding if (!(yield (0, _effects.select)(_selectors2.default.views.atLastInstructionForSourceRange))) { return; } switch (node.nodeType) { case "FunctionDefinition": parameters = node.parameters.parameters.map((p, i) => `${pointer}/parameters/parameters/${i}`); returnParameters = node.returnParameters.parameters.map((p, i) => `${pointer}/returnParameters/parameters/${i}`); assignments = returnParameters.concat(parameters).reverse().map(pointer => _jsonPointer2.default.get(tree, pointer).id).map((id, i) => ({ [id]: { "stack": top - i } })).reduce((acc, assignment) => (0, _assign2.default)(acc, assignment), {}); yield (0, _effects.put)(actions.assign(treeId, assignments)); break; case "ContractDefinition": let storageVars = scopes[node.id].variables || []; let slot = 0; let index = _utils.WORD_SIZE - 1; // cause lower-order debug("storage vars %o", storageVars); let allocation = utils.allocateDeclarations(storageVars, definitions); assignments = (0, _assign2.default)({}, ...(0, _entries2.default)(allocation.children).map(([id, storage]) => ({ [id]: (0, _extends3.default)({}, (currentAssignments[id] || { ref: {} }).ref, { storage }) }))); debug("assignments %O", assignments); yield (0, _effects.put)(actions.assign(treeId, assignments)); break; case "VariableDeclaration": yield (0, _effects.put)(actions.assign(treeId, { [_jsonPointer2.default.get(tree, pointer).id]: { "stack": top } })); break; case "IndexAccess": // to track `mapping` types known indexes let { baseExpression: { id: baseId, referencedDeclaration: baseDeclarationId }, indexExpression: { id: indexId } } = node; let baseAssignment = (currentAssignments[baseDeclarationId] || { ref: {} }).ref; debug("baseAssignment %O", baseAssignment); let baseDefinition = definitions[baseDeclarationId].definition; if (utils.typeClass(baseDefinition) !== "mapping") { break; } const indexAssignment = (currentAssignments[indexId] || {}).ref; const indexValue = indexAssignment ? decode(node.indexExpression, indexAssignment) : utils.toBigNumber(node.indexExpression.hexValue); debug("index value %O", indexValue); if (indexValue == undefined) { break; } assignments = { [baseDeclarationId]: (0, _extends3.default)({}, baseAssignment, { keys: [...new _set2.default([...(baseAssignment.keys || []), indexValue])] }) }; debug("mapping assignments %O", assignments); yield (0, _effects.put)(actions.assign(treeId, assignments)); debug("new assignments %O", (yield (0, _effects.select)(_selectors2.default.proc.assignments))); break; case "Assignment": break; default: if (node.typeDescriptions == undefined) { break; } debug("decoding expression value %O", node.typeDescriptions); let literal = decode(node, { "stack": top }); yield (0, _effects.put)(actions.assign(treeId, { [node.id]: { literal } })); break; } } function* saga() { yield (0, _effects.takeEvery)(_actions.TICK, function* () { try { yield* tickSaga(); } catch (e) { debug(e); } }); } exports.default = (0, _helpers.prefixName)("data", saga); /***/ }), /* 31 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.scope = scope; exports.declare = declare; exports.assign = assign; const SCOPE = exports.SCOPE = "SCOPE"; function scope(id, pointer, parentId, sourceId) { return { type: SCOPE, id, pointer, parentId, sourceId }; } const DECLARE = exports.DECLARE = "DECLARE_VARIABLE"; function declare(node) { return { type: DECLARE, node }; } const ASSIGN = exports.ASSIGN = "ASSIGN"; function assign(context, assignments) { return { type: ASSIGN, context, assignments }; } /***/ }), /* 32 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _set = __webpack_require__(22); var _set2 = _interopRequireDefault(_set); exports.advance = advance; exports.wait = wait; exports.processTrace = processTrace; exports.saga = saga; var _debug = __webpack_require__(0); var _debug2 = _interopRequireDefault(_debug); var _effects = __webpack_require__(10); var _helpers = __webpack_require__(5); var _actions = __webpack_require__(21); var actions = _interopRequireWildcard(_actions); var _selectors = __webpack_require__(19); var _selectors2 = _interopRequireDefault(_selectors); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {};if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } }newObj.default = obj;return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } const debug = (0, _debug2.default)("debugger:trace:sagas"); function* waitForTrace() { let { steps } = yield (0, _effects.take)(actions.SAVE_STEPS); let addresses = [...new _set2.default(steps.filter(({ op }) => op == "CALL" || op == "DELEGATECALL").map(({ stack }) => "0x" + stack[stack.length - 2].substring(24)))]; yield (0, _effects.put)(actions.receiveAddresses(addresses)); } function* advance() { yield (0, _effects.put)(actions.next()); yield (0, _effects.take)(actions.TOCK); } function* next() { let remaining = yield (0, _effects.select)(_selectors2.default.stepsRemaining); debug("remaining: %o", remaining); let steps = yield (0, _effects.select)(_selectors2.default.steps); debug("total steps: %o", steps.length); if (remaining > 0) { debug("putting TICK"); // updates state for current step yield (0, _effects.put)(actions.tick()); debug("put TICK"); remaining--; // local update, just for convenience } if (remaining) { debug("putting TOCK"); // updates step to next step in trace yield (0, _effects.put)(actions.tock()); debug("put TOCK"); } else { yield (0, _effects.put)(actions.endTrace()); } } function* wait() { yield (0, _effects.take)(actions.END_OF_TRACE); } function* processTrace(trace) { yield (0, _effects.put)(actions.saveSteps(trace)); let { addresses } = yield (0, _effects.take)(actions.RECEIVE_ADDRESSES); debug("received addresses"); return addresses; } function* saga() { // wait for trace to be defined yield* waitForTrace(); yield (0, _effects.takeEvery)(actions.NEXT, next); } exports.default = (0, _helpers.prefixName)("trace", saga); /***/ }), /* 33 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.addSource = addSource; exports.addSourceMap = addSourceMap; exports.jump = jump; const ADD_SOURCE = exports.ADD_SOURCE = "SOLIDITY_ADD_SOURCE"; function addSource(source, sourcePath, ast) { return { type: ADD_SOURCE, source, sourcePath, ast }; } const ADD_SOURCEMAP = exports.ADD_SOURCEMAP = "SOLIDITY_ADD_SOURCEMAP"; function addSourceMap(binary, sourceMap) { return { type: ADD_SOURCEMAP, binary, sourceMap }; } const JUMP = exports.JUMP = "JUMP"; function jump(jumpDirection) { return { type: JUMP, jumpDirection }; } /***/ }), /* 34 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.addContext = addContext; exports.addInstance = addInstance; exports.call = call; exports.create = create; exports.returnCall = returnCall; const ADD_CONTEXT = exports.ADD_CONTEXT = "EVM_ADD_CONTEXT"; function addContext(contractName, binary) { return { type: ADD_CONTEXT, contractName, binary }; } const ADD_INSTANCE = exports.ADD_INSTANCE = "EVM_ADD_INSTANCE"; function addInstance(address, context, binary) { return { type: ADD_INSTANCE, address, context, binary }; } const CALL = exports.CALL = "CALL"; function call(address) { return { type: CALL, address }; } const CREATE = exports.CREATE = "CREATE"; function create(binary) { return { type: CREATE, binary }; } const RETURN = exports.RETURN = "RETURN"; function returnCall() { return { type: RETURN }; } /***/ }), /* 35 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _entries = __webpack_require__(1); var _entries2 = _interopRequireDefault(_entries); var _assign = __webpack_require__(4); var _assign2 = _interopRequireDefault(_assign); var _debug = __webpack_require__(0); var _debug2 = _interopRequireDefault(_debug); var _reselectTree = __webpack_require__(9); var _selectors = __webpack_require__(2); var _selectors2 = _interopRequireDefault(_selectors); var _selectors3 = __webpack_require__(6); var _selectors4 = _interopRequireDefault(_selectors3); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } const debug = (0, _debug2.default)("debugger:session:selectors"); const session = (0, _reselectTree.createSelectorTree)({ /** * session.info */ info: { /** * session.info.affectedInstances */ affectedInstances: (0, _reselectTree.createLeaf)([_selectors2.default.info.instances, _selectors2.default.info.contexts, _selectors4.default.info.sources, _selectors4.default.info.sourceMaps], (instances, contexts, sources, sourceMaps) => (0, _assign2.default)({}, ...(0, _entries2.default)(instances).map(([address, { context }]) => { let { contractName, binary } = contexts[context]; let { sourceMap } = sourceMaps[context]; let { source } = sourceMap ? // look for source ID between second and third colons (HACK) sources[sourceMap.match(/^[^:]+:[^:]+:([^:]+):/)[1]] : {}; return { [address]: { contractName, source, binary } }; }))) } }); exports.default = session; /***/ }), /* 36 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _asyncToGenerator2 = __webpack_require__(7); var _asyncToGenerator3 = _interopRequireDefault(_asyncToGenerator2); let prepareDebugger = (() => { var _ref2 = (0, _asyncToGenerator3.default)(function* (testName, sources) { const provider = _ganacheCli2.default.provider({ seed: "debugger", gasLimit: 7000000 }); const web3 = new _web2.default(provider); let { abstractions, artifacts: contracts, files } = yield (0, _helpers.prepareContracts)(provider, sources); let instance = yield abstractions[contractName(testName)].deployed(); let receipt = yield instance.run(); let txHash = receipt.tx; let bugger = yield _debugger2.default.forTx(txHash, { provider, files, contracts }); let session = bugger.connect(); let breakpoint = { address: instance.address, line: lastStatementLine(sources[fileName(testName)]) }; session.continueUntil(breakpoint); return session; }); return function prepareDebugger(_x, _x2) { return _ref2.apply(this, arguments); }; })(); let getDecode = (() => { var _ref3 = (0, _asyncToGenerator3.default)(function* (session) { const definitions = session.view(_selectors2.default.current.identifiers.definitions); const refs = session.view(_selectors2.default.current.identifiers.refs); const decode = session.view(_selectors2.default.views.decoder); return function (name) { return (0, _utils.cleanBigNumbers)(decode(definitions[name], refs[name])); }; }); return function getDecode(_x3) { return _ref3.apply(this, arguments); }; })(); exports.generateUints = generateUints; exports.describeDecoding = describeDecoding; var _debug = __webpack_require__(0); var _debug2 = _interopRequireDefault(_debug); var _ganacheCli = __webpack_require__(16); var _ganacheCli2 = _interopRequireDefault(_ganacheCli); var _web = __webpack_require__(8); var _web2 = _interopRequireDefault(_web); var _chai = __webpack_require__(12); var _changeCase = __webpack_require__(82); var _changeCase2 = _interopRequireDefault(_changeCase); var _helpers = __webpack_require__(13); var _debugger = __webpack_require__(18); var _debugger2 = _interopRequireDefault(_debugger); var _utils = __webpack_require__(11); var _selectors = __webpack_require__(26); var _selectors2 = _interopRequireDefault(_selectors); var _selectors3 = __webpack_require__(2); var _selectors4 = _interopRequireDefault(_selectors3); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } const debug = (0, _debug2.default)("test:data:decode"); function* generateUints() { let x = 0; while (true) { yield x; x++; } } function contractName(testName) { return testName.replace(/ /g, ""); } function
(testName) { return `${contractName(testName)}.sol`; } function generateTests(fixtures) { for (let _ref of fixtures) { let { name, value: expected } = _ref; it(`correctly decodes ${name}`, () => { _chai.assert.deepEqual(this.decode(name), expected); }); } } function lastStatementLine(source) { const lines = source.split("\n"); for (let i = lines.length - 1; i >= 0; i--) { let line = lines[i]; if (line.indexOf(";") != -1) { return i; } } } function describeDecoding(testName, fixtures, selector, generateSource) { const sources = { [fileName(testName)]: generateSource(contractName(testName), fixtures) }; describe(testName, function () { var _this = this; const testDebug = (0, _debug2.default)(`test:data:decode:${_changeCase2.default.paramCase(testName)}`); this.timeout(30000); before("runs and observes debugger", (0, _asyncToGenerator3.default)(function* () { const session = yield prepareDebugger(testName, sources); _this.decode = yield getDecode(session); testDebug("storage %O", session.view(_selectors4.default.current.state.storage)); if (selector) { debug("selector %O", session.view(selector)); } })); generateTests.bind(this)(fixtures); }); } /***/ }), /* 37 */ /***/ (function(module, exports, __webpack_require__) { // runtime helper function inManifest(id) { return global.__webpackManifest__.indexOf(id) >= 0;} function run(id) { __webpack_require__(id);} // modules to execute goes here var ids = [ /*require.resolve*/(38),/*require.resolve*/(78),/*require.resolve*/(79),/*require.resolve*/(36),/*require.resolve*/(83),/*require.resolve*/(84),/*require.resolve*/(13),/*require.resolve*/(85) ]; ids.filter(inManifest).forEach(run) /***/ }), /* 38 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var _asyncToGenerator2 = __webpack_require__(7); var _asyncToGenerator3 = _interopRequireDefault(_asyncToGenerator2); var _debug = __webpack_require__(0); var _debug2 = _interopRequireDefault(_debug); var _chai = __webpack_require__(12); var _ganacheCli = __webpack_require__(16); var _ganacheCli2 = _interopRequireDefault(_ganacheCli); var _web = __webpack_require__(8); var _web2 = _interopRequireDefault(_web); var _helpers = __webpack_require__(13); var _debugger = __webpack_require__(18); var _debugger2 = _interopRequireDefault(_debugger); var _selectors = __webpack_require__(14); var _selectors2 = _interopRequireDefault(_selectors); var _selectors3 = __webpack_require__(6); var _selectors4 = _interopRequireDefault(_selectors3); var _map = __webpack_require__(28); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } const debug = (0, _debug2.default)("test:ast"); const __VARIABLES = ` pragma solidity ^0.4.18; contract Variables { event Result(uint256 result); uint256 qux; string quux; function stack(uint256 foo) public returns (uint256) { uint256 bar = foo + 1; uint256 baz = innerStack(bar); baz += 4; qux = baz; Result(baz); return baz; } function innerStack(uint256 baz) public returns (uint256) { uint256 bar = baz + 2; return bar; } } `; let sources = { "Variables.sol": __VARIABLES }; describe("AST", function () { var provider; var web3; var abstractions; var artifacts; var files; before("Create Provider", (0, _asyncToGenerator3.default)(function* () { provider = _ganacheCli2.default.provider({ seed: "debugger", gasLimit: 7000000 }); web3 = new _web2.default(provider); })); before("Prepare contracts and artifacts", (0, _asyncToGenerator3.default)(function* () { this.timeout(30000); let prepared = yield (0, _helpers.prepareContracts)(provider, sources); abstractions = prepared.abstractions; artifacts = prepared.artifacts; files = prepared.files; })); describe("Node pointer", function () { it("traverses", (0, _asyncToGenerator3.default)(function* () { this.timeout(0); let instance = yield abstractions.Variables.deployed(); let receipt = yield instance.stack(4); let txHash = receipt.tx; let bugger = yield _debugger2.default.forTx(txHash, { provider, files, contracts: artifacts }); let session = bugger.connect(); debug("ast: %O", session.view(_selectors2.default.current.tree)); do { let { start, length } = session.view(_selectors4.default.current.sourceRange); let end = start + length; let node = session.view(_selectors2.default.current.node); let [nodeStart, nodeLength] = (0, _map.getRange)(node); let nodeEnd = nodeStart + nodeLength; let pointer = session.view(_selectors2.default.current.pointer); _chai.assert.isAtMost(nodeStart, start, `Node ${pointer} at should not begin after instruction source range`); _chai.assert.isAtLeast(nodeEnd, end, `Node ${pointer} should not end after source`); session.stepNext(); } while (!session.finished); })); }); }); /***/ }), /* 39 */ /***/ (function(module, exports) { module.exports = require("path"); /***/ }), /* 40 */ /***/ (function(module, exports) { module.exports = require("fs-extra"); /***/ }), /* 41 */ /***/ (function(module, exports) { module.exports = require("async"); /***/ }), /* 42 */ /***/ (function(module, exports) { module.exports = require("truffle-workflow-compile"); /***/ }), /* 43 */ /***/ (function(module, exports) { module.exports = require("truffle-debug-utils"); /***/ }), /* 44 */ /***/ (function(module, exports) { module.exports = require("truffle-artifactor"); /***/ }), /* 45 */ /***/ (function(module, exports) { module.exports = require("truffle-migrate"); /***/ }), /* 46 */ /***/ (function(module, exports) { module.exports = require("truffle-box"); /***/ }), /* 47 */ /***/ (function(module, exports) { module.exports = require("truffle-resolver"); /***/ }), /* 48 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _values = __webpack_require__(49); var _values2 = _interopRequireDefault(_values); var _promise = __webpack_require__(23); var _promise2 = _interopRequireDefault(_promise); var _debug = __webpack_require__(0); var _debug2 = _interopRequireDefault(_debug); var _selectors = __webpack_require__(19); var _selectors2 = _interopRequireDefault(_selectors); var _selectors3 = __webpack_require__(2); var _selectors4 = _interopRequireDefault(_selectors3); var _selectors5 = __webpack_require__(14); var _selectors6 = _interopRequireDefault(_selectors5); var _selectors7 = __webpack_require__(6); var _selectors8 = _interopRequireDefault(_selectors7); var _store = __webpack_require__(54); var _store2 = _interopRequireDefault(_store); var _actions = __webpack_require__(29); var controller = _interopRequireWildcard(_actions); var _actions2 = __webpack_require__(25); var actions = _interopRequireWildcard(_actions2); var _sagas = __webpack_require__(59); var _sagas2 = _interopRequireDefault(_sagas); var _reducers = __webpack_require__(72); var _reducers2 = _interopRequireDefault(_reducers); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {};if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } }newObj.default = obj;return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } const debug = (0, _debug2.default)("debugger:session"); /** * Debugger Session */ class Session { /** * @param {Array<Contract>} contracts - contract definitions * @param {Array<String>} files - array of filenames for sourceMap indexes * @param {string} txHash - transaction hash * @param {Web3Provider} provider - web3 provider * @private */ constructor(contracts, files, txHash, provider) { /** * @private */ this._store = (0, _store2.default)(_reducers2.default, _sagas2.default); let { contexts, sources } = Session.normalize(contracts, files); // record contracts this._store.dispatch(actions.recordContracts(contexts, sources)); this._store.dispatch(actions.start(txHash, provider)); } ready() { return new _promise2.default((accept, reject) => { this._store.subscribe(() => { if (this.state.session == "ACTIVE") { accept(); } else if (typeof this.state.session == "object") { reject(this.state.session.error); } }); }); } /** * Split up artifacts into "contexts" and "sources", dividing artifact * data into appropriate buckets. * * Multiple contracts can be defined in the same source file, but have * different bytecodes. * * This iterates over the contracts and collects binaries separately * from sources, using the optional `files` argument to force * source ordering. * @private */ static normalize(contracts, files = null) { let sourcesByPath = {}; let contexts = []; let sources; for (let contract of contracts) { let { contractName, binary, sourceMap, deployedBinary, deployedSourceMap, sourcePath, source, ast } = contract; sourcesByPath[sourcePath] = { sourcePath, source, ast }; if (binary && binary != "0x") { contexts.push({ contractName, binary, sourceMap }); } if (deployedBinary && deployedBinary != "0x") { contexts.push({ contractName, binary: deployedBinary, sourceMap: deployedSourceMap }); } } if (!files) { sources = (0, _values2.default)(sourcesByPath); } else { sources = files.map(file => sourcesByPath[file]); } return { contexts, sources }; } get state() { return this._store.getState(); } view(selector) { return selector(this.state); } get finished() { return this.state.session == "FINISHED"; } get failed() { return this.finished && this.view(_selectors4.default.current.callstack).length; } dispatch(action) { if (this.finished) { debug("finished: intercepting action %o", action); return false; } this._store.dispatch(action); return true; } interrupt() { return this.dispatch(controller.interrupt()); } advance() { return this.dispatch(controller.advance()); } stepNext() { return this.dispatch(controller.stepNext()); } stepOver() { return this.dispatch(controller.stepOver()); } stepInto() { return this.dispatch(controller.stepInto()); } stepOut() { return this.dispatch(controller.stepOut()); } continueUntil(...breakpoints) { return this.dispatch(controller.continueUntil(...breakpoints)); } } exports.default = Session; /***/ }), /* 49 */ /***/ (function(module, exports) { module.exports = require("babel-runtime/core-js/object/values"); /***/ }), /* 50 */ /***/ (function(module, exports) { module.exports = require("truffle-solidity-utils"); /***/ }), /* 51 */ /***/ (function(module, exports) { module.exports = require("truffle-code-utils"); /***/ }), /* 52 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; // An augmented AVL Tree where each node maintains a list of records and their search intervals. // Record is composed of an interval and its underlying data, sent by a client. This allows the // interval tree to have the same interval inserted multiple times, as long its data is different. // Both insertion and deletion require O(log n) time. Searching requires O(k*logn) time, where `k` // is the number of intervals in the output list. Object.defineProperty(exports, "__esModule", { value: true }); var isSame = __webpack_require__(53); function height(node) { if (node === undefined) { return -1; } else { return node.height; } } var Node = /** @class */ (function () { function Node(intervalTree, record) { this.intervalTree = intervalTree; this.records = []; this.height = 0; this.key = record.low; this.max = record.high; // Save the array of all records with the same key for this node this.records.push(record); } // Gets the highest record.high value for this node Node.prototype.getNodeHigh = function () { var high = this.records[0].high; for (var i = 1; i < this.records.length; i++) { if (this.records[i].high > high) { high = this.records[i].high; } } return high; }; // Updates height value of the node. Called during insertion, rebalance, removal Node.prototype.updateHeight = function () { this.height = Math.max(height(this.left), height(this.right)) + 1; }; // Updates the max value of all the parents after inserting into already existing node, as well as // removing the node completely or removing the record of an already existing node. Starts with // the parent of an affected node and bubbles up to root Node.prototype.updateMaxOfParents = function () { if (this === undefined) { return; } var thisHigh = this.getNodeHigh(); if (this.left !== undefined && this.right !== undefined) { this.max = Math.max(Math.max(this.left.max, this.right.max), thisHigh); } else if (this.left !== undefined && this.right === undefined) { this.max = Math.max(this.left.max, thisHigh); } else if (this.left === undefined && this.right !== undefined) { this.max = Math.max(this.right.max, thisHigh); } else { this.max = thisHigh; } if (this.parent) { this.parent.updateMaxOfParents(); } }; /* Left-Left case: z y / \ / \ y T4 Right Rotate (z) x z / \ - - - - - - - - -> / \ / \ x T3 T1 T2 T3 T4 / \ T1 T2 Left-Right case: z z x / \ / \ / \ y T4 Left Rotate (y) x T4 Right Rotate(z) y z / \ - - - - - - - - -> / \ - - - - - - - -> / \ / \ T1 x y T3 T1 T2 T3 T4 / \ / \ T2 T3 T1 T2 */ // Handles Left-Left case and Left-Right case after rebalancing AVL tree Node.prototype._updateMaxAfterRightRotate = function () { var parent = this.parent; var left = parent.left; // Update max of left sibling (x in first case, y in second) var thisParentLeftHigh = left.getNodeHigh(); if (left.left === undefined && left.right !== undefined) { left.max = Math.max(thisParentLeftHigh, left.right.max); } else if (left.left !== undefined && left.right === undefined) { left.max = Math.max(thisParentLeftHigh, left.left.max); } else if (left.left === undefined && left.right === undefined) { left.max = thisParentLeftHigh; } else { left.max = Math.max(Math.max(left.left.max, left.right.max), thisParentLeftHigh); } // Update max of itself (z) var thisHigh = this.getNodeHigh(); if (this.left === undefined && this.right !== undefined) { this.max = Math.max(thisHigh, this.right.max); } else if (this.left !== undefined && this.right === undefined) { this.max = Math.max(thisHigh, this.left.max); } else if (this.left === undefined && this.right === undefined) { this.max = thisHigh; } else { this.max = Math.max(Math.max(this.left.max, this.right.max), thisHigh); } // Update max of parent (y in first case, x in second) parent.max = Math.max(Math.max(parent.left.max, parent.right.max), parent.getNodeHigh()); }; /* Right-Right case: z y / \ / \ T1 y Left Rotate(z) z x / \ - - - - - - - -> / \ / \ T2 x T1 T2 T3 T4 / \ T3 T4 Right-Left case: z z x / \ / \ / \ T1 y Right Rotate (y) T1 x Left Rotate(z) z y / \ - - - - - - - - -> / \ - - - - - - - -> / \ / \ x T4 T2 y T1 T2 T3 T4 / \ / \ T2 T3 T3 T4 */ // Handles Right-Right case and Right-Left case in rebalancing AVL tree Node.prototype._updateMaxAfterLeftRotate = function () { var parent = this.parent; var right = parent.right; // Update max of right sibling (x in first case, y in second) var thisParentRightHigh = right.getNodeHigh(); if (right.left === undefined && right.right !== undefined) { right.max = Math.max(thisParentRightHigh, right.right.max); } else if (right.left !== undefined && right.right === undefined) { right.max = Math.max(thisParentRightHigh, right.left.max); } else if (right.left === undefined && right.right === undefined) { right.max = thisParentRightHigh; } else { right.max = Math.max(Math.max(right.left.max, right.right.max), thisParentRightHigh); } // Update max of itself (z) var thisHigh = this.getNodeHigh(); if (this.left === undefined && this.right !== undefined) { this.max = Math.max(thisHigh, this.right.max); } else if (this.left !== undefined && this.right === undefined) { this.max = Math.max(thisHigh, this.left.max); } else if (this.left === undefined && this.right === undefined) { this.max = thisHigh; } else { this.max = Math.max(Math.max(this.left.max, this.right.max), thisHigh); } // Update max of parent (y in first case, x in second) parent.max = Math.max(Math.max(parent.left.max, right.max), parent.getNodeHigh()); }; Node.prototype._leftRotate = function () { var rightChild = this.right; rightChild.parent = this.parent; if (rightChild.parent === undefined) { this.intervalTree.root = rightChild; } else { if (rightChild.parent.left === this) { rightChild.parent.left = rightChild; } else if (rightChild.parent.right === this) { rightChild.parent.right = rightChild; } } this.right = rightChild.left; if (this.right !== undefined) { this.right.parent = this; } rightChild.left = this; this.parent = rightChild; this.updateHeight(); rightChild.updateHeight(); }; Node.prototype._rightRotate = function () { var leftChild = this.left; leftChild.parent = this.parent; if (leftChild.parent === undefined) { this.intervalTree.root = leftChild; } else { if (leftChild.parent.left === this) { leftChild.parent.left = leftChild; } else if (leftChild.parent.right === this) { leftChild.parent.right = leftChild; } } this.left = leftChild.right; if (this.left !== undefined) { this.left.parent = this; } leftChild.right = this; this.parent = leftChild; this.updateHeight(); leftChild.updateHeight(); }; // Rebalances the tree if the height value between two nodes of the same parent is greater than // two. There are 4 cases that can happen which are outlined in the graphics above Node.prototype._rebalance = function () { if (height(this.left) >= 2 + height(this.right)) { var left = this.left; if (height(left.left) >= height(left.right)) { // Left-Left case this._rightRotate(); this._updateMaxAfterRightRotate(); } else { // Left-Right case left._leftRotate(); this._rightRotate(); this._updateMaxAfterRightRotate(); } } else if (height(this.right) >= 2 + height(this.left)) { var right = this.right; if (height(right.right) >= height(right.left)) { // Right-Right case this._leftRotate(); this._updateMaxAfterLeftRotate(); } else { // Right-Left case right._rightRotate(); this._leftRotate(); this._updateMaxAfterLeftRotate(); } } }; Node.prototype.insert = function (record) { if (record.low < this.key) { // Insert into left subtree if (this.left === undefined) { this.left = new Node(this.intervalTree, record); this.left.parent = this; } else { this.left.insert(record); } } else { // Insert into right subtree if (this.right === undefined) { this.right = new Node(this.intervalTree, record); this.right.parent = this; } else { this.right.insert(record); } } // Update the max value of this ancestor if needed if (this.max < record.high) { this.max = record.high; } // Update height of each node this.updateHeight(); // Rebalance the tree to ensure all operations are executed in O(logn) time. This is especially // important in searching, as the tree has a high chance of degenerating without the rebalancing this._rebalance(); }; Node.prototype._getOverlappingRecords = function (currentNode, low, high) { if (currentNode.key <= high && low <= currentNode.getNodeHigh()) { // Nodes are overlapping, check if individual records in the node are overlapping var tempResults = []; for (var i = 0; i < currentNode.records.length; i++) { if (currentNode.records[i].high >= low) { tempResults.push(currentNode.records[i]); } } return tempResults; } return []; }; Node.prototype.search = function (low, high) { // Don't search nodes that don't exist if (this === undefined) { return []; } var leftSearch = []; var ownSearch = []; var rightSearch = []; // If interval is to the right of the rightmost point of any interval in this node and all its // children, there won't be any matches if (low > this.max) { return []; } // Search left children if (this.left !== undefined && this.left.max >= low) { leftSearch = this.left.search(low, high); } // Check this node ownSearch = this._getOverlappingRecords(this, low, high); // If interval is to the left of the start of this interval, then it can't be in any child to // the right if (high < this.key) { return leftSearch.concat(ownSearch); } // Otherwise, search right children if (this.right !== undefined) { rightSearch = this.right.search(low, high); } // Return accumulated results, if any return leftSearch.concat(ownSearch, rightSearch); }; // Searches for a node by a `key` value Node.prototype.searchExisting = function (low) { if (this === undefined) { return undefined; } if (this.key === low) { return this; } else if (low < this.key) { if (this.left !== undefined) { return this.left.searchExisting(low); } } else { if (this.right !== undefined) { return this.right.searchExisting(low); } } return undefined; }; // Returns the smallest node of the subtree Node.prototype._minValue = function () { if (this.left === undefined) { return this; } else { return this.left._minValue(); } }; Node.prototype.remove = function (node) { var parent = this.parent; if (node.key < this.key) { // Node to be removed is on the left side if (this.left !== undefined) { return this.left.remove(node); } else { return undefined; } } else if (node.key > this.key) { // Node to be removed is on the right side if (this.right !== undefined) { return this.right.remove(node); } else { return undefined; } } else { if (this.left !== undefined && this.right !== undefined) { // Node has two children var minValue = this.right._minValue(); this.key = minValue.key; this.records = minValue.records; return this.right.remove(this); } else if (parent.left === this) { // One child or no child case on left side if (this.right !== undefined) { parent.left = this.right; this.right.parent = parent; } else { parent.left = this.left; if (this.left !== undefined) { this.left.parent = parent; } } parent.updateMaxOfParents(); parent.updateHeight(); parent._rebalance(); return this; } else if (parent.right === this) { // One child or no child case on right side if (this.right !== undefined) { parent.right = this.right; this.right.parent = parent; } else { parent.right = this.left; if (this.left !== undefined) { this.left.parent = parent; } } parent.updateMaxOfParents(); parent.updateHeight(); parent._rebalance(); return this; } } }; return Node; }()); exports.Node = Node; var IntervalTree = /** @class */ (function () { function IntervalTree() { this.count = 0; } IntervalTree.prototype.insert = function (record) { if (record.low > record.high) { throw new Error('`low` value must be lower or equal to `high` value'); } if (this.root === undefined) { // Base case: Tree is empty, new node becomes root this.root = new Node(this, record); this.count++; return true; } else { // Otherwise, check if node already exists with the same key var node = this.root.searchExisting(record.low); if (node !== undefined) { // Check the records in this node if there already is the one with same low, high, data for (var i = 0; i < node.records.length; i++) { if (isSame(node.records[i], record)) { // This record is same as the one we're trying to insert; return false to indicate // nothing has been inserted return false; } } // Add the record to the node node.records.push(record); // Update max of the node and its parents if necessary if (record.high > node.max) { node.max = record.high; if (node.parent) { node.parent.updateMaxOfParents(); } } this.count++; return true; } else { // Node with this key doesn't already exist. Call insert function on root's node this.root.insert(record); this.count++; return true; } } }; IntervalTree.prototype.search = function (low, high) { if (this.root === undefined) { // Tree is empty; return empty array return []; } else { return this.root.search(low, high); } }; IntervalTree.prototype.remove = function (record) { if (this.root === undefined) { // Tree is empty; nothing to remove return false; } else { var node = this.root.searchExisting(record.low); if (node === undefined) { return false; } else if (node.records.length > 1) { var removedRecord = void 0; // Node with this key has 2 or more records. Find the one we need and remove it for (var i = 0; i < node.records.length; i++) { if (isSame(node.records[i], record)) { removedRecord = node.records[i]; node.records.splice(i, 1); break; } } if (removedRecord) { removedRecord = undefined; // Update max of that node and its parents if necessary if (record.high === node.max) { var nodeHigh = node.getNodeHigh(); if (node.left !== undefined && node.right !== undefined) { node.max = Math.max(Math.max(node.left.max, node.right.max), nodeHigh); } else if (node.left !== undefined && node.right === undefined) { node.max = Math.max(node.left.max, nodeHigh); } else if (node.left === undefined && node.right !== undefined) { node.max = Math.max(node.right.max, nodeHigh); } else { node.max = nodeHigh; } if (node.parent) { node.parent.updateMaxOfParents(); } } this.count--; return true; } else { return false; } } else if (node.records.length === 1) { // Node with this key has only 1 record. Check if the remaining record in this node is // actually the one we want to remove if (isSame(node.records[0], record)) { // The remaining record is the one we want to remove. Remove the whole node from the tree if (this.root.key === node.key) { // We're removing the root element. Create a dummy node that will temporarily take // root's parent role var rootParent = new Node(this, { low: record.low, high: record.low }); rootParent.left = this.root; this.root.parent = rootParent; var removedNode = this.root.remove(node); this.root = rootParent.left; if (this.root !== undefined) { this.root.parent = undefined; } if (removedNode) { removedNode = undefined; this.count--; return true; } else { return false; } } else { var removedNode = this.root.remove(node); if (removedNode) { removedNode = undefined; this.count--; return true; } else { return false; } } } else { // The remaining record is not the one we want to remove return false; } } else { // No records at all in this node?! Shouldn't happen return false; } } }; IntervalTree.prototype.inOrder = function () { return new InOrder(this.root); }; IntervalTree.prototype.preOrder = function () { return new PreOrder(this.root); }; return IntervalTree; }()); exports.IntervalTree = IntervalTree; var DataIntervalTree = /** @class */ (function () { function DataIntervalTree() { this.tree = new IntervalTree(); } DataIntervalTree.prototype.insert = function (low, high, data) { return this.tree.insert({ low: low, high: high, data: data }); }; DataIntervalTree.prototype.remove = function (low, high, data) { return this.tree.remove({ low: low, high: high, data: data }); }; DataIntervalTree.prototype.search = function (low, high) { return this.tree.search(low, high).map(function (v) { return v.data; }); }; DataIntervalTree.prototype.inOrder = function () { return this.tree.inOrder(); }; DataIntervalTree.prototype.preOrder = function () { return this.tree.preOrder(); }; Object.defineProperty(DataIntervalTree.prototype, "count", { get: function () { return this.tree.count; }, enumerable: true, configurable: true }); return DataIntervalTree; }()); exports.default = DataIntervalTree; var InOrder = /** @class */ (function () { function InOrder(startNode) { this.stack = []; if (startNode !== undefined) { this.push(startNode); } } InOrder.prototype.next = function () { // Will only happen if stack is empty and pop is called if (this.currentNode === undefined) { return { done: true, value: undefined, }; } // Process this node if (this.i < this.currentNode.records.length) { return { done: false, value: this.currentNode.records[this.i++], }; } if (this.currentNode.right !== undefined) { this.push(this.currentNode.right); } else { // Might pop the last and set this.currentNode = undefined this.pop(); } return this.next(); }; InOrder.prototype.push = function (node) { this.currentNode = node; this.i = 0; while (this.currentNode.left !== undefined) { this.stack.push(this.currentNode); this.currentNode = this.currentNode.left; } }; InOrder.prototype.pop = function () { this.currentNode = this.stack.pop(); this.i = 0; }; return InOrder; }()); exports.InOrder = InOrder; if (typeof Symbol === 'function') { InOrder.prototype[Symbol.iterator] = function () { return this; }; } var PreOrder = /** @class */ (function () { function PreOrder(startNode) { this.stack = []; this.i = 0; this.currentNode = startNode; } PreOrder.prototype.next = function () { // Will only happen if stack is empty and pop is called, // which only happens if there is no right node (i.e we are done) if (this.currentNode === undefined) { return { done: true, value: undefined, }; } // Process this node if (this.i < this.currentNode.records.length) { return { done: false, value: this.currentNode.records[this.i++], }; } if (this.currentNode.right !== undefined) { this.push(this.currentNode.right); } if (this.currentNode.left !== undefined) { this.push(this.currentNode.left); } this.pop(); return this.next(); }; PreOrder.prototype.push = function (node) { this.stack.push(node); }; PreOrder.prototype.pop = function () { this.currentNode = this.stack.pop(); this.i = 0; }; return PreOrder; }()); exports.PreOrder = PreOrder; if (typeof Symbol === 'function') { PreOrder.prototype[Symbol.iterator] = function () { return this; }; } //# sourceMappingURL=index.js.map /***/ }), /* 53 */ /***/ (function(module, exports) { // module.exports = function shallowEqual(objA, objB, compare, compareContext) { var ret = compare ? compare.call(compareContext, objA, objB) : void 0; if (ret !== void 0) { return !!ret; } if (objA === objB) { return true; } if (typeof objA !== "object" || !objA || typeof objB !== "object" || !objB) { return false; } var keysA = Object.keys(objA); var keysB = Object.keys(objB); if (keysA.length !== keysB.length) { return false; } var bHasOwnProperty = Object.prototype.hasOwnProperty.bind(objB); // Test for A's keys different from B. for (var idx = 0; idx < keysA.length; idx++) { var key = keysA[idx]; if (!bHasOwnProperty(key)) { return false; } var valueA = objA[key]; var valueB = objB[key]; ret = compare ? compare.call(compareContext, valueA, valueB, key) : void 0; if (ret === false || (ret === void 0 && valueA !== valueB)) { return false; } } return true; }; /***/ }), /* 54 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; if (false) { module.exports = require("./production"); } else if (true) { module.exports = __webpack_require__(55); } else { module.exports = require("./development"); } /***/ }), /* 55 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _common = __webpack_require__(56); var _common2 = _interopRequireDefault(_common); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } exports.default = _common2.default; /***/ }), /* 56 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _entries = __webpack_require__(1); var _entries2 = _interopRequireDefault(_entries); var _assign = __webpack_require__(4); var _assign2 = _interopRequireDefault(_assign); exports.abbreviateValues = abbreviateValues; exports.default = configureStore; var _debug = __webpack_require__(0); var _debug2 = _interopRequireDefault(_debug); var _redux = __webpack_require__(15); var _reduxSaga = __webpack_require__(57); var _reduxSaga2 = _interopRequireDefault(_reduxSaga); var _reduxCliLogger = __webpack_require__(58); var _reduxCliLogger2 = _interopRequireDefault(_reduxCliLogger); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } const debug = (0, _debug2.default)("debugger:store:common"); const reduxDebug = (0, _debug2.default)("debugger:redux"); function abbreviateValues(value, options = {}, depth = 0) { options.stringLimit = options.stringLimit || 66; options.arrayLimit = options.arrayLimit || 8; options.recurseLimit = options.recurseLimit || 4; if (depth > options.recurseLimit) { return "..."; } const recurse = child => abbreviateValues(child, options, depth + 1); if (value instanceof Array) { if (value.length > options.arrayLimit) { value = [...value.slice(0, options.arrayLimit / 2), "...", ...value.slice(value.length - options.arrayLimit / 2 + 1)]; } return value.map(recurse); } else if (value instanceof Object) { return (0, _assign2.default)({}, ...(0, _entries2.default)(value).map(([k, v]) => ({ [recurse(k)]: recurse(v) }))); } else if (typeof value === "string" && value.length > options.stringLimit) { let inner = "..."; let extractAmount = (options.stringLimit - inner.length) / 2; let leading = value.slice(0, Math.ceil(extractAmount)); let trailing = value.slice(value.length - Math.floor(extractAmount)); return `${leading}${inner}${trailing}`; } else { return value; } } function configureStore(reducer, saga, initialState, composeEnhancers) { const sagaMiddleware = (0, _reduxSaga2.default)(); if (!composeEnhancers) { composeEnhancers = _redux.compose; } const loggerMiddleware = (0, _reduxCliLogger2.default)({ log: reduxDebug, stateTransformer: state => abbreviateValues(state, { arrayLimit: 4, recurseLimit: 3 }), actionTransformer: abbreviateValues }); let store = (0, _redux.createStore)(reducer, initialState, composeEnhancers((0, _redux.applyMiddleware)(sagaMiddleware, loggerMiddleware))); sagaMiddleware.run(saga); return store; } /***/ }), /* 57 */ /***/ (function(module, exports) { module.exports = require("redux-saga"); /***/ }), /* 58 */ /***/ (function(module, exports) { module.exports = require("redux-cli-logger"); /***/ }), /* 59 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.saga = saga; var _debug = __webpack_require__(0); var _debug2 = _interopRequireDefault(_debug); var _effects = __webpack_require__(10); var _helpers = __webpack_require__(5); var _sagas = __webpack_require__(60); var ast = _interopRequireWildcard(_sagas); var _sagas2 = __webpack_require__(65); var controller = _interopRequireWildcard(_sagas2); var _sagas3 = __webpack_require__(67); var solidity = _interopRequireWildcard(_sagas3); var _sagas4 = __webpack_require__(68); var evm = _interopRequireWildcard(_sagas4); var _sagas5 = __webpack_require__(32); var trace = _interopRequireWildcard(_sagas5); var _sagas6 = __webpack_require__(30); var data = _interopRequireWildcard(_sagas6); var _sagas7 = __webpack_require__(69); var web3 = _interopRequireWildcard(_sagas7); var _actions = __webpack_require__(25); var actions = _interopRequireWildcard(_actions); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {};if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } }newObj.default = obj;return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } const debug = (0, _debug2.default)("debugger:session:sagas"); function* saga() { debug("starting listeners"); let listeners = yield* forkListeners(); // receiving & saving contracts into state debug("waiting for contract information"); let { contexts, sources } = yield (0, _effects.take)(actions.RECORD_CONTRACTS); debug("recording contract binaries"); yield* recordContexts(...contexts); debug("recording contract sources"); yield* recordSources(...sources); debug("waiting for start"); // wait for start signal let { txHash, provider } = yield (0, _effects.take)(actions.START); debug("starting"); // process transaction debug("fetching transaction info"); let err = yield* fetchTx(txHash, provider); if (err) { debug("error %o", err); yield* error(err); } else { debug("visiting ASTs"); // visit asts yield* ast.visitAll(); debug("readying"); // signal that stepping can begin yield* ready(); debug("waiting for trace EOT"); // wait until trace hits EOT yield* trace.wait(); debug("finishing"); // finish yield (0, _effects.put)(actions.finish()); } debug("stopping listeners"); yield (0, _effects.all)(listeners.map(task => (0, _effects.cancel)(task))); } exports.default = (0, _helpers.prefixName)("session", saga); function* forkListeners() { return yield (0, _effects.all)([ast, controller, data, evm, solidity, trace, web3].map(app => (0, _effects.fork)(app.saga))); } function* fetchTx(txHash, provider) { let result = yield* web3.inspectTransaction(txHash, provider); if (result.error) { return result.error; } yield* evm.begin(result); let addresses = yield* trace.processTrace(result.trace); if (result.address && addresses.indexOf(result.address) == -1) { addresses.push(result.address); } let binaries = yield* web3.obtainBinaries(addresses); yield (0, _effects.all)(addresses.map((address, i) => (0, _effects.call)(recordInstance, address, binaries[i]))); } function* recordContexts(...contexts) { for (let _ref of contexts) { let { contractName, binary, sourceMap } = _ref; yield* evm.addContext(contractName, binary); if (sourceMap) { yield* solidity.addSourceMap(binary, sourceMap); } } } function* recordSources(...sources) { for (let _ref2 of sources) { let { sourcePath, source, ast } = _ref2; yield* solidity.addSource(source, sourcePath, ast); } } function* recordInstance(address, binary) { yield* evm.addInstance(address, binary); } function* ready() { yield (0, _effects.put)(actions.ready()); } function* error(err) { yield (0, _effects.put)(actions.error(err)); } /***/ }), /* 60 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _entries = __webpack_require__(1); var _entries2 = _interopRequireDefault(_entries); exports.visitAll = visitAll; exports.saga = saga; var _debug = __webpack_require__(0); var _debug2 = _interopRequireDefault(_debug); var _effects = __webpack_require__(10); var _helpers = __webpack_require__(5); var _sagas = __webpack_require__(30); var data = _interopRequireWildcard(_sagas); var _actions = __webpack_require__(64); var actions = _interopRequireWildcard(_actions); var _selectors = __webpack_require__(14); var _selectors2 = _interopRequireDefault(_selectors); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {};if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } }newObj.default = obj;return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } const debug = (0, _debug2.default)("debugger:ast:sagas"); function* walk(sourceId, node, pointer = "", parentId = null) { debug("walking %o %o", pointer, node); yield* handleEnter(sourceId, node, pointer, parentId); if (node instanceof Array) { for (let [i, child] of node.entries()) { yield (0, _effects.call)(walk, sourceId, child, `${pointer}/${i}`, parentId); } } else if (node instanceof Object) { for (let [key, child] of (0, _entries2.default)(node)) { yield (0, _effects.call)(walk, sourceId, child, `${pointer}/${key}`, node.id); } } yield* handleExit(sourceId, node, pointer); } function* handleEnter(sourceId, node, pointer, parentId) { if (!(node instanceof Object)) { return; } debug("entering %s", pointer); if (node.id !== undefined) { debug("%s recording scope %s", pointer, node.id); yield* data.scope(node.id, pointer, parentId, sourceId); } switch (node.nodeType) { case "VariableDeclaration": debug("%s recording variable %o", pointer, node); yield* data.declare(node); break; } } function* handleExit(sourceId, node, pointer) { debug("exiting %s", pointer); // no-op right now } function* walkSaga({ sourceId, ast }) { yield walk(sourceId, ast); } function* visitAll(idx) { let sources = yield (0, _effects.select)(_selectors2.default.views.sources); let tasks = yield (0, _effects.all)((0, _entries2.default)(sources).filter(([id, { ast }]) => !!ast).map(([id, { ast }]) => (0, _effects.fork)(() => (0, _effects.put)(actions.visit(id, ast))))); if (tasks.length > 0) { yield (0, _effects.join)(...tasks); } yield (0, _effects.put)(actions.doneVisiting()); } function* saga() { yield (0, _effects.race)({ visitor: (0, _effects.takeEvery)(actions.VISIT, walkSaga), done: (0, _effects.take)(actions.DONE_VISITING) }); } exports.default = (0, _helpers.prefixName)("ast", saga); /***/ }), /* 61 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _entries = __webpack_require__(1); var _entries2 = _interopRequireDefault(_entries); var _extends2 = __webpack_require__(3); var _extends3 = _interopRequireDefault(_extends2); var _assign = __webpack_require__(4); var _assign2 = _interopRequireDefault(_assign); exports.read = read; exports.decodeValue = decodeValue; exports.decodeMemoryReference = decodeMemoryReference; exports.decodeStorageReference = decodeStorageReference; exports.decodeMapping = decodeMapping; exports.default = decode; var _debug = __webpack_require__(0); var _debug2 = _interopRequireDefault(_debug); var _bignumber = __webpack_require__(20); var _memory = __webpack_require__(62); var memory = _interopRequireWildcard(_memory); var _storage = __webpack_require__(63); var storage = _interopRequireWildcard(_storage); var _utils = __webpack_require__(11); var utils = _interopRequireWildcard(_utils); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {};if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } }newObj.default = obj;return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } const debug = (0, _debug2.default)("debugger:data:decode"); function read(pointer, state) { if (pointer.stack != undefined && state.stack && pointer.stack < state.stack.length) { return state.stack[pointer.stack]; } else if (pointer.storage != undefined && state.storage) { return storage.readRange(state.storage, pointer.storage); } else if (pointer.memory != undefined && state.memory) { return memory.readBytes(state.memory, pointer.memory.start, pointer.memory.length); } else if (pointer.literal) { return pointer.literal; } } function decodeValue(definition, pointer, state, ...args) { debug("decoding value, pointer: %o, typeClass: %s", pointer, utils.typeClass(definition)); let bytes = read(pointer, state); if (!bytes) { debug("segfault, state: %O", state); return undefined; } switch (utils.typeClass(definition)) { case "bool": return !utils.toBigNumber(bytes).isZero(); case "uint": return utils.toBigNumber(bytes); case "int": return utils.toSignedBigNumber(bytes); case "address": return utils.toHexString(bytes, true); case "bytes": debug("typeIdentifier %s %o", utils.typeIdentifier(definition), bytes); let length = utils.specifiedSize(definition); return utils.toHexString(bytes, length); case "string": debug("typeIdentifier %s %o", utils.typeIdentifier(definition), bytes); return String.fromCharCode.apply(null, bytes); case "rational": debug("typeIdentifier %s %o", utils.typeIdentifier(definition), bytes); return utils.toBigNumber(bytes); default: debug("Unknown value type: %s", utils.typeIdentifier(definition)); return null; } } function decodeMemoryReference(definition, pointer, state, ...args) { let rawValue = utils.toBigNumber(read(pointer, state)).toNumber(); var bytes; switch (utils.typeClass(definition)) { case "bytes": case "string": bytes = read({ memory: { start: rawValue, length: _utils.WORD_SIZE } }, state); // bytes contain length return decodeValue(definition, { memory: { start: rawValue + _utils.WORD_SIZE, length: bytes } }, state, ...args); case "array": bytes = utils.toBigNumber(read({ memory: { start: rawValue, length: _utils.WORD_SIZE } }, state)).toNumber(); // bytes contain array length bytes = read({ memory: { start: rawValue + _utils.WORD_SIZE, length: bytes * _utils.WORD_SIZE } }, state); // now bytes contain items return memory.chunk(bytes, _utils.WORD_SIZE).map(chunk => decode(utils.baseDefinition(definition), { literal: chunk }, state, ...args)); case "struct": let [refs] = args; let structDefinition = refs[definition.typeName.referencedDeclaration]; let structVariables = structDefinition.variables || []; return (0, _assign2.default)({}, ...structVariables.map(({ name, id }, i) => { let memberDefinition = refs[id].definition; let memberPointer = { memory: { start: rawValue + i * _utils.WORD_SIZE, length: _utils.WORD_SIZE } }; // let memberPointer = memory.read(state.memory, pointer + i * WORD_SIZE); // HACK memberDefinition = (0, _extends3.default)({}, memberDefinition, { typeDescriptions: (0, _extends3.default)({}, memberDefinition.typeDescriptions, { typeIdentifier: memberDefinition.typeDescriptions.typeIdentifier.replace(/_storage_/g, "_memory_") }) }); return { [name]: decode(memberDefinition, memberPointer, state, ...args) }; })); default: debug("Unknown memory reference type: %s", utils.typeIdentifier(definition)); return null; } } function decodeStorageReference(definition, pointer, state, ...args) { var data; var bytes; var length; var slot; switch (utils.typeClass(definition)) { case "array": debug("storage array! %o", pointer); data = read(pointer, state); if (!data) { return null; } length = utils.toBigNumber(data).toNumber(); debug("length %o", length); const baseSize = utils.storageSize(utils.baseDefinition(definition)); const perWord = Math.floor(_utils.WORD_SIZE / baseSize); debug("baseSize %o", baseSize); debug("perWord %d", perWord); const offset = i => { if (perWord == 1) { return i; } return Math.floor(i * baseSize / _utils.WORD_SIZE); }; const index = i => { if (perWord == 1) { return _utils.WORD_SIZE - baseSize; } const position = perWord - i % perWord - 1; return position * baseSize; }; debug("pointer: %o", pointer); return [...Array(length).keys()].map(i => { let childFrom = pointer.storage.from.offset != undefined ? { slot: ["0x" + utils.toBigNumber(utils.keccak256(...pointer.storage.from.slot)).plus(pointer.storage.from.offset).toString(16)], offset: offset(i), index: index(i) } : { slot: [pointer.storage.from.slot], offset: offset(i), index: index(i) }; return childFrom; }).map((childFrom, idx) => { debug("childFrom %d, %o", idx, childFrom); return decode(utils.baseDefinition(definition), { storage: { from: childFrom, length: baseSize } }, state, ...args); }); case "bytes": case "string": debug("string pointer %O", pointer); debug("storage %o", state.storage); data = read(pointer, state); if (!data) { return null; } debug("data %O", data); if (data[_utils.WORD_SIZE - 1] % 2 == 0) { // string lives in word, length is last byte / 2 length = data[_utils.WORD_SIZE - 1] / 2; debug("in-word; length %o", length); if (length == 0) { return ""; } return decodeValue(definition, { storage: { from: { slot: pointer.storage.from.slot, index: 0 }, to: { slot: pointer.storage.from.slot, index: length - 1 } } }, state, ...args); } else { length = utils.toBigNumber(data).minus(1).div(2).toNumber(); debug("new-word, length %o", length); return decodeValue(definition, { storage: { from: { slot: [pointer.storage.from.slot], index: 0 }, length } }, state, ...args); } case "struct": let [refs] = args; return (0, _assign2.default)({}, ...(0, _entries2.default)(pointer.storage.children).map(([id, childPointer]) => ({ [childPointer.name]: decode(refs[id].definition, { storage: childPointer }, state, ...args) }))); default: debug("Unknown storage reference type: %s", utils.typeIdentifier(definition)); return undefined; } } function decodeMapping(definition, pointer, ...args) { if (definition.referencedDeclaration) { // attempting to decode reference to mapping, thus missing valid pointer return undefined; } debug("mapping %O", pointer); debug("mapping definition %O", definition); let { keys } = pointer; keys = keys || []; debug("known keys %o", keys); let keyDefinition = definition.typeName.keyType; let valueDefinition = definition.typeName.valueType; let baseSlot = pointer.storage.from.slot; if (!Array.isArray(baseSlot)) { baseSlot = [baseSlot]; } let mapping = {}; debug("mapping %O", mapping); for (let key of keys) { let keyPointer = { "literal": key }; let valuePointer = { storage: { from: { slot: [key.toNumber(), ...baseSlot], index: 0 }, to: { slot: [key.toNumber(), ...baseSlot], index: 31 } } }; // NOTE mapping keys are potentially lossy because JS only likes strings let keyValue = decode(keyDefinition, keyPointer, ...args).toString(); mapping[keyValue] = decode(valueDefinition, valuePointer, ...args); } return mapping; } function decode(definition, ...args) { const identifier = utils.typeIdentifier(definition); if (utils.isReference(definition)) { switch (utils.referenceType(definition)) { case "memory": debug("decoding memory reference, type: %s", identifier); return decodeMemoryReference(definition, ...args); case "storage": debug("decoding storage reference, type: %s", identifier); return decodeStorageReference(definition, ...args); default: debug("Unknown reference category: %s", utils.typeIdentifier(definition)); return undefined; } } if (utils.isMapping(definition)) { debug("decoding mapping, type: %s", identifier); return decodeMapping(definition, ...args); } debug("decoding value, type: %s", identifier); return decodeValue(definition, ...args); } /***/ }), /* 62 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.read = read; exports.readBytes = readBytes; exports.chunk = chunk; var _debug = __webpack_require__(0); var _debug2 = _interopRequireDefault(_debug); var _bignumber = __webpack_require__(20); var _utils = __webpack_require__(11); var utils = _interopRequireWildcard(_utils); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {};if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } }newObj.default = obj;return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } const debug = (0, _debug2.default)("debugger:data:decode:memory"); /** * read word from memory * * requires `byte` to be a multiple of WORD_SIZE (32) * * @param memory - Uint8Array * @return {BigNumber} */ function read(memory, byte) { return readBytes(memory, byte, _utils.WORD_SIZE); } /** * read <bytes> amount of bytes from memory, starting at byte <start> * * @param memory - Uint8Array */ function readBytes(memory, byte, length) { byte = utils.toBigNumber(byte); length = utils.toBigNumber(length); if (byte.toNumber() >= memory.length) { return new Uint8Array(length ? length.toNumber() : 0); } if (length == undefined) { return new Uint8Array(memory.buffer, byte.toNumber()); } // grab `length` bytes no matter what, here fill this array var bytes = new Uint8Array(length.toNumber()); // if we're reading past the end of memory, truncate the length to read let excess = byte.plus(length).minus(memory.length).toNumber(); if (excess > 0) { length = new _bignumber.BigNumber(memory.length).minus(byte); } let existing = new Uint8Array(memory.buffer, byte.toNumber(), length.toNumber()); bytes.set(existing); return bytes; } /** * Split memory into chunks */ function chunk(memory, size = _utils.WORD_SIZE) { let chunks = []; for (let i = 0; i < memory.length; i += size) { let chunk = readBytes(memory, i, size); chunks.push(chunk); } return chunks; } /***/ }), /* 63 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _extends2 = __webpack_require__(3); var _extends3 = _interopRequireDefault(_extends2); exports.slotAddress = slotAddress; exports.read = read; exports.readRange = readRange; var _debug = __webpack_require__(0); var _debug2 = _interopRequireDefault(_debug); var _utils = __webpack_require__(11); var utils = _interopRequireWildcard(_utils); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {};if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } }newObj.default = obj;return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } const debug = (0, _debug2.default)("debugger:data:decode:storage"); /** * convert a slot to a word corresponding to actual storage address * * if `slot` is an array, return hash of array values. * if `slot` array is nested, recurse on sub-arrays * * @param slot - number or possibly-nested array of numbers */ function slotAddress(slot) { if (slot instanceof Array) { return utils.keccak256(...slot.map(slotAddress)); } else { return utils.toBigNumber(slot); } } /** * read slot from storage * * @param slot - big number or array of regular numbers * @param offset - for array, offset from the keccak determined location */ function read(storage, slot, offset = 0) { const address = slotAddress(slot).plus(offset); debug("reading slot: %o", utils.toHexString(address)); let word = storage[utils.toHexString(address, _utils.WORD_SIZE)] || new Uint8Array(_utils.WORD_SIZE); debug("word %o", word); return word; } /** * read all bytes in some range. * * parameters `from` and `to` are objects with the following properties: * * slot - (required) either a bignumber or a "path" array of integer offsets * * path array values get converted into keccak256 hash as per solidity * storage allocation method * * ref: https://solidity.readthedocs.io/en/v0.4.23/miscellaneous.html#layout-of-state-variables-in-storage * (search "concatenation") * * offset - (default: 0) slot offset * * index - (default: 0) byte index in word * * @param from - location (see ^) * @param to - location (see ^). inclusive. * @param length - instead of `to`, number of bytes after `from` */ function readRange(storage, { from, to, length }) { if (!length && !to || length && to) { throw new Error("must specify exactly one `to`|`length`"); } from = (0, _extends3.default)({}, from, { offset: from.offset || 0 }); if (length) { to = { slot: from.slot, offset: from.offset + Math.floor((from.index + length - 1) / _utils.WORD_SIZE), index: (from.index + length - 1) % _utils.WORD_SIZE }; } else { to = (0, _extends3.default)({}, to, { offset: to.offset || 0 }); } debug("readRange %o", { from, to }); const totalWords = to.offset - from.offset + 1; debug("totalWords %o", totalWords); let data = new Uint8Array(totalWords * _utils.WORD_SIZE); for (let i = 0; i < totalWords; i++) { let offset = i + from.offset; data.set(read(storage, from.slot, offset), i * _utils.WORD_SIZE); } debug("words %o", data); data = data.slice(from.index, (totalWords - 1) * _utils.WORD_SIZE + to.index + 1); debug("data: %o", data); return data; } /***/ }), /* 64 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.visit = visit; exports.doneVisiting = doneVisiting; const VISIT = exports.VISIT = "VISIT"; function visit(sourceId, ast) { return { type: VISIT, sourceId, ast }; } const DONE_VISITING = exports.DONE_VISITING = "DONE_VISITING"; function doneVisiting() { return { type: DONE_VISITING }; } /***/ }), /* 65 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _keys = __webpack_require__(17); var _keys2 = _interopRequireDefault(_keys); var _set = __webpack_require__(22); var _set2 = _interopRequireDefault(_set); exports.saga = saga; var _debug = __webpack_require__(0); var _debug2 = _interopRequireDefault(_debug); var _effects = __webpack_require__(10); var _helpers = __webpack_require__(5); var _sagas = __webpack_require__(32); var trace = _interopRequireWildcard(_sagas); var _actions = __webpack_require__(29); var actions = _interopRequireWildcard(_actions); var _selectors = __webpack_require__(66); var _selectors2 = _interopRequireDefault(_selectors); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {};if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } }newObj.default = obj;return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } const debug = (0, _debug2.default)("debugger:controller:sagas"); const CONTROL_SAGAS = { [actions.ADVANCE]: advance, [actions.STEP_NEXT]: stepNext, [actions.STEP_OVER]: stepOver, [actions.STEP_INTO]: stepInto, [actions.STEP_OUT]: stepOut, [actions.CONTINUE_UNTIL]: continueUntil }; /** AST node types that are skipped to filter out some noise */ const SKIPPED_TYPES = new _set2.default(["ContractDefinition", "VariableDeclaration"]); function* saga() { while (true) { debug("waiting for control action"); let action = yield (0, _effects.take)((0, _keys2.default)(CONTROL_SAGAS)); debug("got control action"); let saga = CONTROL_SAGAS[action.type]; yield (0, _effects.put)(actions.beginStep(action.type)); yield (0, _effects.race)({ exec: (0, _effects.call)(saga, action), interrupt: (0, _effects.take)(actions.INTERRUPT) }); } } exports.default = (0, _helpers.prefixName)("controller", saga); /** * Advance the state by one instruction */ function* advance() { // send action to advance trace yield* trace.advance(); } /** * stepNext - step to the next logical code segment * * Note: It might take multiple instructions to express the same section of code. * "Stepping", then, is stepping to the next logical item, not stepping to the next * instruction. See advance() if you'd like to advance by one instruction. */ function* stepNext() { const startingRange = yield (0, _effects.select)(_selectors2.default.current.location.sourceRange); var upcoming; do { // advance at least once step yield* advance(); // and check the next source range upcoming = yield (0, _effects.select)(_selectors2.default.current.location); // if the next step's source range is still the same, keep going } while (!upcoming.node || SKIPPED_TYPES.has(upcoming.node.nodeType) || upcoming.sourceRange.start == startingRange.start && upcoming.sourceRange.length == startingRange.length); } /** * stepInto - step into the current function * * Conceptually this is easy, but from a programming standpoint it's hard. * Code like `getBalance(msg.sender)` might be highlighted, but there could * be a number of different intermediate steps (like evaluating `msg.sender`) * before `getBalance` is stepped into. This function will step into the first * function available (where instruction.jump == "i"), ignoring any intermediate * steps that fall within the same code range. If there's a step encountered * that exists outside of the range, then stepInto will only execute until that * step. */ function* stepInto() { if (yield (0, _effects.select)(_selectors2.default.current.willJump)) { yield* stepNext(); return; } if (yield (0, _effects.select)(_selectors2.default.current.location.isMultiline)) { yield* stepOver(); return; } const startingDepth = yield (0, _effects.select)(_selectors2.default.current.functionDepth); const startingRange = yield (0, _effects.select)(_selectors2.default.current.location.sourceRange); var currentDepth; var currentRange; do { yield* stepNext(); currentDepth = yield (0, _effects.select)(_selectors2.default.current.functionDepth); currentRange = yield (0, _effects.select)(_selectors2.default.current.location.sourceRange); } while ( // the function stack has not increased, currentDepth <= startingDepth && // the current source range begins on or after the starting range currentRange.start >= startingRange.start && // and the current range ends on or before the starting range ends currentRange.start + currentRange.length <= startingRange.start + startingRange.length); } /** * Step out of the current function * * This will run until the debugger encounters a decrease in function depth. */ function* stepOut() { if (yield (0, _effects.select)(_selectors2.default.current.location.isMultiline)) { yield* stepOver(); return; } const startingDepth = yield (0, _effects.select)(_selectors2.default.current.functionDepth); var currentDepth; do { yield* stepNext(); currentDepth = yield (0, _effects.select)(_selectors2.default.current.functionDepth); } while (currentDepth >= startingDepth); } /** * stepOver - step over the current line * * Step over the current line. This will step to the next instruction that * exists on a different line of code within the same function depth. */ function* stepOver() { const startingDepth = yield (0, _effects.select)(_selectors2.default.current.functionDepth); const startingRange = yield (0, _effects.select)(_selectors2.default.current.location.sourceRange); var currentDepth; var currentRange; do { yield* stepNext(); currentDepth = yield (0, _effects.select)(_selectors2.default.current.functionDepth); currentRange = yield (0, _effects.select)(_selectors2.default.current.location.sourceRange); } while ( // keep stepping provided: // // we haven't jumped out !(currentDepth < startingDepth) && ( // either: function depth is greater than starting (ignore function calls) // or, if we're at the same depth, keep stepping until we're on a new // line. currentDepth > startingDepth || currentRange.lines.start.line == startingRange.lines.start.line)); } /** * continueUntil - step through execution until a breakpoint * * @param breakpoints - array of breakpoints ({ ...call, line }) */ function* continueUntil({ breakpoints }) { var currentCall; var currentLocation; let breakpointHit = false; do { yield* stepNext(); currentCall = yield (0, _effects.select)(_selectors2.default.current.executionContext); currentLocation = yield (0, _effects.select)(_selectors2.default.current.location); breakpointHit = breakpoints.filter(({ address, binary, line, node }) => (address == currentCall.address || binary == currentCall.binary) && (line == currentLocation.sourceRange.lines.start.line || node == currentLocation.node.id)).length > 0; } while (!breakpointHit); } /***/ }), /* 66 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _debug = __webpack_require__(0); var _debug2 = _interopRequireDefault(_debug); var _reselectTree = __webpack_require__(9); var _selectors = __webpack_require__(2); var _selectors2 = _interopRequireDefault(_selectors); var _selectors3 = __webpack_require__(6); var _selectors4 = _interopRequireDefault(_selectors3); var _selectors5 = __webpack_require__(14); var _selectors6 = _interopRequireDefault(_selectors5); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } const debug = (0, _debug2.default)("debugger:controller:sagas"); /** * @private */ const identity = x => x; /** * controller */ const controller = (0, _reselectTree.createSelectorTree)({ /** * controller.current */ current: { /** * controller.current.functionDepth */ functionDepth: (0, _reselectTree.createLeaf)([_selectors4.default.current.functionDepth], identity), /** * controller.current.executionContext */ executionContext: (0, _reselectTree.createLeaf)([_selectors2.default.current.call], identity), /** * controller.current.willJump */ willJump: (0, _reselectTree.createLeaf)([_selectors2.default.current.step.isJump], identity), /** * controller.current.location */ location: { /** * controller.current.location.sourceRange */ sourceRange: (0, _reselectTree.createLeaf)([_selectors4.default.current.sourceRange], identity), /** * controller.current.location.node */ node: (0, _reselectTree.createLeaf)([_selectors6.default.current.node], identity), /** * controller.current.location.isMultiline */ isMultiline: (0, _reselectTree.createLeaf)([_selectors4.default.current.isMultiline], identity) } } }); exports.default = controller; /***/ }), /* 67 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.addSource = addSource; exports.addSourceMap = addSourceMap; exports.saga = saga; var _debug = __webpack_require__(0); var _debug2 = _interopRequireDefault(_debug); var _effects = __webpack_require__(10); var _helpers = __webpack_require__(5); var _actions = __webpack_require__(33); var actions = _interopRequireWildcard(_actions); var _actions2 = __webpack_require__(21); var _selectors = __webpack_require__(6); var _selectors2 = _interopRequireDefault(_selectors); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {};if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } }newObj.default = obj;return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } const debug = (0, _debug2.default)("debugger:solidity:sagas"); function* addSource(source, sourcePath, ast) { yield (0, _effects.put)(actions.addSource(source, sourcePath, ast)); } function* addSourceMap(binary, sourceMap) { yield (0, _effects.put)(actions.addSourceMap(binary, sourceMap)); } function* functionDepthSaga() { while (true) { yield (0, _effects.take)(_actions2.TICK); debug("got TICK"); let instruction = yield (0, _effects.select)(_selectors2.default.current.instruction); debug("instruction: %o", instruction); if (yield (0, _effects.select)(_selectors2.default.current.willJump)) { let jumpDirection = yield (0, _effects.select)(_selectors2.default.current.jumpDirection); yield (0, _effects.put)(actions.jump(jumpDirection)); } } } function* saga() { yield (0, _effects.call)(functionDepthSaga); } exports.default = (0, _helpers.prefixName)("solidity", saga); /***/ }), /* 68 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.addContext = addContext; exports.addInstance = addInstance; exports.begin = begin; exports.callstackSaga = callstackSaga; exports.saga = saga; var _debug = __webpack_require__(0); var _debug2 = _interopRequireDefault(_debug); var _effects = __webpack_require__(10); var _helpers = __webpack_require__(5); var _actions = __webpack_require__(21); var _actions2 = __webpack_require__(34); var actions = _interopRequireWildcard(_actions2); var _selectors = __webpack_require__(2); var _selectors2 = _interopRequireDefault(_selectors); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {};if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } }newObj.default = obj;return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } const debug = (0, _debug2.default)("debugger:evm:sagas"); /** * Adds EVM bytecode context * * @return {string} ID (0x-prefixed keccak of binary) */ function* addContext(contractName, binary) { yield (0, _effects.put)(actions.addContext(contractName, binary)); return (0, _helpers.keccak256)(binary); } /** * Adds known deployed instance of binary at address * * @return {string} ID (0x-prefixed keccak of binary) */ function* addInstance(address, binary) { let search = yield (0, _effects.select)(_selectors2.default.info.binaries.search); if (binary != "0x0") { let { context } = search(binary); yield (0, _effects.put)(actions.addInstance(address, context, binary)); return context; } } function* begin({ address, binary }) { if (address) { yield (0, _effects.put)(actions.call(address)); } else { yield (0, _effects.put)(actions.create(binary)); } } function* callstackSaga() { while (true) { yield (0, _effects.take)(_actions.TICK); debug("got TICK"); if (yield (0, _effects.select)(_selectors2.default.current.step.isCall)) { debug("got call"); let address = yield (0, _effects.select)(_selectors2.default.current.step.callAddress); yield (0, _effects.put)(actions.call(address)); } else if (yield (0, _effects.select)(_selectors2.default.current.step.isCreate)) { debug("got create"); let binary = yield (0, _effects.select)(_selectors2.default.current.step.createBinary); yield (0, _effects.put)(actions.create(binary)); } else if (yield (0, _effects.select)(_selectors2.default.current.step.isHalting)) { debug("got return"); yield (0, _effects.put)(actions.returnCall()); } } } function* saga() { yield (0, _effects.call)(callstackSaga); } exports.default = (0, _helpers.prefixName)("evm", saga); /***/ }), /* 69 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.inspectTransaction = inspectTransaction; exports.obtainBinaries = obtainBinaries; exports.saga = saga; var _debug = __webpack_require__(0); var _debug2 = _interopRequireDefault(_debug); var _effects = __webpack_require__(10); var _helpers = __webpack_require__(5); var _actions = __webpack_require__(70); var actions = _interopRequireWildcard(_actions); var _adapter = __webpack_require__(71); var _adapter2 = _interopRequireDefault(_adapter); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {};if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } }newObj.default = obj;return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } const debug = (0, _debug2.default)("debugger:web3:sagas"); function* fetchTransactionInfo(adapter, { txHash }) { debug("inspecting transaction"); var trace; try { trace = yield (0, _effects.apply)(adapter, adapter.getTrace, [txHash]); } catch (e) { debug("putting error"); yield (0, _effects.put)(actions.error(e)); return; } debug("got trace"); yield (0, _effects.put)(actions.receiveTrace(trace)); let tx = yield (0, _effects.apply)(adapter, adapter.getTransaction, [txHash]); if (tx.to && tx.to != "0x0") { yield (0, _effects.put)(actions.receiveCall({ address: tx.to })); return; } let receipt = yield (0, _effects.apply)(adapter, adapter.getReceipt, [txHash]); if (receipt.contractAddress) { yield (0, _effects.put)(actions.receiveCall({ binary: tx.input })); return; } throw new Error("Could not find contract associated with transaction. " + "Please make sure you're debugging a transaction that executes a " + "contract function or creates a new contract."); } function* fetchBinary(adapter, { address }) { debug("fetching binary for %s", address); let binary = yield (0, _effects.apply)(adapter, adapter.getDeployedCode, [address]); debug("received binary for %s", address); yield (0, _effects.put)(actions.receiveBinary(address, binary)); } function* inspectTransaction(txHash, provider) { yield (0, _effects.put)(actions.init(provider)); yield (0, _effects.put)(actions.inspect(txHash)); let action = yield (0, _effects.take)(({ type }) => type == actions.RECEIVE_TRACE || type == actions.ERROR_WEB3); debug("action %o", action); var trace; if (action.type == actions.RECEIVE_TRACE) { trace = action.trace; debug("received trace"); } else { return { error: action.error }; } let { address, binary } = yield (0, _effects.take)(actions.RECEIVE_CALL); debug("received call"); return { trace, address, binary }; } function* obtainBinaries(addresses) { let tasks = yield (0, _effects.all)(addresses.map(address => (0, _effects.fork)(receiveBinary, address))); debug("requesting binaries"); yield (0, _effects.all)(addresses.map(address => (0, _effects.put)(actions.fetchBinary(address)))); let binaries = []; binaries = yield (0, _effects.all)(tasks.map(task => (0, _effects.join)(task))); debug("binaries %o", binaries); return binaries; } function* receiveBinary(address) { let { binary } = yield (0, _effects.take)(action => action.type == actions.RECEIVE_BINARY && action.address == address); debug("got binary for %s", address); return binary; } function* saga() { // wait for web3 init signal let { provider } = yield (0, _effects.take)(actions.INIT_WEB3); let adapter = new _adapter2.default(provider); yield (0, _effects.takeEvery)(actions.INSPECT, fetchTransactionInfo, adapter); yield (0, _effects.takeEvery)(actions.FETCH_BINARY, fetchBinary, adapter); } exports.default = (0, _helpers.prefixName)("web3", saga); /***/ }), /* 70 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.init = init; exports.inspect = inspect; exports.fetchBinary = fetchBinary; exports.receiveBinary = receiveBinary; exports.receiveTrace = receiveTrace; exports.receiveCall = receiveCall; exports.error = error; const INIT_WEB3 = exports.INIT_WEB3 = "INIT_WEB3"; function init(provider) { return { type: INIT_WEB3, provider }; } const INSPECT = exports.INSPECT = "INSPECT_TRANSACTION"; function inspect(txHash) { return { type: INSPECT, txHash }; } const FETCH_BINARY = exports.FETCH_BINARY = "FETCH_BINARY"; function fetchBinary(address) { return { type: FETCH_BINARY, address }; } const RECEIVE_BINARY = exports.RECEIVE_BINARY = "RECEIVE_BINARY"; function receiveBinary(address, binary) { return { type: RECEIVE_BINARY, address, binary }; } const RECEIVE_TRACE = exports.RECEIVE_TRACE = "RECEIVE_TRACE"; function receiveTrace(trace) { return { type: RECEIVE_TRACE, trace }; } const RECEIVE_CALL = exports.RECEIVE_CALL = "RECEIVE_CALL"; function receiveCall({ address, binary }) { return { type: RECEIVE_CALL, address, binary }; } const ERROR_WEB3 = exports.ERROR_WEB3 = "ERROR_WEB3"; function error(error) { return { type: ERROR_WEB3, error }; } /***/ }), /* 71 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _promise = __webpack_require__(23); var _promise2 = _interopRequireDefault(_promise); var _asyncToGenerator2 = __webpack_require__(7); var _asyncToGenerator3 = _interopRequireDefault(_asyncToGenerator2); var _debug = __webpack_require__(0); var _debug2 = _interopRequireDefault(_debug); var _web = __webpack_require__(8); var _web2 = _interopRequireDefault(_web); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } const debug = (0, _debug2.default)("debugger:web3:adapter"); class Web3Adapter { constructor(provider) { this.web3 = new _web2.default(provider); } getTrace(txHash) { var _this = this; return (0, _asyncToGenerator3.default)(function* () { return new _promise2.default(function (accept, reject) { _this.web3.currentProvider.send({ jsonrpc: "2.0", method: "debug_traceTransaction", params: [txHash, {}], id: new Date().getTime() }, function (err, result) { if (err) return reject(err); if (result.error) return reject(new Error(result.error.message)); debug("result: %o", result); accept(result.result.structLogs); }); }); })(); } getTransaction(txHash) { var _this2 = this; return (0, _asyncToGenerator3.default)(function* () { return new _promise2.default(function (accept, reject) { _this2.web3.eth.getTransaction(txHash, function (err, tx) { if (err) return reject(err); return accept(tx); }); }); })(); } getReceipt(txHash) { var _this3 = this; return (0, _asyncToGenerator3.default)(function* () { return new _promise2.default(function (accept, reject) { _this3.web3.eth.getTransactionReceipt(txHash, function (err, receipt) { if (err) return reject(err); return accept(receipt); }); }); })(); } /** * getDeployedCode - get the deployed code for an address from the client * @param {String} address * @return {String} deployedBinary */ getDeployedCode(address) { var _this4 = this; return (0, _asyncToGenerator3.default)(function* () { debug("getting deployed code for %s", address); return new _promise2.default(function (accept, reject) { _this4.web3.eth.getCode(address, function (err, deployedBinary) { if (err) debug("error: %o", err); if (err) return reject(err); debug("got deployed code for %s", address); accept(deployedBinary); }); }); })(); } } exports.default = Web3Adapter; /***/ }), /* 72 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.FINISHED = exports.ERROR = exports.ACTIVE = exports.WAITING = undefined; exports.session = session; var _redux = __webpack_require__(15); var _reducers = __webpack_require__(73); var _reducers2 = _interopRequireDefault(_reducers); var _reducers3 = __webpack_require__(74); var _reducers4 = _interopRequireDefault(_reducers3); var _reducers5 = __webpack_require__(76); var _reducers6 = _interopRequireDefault(_reducers5); var _reducers7 = __webpack_require__(77); var _reducers8 = _interopRequireDefault(_reducers7); var _actions = __webpack_require__(25); var actions = _interopRequireWildcard(_actions); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {};if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } }newObj.default = obj;return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } const WAITING = exports.WAITING = "WAITING"; const ACTIVE = exports.ACTIVE = "ACTIVE"; const ERROR = exports.ERROR = "ERROR"; const FINISHED = exports.FINISHED = "FINISHED"; function session(state = WAITING, action) { switch (action.type) { case actions.READY: return ACTIVE; case actions.ERROR: return { error: action.error }; case actions.FINISH: return FINISHED; default: return state; } } const reduceState = (0, _redux.combineReducers)({ session, data: _reducers2.default, evm: _reducers4.default, solidity: _reducers6.default, trace: _reducers8.default }); exports.default = reduceState; /***/ }), /* 73 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _entries = __webpack_require__(1); var _entries2 = _interopRequireDefault(_entries); var _assign = __webpack_require__(4); var _assign2 = _interopRequireDefault(_assign); var _extends2 = __webpack_require__(3); var _extends3 = _interopRequireDefault(_extends2); var _debug = __webpack_require__(0); var _debug2 = _interopRequireDefault(_debug); var _redux = __webpack_require__(15); var _actions = __webpack_require__(31); var actions = _interopRequireWildcard(_actions); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {};if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } }newObj.default = obj;return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } const debug = (0, _debug2.default)("debugger:data:reducers"); const DEFAULT_SCOPES = { byId: {} }; function scopes(state = DEFAULT_SCOPES, action) { var context; var scope; var variables; switch (action.type) { case actions.SCOPE: scope = state.byId[action.id] || {}; return { byId: (0, _extends3.default)({}, state.byId, { [action.id]: (0, _extends3.default)({}, scope, { id: action.id, sourceId: action.sourceId, parentId: action.parentId, pointer: action.pointer }) }) }; case actions.DECLARE: scope = state.byId[action.node.scope] || {}; variables = scope.variables || []; return { byId: (0, _extends3.default)({}, state.byId, { [action.node.scope]: (0, _extends3.default)({}, scope, { variables: [...variables, { name: action.node.name, id: action.node.id }] }) }) }; default: return state; } } const info = (0, _redux.combineReducers)({ scopes }); const DEFAULT_ASSIGNMENTS = { byId: {} }; function assignments(state = DEFAULT_ASSIGNMENTS, action) { switch (action.type) { case actions.ASSIGN: return { byId: (0, _extends3.default)({}, state.byId, (0, _assign2.default)({}, ...(0, _entries2.default)(action.assignments).map(([id, ref]) => ({ [id]: (0, _extends3.default)({}, state.byId[id], { ref }) })))) }; default: return state; } }; const proc = (0, _redux.combineReducers)({ assignments }); const reducer = (0, _redux.combineReducers)({ info, proc }); exports.default = reducer; /***/ }), /* 74 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _set = __webpack_require__(22); var _set2 = _interopRequireDefault(_set); var _from = __webpack_require__(75); var _from2 = _interopRequireDefault(_from); var _extends2 = __webpack_require__(3); var _extends3 = _interopRequireDefault(_extends2); exports.callstack = callstack; var _redux = __webpack_require__(15); var _actions = __webpack_require__(34); var actions = _interopRequireWildcard(_actions); var _helpers = __webpack_require__(5); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {};if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } }newObj.default = obj;return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } const DEFAULT_CONTEXTS = { byContext: {}, byBinary: {} }; function contexts(state = DEFAULT_CONTEXTS, action) { switch (action.type) { /* * Adding a new context */ case actions.ADD_CONTEXT: let { contractName, binary } = action; if (state.byBinary[binary]) { return state; } let context = (0, _helpers.keccak256)(binary); return { byContext: (0, _extends3.default)({}, state.byContext, { [context]: { context, binary, contractName } }), byBinary: (0, _extends3.default)({}, state.byBinary, { [binary]: { context: context } }) }; /* * Default case */ default: return state; } } const DEFAULT_INSTANCES = { byAddress: {}, byContext: {} }; function instances(state = DEFAULT_INSTANCES, action) { switch (action.type) { /* * Adding a new address for context */ case actions.ADD_INSTANCE: let { address, context, binary } = action; // get known addresses for this context let otherInstances = state.byContext[context] || []; let otherAddresses = otherInstances.map(({ address }) => address); return { byAddress: (0, _extends3.default)({}, state.byAddress, { [address]: { context, binary } }), byContext: (0, _extends3.default)({}, state.byContext, { // reconstruct context instances to include new address [context]: (0, _from2.default)(new _set2.default(otherAddresses).add(address)).map(address => ({ address })) }) }; /* * Default case */ default: return state; } } const info = (0, _redux.combineReducers)({ contexts, instances }); function callstack(state = [], action) { switch (action.type) { case actions.CALL: let address = action.address; return state.concat([{ address }]); case actions.CREATE: const binary = action.binary; return state.concat([{ binary }]); case actions.RETURN: return state.slice(0, -1); // pop default: return state; }; } const proc = (0, _redux.combineReducers)({ callstack }); const reducer = (0, _redux.combineReducers)({ info, proc }); exports.default = reducer; /***/ }), /* 75 */ /***/ (function(module, exports) { module.exports = require("babel-runtime/core-js/array/from"); /***/ }), /* 76 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _extends2 = __webpack_require__(3); var _extends3 = _interopRequireDefault(_extends2); var _keys = __webpack_require__(17); var _keys2 = _interopRequireDefault(_keys); exports.functionDepth = functionDepth; var _redux = __webpack_require__(15); var _helpers = __webpack_require__(5); var _actions = __webpack_require__(33); var actions = _interopRequireWildcard(_actions); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {};if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } }newObj.default = obj;return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } const DEFAULT_SOURCES = { byId: {} }; function sources(state = DEFAULT_SOURCES, action) { switch (action.type) { /* * Adding a new source */ case actions.ADD_SOURCE: let { ast, source, sourcePath } = action; let id = (0, _keys2.default)(state.byId).length; return { byId: (0, _extends3.default)({}, state.byId, { [id]: { id, ast, source, sourcePath } }) /* * Default case */ };default: return state; } } const DEFAULT_SOURCEMAPS = { byContext: {} }; function sourceMaps(state = DEFAULT_SOURCEMAPS, action) { switch (action.type) { /* * Adding a new sourceMap */ case actions.ADD_SOURCEMAP: let { binary, sourceMap } = action; let context = (0, _helpers.keccak256)(binary); return { byContext: (0, _extends3.default)({}, state.byContext, { [context]: { context, sourceMap } }) }; /* * Default Case */ default: return state; } } const info = (0, _redux.combineReducers)({ sources, sourceMaps }); function functionDepth(state = 1, action) { if (action.type === actions.JUMP) { const delta = spelunk(action.jumpDirection); return state + delta; } else { return state; } } function spelunk(jump) { if (jump == "i") { return 1; } else if (jump == "o") { return -1; } else { return 0; } } const proc = (0, _redux.combineReducers)({ functionDepth }); const reducer = (0, _redux.combineReducers)({ info, proc }); exports.default = reducer; /***/ }), /* 77 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.index = index; exports.steps = steps; var _redux = __webpack_require__(15); var _actions = __webpack_require__(21); var actions = _interopRequireWildcard(_actions); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {};if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } }newObj.default = obj;return newObj; } } function index(state = 0, action) { if (action.type == actions.TOCK || action.type == actions.END_OF_TRACE) { return state + 1; } else { return state; } } function steps(state = null, action) { if (action.type == actions.SAVE_STEPS) { return action.steps; } else { return state; } } const info = (0, _redux.combineReducers)({ steps }); const proc = (0, _redux.combineReducers)({ index }); const reducer = (0, _redux.combineReducers)({ info, proc }); exports.default = reducer; /***/ }), /* 78 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var _keys = __webpack_require__(17); var _keys2 = _interopRequireDefault(_keys); var _asyncToGenerator2 = __webpack_require__(7); var _asyncToGenerator3 = _interopRequireDefault(_asyncToGenerator2); var _debug = __webpack_require__(0); var _debug2 = _interopRequireDefault(_debug); var _chai = __webpack_require__(12); var _ganacheCli = __webpack_require__(16); var _ganacheCli2 = _interopRequireDefault(_ganacheCli); var _web = __webpack_require__(8); var _web2 = _interopRequireDefault(_web); var _helpers = __webpack_require__(13); var _debugger = __webpack_require__(18); var _debugger2 = _interopRequireDefault(_debugger); var _selectors = __webpack_require__(35); var _selectors2 = _interopRequireDefault(_selectors); var _selectors3 = __webpack_require__(19); var _selectors4 = _interopRequireDefault(_selectors3); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } const debug = (0, _debug2.default)("test:context"); const __OUTER = ` pragma solidity ^0.4.18; import "./InnerContract.sol"; contract OuterContract { event Outer(); InnerContract inner; function OuterContract(address _inner) public { inner = InnerContract(_inner); } function run() public { inner.run(); Outer(); } } `; const __INNER = ` pragma solidity ^0.4.18; contract InnerContract { event Inner(); function run() public { Inner(); } } `; const __MIGRATION = ` let OuterContract = artifacts.require("OuterContract"); let InnerContract = artifacts.require("InnerContract"); module.exports = function(deployer) { return deployer .then(function() { return deployer.deploy(InnerContract); }) .then(function() { return InnerContract.deployed(); }) .then(function(inner) { return deployer.deploy(OuterContract, inner.address); }); }; `; let migrations = { "2_deploy_contracts.js": __MIGRATION }; let sources = { "OuterLibrary.sol": __OUTER, "InnerContract.sol": __INNER }; describe("Contexts", function () { var provider; var web3; var abstractions; var artifacts; before("Create Provider", (0, _asyncToGenerator3.default)(function* () { provider = _ganacheCli2.default.provider({ seed: "debugger", gasLimit: 7000000 }); web3 = new _web2.default(provider); })); before("Prepare contracts and artifacts", (0, _asyncToGenerator3.default)(function* () { this.timeout(30000); let prepared = yield (0, _helpers.prepareContracts)(provider, sources, migrations); abstractions = prepared.abstractions; artifacts = prepared.artifacts; })); it("returns view of addresses affected", (0, _asyncToGenerator3.default)(function* () { let outer = yield abstractions.OuterContract.deployed(); let inner = yield abstractions.InnerContract.deployed(); // run outer contract method let result = yield outer.run(); _chai.assert.equal(2, result.receipt.logs.length, "There should be two logs"); let txHash = result.tx; let bugger = yield _debugger2.default.forTx(txHash, { provider, contracts: artifacts }); debug("debugger ready"); let session = bugger.connect(); let affectedInstances = session.view(_selectors2.default.info.affectedInstances); debug("affectedInstances: %o", affectedInstances); let affectedAddresses = (0, _keys2.default)(affectedInstances).map(function (address) { return address.toLowerCase(); }); _chai.assert.equal(2, affectedAddresses.length); _chai.assert.include(affectedAddresses, outer.address.toLowerCase(), "OuterContract should be an affected address"); _chai.assert.include(affectedAddresses, inner.address.toLowerCase(), "InnerContract should be an affected address"); })); }); /***/ }), /* 79 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var _entries = __webpack_require__(1); var _entries2 = _interopRequireDefault(_entries); var _stringify = __webpack_require__(80); var _stringify2 = _interopRequireDefault(_stringify); var _assign = __webpack_require__(4); var _assign2 = _interopRequireDefault(_assign); var _extends2 = __webpack_require__(3); var _extends3 = _interopRequireDefault(_extends2); var _debug = __webpack_require__(0); var _debug2 = _interopRequireDefault(_debug); var _faker = __webpack_require__(81); var _faker2 = _interopRequireDefault(_faker); var _selectors = __webpack_require__(2); var _selectors2 = _interopRequireDefault(_selectors); var _helpers = __webpack_require__(36); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } const debug = (0, _debug2.default)("test:data:decode"); const uints = (0, _helpers.generateUints)(); function generateArray(length) { return [...Array(length)].map(() => uints.next().value); } const commonFixtures = [{ name: "multipleFullWordArray", type: "uint[]", value: generateArray(3) // takes up 3 whole words }, { name: "withinWordArray", type: "uint16[]", value: generateArray(10) // takes up >1/2 word }, { name: "multiplePartWordArray", type: "uint64[]", value: generateArray(9) // takes up 2.25 words }, { name: "inconvenientlyWordOffsetArray", type: "uint240[]", value: generateArray(3) // takes up ~2.8 words }, { name: "shortString", type: "string", value: "hello world" }, { name: "longString", type: "string", value: "solidity allocation is a fun lesson in endianness" }]; const mappingFixtures = [{ // name: "simpleMapping", // type: { // from: "uint256", // to: "uint256" // }, // value: { // ...Object.assign({}, ...generateArray(5).map( // (value, idx) => ({ [idx]: value }) // )) // } // }, { // name: "numberedStrings", // type: { // from: "uint256", // to: "string" // }, // value: { // ...Object.assign({}, ...generateArray(7).map( // (value, idx) => ({ [value]: faker.lorem.slug(idx) }) // )) // } // }, { name: "stringsToStrings", type: { from: "string", to: "string" }, value: (0, _extends3.default)({}, (0, _assign2.default)({}, ...[0, 1, 2, 3, 4].map(idx => ({ [_faker2.default.lorem.slug(idx)]: _faker2.default.lorem.slug(idx) })))) }]; debug("mappingFixtures %O", mappingFixtures); describe("Decoding", function () { /* * Storage Tests */ (0, _helpers.describeDecoding)("Storage Variables", commonFixtures, _selectors2.default.current.state.storage, (contractName, fixtures) => { return `pragma solidity ^0.4.23; contract ${contractName} { event Done(); // declarations ${fixtures.map(({ type, name }) => `${type} ${name};`).join("\n ")} function run() public { ${fixtures.map(({ name, value }) => `${name} = ${(0, _stringify2.default)(value)};`).join("\n ")} emit Done(); } } `; }); (0, _helpers.describeDecoding)("Mapping Variables", mappingFixtures, _selectors2.default.current.state.storage, (contractName, fixtures) => { return `pragma solidity ^0.4.24; contract ${contractName} { event Done(); // declarations ${fixtures.map(({ name, type: { from, to } }) => `mapping (${from} => ${to}) ${name};`).join("\n ")} function run() public { ${fixtures.map(({ name, type: { from }, value }) => (0, _entries2.default)(value).map(([k, v]) => from === "string" ? `${name}["${k}"] = ${(0, _stringify2.default)(v)};` : `${name}[${k}] = ${(0, _stringify2.default)(v)};`).join("\n ")).join("\n\n ")} emit Done(); } } `; }); /* * Memory Tests */ (0, _helpers.describeDecoding)("Memory Variables", commonFixtures, _selectors2.default.current.state.memory, (contractName, fixtures) => { const separator = ";\n "; function declareAssign({ name, type, value }) { if (type.indexOf("[]") != -1) { // array, must `new` let declare = `${type} memory ${name} = new ${type}(${value.length})`; let assigns = value.map((k, i) => `${name}[${i}] = ${k}`); return `${declare}${separator}${assigns.join(separator)}`; } else { return `${type} memory ${name} = ${(0, _stringify2.default)(value)}`; } } return `pragma solidity ^0.4.23; contract ${contractName} { event Done(); function run() public { uint i; // declarations ${fixtures.map(declareAssign).join(separator)}; emit Done(); } } `; }); }); /***/ }), /* 80 */ /***/ (function(module, exports) { module.exports = require("babel-runtime/core-js/json/stringify"); /***/ }), /* 81 */ /***/ (function(module, exports) { module.exports = require("faker"); /***/ }), /* 82 */ /***/ (function(module, exports) { module.exports = require("change-case"); /***/ }), /* 83 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var _debug = __webpack_require__(0); var _debug2 = _interopRequireDefault(_debug); var _chai = __webpack_require__(12); var _bignumber = __webpack_require__(20); var _utils = __webpack_require__(11); var utils = _interopRequireWildcard(_utils); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } const debug = (0, _debug2.default)("test:data:decode:utils"); describe("Utils", function () { describe("typeClass()", function () { it("handles mappings", function () { let definition = { typeDescriptions: { typeIdentifier: "t_mapping$_t_uint256_$_t_uint256_$" } }; _chai.assert.equal(utils.typeClass(definition), "mapping"); }); }); describe("toBigNumber()", function () { it("returns correct value", function () { let bytes = [0xf5, 0xe2, 0xc5, 0x17]; let expectedValue = new _bignumber.BigNumber("f5e2c517", 16); let result = utils.toBigNumber(bytes); _chai.assert.equal(result.toString(), expectedValue.toString()); }); }); describe("toSignedBigNumber()", function () { it("returns correct negative value", function () { let bytes = [0xf5, 0xe2, 0xc5, 0x17]; // starts with 0b1 let raw = new _bignumber.BigNumber("f5e2c517", 16); let bitfipped = new _bignumber.BigNumber(raw.toString(2).replace(/0/g, "x").replace(/1/g, "0").replace(/x/g, "1"), 2); let expectedValue = bitfipped.plus(1).negated(); let result = utils.toSignedBigNumber(bytes); _chai.assert.equal(result.toString(), expectedValue.toString()); }); it("returns correct positive value", function () { let bytes = [0x05, 0xe2, 0xc5, 0x17]; // starts with 0b0 let raw = new _bignumber.BigNumber("05e2c517", 16); let expectedValue = raw; let result = utils.toSignedBigNumber(bytes); _chai.assert.equal(result.toString(), expectedValue.toString()); }); }); describe("toHexString()", function () { it("returns correct representation with full bytes", function () { // ie, 0x00 instead of 0x0 _chai.assert.equal(utils.toHexString([0x05, 0x11]), "0x0511"); _chai.assert.equal(utils.toHexString([0xff, 0x00, 0xff]), "0xff00ff"); }); it("allows removing leading zeroes", function () { _chai.assert.equal(utils.toHexString([0x00, 0x00, 0xcc], true), "0xcc"); }); }); }); /***/ }), /* 84 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var _asyncToGenerator2 = __webpack_require__(7); var _asyncToGenerator3 = _interopRequireDefault(_asyncToGenerator2); var _debug = __webpack_require__(0); var _debug2 = _interopRequireDefault(_debug); var _chai = __webpack_require__(12); var _ganacheCli = __webpack_require__(16); var _ganacheCli2 = _interopRequireDefault(_ganacheCli); var _web = __webpack_require__(8); var _web2 = _interopRequireDefault(_web); var _helpers = __webpack_require__(13); var _debugger = __webpack_require__(18); var _debugger2 = _interopRequireDefault(_debugger); var _selectors = __webpack_require__(2); var _selectors2 = _interopRequireDefault(_selectors); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } const debug = (0, _debug2.default)("test:solidity"); const __OUTER = ` pragma solidity ^0.4.18; import "./Inner.sol"; contract Outer { event Called(); Inner inner; function Outer(address _inner) { inner = Inner(_inner); } function runSingle() public { } function run() public { inner.run(); } } `; const __INNER = ` pragma solidity ^0.4.18; contract Inner { function run() public { } } `; const __MIGRATION = ` let Outer = artifacts.require("Outer"); let Inner = artifacts.require("Inner"); module.exports = function(deployer) { return deployer .then(function() { return deployer.deploy(Inner); }) .then(function() { return Inner.deployed(); }) .then(function(inner) { return deployer.deploy(Outer, inner.address); }); }; `; let sources = { "Inner.sol": __INNER, "Outer.sol": __OUTER }; let migrations = { "2_deploy_contracts.js": __MIGRATION }; describe("EVM Debugging", function () { var provider; var web3; var abstractions; var artifacts; var files; before("Create Provider", (0, _asyncToGenerator3.default)(function* () { provider = _ganacheCli2.default.provider({ seed: "debugger", gasLimit: 7000000 }); web3 = new _web2.default(provider); })); before("Prepare contracts and artifacts", (0, _asyncToGenerator3.default)(function* () { this.timeout(30000); let prepared = yield (0, _helpers.prepareContracts)(provider, sources, migrations); abstractions = prepared.abstractions; artifacts = prepared.artifacts; files = prepared.files; })); describe("Function Depth", function () { it("remains at 1 in absence of cross-contract calls", (0, _asyncToGenerator3.default)(function* () { const maxExpected = 1; let instance = yield abstractions.Inner.deployed(); let receipt = yield instance.run(); let txHash = receipt.tx; let bugger = yield _debugger2.default.forTx(txHash, { provider, files, contracts: artifacts }); let session = bugger.connect(); var stepped; // session steppers return false when done do { stepped = session.stepNext(); let actual = session.view(_selectors2.default.current.callstack).length; _chai.assert.isAtMost(actual, maxExpected); } while (stepped); })); it("tracks callstack correctly", (0, _asyncToGenerator3.default)(function* () { // prepare let instance = yield abstractions.Outer.deployed(); let receipt = yield instance.run(); let txHash = receipt.tx; let bugger = yield _debugger2.default.forTx(txHash, { provider, files, contracts: artifacts }); let session = bugger.connect(); // follow callstack length values in list // see source above let expectedDepthSequence = [1, 2, 1, 0]; let actualSequence = [session.view(_selectors2.default.current.callstack).length]; var stepped; do { stepped = session.stepNext(); let currentDepth = session.view(_selectors2.default.current.callstack).length; let lastKnown = actualSequence[actualSequence.length - 1]; if (currentDepth !== lastKnown) { actualSequence.push(currentDepth); } } while (stepped); _chai.assert.deepEqual(actualSequence, expectedDepthSequence); })); }); }); /***/ }), /* 85 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var _asyncToGenerator2 = __webpack_require__(7); var _asyncToGenerator3 = _interopRequireDefault(_asyncToGenerator2); var _debug = __webpack_require__(0); var _debug2 = _interopRequireDefault(_debug); var _chai = __webpack_require__(12); var _ganacheCli = __webpack_require__(16); var _ganacheCli2 = _interopRequireDefault(_ganacheCli); var _web = __webpack_require__(8); var _web2 = _interopRequireDefault(_web); var _helpers = __webpack_require__(13); var _debugger = __webpack_require__(18); var _debugger2 = _interopRequireDefault(_debugger); var _selectors = __webpack_require__(6); var _selectors2 = _interopRequireDefault(_selectors); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } const debug = (0, _debug2.default)("test:solidity"); const __SINGLE_CALL = ` pragma solidity ^0.4.18; contract SingleCall { event Called(); function run() public { Called(); } } `; const __NESTED_CALL = `pragma solidity ^0.4.18; contract NestedCall { event First(); event Second(); // run() // first() 1 // inner() 2 // event 3 // 2 // second 1 // event 2 // 1 function run() public { first(); second(); } function first() public { inner(); } function inner() public { First(); } function second() public { Second(); } } `; let sources = { "SingleCall.sol": __SINGLE_CALL, "NestedCall.sol": __NESTED_CALL }; describe("Solidity Debugging", function () { var provider; var web3; var abstractions; var artifacts; var files; before("Create Provider", (0, _asyncToGenerator3.default)(function* () { provider = _ganacheCli2.default.provider({ seed: "debugger", gasLimit: 7000000 }); web3 = new _web2.default(provider); })); before("Prepare contracts and artifacts", (0, _asyncToGenerator3.default)(function* () { this.timeout(30000); let prepared = yield (0, _helpers.prepareContracts)(provider, sources); abstractions = prepared.abstractions; artifacts = prepared.artifacts; files = prepared.files; })); it("exposes functionality to stop at breakpoints", (0, _asyncToGenerator3.default)(function* () { // prepare let instance = yield abstractions.NestedCall.deployed(); let receipt = yield instance.run(); let txHash = receipt.tx; let bugger = yield _debugger2.default.forTx(txHash, { provider, files, contracts: artifacts }); let session = bugger.connect(); // at `second();` let breakpoint = { "address": instance.address, line: 16 }; let breakpointStopped = false; do { session.continueUntil(breakpoint); if (!session.finished) { let range = yield session.view(_selectors2.default.current.sourceRange); _chai.assert.equal(range.lines.start.line, 16); breakpointStopped = true; } } while (!session.finished); })); describe("Function Depth", function () { it("remains at 1 in absence of inner function calls", (0, _asyncToGenerator3.default)(function* () { const maxExpected = 1; let instance = yield abstractions.SingleCall.deployed(); let receipt = yield instance.run(); let txHash = receipt.tx; let bugger = yield _debugger2.default.forTx(txHash, { provider, files, contracts: artifacts }); let session = bugger.connect(); var stepped; // session steppers return false when done do { stepped = session.stepNext(); let actual = session.view(_selectors2.default.current.functionDepth); _chai.assert.isAtMost(actual, maxExpected); } while (stepped); })); it("spelunks correctly", (0, _asyncToGenerator3.default)(function* () { // prepare let instance = yield abstractions.NestedCall.deployed(); let receipt = yield instance.run(); let txHash = receipt.tx; let bugger = yield _debugger2.default.forTx(txHash, { provider, files, contracts: artifacts }); let session = bugger.connect(); // follow functionDepth values in list // see source above let expectedDepthSequence = [1, 2, 3, 2, 1, 2, 1, 0]; let actualSequence = [session.view(_selectors2.default.current.functionDepth)]; var stepped; do { stepped = session.stepNext(); let currentDepth = session.view(_selectors2.default.current.functionDepth); let lastKnown = actualSequence[actualSequence.length - 1]; if (currentDepth !== lastKnown) { actualSequence.push(currentDepth); } } while (stepped); _chai.assert.deepEqual(actualSequence, expectedDepthSequence); })); }); }); /***/ }) /******/ ]); }); //# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIj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O1xuICAgICAgICBpZiAoYWRkcmVzcykge1xuICAgICAgICAgIHJlY29yZCA9IGluc3RhbmNlc1thZGRyZXNzXTtcbiAgICAgICAgICBiaW5hcnkgPSByZWNvcmQuYmluYXJ5XG4gICAgICAgIH0gZWxzZSB7XG4gICAgICAgICAgcmVjb3JkID0gc2VhcmNoKGJpbmFyeSk7XG4gICAgICAgIH1cblxuICAgICAgICBsZXQgY29udGV4dCA9IGNvbnRleHRzWyhyZWNvcmQgfHwge30pLmNvbnRleHRdO1xuXG4gICAgICAgIHJldHVybiB7XG4gICAgICAgICAgLi4uY29udGV4dCxcbiAgICAgICAgICBiaW5hcnlcbiAgICAgICAgfVxuICAgICAgfVxuICAgICksXG5cbiAgICAvKipcbiAgICAgKiBldm0uY3VycmVudC5zdGF0ZVxuICAgICAqXG4gICAgICogZXZtIHN0YXRlIGluZm86IGFzIG9mIGxhc3Qgb3BlcmF0aW9uLCBiZWZvcmUgb3AgZGVmaW5lZCBpbiBzdGVwXG4gICAgICovXG4gICAgc3RhdGU6IE9iamVjdC5hc3NpZ24oe30sIC4uLihcbiAgICAgIFtcbiAgICAgICAgXCJkZXB0aFwiLFxuICAgICAgICBcImVycm9yXCIsXG4gICAgICAgIFwiZ2FzXCIsXG4gICAgICAgIFwibWVtb3J5XCIsXG4gICAgICAgIFwic3RhY2tcIixcbiAgICAgICAgXCJzdG9yYWdlXCJcbiAgICAgIF0ubWFwKCAocGFyYW0pID0+ICh7XG4gICAgICAgIFtwYXJhbV06IGNyZWF0ZUxlYWYoW3RyYWNlLnN0ZXBdLCAoc3RlcCkgPT4gc3RlcFtwYXJhbV0pXG4gICAgICB9KSlcbiAgICApKSxcblxuICAgIC8qKlxuICAgICAqIGV2bS5jdXJyZW50LnN0ZXBcbiAgICAgKi9cbiAgICBzdGVwOiBjcmVhdGVTdGVwU2VsZWN0b3JzKHRyYWNlLnN0ZXAsIFwiLi9zdGF0ZVwiKVxuICB9LFxuXG4gIC8qKlxuICAgKiBldm0ubmV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5kQ29sdW1uTWFwcGluZ1tzdGFydF0gfHxcbiAgICAgICAgICAgICAgICB7IGxpbmU6IG51bGwsIGNvbHVtbjogbnVsbCB9LFxuICAgICAgICAgICAgICBlbmQ6IGxpbmVBbmRDb2x1bW5NYXBwaW5nW3N0YXJ0ICsgbGVuZ3RoXSB8fFxuICAgICAgICAgICAgICAgIHsgbGluZTogbnVsbCwgY29sdW1uOiBudWxsIH1cbiAgICAgICAgICAgIH07XG5cbiAgICAgICAgICAgIGlmIChyYW5nZS5zdGFydC5saW5lID09PSBudWxsKSB7XG4gICAgICAgICAgICAgIGRlYnVnKFwic291cmNlTWFwICVvXCIsIHNvdXJjZU1hcCk7XG4gICAgICAgICAgICB9XG5cbiAgICAgICAgICAgIHJldHVybiB7XG4gICAgICAgICAgICAgIC4uLmluc3RydWN0aW9uLFxuXG4gICAgICAgICAgICAgIGp1bXAsXG4gICAgICAgICAgICAgIHN0YXJ0LFxuICAgICAgICAgICAgICBsZW5ndGgsXG4gICAgICAgICAgICAgIGZpbGUsXG4gICAgICAgICAgICAgIHJhbmdlXG4gICAgICAgICAgICB9XG4gICAgICAgICAgfSk7XG4gICAgICB9XG4gICAgKSxcblxuICAgIC8qKlxuICAgICAqIHNvbGlkaXR5LmN1cnJlbnQuaW5zdHJ1Y3Rpb25BdFByb2dyYW1Db3VudGVyXG4gICAgICovXG4gICAgaW5zdHJ1Y3Rpb25BdFByb2dyYW1Db3VudGVyOiBjcmVhdGVMZWFmKFxuICAgICAgW1wiLi9pbnN0cnVjdGlvbnNcIl0sXG5cbiAgICAgIChpbnN0cnVjdGlvbnMpID0+IHtcbiAgICAgICAgbGV0IG1hcCA9IFtdO1xuICAgICAgICBpbnN0cnVjdGlvbnMuZm9yRWFjaChmdW5jdGlvbihpbnN0cnVjdGlvbikge1xuICAgICAgICAgIG1hcFtpbnN0cnVjdGlvbi5wY10gPSBpbnN0cnVjdGlvbjtcbiAgICAgICAgfSk7XG5cbiAgICAgICAgLy8gZmlsbCBpb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cmNlUmFuZ2UpLFxuXG4gICAgLyoqXG4gICAgICogc29saWRpdHkuY3VycmVudC5pc1NvdXJjZVJhbmdlRmluYWxcbiAgICAgKi9cbiAgICBpc1NvdXJjZVJhbmdlRmluYWw6IGNyZWF0ZUxlYWYoXG4gICAgICBbXG4gICAgICAgIFwiLi9pbnN0cnVjdGlvbkF0UHJvZ3JhbUNvdW50ZXJcIixcbiAgICAgICAgZXZtLmN1cnJlbnQuc3RlcC5wcm9ncmFtQ291bnRlcixcbiAgICAgICAgZXZtLm5leHQuc3RlcC5wcm9ncmFtQ291bnRlclxuICAgICAgXSxcblxuICAgICAgKG1hcCwgY3VycmVudCwgbmV4dCkgPT4ge1xuICAgICAgICBpZiAoIW1hcFtuZXh0XSkge1xuICAgICAgICAgIHJldHVybiB0cnVlO1xuICAgICAgICB9XG5cbiAgICAgICAgY3VycmVudCA9IG1hcFtjdXJyZW50XTtcbiAgICAgICAgbmV4dCA9IG1hcFtuZXh0XTtcblxuICAgICAgICByZXR1cm4gKFxuICAgICAgICAgIGN1cnJlbnQuc3RhcnQgIT0gbmV4dC5zdGFydCB8fFxuICAgICAgICAgIGN1cnJlbnQubGVuZ3RoICE9IG5leHQubGVuZ3RoIHx8XG4gICAgICAgICAgY3VycmVudC5maWxlICE9IG5leHQuZmlsZVxuICAgICAgICApO1xuICAgICAgfVxuICAgICksXG5cbiAgICAvKipcbiAgICAgKiBzb2xpZGl0eS5jdXJyZW50LmlzTXVsdGlsaW5lXG4gICAgICovXG4gICAgaXNNdWx0aWxpbmU6IGNyZWF0ZUxlYWYoXG4gICAgICBbXCIuL3NvdXJjZVJhbmdlXCJdLFxuXG4gICAgICAoIHtsaW5lc30gKSA9PiBsaW5lcy5zdGFydC5saW5lICE9IGxpbmVzLmVuZC5saW5lXG4gICAgKSxcblxuICAgIC8qKlxuICAgICAqIHNvbGlkaXR5LmN1cnJlbnQud2lsbEp1bXBcbiAgICAgKi9cbiAgICB3aWxsSnVtcDogY3JlYXRlTGVhZ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iAgICAgIGlubGluZWQ6IGNyZWF0ZUxlYWYoXG4gICAgICAgIFtcIi9pbmZvL3Njb3Blc1wiLCBzb2xpZGl0eS5pbmZvLnNvdXJjZXNdLFxuXG4gICAgICAgIChzY29wZXMsIHNvdXJjZXMpID0+IE9iamVjdC5hc3NpZ24oe30sXG4gICAgICAgICAgLi4uT2JqZWN0LmVudHJpZXMoc2NvcGVzKS5tYXAoXG4gICAgICAgICAgICAoW2lkLCBlbnRyeV0pID0+ICh7XG4gICAgICAgICAgICAgIFtpZF06IHtcbiAgICAgICAgICAgICAgICAuLi5lbnRyeSxcblxuICAgICAgICAgICAgICAgIGRlZmluaXRpb246IGpzb25wb2ludGVyLmdldChcbiAgICAgICAgICAgICAgICAgIHNvdXJjZXNbZW50cnkuc291cmNlSWRdLmFzdCwgZW50cnkucG9pbnRlclxuICAgICAgICAgICAgICAgIClcbiAgICAgICAgICAgICAgfVxuICAgICAgICAgICAgfSlcbiAgICAgICAgICApXG4gICAgICAgIClcbiAgICAgIClcbiAgICB9LFxuXG4gICAgLyoqXG4gICAgICogZGF0YS52aWV3cy5kZWNvZGVyXG4gICAgICpcbiAgICAgKiBzZWxlY3RvciByZXR1cm5zIChhc3Qgbm9kZSBkZWZpbml0aW9uLCBkYXRhIHJlZmVyZW5jZSkgPT4gdmFsdWVcbiAgICAgKi9cbiAgICBkZWNvZGVyOiBjcmVhdGVMZWFmKFxuICAgICAgW1wiL3ZpZXdzL3Njb3Blcy9pbmxpbmVkXCIsIFwiL25leHQvc3RhdGVcIl0sXG5cbiAgICAgIChzY29wZXMsIHN0YXRlKSA9PiB7XG4gICAgICAgIHJldHVybiAoZGVmaW5pdGlvbiwgcmVmKSA9PiBkZWNvZGUoZGVmaW5pdGlvbiwgcmVmLCBzdGF0ZSwgc2NvcGVzKVxuICAgICAgfVxuICAgIClcbiAgfSxcblxuICAvKipcbiAgICogZGF0YS5pbmZvXG4gICAqL1xuICBpbmZvOiB7XG5cbiAgICAvKipcbiAgICAgKi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IGNvcnJlc3BvbmRpbmcgZGVmaW5pdGlvbiBub2RlIElEXG4gICAgICAgKi9cbiAgICAgIF86IGNyZWF0ZUxlYWYoXG4gICAgICAgIFtcbiAgICAgICAgICBcIi92aWV3cy9zY29wZXMvaW5saW5lZFwiLFxuICAgICAgICAgIFwiL2N1cnJlbnQvc2NvcGVcIixcbiAgICAgICAgXSxcblxuICAgICAgICAoc2NvcGVzLCBzY29wZSkgPT4ge1xuICAgICAgICAgIGxldCBjdXIgPSBzY29wZS5pZDtcbiAgICAgICAgICBsZXQgdmFyaWFibGVzID0ge307XG5cbiAgICAgICAgICBkbyB7XG4gICAgICAgICAgICB2YXJpYWJsZXMgPSBPYmplY3QuYXNzaWduKFxuICAgICAgICAgICAgICB2YXJpYWJsZXMsXG4gICAgICAgICAgICAgIC4uLihzY29wZXNbY3VyXS52YXJpYWJsZXMgfHwgW10pXG4gICAgICAgICAgICAgICAgLmZpbHRlciggKHYpID0+IHZhcmlhYmxlc1t2Lm5hbWVdID09IHVuZGVmaW5lZCApXG4gICAgICAgICAgICAgICAgLm1hcCggKHYpID0+ICh7IFt2Lm5hbWVdOiB2LmlkIH0pIClcbiAgICAgICAgICAgICk7XG5cbiAgICAgICAgICAgIGN1ciA9IHNjb3Blc1tjdXJdLnBhcmVudElkO1xuICAgICAgICAgIH0gd2hpbGUgKGN1ciAhPSBudWxsKTtcblxuICAgICAgICAgIHJldHVybiB2YXJpYWJsZXM7XG4gICAgICAgIH1cbiAgICAgICksXG5cbiAgICAgIC8qKlxuICAgICAgICogZGF0YS5jdXJyZW50LmlkZW50aWZpZXJzLmRlZmluaXRpb25zXG4gICAgICAgKlxuICAgICAgICogY3VycmVudCB2YXJpYWJsZSBkZWZpbml0aW9uc1xuICAgICAgICovXG4gICAgICBkZWZpbml0aW9uczogY3JlYXRlTGVhZihcbiAgICAgICAgW1xuICAgICAgICAgIFwiL3ZpZXdzL3Njb3Blcy9pbmxpbmVkXCIsXG4gICAgICAgICAgXCIuL19cIlxuICAgICAgICBdLFxuXG4gICAgICAgIChzY29wZXMsIGlkZW50aWZpZXJzKSA9PiBPYmplY3QuYXNzaWduKHt9LFxuICAgICAgICAgIC4uLk9iamVjdC5lbnRyaWVzKGlkZW50aWZpZXJzKVxuICAgICAgICAgICAgLm1hcCggKFtpZGVudGlmaWVyLCBpZF0pID0+IHtcbiAgICAgICAgICAgICAgbGV0IHsgZGVmaW5pdGlvbiB9ID0gc2NvcGVzW2lkXTtcblxuICAgICAgICAgICAgICByZXR1cm4geyBbaWRlbnRpZmllcl06IGRlZmluaXRpb24gfTtcbiAgICAgICAgICAgIH0pXG4gICAgICAgIClcbiAgICAgICksXG5cbiAgICAgIC8qKlxuICAgICAgICogZGF0YS5jdXJyZW50LmlkZW50aWZpZXJzLnJlZnNcbiAgICAgICAqXG4gICAgICAgKiBjdXJyZW50IHZhcmlhYmxlcycgdmFsdWUgcmVmc1xuICAgICAgICovXG4gICAgICByZWZzOiBjcmVhdGVMZWFmKFxuICAgICAgICBbXG4gICAgICAgICAgXCIvcHJvYy9hc3NpZ25tZW50c1wiLFxuICAgICAgICAgIFwiLi9fXCJcbiAgICAgICAgXSxcblxuICAgICAgICAoYXNzaWdubWVudHMsIGlkZW50aWZpZXJzKSA9PiBPYmplY3QuYXNzaWduKHt9LFxuICAgICAgICAgIC4uLk9iamVjdC5lbnRyaWVzKGlkZW50aWZpZXJzKVxuICAgICAgICAgICAgLm1hcCggKFtpZGVudGlmaWVyLCBpZF0pID0+IHtcbiAgICAgICAgICAgICAgbGV0IHsgcmVmIH0gPSAoYXNzaWdubWVudHNbaWRdIHx8IHt9KVxuICAgICAgICAgICAgICBpZiAoIXJlZikgeyByZXR1cm4gdW5kZWZpbmVkIH07XG5cbiAgICAgICAgICAgICAgcmV0dXJuIHtcbiAgICAgICAgICAgICAgICBbaWRlbnRpZmllcl06IHJlZlxuICAgICAgICAgICAgICB9O1xuICAgICAgICAgICAgfSlcbiAgICAgICAgKVxuICAgICAgKSxcblxuICAgICAg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ubWVudHNbaW5kZXhJZF0gfHwge30pLnJlZjtcbiAgICAgIGNvbnN0IGluZGV4VmFsdWUgPSAoaW5kZXhBc3NpZ25tZW50KVxuICAgICAgICA/IGRlY29kZShub2RlLmluZGV4RXhwcmVzc2lvbiwgaW5kZXhBc3NpZ25tZW50KVxuICAgICAgICA6IHV0aWxzLnRvQmlnTnVtYmVyKG5vZGUuaW5kZXhFeHByZXNzaW9uLmhleFZhbHVlKTtcblxuICAgICAgZGVidWcoXCJpbmRleCB2YWx1ZSAlT1wiLCBpbmRleFZhbHVlKTtcbiAgICAgIGlmIChpbmRleFZhbHVlID09IHVuZGVmaW5lZCkge1xuICAgICAgICBicmVhaztcbiAgICAgIH1cblxuICAgICAgYXNzaWdubWVudHMgPSB7XG4gICAgICAgIFtiYXNlRGVjbGFyYXRpb25JZF06IHtcbiAgICAgICAgICAuLi5iYXNlQXNzaWdubWVudCxcbiAgICAgICAgICBrZXlzOiBbXG4gICAgICAgICAgICAuLi5uZXcgU2V0KFtcbiAgICAgICAgICAgICAgLi4uKGJhc2VBc3NpZ25tZW50LmtleXMgfHwgW10pLFxuICAgICAgICAgICAgICBpbmRleFZhbHVlXG4gICAgICAgICAgICBdKVxuICAgICAgICAgIF1cbiAgICAgICAgfVxuICAgICAgfVxuXG4gICAgICBkZWJ1ZyhcIm1hcHBpbmcgYXNzaWdubWVudHMgJU9cIiwgYXNzaWdubWVudHMpO1xuICAgICAgeWllbGQgcHV0KGFjdGlvbnMuYXNzaWduKHRyZWVJZCwgYXNzaWdubWVudHMpKTtcbiAgICAgIGRlYnVnKFwibmV3IGFzc2lnbm1lbnRzICVPXCIsIHlpZWxkIHNlbGVjdChkYXRhLnByb2MuYXNzaWdubWVudHMpKTtcbiAgICAgIGJyZWFrO1xuXG4gICAgY2FzZSBcIkFzc2lnbm1lbnRcIjpcbiAgICAgIGJyZWFrO1xuXG5cbiAgICBkZWZhdWx0OlxuICAgICAgaWYgKG5vZGUudHlwZURlc2NyaXB0aW9ucy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xuICAgICAgICAuLi5PYmplY3QuZW50cmllcyhpbnN0YW5jZXMpLm1hcChcbiAgICAgICAgICAoW2FkZHJlc3MsIHtjb250ZXh0fV0pID0+IHtcbiAgICAgICAgICAgIGxldCB7IGNvbnRyYWN0TmFtZSwgYmluYXJ5IH0gPSBjb250ZXh0c1tjb250ZXh0XTtcbiAgICAgICAgICAgIGxldCB7IHNvdXJjZU1hcCB9ID0gc291cmNlTWFwc1tjb250ZXh0XTtcblxuICAgICAgICAgICAgbGV0IHsgc291cmNlIH0gPSBzb3VyY2VNYXAgP1xuICAgICAgICAgICAgICAvLyBsb29rIGZvciBzb3VyY2UgSUQgYmV0d2VlbiBzZWNvbmQgYW5kIHRoaXJkIGNvbG9ucyAoSEFDSylcbiAgICAgICAgICAgICAgc291cmNlc1tzb3VyY2VNYXAubWF0Y2goL15bXjpdKzpbXjpdKzooW146XSspOi8pWzFdXSA6XG4gICAgICAgICAgICAgIHt9O1xuXG4gICAgICAgICAgICByZXR1cm4ge1xuICAgICAgICAgICAgICBbYWRkcmVzc106IHtcbiAgICAgICAgICAgICAgICBjb250cmFjdE5hbWUsIHNvdXJjZSwgYmluYXJ5XG4gICAgICAgICAgICAgIH1cbiAgICAgICAgICAgIH07XG4gICAgICAgICAgfVxuICAgICAgICApXG4gICAgICApXG4gICAgKVxuICB9XG59KTtcblxuZXhwb3J0IGRlZmF1bHQgc2Vzc2lvbjtcblxuXG5cbi8vIFdFQlBBQ0sgRk9PVEVSIC8vXG4vLyBsaWIvc2Vzc2lvbi9zZWxlY3RvcnMvaW5kZXguanMiLCJpbXBvcnQgZGVidWdNb2R1bGUgZnJvbSBcImRlYnVnXCI7XG5jb25zdCBkZWJ1ZyA9IGRlYnVnTW9kdWxlKFwidGVzdDpkYXRhOmRlY29kZVwiKTtcblxuaW1wb3J0IEdhbmFjaGUgZnJvbSBcImdhbmFjaGUtY2xpXCI7XG5pbXBvcnQgV2ViMyBmcm9tIFwid2ViM1wiO1xuaW1wb3J0IHsgY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lzLnBhcmVudCkge1xyXG4gICAgICAgICAgICB0aGlzLnBhcmVudC51cGRhdGVNYXhPZlBhcmVudHMoKTtcclxuICAgICAgICB9XHJcbiAgICB9O1xyXG4gICAgLypcclxuICAgIExlZnQtTGVmdCBjYXNlOlxyXG4gIFxyXG4gICAgICAgICAgIHogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIHlcclxuICAgICAgICAgIC8gXFwgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIC8gICBcXFxyXG4gICAgICAgICB5ICAgVDQgICAgICBSaWdodCBSb3RhdGUgKHopICAgICAgICAgIHggICAgIHpcclxuICAgICAgICAvIFxcICAgICAgICAgIC0gLSAtIC0gLSAtIC0gLSAtPiAgICAgICAvIFxcICAgLyBcXFxyXG4gICAgICAgeCAgIFQzICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICBUMSBUMiBUMyBUNFxyXG4gICAgICAvIFxcXHJcbiAgICBUMSAgIFQyXHJcbiAgXHJcbiAgICBMZWZ0LVJpZ2h0IGNhc2U6XHJcbiAgXHJcbiAgICAgICAgIHogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgeiAgICAgICAgICAgICAgICAgICAgICAgICAgIHhcclxuICAgICAgICAvIFxcICAgICAgICAgICAgICAgICAgICAgICAgICAgICAvIFxcICAgICAgICAgICAgICAgICAgICAgICAgLyAgIFxcXHJcbiAgICAgICB5ICAgVDQgIExlZnQgUm90YXRlICh5KSAgICAgICAgIHggIFQ0ICBSaWdodCBSb3RhdGUoeikgICAgIHkgICAgIHpcclxuICAgICAgLyBcXCAgICAgIC0gLSAtIC0gLSAtIC0gLSAtPiAgICAgLyBcXCAgICAgIC0gLSAtIC0gLSAtIC0gLT4gIC8gXFwgICAvIFxcXHJcbiAgICBUMSAgIHggICAgICAgICAgICAgICAgICAgICAgICAgICB5ICBUMyAgICAgICAgICAgICAgICAgICAgICBUMSBUMiBUMyBUNFxyXG4gICAgICAgIC8gXFwgICAgICAgIC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GluIGZpcnN0IGNhc2UsIHggaW4gc2Vjb25kKVxyXG4gICAgICAgIHBhcmVudC5tYXggPSBNYXRoLm1heChNYXRoLm1heChwYXJlbnQubGVmdC5tYXgsIHBhcmVudC5yaWdodC5tYXgpLCBwYXJlbnQuZ2V0Tm9kZUhpZ2goKSk7XHJcbiAgICB9O1xyXG4gICAgLypcclxuICAgIFJpZ2h0LVJpZ2h0IGNhc2U6XHJcbiAgXHJcbiAgICAgIHogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgeVxyXG4gICAgIC8gXFwgICAgICAgICAgICAgICAgICAgICAgICAgICAgLyAgIFxcXHJcbiAgICBUMSAgeSAgICAgTGVmdCBSb3RhdGUoeikgICAgICAgeiAgICAgeFxyXG4gICAgICAgLyBcXCAgIC0gLSAtIC0gLSAtIC0gLT4gICAgIC8gXFwgICAvIFxcXHJcbiAgICAgIFQyICB4ICAgICAgICAgICAgICAgICAgICAgIFQxIFQyIFQzIFQ0XHJcbiAgICAgICAgIC8gXFxcclxuICAgICAgICBUMyBUNFxyXG4gIFxyXG4gICAgUmlnaHQtTGVmdCBjYXNlOlxyXG4gIFxyXG4gICAgICAgeiAgICAgICAgICAgICAgICAgICAgICAgICAgICB6ICAgICAgICAgICAgICAgICAgICAgICAgICAgIHhcclxuICAgICAgLyBcXCAgICAgICAgICAgICAgICAgICAgICAgICAgLyBcXCAgICAgICAgICAgICAgICAgICAgICAgICAvICAgXFxcclxuICAgICBUMSAgeSAgIFJpZ2h0IFJvdGF0ZSAoeSkgICAgIFQxICB4ICAgICAgTGVmdCBSb3RhdGUoeikgICB6ICAgICB5XHJcbiAgICAgICAgLyBcXCAgLSAtIC0gLSAtIC0gLSAtIC0+ICAgICAgLyBcXCAgIC0gLSAtIC0gLSAtIC0gLT4gIC8gXFwgICAvIFxcXHJcbiAgICAgICB4ICBUNCAgICAgICAgICAgICAgICAgICAgICAgIFQyICB5ICAgICAgICAgICAgICAgICAgIFQxIFQyIFQzIFQ0XHJcbiAgIC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ICAgICB9XHJcbiAgICAgICAgLy8gVXBkYXRlIG1heCBvZiBwYXJlbnQgKHkgaW4gZmlyc3QgY2FzZSwgeCBpbiBzZWNvbmQpXHJcbiAgICAgICAgcGFyZW50Lm1heCA9IE1hdGgubWF4KE1hdGgubWF4KHBhcmVudC5sZWZ0Lm1heCwgcmlnaHQubWF4KSwgcGFyZW50LmdldE5vZGVIaWdoKCkpO1xyXG4gICAgfTtcclxuICAgIE5vZGUucHJvdG90eXBlLl9sZWZ0Um90YXRlID0gZnVuY3Rpb24gKCkge1xyXG4gICAgICAgIHZhciByaWdodENoaWxkID0gdGhpcy5yaWdodDtcclxuICAgICAgICByaWdodENoaWxkLnBhcmVudCA9IHRoaXMucGFyZW50O1xyXG4gICAgICAgIGlmIChyaWdodENoaWxkLnBhcmVudCA9PT0gdW5kZWZpbmVkKSB7XHJcbiAgICAgICAgICAgIHRoaXMuaW50ZXJ2YWxUcmVlLnJvb3QgPSByaWdodENoaWxkO1xyXG4gICAgICAgIH1cclxuICAgICAgICBlbHNlIHtcclxuICAgICAgICAgICAgaWYgKHJpZ2h0Q2hpbGQucGFyZW50LmxlZnQgPT09IHRoaXMpIHtcclxuICAgICAgICAgICAgICAgIHJpZ2h0Q2hpbGQucGFyZW50LmxlZnQgPSByaWdodENoaWxkO1xyXG4gICAgICAgICAgICB9XHJcbiAgICAgICAgICAgIGVsc2UgaWYgKHJpZ2h0Q2hpbGQucGFyZW50LnJpZ2h0ID09PSB0aGlzKSB7XHJcbiAgICAgICAgICAgICAgICByaWdodENoaWxkLnBhcmVudC5yaWdodCA9IHJpZ2h0Q2hpbGQ7XHJcbiAgICAgICAgICAgIH1cclxuICAgICAgICB9XHJcbiAgICAgICAgdGhpcy5yaWdodCA9IHJpZ2h0Q2hpbGQubGVmdDtcclxuICAgICAgICBpZiAodGhpcy5yaWdodCAhPT0gdW5kZWZpbmVkKSB7XHJcbiAgICAgICAgICAgIHRoaXMucmlnaHQucGFyZW50ID0gdGhpcztcclxuICAg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dGUoKTtcclxuICAgICAgICAgICAgICAgIHRoaXMuX3VwZGF0ZU1heEFmdGVyUmlnaHRSb3RhdGUoKTtcclxuICAgICAgICAgICAgfVxyXG4gICAgICAgIH1cclxuICAgICAgICBlbHNlIGlmIChoZWlnaHQodGhpcy5yaWdodCkgPj0gMiArIGhlaWdodCh0aGlzLmxlZnQpKSB7XHJcbiAgICAgICAgICAgIHZhciByaWdodCA9IHRoaXMucmlnaHQ7XHJcbiAgICAgICAgICAgIGlmIChoZWlnaHQocmlnaHQucmlnaHQpID49IGhlaWdodChyaWdodC5sZWZ0KSkge1xyXG4gICAgICAgICAgICAgICAgLy8gUmlnaHQtUmlnaHQgY2FzZVxyXG4gICAgICAgICAgICAgICAgdGhpcy5fbGVmdFJvdGF0ZSgpO1xyXG4gICAgICAgICAgICAgICAgdGhpcy5fdXBkYXRlTWF4QWZ0ZXJMZWZ0Um90YXRlKCk7XHJcbiAgICAgICAgICAgIH1cclxuICAgICAgICAgICAgZWxzZSB7XHJcbiAgICAgICAgICAgICAgICAvLyBSaWdodC1MZWZ0IGNhc2VcclxuICAgICAgICAgICAgICAgIHJpZ2h0Ll9yaWdodFJvdGF0ZSgpO1xyXG4gICAgICAgICAgICAgICAgdGhpcy5fbGVmdFJvdGF0ZSgpO1xyXG4gICAgICAgICAgICAgICAgdGhpcy5fdXBkYXRlTWF4QWZ0ZXJMZWZ0Um90YXRlKCk7XHJcbiAgICAgICAgICAgIH1cclxuICAgICAgICB9XHJcbiAgICB9O1xyXG4gICAgTm9kZS5wcm90b3R5cGUuaW5zZXJ0ID0gZnVuY3Rpb24gKHJlY29yZCkge1xyXG4gICAgICAgIGlmIChyZWNvcmQubG93IDwgdGhpcy5rZXkpIHtcclxuICAgICAgICAgICAgLy8gSW5zZXJ0IGludG8gbGVmdCBzdWJ0cmVlXHJcbiAgICAgICAgICAgIGlmICh0aGlzLmxlZnQgPT09IHVuZGVmaW5lZCkge1xyXG4gICAgICAgICAgICAgICAgdGhpcy5sZWZ0ID0gbmV3IE5vZGUodGhpcy5pbnRlcnZhbFRyZWUsIHJlY29yZCk7XHJcbiAgICAgICAgICAgICAgICB0aGlzLmxlZnQucGFyZW50ID0gdGhpcztcclxuICAgICAgICAgICAgfVxyXG4gICAgICAgICAgICBlbHNlIHtcclxuICAgICAgICAgICAgICAgIHRoaXMubGVmdC5pbnNlcnQocmVjb3JkKTtcclxuICAgICAgICAgICAgfVxyXG4gICAgICAgIH1cclxuICAgICAgICBlbHNlIHtcclxuICAgICAgICAgICAgLy8gSW5zZXJ0IGludG8gcmlnaHQgc3VidHJlZVxyXG4gICAgICAgICAgICBpZiAodGhpcy5yaWdodCA9PT0gdW5kZWZpbmVkKSB7XHJcbiAgICAgICAgICAgICAgICB0aGlzLnJpZ2h0ID0gbmV3IE5vZGUodGhpcy5pbnRlcnZhbFRyZWUsIHJlY29yZCk7XHJcbiAgICAgICAgICAgICAgICB0aGlzLnJpZ2h0LnBhcmVudCA9IHRoaXM7XHJcbiAgICAgICAgICAgIH1cclxuICAgICAgICAgICAgZWxzZSB7XHJcbiAgICAgICAgICAgICAgICB0aGlzLnJpZ2h0Lmluc2VydChyZWNvcmQpO1xyXG4gICAgICAgICAgICB9XHJcbiAgICAgICAgfVxyXG4gICAgICAgIC8vIFVwZGF0ZSB0aGUgbWF4IHZhbHVlIG9mIHRoaXMgYW5jZXN0b3IgaWYgbmVlZGVkXHJcbiAgICAgICAgaWYgKHRoaXMubWF4IDwgcmVjb3JkLmhpZ2gpIHtcclxuICAgICAgICAgICAgdGhpcy5tYXggPSByZWNvcmQuaGlnaDtcclxuICAgICAgICB9XHJcbiAgICAgICAgLy8gVXBkYXRlIGhlaWdodCBvZiBlYWNoIG5vZGVcclxuICAgICAgICB0aGlzLnVwZGF0ZUhlaWdodCgpO1xyXG4gICAgICAgIC8vIFJlYmFsYW5jZSB0aGUgdHJlZSB0byBlbnN1cmUgYWxsIG9wZXJhdGlvbnMgYXJlIGV4ZWN1dGVkIGluIE8obG9nbikgdG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xyXG4gICAgICAgIC8vIERvbid0IHNlYXJjaCBub2RlcyB0aGF0IGRvbid0IGV4aXN0XHJcbiAgICAgICAgaWYgKHRoaXMgPT09IHVuZGVmaW5lZCkge1xyXG4gICAgICAgICAgICByZXR1cm4gW107XHJcbiAgICAgICAgfVxyXG4gICAgICAgIHZhciBsZWZ0U2VhcmNoID0gW107XHJcbiAgICAgICAgdmFyIG93blNlYXJjaCA9IFtdO1xyXG4gICAgICAgIHZhciByaWdodFNlYXJjaCA9IFtdO1xyXG4gICAgICAgIC8vIElmIGludGVydmFsIGlzIHRvIHRoZSByaWdodCBvZiB0aGUgcmlnaHRtb3N0IHBvaW50IG9mIGFueSBpbnRlcnZhbCBpbiB0aGlzIG5vZGUgYW5kIGFsbCBpdHNcclxuICAgICAgICAvLyBjaGlsZHJlbiwgdGhlcmUgd29uJ3QgYmUgYW55IG1hdGNoZXNcclxuICAgICAgICBpZiAobG93ID4gdGhpcy5tYXgpIHtcclxuICAgICAgICAgICAgcmV0dXJuIFtdO1xyXG4gICAgICAgIH1cclxuICAgICAgICAvLyBTZWFyY2ggbGVmdCBjaGlsZHJlblxyXG4gICAgICAgIGlmICh0aGlzLmxlZnQgIT09IHVuZGVmaW5lZCAmJiB0aGlzLmxlZnQubWF4ID49IGxvdykge1xyXG4gICAgICAgICAgICBsZWZ0U2VhcmNoID0gdGhpcy5sZWZ0LnNlYXJjaChsb3csIGhpZ2gpO1xyXG4gICAgICAgIH1cclxuICAgICAgICAvLyBDaGVjayB0aGlzIG5vZGVcclxuICAgICAgICBvd25TZWFyY2ggPSB0aGlzLl9nZXRPdmVybGFwcGluZ1JlY29yZHModGhpcywgbG93LCBoaWdoKTtcclxuICAgICAgICAvLyBJZiBpbnRlcnZhbCBpcyB0byB0aGUgbGVmdCBvZiB0aGUgc3RhcnQgb2YgdGhpcyBpbnRlcnZhbCwgdGhlbiBpdCBjYW4ndCBiZSBpbiBhbnkgY2hpbGQgdG9cclxuICAgICAgICAvLyB0aGUgcmlnaHRcclxuICAgICAgICBpZiAoaGlnaCA8IHRoaXMua2V5KSB7XHJcbiAgICAgICAgICAgIHJldHVybiBsZWZ0U2VhcmNoLmNvbmNhdChvd25TZWFyY2gpO1xyXG4gICAgICAgIH1cclxuICAgICAgICAvLyBPdGhlcndpc2UsIHNlYXJjaCByaWdodCBjaGlsZHJlblxyXG4gICAgICAgIGlmICh0aGlzLnJpZ2h0ICE9PSB1bmRlZmluZWQpIHtcclxuICAgICAgICAgICAgcmlnaHRTZWFyY2ggPSB0aGlzLnJpZ2h0LnNlYXJjaChsb3csIGhpZ2gpO1xyXG4gICAgICAgIH1cclxuICAgICAgICAvLyBSZXR1cm4gYWNjdW11bGF0ZWQgcmVzdWx0cywgaWYgYW55XHJcbiAgICAgICAgcmV0dXJuIGxlZnRTZWFyY2guY29uY2F0KG93blNlYXJjaCwgcmlnaHRTZWFyY2gpO1xyXG4gICAgfTtcclxuICAgIC8vIFNlYXJjaGVzIGZvciBhIG5vZGUgYnkgYSBga2V5YCB2YWx1ZVxyXG4gICAgTm9kZS5wcm90b3R5cGUuc2VhcmNoRXhpc3RpbmcgPSBmdW5jdGlvbiAobG93KSB7XHJcbiAgICAgICAgaWYgKHRoaXMgPT09IHVuZGVmaW5lZCkge1xyXG4gICAgICAgICAgICByZXR1cm4gdW5kZWZpbmVkO1xyXG4gICAgICAgIH1cclxuICAgICAgICBpZiAodGhpcy5rZXkgPT09IGxvdykge1xyXG4gICAgICAgICAgICByZXR1cm4gdGhpcztcclxuICAgICAgICB9XHJcbiAgICAgICAgZWxzZSBpZiAobG93IDwgdGhpcy5rZXkpIHtcclxuICAgICAgICAgICAgaWYgKHRoaXMubGVmdCAhPT0gdW5kZWZpbmVkKSB7XHJcbiAgICAgICAgICAgICAgICByZXR1cm4gdGhpcy5sZWZ0LnNlYXJjaEV4aXN0aW5nKGxvdyk7XHJcbiAgICAgICAgICAgIH1cclxuICAgICAgICB9XHJcbiAgICAgICAgZWxzZSB7XHJcbiAgICAgICAgICAgIGlmICh0aGlzLnJpZ2h0ICE9PSB1bmRlZmluZWQpIHtcclxuICAgICAgICAgICAgICAgIHJldHVybiB0aGlzLnJpZ2h0LnNlYXJjaEV4aXN0aW5nKGxvdyk7XHJcbiAgICAgICAgICAgIH1cclxuICAgICAgICB9XHJcbiAgICAgICAgcmV0dXJuIHVuZGVmaW5lZDtcclxuICAgIH07XHJcbiAgICAvLyBSZXR1cm5zIHRoZSBzbWFsbGVzdCBub2RlIG9mIHRoZSBzdWJ0cmVlXHJcbiAgICBOb2RlLnByb3RvdHlwZS5fbWluVmFsdWUgPSBmdW5jdGlvbiAoKSB7XHJcbiAgICAgICAgaWYgKHRoaXMubGVmdCA9PT0gdW5kZWZpbmVkKSB7XHJcbiAgICAgICAgICAgIHJldHVybiB0aGlzO1xyXG4gICAgICAgIH1cclxuICAgICAgICBlbHNlIHtcclxuICAgICAgICAgICAgcmV0dXJuIHRoaXMubGVmdC5fbWluVmFsdWUoKTtcclxuICAgICAgICB9XHJcbiAgICB9O1xyXG4gICAgTm9kZS5wcm90b3R5cGUucmVtb3ZlID0gZnVuY3Rpb24gKG5vZGUpIHtcclxuICAgICAgICB2YXIgcGFyZW50ID0gdGhpcy5wYXJlbnQ7XHJcbiAgICAgICAgaWYgKG5vZGUua2V5IDwgdGhpcy5rZXkpIHtcclxuICAgICAgICAgICAgLy8gTm9kZSB0byBiZSByZW1vdmVkIGlzIG9uIHRoZSBsZWZ0IHNpZGVcclxuICAgICAgICAgICAgaWYgKHRoaXMubGVmdCAhPT0gdW5kZWZpbmVkKSB7XHJcbiAgICAgICAgICAgICAgICByZXR1cm4gdGhpcy5sZWZ0LnJlbW92ZShub2RlKTtcclxuICAgICAgICAgICAgfVxyXG4gICAgICAgICAgICBlbHNlIHtcclxuICAgICAgICAgICAgICAgIHJldHVybiB1bmRlZmluZWQ7XHJcbiAgICAgICAgICAgIH1cclxuICAgICAgICB9XHJcbiAgICAgICAgZWxzZSBpZiAobm9kZS5rZXkgPiB0aGlzLmtleSkge1xyXG4gICAgICAgICAgICAvLyBOb2RlIHRvIGJlIHJlbW92ZWQgaXMgb24gdGhlIHJpZ2h0IHNpZGVcclxuICAgICAgICAgICAgaWYgKHRoaXMucmlnaHQgIT09IHVuZGVmaW5lZCkge1xyXG4gICAgICAgICAgICAgICAgcmV0dXJuIHRoaXMucmlnaHQucmVtb3ZlKG5vZGUpO1xyXG4gICAgICAgICAgICB9XHJcbiAgICAgICAgICAgIGVsc2Uge1xyXG4gICAgICAgICAgICAgICAgcmV0dXJuIHVuZGVmaW5lZDtcclxuICAgICAgICAgICAgfVxyXG4gICAgICAgIH1cclxuICAgICAgICBlbHNlIHtcclxuICAgICAgICAgICAgaWYgKHRoaXMubGVmdCAhPT0gdW5kZWZpbmVkICYmIHRoaXMucmlnaHQgIT09IHVuZGVmaW5lZCkge1xyXG4gICAgICAgICAgICAgICAgLy8gTm9kZSBoYXMgdHdvIGNoaWxkcmVuXHJcbiAgICAgICAgICAgICAgICB2YXIgbWluVmFsdWUgPSB0aGlzLnJpZ2h0Ll9taW5WYWx1ZSgpO1xyXG4gICAgICAgICAgICAgICAgdGhpcy5rZXkgPSBtaW5WYWx1ZS5rZXk7XHJcbiAgICAgICAgICAgICAgICB0aGlzLnJlY29yZHMgPSBtaW5WYWx1ZS5yZWNvcmRzO1xyXG4gICAgICAgICAgICAgICAgcmV0dXJuIHRoaXMucmlnaHQucmVtb3ZlKHRoaXMpO1xyXG4gICAgICAgICAgICB9XHJcbiAgICAgICAgICAgIGVsc2UgaWYgKHBhcmVudC5sZWZ0ID09PSB0aGlzKSB7XHJcbiAgICAgICAgICAgICAgICAvLyBPbmUgY2hpbGQgb3Igbm8gY2hpbGQgY2FzZSBvbiBsZWZ0IHNpZGVcclxuICAgICAgICAgICAgICAgIGlmICh0aGlzLnJpZ2h0ICE9PSB1bmRlZmluZWQpIHtcclxuICAgICAgICAgICAgICAgICAgICBwYXJlbnQubGVmdCA9IHRoaXMucmlnaHQ7XHJcbiAgICAgICAgICAgICAgICAgICAgdGhpcy5yaWdodC5wYXJlbnQgPSBwYXJlbnQ7XHJcbiAgICAgICAgICAgICAgICB9XHJcbiAgICAgICAgICAgICAgICBlbHNlIHtcclxuICAgICAgICAgICAgICAgICAgICBwYXJlbnQubGVmdCA9IHRoaXMubGVmdDtcclxuICAgICAgICAgICAgICAgICAgICBpZiAodGhpcy5sZWZ0ICE9PSB1bmRlZmluZWQpIHtcclxuICAgICAgICAgICAgICAgICAgICAgICAgdGhpcy5sZWZ0LnBhcmVudCA9IHBhcmVudDtcclxuICAgICAgICAgICAgICAgICAgICB9XHJcbiAgICAgICAgICAgICAgICB9XHJcbiAgICAgICAgICAgICAgICBwYXJlbnQudXBkYXRlTWF4T2ZQYXJlbnRzKCk7XHJcbiAgICAgICAgICAgICAgICBwYXJlbnQudXBkYXRlSGVpZ2h0KCk7XHJcbiAgICAgICAgICAgICAgICBwYXJlbnQuX3JlYmFsYW5jZSgpO1xyXG4gICAgICAgICAgICAgICAgcmV0dXJuIHRoaXM7XHJcbiAgICAgICAgICAgIH1cclxuICAgICAgICAgICAgZWxzZSBpZiAocGFyZW50LnJpZ2h0ID09PSB0aGlzKSB7XHJcbiAgICAgICAgICAgICAgICAvLyBPbmUgY2hpbGQgb3Igbm8gY2hpbGQgY2FzZSBvbiByaWdodCBzaWRlXHJcbiAgICAgICAgICAgICAgICBpZiAodGhpcy5yaWdodCAhPT0gdW5kZWZpbmVkKSB7XHJcbiAgICAgICAgICAgICAgICAgICAgcGFyZW50LnJpZ2h0ID0gdGhpcy5yaWdodDtcclxuICAgICAgICAgICAgICAgICAgICB0aGlzLnJpZ2h0LnBhcmVudCA9IHBhcmVudDtcclxuICAgICAgICAgICAgICAgIH1cclxuICAgICAgICAgICAgICAgIGVsc2Uge1xyXG4gICAgICAgICAgICAgICAgICAgIHBhcmVudC5yaWdodCA9IHRoaXMubGVmdDtcclxuICAgICAgICAgICAgICAgICAgICBpZiAodGhpcy5sZWZ0ICE9PSB1bmRlZmluZWQpIHtcclxuICAgICAgICAgICAgICAgICAgICAgICAgdGhpcy5sZWZ0LnBhcmVudCA9IHBhcmVudDtcclxuICAgICAgICAgICAgICAgICAgICB9XHJcbiAgICAgICAgICAgICAgICB9XHJcbiAgICAgICAgICAgICAgICBwYXJlbnQudXBkYXRlTWF4T2ZQYXJlbnRzKCk7XHJcbiAgICAgICAgICAgICAgICBwYXJlbnQudXBkYXRlSGVpZ2h0KCk7XHJcbiAgICAgICAgICAgICAgICBwYXJlbnQuX3JlYmFsYW5jZSgpO1xyXG4gICAgICAgICAgICAgICAgcmV0dXJuIHRoaXM7XHJcbiAgICAgICAgICAgIH1cclxuICAgICAgICB9XHJcbiAgICB9O1xyXG4gICAgcmV0dXJuIE5vZGU7XHJcbn0oKSk7XHJcbmV4cG9ydHMuTm9kZSA9IE5vZGU7XHJcbnZhciBJbnRlcnZhbFRyZWUgPSAvKiogQGNsYXNzICovIChmdW5jdGlvbiAoKSB7XHJcbiAgICBmdW5jdGlvbiBJbnRlcnZhbFRyZWUoKSB7XHJcbiAgICAgICAgdGhpcy5jb3VudCA9IDA7XHJcbiAgICB9XHJcbiAgICBJbnRlcnZhbFRyZWUucHJvdG90eXBlLmluc2VydCA9IGZ1bmN0aW9uIChyZWNvcmQpIHtcclxuICAgICAgICBpZiAocmVjb3JkLmxvdyA+IHJlY29yZC5oaWdoKSB7XHJcbiAgICAgICAgICAgIHRocm93IG5ldyBFcnJvcignYGxvd2AgdmFsdWUgbXVzdCBiZSBsb3dlciBvciBlcXVhbCB0byBgaGlnaGAgdmFsdWUnKTtcclxuICAgICAgICB9XHJcbiAgICAgICAgaWYgKHRoaXMucm9vdCA9PT0gdW5kZWZpbmVkKSB7XHJcbiAgICAgICAgICAgIC8vIEJhc2UgY2FzZTogVHJlZSBpcyBlbXB0eSwgbmV3IG5vZGUgYmVjb21lcyByb290XHJcbiAgICAgICAgICAgIHRoaXMucm9vdCA9IG5ldyBOb2RlKHRoaXMsIHJlY29yZCk7XHJcbiAgICAgICAgICAgIHRoaXMuY291bnQrKztcclxuICAgICAgICAgICAgcmV0dXJuIHRydWU7XHJcbiAgICAgICAgfVxyXG4gICAgICAgIGVsc2Uge1xyXG4gICAgICAgICAgICAvLyBPdGhlcndpc2UsIGNoZWNrIGlmIG5vZGUgYWxyZWFkeSBleGlzdHMgd2l0aCB0aGUgc2FtZSBrZXlcclxuICAgICAgICAgICAgdmFyIG5vZGUgPSB0aGlzLnJvb3Quc2VhcmNoRXhpc3RpbmcocmVjb3JkLmxvdyk7XHJcbiAgICAgICAgICAgIGlmIChub2RlICE9PSB1bmRlZmluZWQpIHtcclxuICAgICAgICAgICAgICAgIC8vIENoZWNrIHRoZSByZWNvcmRzIGluIHRoaXMgbm9kZSBpZiB0aGVyZSBhbHJlYWR5IGlzIHRoZSBvbmUgd2l0aCBzYW1lIGxvdywgaGlnaCwgZGF0YVxyXG4gICAgICAgICAgICAgICAgZm9yICh2YXIgaSA9IDA7IGkgPCBub2RlLnJlY29yZHMubGVuZ3RoOyBpKyspIHtcclxuICAgICAgICAgICAgICAgICAgICBpZiAoaXNTYW1lKG5vZGUucmVjb3Jkc1tpXSwgcmVjb3JkKSkge1xyXG4gICAgICAgICAgICAgICAgICAgICAgICAvLyBUaGlzIHJlY29yZCBpcyBzYW1lIGFzIHRoZSBvbmUgd2UncmUgdHJ5aW5nIHRvIGluc2VydDsgcmV0dXJuIGZhbHNlIHRvIGluZGljYXRlXHJcbiAgICAgICAgICAgICAgICAgICAgICAgIC8vIG5vdGhpbmcgaGFzIGJlZW4gaW5zZXJ0ZWRcclxuICAgICAgICAgICAgICAgICAgICAgICAgcmV0dXJuIGZhbHNlO1xyXG4gICAgICAgICAgICAgICAgICAgIH1cclxuICAgICAgICAgICAgICAgIH1cclxuICAgICAgICAgICAgICAgIC8vIEFkZCB0aGUgcmVjb3JkIHRvIHRoZSBub2RlXHJcbiAgICAgICAgICAgICAgICBub2RlLnJlY29yZHMucHVzaChyZWNvcmQpO1xyXG4gICAgICAgICAgICAgICAgLy8gVXBkYXRlIG1heCBvZiB0aGUgbm9kZSBhbmQgaXRzIHBhcmVudHMgaWYgbmVjZXNzYXJ5XHJcbiAgICAgICAgICAgICAgICBpZiAocmVjb3JkLmhpZ2ggPiBub2RlLm1heCkge1xyXG4gICAgICAgICAgICAgICAgICAgIG5vZGUubWF4ID0gcmVjb3JkLmhpZ2g7XHJcbiAgICAgICAgICAgICAgICAgICAgaWYgKG5vZGUucGFyZW50KSB7XHJcbiAgICAgICAgICAgICAgICAgICAgICAgIG5vZGUucGFyZW50LnVwZGF0ZU1heE9mUGFyZW50cygpO1xyXG4gICAgICAgICAgICAgICAgICAgIH1cclxuICAgICAgICAgICAgICAgIH1cclxuICAgICAgICAgICAgICAgIHRoaXMuY291bnQrKztcclxuICAgICAgICAgICAgICAgIHJldHVybiB0cnVlO1xyXG4gICAgICAgICAgICB9XHJcbiAgICAgICAgICAgIGVsc2Uge1xyXG4gICAgICAgICAgICAgICAgLy8gTm9kZSB3aXRoIHRoaXMga2V5IGRvZXNuJ3QgYWxyZWFkeSBleGlzdC4gQ2FsbCBpbnNlcnQgZnVuY3Rpb24gb24gcm9vdCdzIG5vZGVcclxuICAgICAgICAgICAgICAgIHRoaXMucm9vdC5pbnNlcnQocmVjb3JkKTtcclxuICAgICAgICAgICAgICAgIHRoaXMuY291bnQrKztcclxuICAgICAgICAgICAgICAgIHJldHVybiB0cnVlO1xyXG4gICAgICAgICAgICB9XHJcbiAgICAgICAgfVxyXG4gICAgfTtcclxuICAgIEludGVydmFsVHJlZS5wcm90b3R5cGUuc2VhcmNoID0gZnVuY3Rpb24gKGxvdywgaGlnaCkge1xyXG4gICAgICAgIGlmICh0aGlzLnJvb3QgPT09IHVuZGVmaW5lZCkge1xyXG4gICAgICAgICAgICAvLyBUcmVlIGlzIGVtcHR5OyByZXR1cm4gZW1wdHkgYXJyYXlcclxuICAgICAgICAgICAgcmV0dXJuIFtdO1xyXG4gICAgICAgIH1cclxuICAgICAgICBlbHNlIHtcclxuICAgICAgICAgICAgcmV0dXJuIHRoaXMucm9vdC5zZWFyY2gobG93LCBoaWdoKTtcclxuICAgICAgICB9XHJcbiAgICB9O1xyXG4gICAgSW50ZXJ2YWxUcmVlLnByb3RvdHlwZS5yZW1vdmUgPSBmdW5jdGlvbiAocmVjb3JkKSB7XHJcbiAgICAgICAgaWYgKHRoaXMucm9vdCA9PT0gdW5kZWZpbmVkKSB7XHJcbiAgICAgICAgICAgIC8vIFRyZWUgaXMgZW1wdHk7IG5vdGhpbmcgdG8gcmVtb3ZlXHJcbiAgICAgICAgICAgIHJldHVybiBmYWxzZTtcclxuICAgICAgICB9XHJcbiAgICAgICAgZWxzZSB7XHJcbiAgICAgICAgICAgIHZhciBub2RlID0gdGhpcy5yb290LnNlYXJjaEV4aXN0aW5nKHJlY29yZC5sb3cpO1xyXG4gICAgICAgICAgICBpZiAobm9kZSA9PT0gdW5kZWZpbmVkKSB7XHJcbiAgICAgICAgICAgICAgICByZXR1cm4gZmFsc2U7XHJcbiAgICAgICAgICAgIH1cclxuICAgICAgICAgICAgZWxzZSBpZiAobm9kZS5yZWNvcmRzLmxlbmd0aCA+IDEpIHtcclxuICAgICAgICAgICAgICAgIHZhciByZW1vdmVkUmVjb3JkID0gdm9pZCAwO1xyXG4gICAgICAgICAgICAgICAgLy8gTm9kZSB3aXRoIHRoaXMga2V5IGhhcyAyIG9yIG1vcmUgcmVjb3Jkcy4gRmluZCB0aGUgb25lIHdlIG5lZWQgYW5kIHJlbW92ZSBpdFxyXG4gICAgICAgICAgICAgICAgZm9yICh2YXIgaSA9IDA7IGkgPCBub2RlLnJlY29yZHMubGVuZ3RoOyBpKyspIHtcclxuICAgICAgICAgICAgICAgICAgICBpZiAoaXNTYW1lKG5vZGUucmVjb3Jkc1tpXSwgcmVjb3JkKSkge1xyXG4gICAgICAgICAgICAgICAgICAgICAgICByZW1vdmVkUmVjb3JkID0gbm9kZS5yZWNvcmRzW2ldO1xyXG4gICAgICAgICAgICAgICAgICAgICAgICBub2RlLnJlY29yZHMuc3BsaWNlKGksIDEpO1xyXG4gICAgICAgICAgICAgICAgICAgICAgICBicmVhaztcclxuICAgICAgICAgICAgICAgICAgICB9XHJcbiAgICAgICAgICAgICAgICB9XHJcbiAgICAgICAgICAgICAgICBpZiAocmVtb3ZlZFJlY29yZCkge1xyXG4gICAgICAgICAgICAgICAgICAgIHJlbW92ZWRSZWNvcmQgPSB1bmRlZmluZWQ7XHJcbiAgICAgICAgICAgICAgICAgICAgLy8gVXBkYXRlIG1heCBvZiB0aGF0IG5vZGUgYW5kIGl0cyBwYXJlbnRzIGlmIG5lY2Vzc2FyeVxyXG4gICAgICAgICAgICAgICAgICAgIGlmIChyZWNvcmQuaGlnaCA9PT0gbm9kZS5tYXgpIHtcclxuICAgICAgICAgICAgICAgICAgICAgICAgdmFyIG5vZGVIaWdoID0gbm9kZS5nZXROb2RlSGlnaCgpO1xyXG4gICAgICAgICAgICAgICAgICAgICAgICBpZiAobm9kZS5sZWZ0ICE9PSB1bmRlZmluZWQgJiYgbm9kZS5yaWdodCAhPT0gdW5kZWZpbmVkKSB7XHJcbiAgICAgICAgICAgICAgICAgICAgICAgICAgICBub2RlLm1heCA9IE1hdGgubWF4KE1hdGgubWF4KG5vZGUubGVmdC5tYXgsIG5vZGUucmlnaHQubWF4KSwgbm9kZUhpZ2gpO1xyXG4gICAgICAgICAgICAgICAgICAgICAgICB9XHJcbiAgICAgICAgICAgICAgICAgICAgICAgIGVsc2UgaWYgKG5vZGUubGVmdCAhPT0gdW5kZWZpbmVkICYmIG5vZGUucmlnaHQgPT09IHVuZGVmaW5lZCkge1xyXG4gICAgICAgICAgICAgICAgICAgICAgICAgICAgbm9kZS5tYXggPSBNYXRoLm1heChub2RlLmxlZnQubWF4LCBub2RlSGlnaCk7XHJcbiAgICAgICAgICAgICAgICAgICAgICAgIH1cclxuICAgICAgICAgICAgICAgICAgICAgICAgZWxzZSBpZiAobm9kZS5sZWZ0ID09PSB1bmRlZmluZWQgJiYgbm9kZS5yaWdodCAhPT0gdW5kZWZpbmVkKSB7XHJcbiAgICAgICAgICAgICAgICAgICAgICAgICAgICBub2RlLm1heCA9IE1hdGgubWF4KG5vZGUucmlnaHQubWF4LCBub2RlSGlnaCk7XHJcbiAgICAgICAgICAgICAgICAgICAgICAgIH1cclxuICAgICAgICAgICAgICAgICAgICAgICAgZWxzZSB7XHJcbiAgICAgICAgICAgICAgICAgICAgICAgICAgICBub2RlLm1heCA9IG5vZGVIaWdoO1xyXG4gICAgICAgICAgICAgICAgICAgICAgICB9XHJcbiAgICAgICAgICAgICAgICAgICAgICAgIGlmIChub2RlLnBhcmVudCkge1xyXG4gICAgICAgICAgICAgICAgICAgICAgICAgICAgbm9kZS5wYXJlbnQudXBkYXRlTWF4T2ZQYXJlbnRzKCk7XHJcbiAgICAgICAgICAgICAgICAgICAgICAgIH1cclxuICAgICAgICAgICAgICAgICAgICB9XHJcbiAgICAgICAgICAgICAgICAgICAgdGhpcy5jb3VudC0tO1xyXG4gICAgICAgICAgICAgICAgICAgIHJldHVybiB0cnVlO1xyXG4gICAgICAgICAgICAgICAgfVxyXG4gICAgICAgICAgICAgICAgZWxzZSB7XHJcbiAgICAgICAgICAgICAgICAgICAgcmV0dXJuIGZhbHNlO1xyXG4gICAgICAgICAgICAgICAgfVxyXG4gICAgICAgICAgICB9XHJcbiAgICAgICAgICAgIGVsc2UgaWYgKG5vZGUucmVjb3Jkcy5sZW5ndGggPT09IDEpIHtcclxuICAgICAgICAgICAgICAgIC8vIE5vZGUgd2l0aCB0aGlzIGtleSBoYXMgb25seSAxIHJlY29yZC4gQ2hlY2sgaWYgdGhlIHJlbWFpbmluZyByZWNvcmQgaW4gdGhpcyBub2RlIGlzXHJcbiAgICAgICAgICAgICAgICAvLyBhY3R1YWxseSB0aGUgb25lIHdlIHdhbnQgdG8gcmVtb3ZlXHJcbiAgICAgICAgICAgICAgICBpZiAoaXNTYW1lKG5vZGUucmVjb3Jkc1swXSwgcmVjb3JkKSkge1xyXG4gICAgICAgICAgICAgICAgICAgIC8vIFRoZSByZW1haW5pbmcgcmVjb3JkIGlzIHRoZSBvbmUgd2Ugd2FudCB0byByZW1vdmUuIFJlbW92ZSB0aGUgd2hvbGUgbm9kZSBmcm9tIHRoZSB0cmVlXHJcbiAgICAgICAgICAgICAgICAgICAgaWYgKHRoaXMucm9vdC5rZXkgPT09IG5vZGUua2V5KSB7XHJcbiAgICAgICAgICAgICAgICAgICAgICAgIC8vIFdlJ3JlIHJlbW92aW5nIHRoZSByb290IGVsZW1lbnQuIENyZWF0ZSBhIGR1bW15IG5vZGUgdGhhdCB3aWxsIHRlbXBvcmFyaWx5IHRha2VcclxuICAgICAgICAgICAgICAgICAgICAgICAgLy8gcm9vdCdzIHBhcmVudCByb2xlXHJcbiAgICAgICAgICAgICAgICAgICAgICAgIHZhciByb290UGFyZW50ID0gbmV3IE5vZGUodGhpcywgeyBsb3c6IHJlY29yZC5sb3csIGhpZ2g6IHJlY29yZC5sb3cgfSk7XHJcbiAgICAgICAgICAgICAgICAgICAgICAgIHJvb3RQYXJlbnQubGVmdCA9IHRoaXMucm9vdDtcclxuICAgICAgICAgICAgICAgICAgICAgICAgdGhpcy5yb290LnBhcmVudCA9IHJvb3RQYXJlbnQ7XHJcbiAgICAgICAgICAgICAgICAgICAgICAgIHZhciByZW1vdmVkTm9kZSA9IHRoaXMucm9vdC5yZW1vdmUobm9kZSk7XHJcbiAgICAgICAgICAgICAgICAgICAgICAgIHRoaXMucm9vdCA9IHJvb3RQYXJlbnQubGVmdDtcclxuICAgICAgICAgICAgICAgICAgICAgICAgaWYgKHRoaXMucm9vdCAhPT0gdW5kZWZpbmVkKSB7XHJcbiAgICAgICAgICAgICAgICAgICAgICAgICAgICB0aGlzLnJvb3QucGFyZW50ID0gdW5kZWZpbmVkO1xyXG4gICAgICAgICAgICAgICAgICAgICAgICB9XHJcbiAgICAgICAgICAgICAgICAgICAgICAgIGlmIChyZW1vdmVkTm9kZSkge1xyXG4gICAgICAgICAgICAgICAgICAgICAgICAgICAgcmVtb3ZlZE5vZGUgPSB1bmRlZmluZWQ7XHJcbiAgICAgICAgICAgICAgICAgICAgICAgICAgICB0aGlzLmNvdW50LS07XHJcbiAgICAgICAgICAgICAgICAgICAgICAgICAgICByZXR1cm4gdHJ1ZTtcclxuICAgICAgICAgICAgICAgICAgICAgICAgfVxyXG4gICAgICAgICAgICAgICAgICAgICAgICBlbHNlIHtcclxuICAgICAgICAgICAgICAgICAgICAgICAgICAgIHJldHVybiBmYWxzZTtcclxuICAgICAgICAgICAgICAgICAgICAgICAgfVxyXG4gICAgICAgICAgICAgICAgICAgIH1cclxuICAgICAgICAgICAgICAgICAgICBlbHNlIHtcclxuICAgICAgICAgICAgICAgICAgICAgICAgdmFyIHJlbW92ZWROb2RlID0gdGhpcy5yb290LnJlbW92ZShub2RlKTtcclxuICAgICAgICAgICAgICAgICAgICAgICAgaWYgKHJlbW92ZWROb2RlKSB7XHJcbiAgICAgICAgICAgICAgICAgICAgICAgICAgICByZW1vdmVkTm9kZSA9IHVuZGVmaW5lZDtcclxuICAgICAgICAgICAgICAgICAgICAgICAgICAgIHRoaXMuY291bnQtLTtcclxuICAgICAgICAgICAgICAgICAgICAgICAgICAgIHJldHVybiB0cnVlO1xyXG4gICAgICAgICAgICAgICAgICAgICAgICB9XHJcbiAgICAgICAgICAgICAgICAgICAgICAgIGVsc2Uge1xyXG4gICAgICAgICAgICAgICAgICAgICAgICAgICAgcmV0dXJuIGZhbHNlO1xyXG4gICAgICAgICAgICAgICAgICAgICAgICB9XHJcbiAgICAgICAgICAgICAgICAgICAgfVxyXG4gICAgICAgICAgICAgICAgfVxyXG4gICAgICAgICAgICAgICAgZWxzZSB7XHJcbiAgICAgICAgICAgICAgICAgICAgLy8gVGhlIHJlbWFpbmluZyByZWNvcmQgaXMgbm90IHRoZSBvbmUgd2Ugd2FudCB0byByZW1vdmVcclxuICAgICAgICAgICAgICAgICAgICByZXR1cm4gZmFsc2U7XHJcbiAgICAgIC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biAoKSB7XHJcbiAgICBmdW5jdGlvbiBJbk9yZGVyKHN0YXJ0Tm9kZSkge1xyXG4gICAgICAgIHRoaXMuc3RhY2sgPSBbXTtcclxuICAgICAgICBpZiAoc3RhcnROb2RlICE9PSB1bmRlZmluZWQpIHtcclxuICAgICAgICAgICAgdGhpcy5wdXNoKHN0YXJ0Tm9kZSk7XHJcbiAgICAgICAgfVxyXG4gICAgfVxyXG4gICAgSW5PcmRlci5wcm90b3R5cGUubmV4dCA9IGZ1bmN0aW9uICgpIHtcclxuICAgICAgICAvLyBXaWxsIG9ubHkgaGFwcGVuIGlmIHN0YWNrIGlzIGVtcHR5IGFuZCBwb3AgaXMgY2FsbGVkXHJcbiAgICAgICAgaWYgKHRoaXMuY3VycmVudE5vZGUgPT09IHVuZGVmaW5lZCkge1xyXG4gICAgICAgICAgICByZXR1cm4ge1xyXG4gICAgICAgICAgICAgICAgZG9uZTogdHJ1ZSxcclxuICAgICAgICAgICAgICAgIHZhbHVlOiB1bmRlZmluZWQsXHJcbiAgICAgICAgICAgIH07XHJcbiAgICAgICAgfVxyXG4gICAgICAgIC8vIFByb2Nlc3MgdGhpcyBub2RlXHJcbiAgICAgICAgaWYgKHRoaXMuaSA8IHRoaXMuY3VycmVudE5vZGUucmVjb3Jkcy5sZW5ndGgpIHtcclxuICAgICAgICAgICAgcmV0dXJuIHtcclxuICAgICAgICAgICAgICAgIGRvbmU6IGZhbHNlLFxyXG4gICAgICAgICAgICAgICAgdmFsdWU6IHRoaXMuY3VycmVudE5vZGUucmVjb3Jkc1t0aGlzLmkrK10sXHJcbiAgICAgICAgICAgIH07XHJcbiAgICAgICAgfVxyXG4gICAgICAgIGlmICh0aGlzLmN1cnJlbnROb2RlLnJpZ2h0ICE9PSB1bmRlZmluZWQpIHtcclxuICAgICAgICAgICAgdGhpcy5wdXNoKHRoaXMuY3VycmVudE5vZGUucmlnaHQpO1xyXG4gICAgICAgIH1cclxuICAgICAgICBlbHNlIHtcclxuICAgICAgICAgIC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ZSkge1xyXG4gICAgICAgIHRoaXMuc3RhY2sgPSBbXTtcclxuICAgICAgICB0aGlzLmkgPSAwO1xyXG4gICAgICAgIHRoaXMuY3VycmVudE5vZGUgPSBzdGFydE5vZGU7XHJcbiAgICB9XHJcbiAgICBQcmVPcmRlci5wcm90b3R5cGUubmV4dCA9IGZ1bmN0aW9uICgpIHtcclxuICAgICAgICAvLyBXaWxsIG9ubHkgaGFwcGVuIGlmIHN0YWNrIGlzIGVtcHR5IGFuZCBwb3AgaXMgY2FsbGVkLFxyXG4gICAgICAgIC8vIHdoaWNoIG9ubHkgaGFwcGVucyBpZiB0aGVyZSBpcyBubyByaWdodCBub2RlIChpLmUgd2UgYXJlIGRvbmUpXHJcbiAgICAgICAgaWYgKHRoaXMuY3VycmVudE5vZGUgPT09IHVuZGVmaW5lZCkge1xyXG4gICAgICAgICAgICByZXR1cm4ge1xyXG4gICAgICAgICAgICAgICAgZG9uZTogdHJ1ZSxcclxuICAgICAgICAgICAgICAgIHZhbHVlOiB1bmRlZmluZWQsXHJcbiAgICAgICAgICAgIH07XHJcbiAgICAgICAgfVxyXG4gICAgICAgIC8vIFByb2Nlc3MgdGhpcyBub2RlXHJcbiAgICAgICAgaWYgKHRoaXMuaSA8IHRoaXMuY3VycmVudE5vZGUucmVjb3Jkcy5sZW5ndGgpIHtcclxuICAgICAgICAgICAgcmV0dXJuIHtcclxuICAgICAgICAgICAgICAgIGRvbmU6IGZhbHNlLFxyXG4gICAgICAgICAgICAgICAgdmFsdWU6IHRoaXMuY3VycmVudE5vZGUucmVjb3Jkc1t0aGlzLmkrK10sXHJcbiAgICAgICAgICAgIH07XHJcbiAgICAgICAgfVxyXG4gICAgICAgIGlmICh0aGlzLmN1cnJlbnROb2RlLnJpZ2h0ICE9PSB1bmRlZmluZWQpIHtcclxuICAgICAgICAgICAgdGhpcy5wdXNoKHRoaXMuY3VycmVudE5vZGUucmlnaHQpO1xyXG4gICAgICAgIH1cclxuICAgICAgICBpZiAodGhpcy5j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m1hcChcbiAgICAgICAgICAgICh7bmFtZSwgaWR9LCBpKSA9PiB7XG4gICAgICAgICAgICAgIGxldCBtZW1iZXJEZWZpbml0aW9uID0gcmVmc1tpZF0uZGVmaW5pdGlvbjtcbiAgICAgICAgICAgICAgbGV0IG1lbWJlclBvaW50ZXIgPSB7XG4gICAgICAgICAgICAgICAgbWVtb3J5OiB7IHN0YXJ0OiByYXdWYWx1ZSArIGkgKiBXT1JEX1NJWkUsIGxlbmd0aDogV09SRF9TSVpFIH1cbiAgICAgICAgICAgICAgfTtcbiAgICAgICAgICAgICAgLy8gbGV0IG1lbWJlclBvaW50ZXIgPSBtZW1vcnkucmVhZChzdGF0ZS5tZW1vcnksIHBvaW50ZXIgKyBpICogV09SRF9TSVpFKTtcblxuICAgICAgICAgICAgICAvLyBIQUNLXG4gICAgICAgICAgICAgIG1lbWJlckRlZmluaXRpb24gPSB7XG4gICAgICAgICAgICAgICAgLi4ubWVtYmVyRGVmaW5pdGlvbixcblxuICAgICAgICAgICAgICAgIHR5cGVEZXNjcmlwdGlvbnM6IHtcbiAgICAgICAgICAgICAgICAgIC4uLm1lbWJlckRlZmluaXRpb24udHlwZURlc2NyaXB0aW9ucyxcblxuICAgICAgICAgICAgICAgICAgdHlwZUlkZW50aWZpZXI6XG4gICAgICAgICAgICAgICAgICAgIG1lbWJlckRlZmluaXRpb24udHlwZURlc2NyaXB0aW9ucy50eXBlSWRlbnRpZmllclxuICAgICAgICAgICAgICAgICAgICAgIC5yZXBsYWNlKC9fc3RvcmFnZV8vZywgXCJfbWVtb3J5X1wiKVxuICAgICAgICAgICAgICAgIH1cbiAgICAgICAgICAgICAgfTtcblxuICAgICAgICAgICAgICByZXR1cm4ge1xuICAgICAgICAgICAgICAgIFtuYW1lXTogZGVjb2RlKFxuICAgICAgICAgICAgICAgICAgbWVtYmVyRGVmaW5pdGlvbiwgbWVtYmVyUG9pbnRlciwgc3RhdGUsIC4uLmFyZ3NcbiAgICAgICAgICAgICAgICApXG4gICA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G5cbiAgICAgIGNvbnN0IG9mZnNldCA9IChpKSA9PiB7XG4gICAgICAgIGlmIChwZXJXb3JkID09IDEpIHtcbiAgICAgICAgICByZXR1cm4gaTtcbiAgICAgICAgfVxuXG4gICAgICAgIHJldHVybiBNYXRoLmZsb29yKGkgKiBiYXNlU2l6ZSAvIFdPUkRfU0laRSk7XG4gICAgICB9XG5cbiAgICAgIGNvbnN0IGluZGV4ID0gKGkpID0+IHtcbiAgICAgICAgaWYgKHBlcldvcmQgPT0gMSkge1xuICAgICAgICAgIHJldHVybiBXT1JEX1NJWkUgLSBiYXNlU2l6ZTtcbiAgICAgICAgfVxuXG4gICAgICAgIGNvbnN0IHBvc2l0aW9uID0gcGVyV29yZCAtIGkgJSBwZXJXb3JkIC0gMTtcbiAgICAgICAgcmV0dXJuIHBvc2l0aW9uICogYmFzZVNpemU7XG4gICAgICB9XG5cbiAgICAgIGRlYnVnKFwicG9pbnRlcjogJW9cIiwgcG9pbnRlcik7XG4gICAgICByZXR1cm4gWy4uLkFycmF5KGxlbmd0aCkua2V5cygpXVxuICAgICAgICAubWFwKCAoaSkgPT4ge1xuICAgICAgICAgIGxldCBjaGlsZEZyb20gPSBwb2ludGVyLnN0b3JhZ2UuZnJvbS5vZmZzZXQgIT0gdW5kZWZpbmVkID9cbiAgICAgICAgICAgIHtcbiAgICAgICAgICAgICAgc2xvdDogW1wiMHhcIiArIHV0aWxzLnRvQmlnTnVtYmVyKFxuICAgICAgICAgICAgICAgIHV0aWxzLmtlY2NhazI1NiguLi5wb2ludGVyLnN0b3JhZ2UuZnJvbS5zbG90KVxuICAgICAgICAgICAgICApLnBsdXMocG9pbnRlci5zdG9yYWdlLmZyb20ub2Zmc2V0KS50b1N0cmluZygxNildLFxuICAgICAgICAgICAgICBvZmZzZXQ6IG9mZnNldChpKSxcbiAgICAgICAgICAgICAgaW5kZXg6IGluZGV4KGkpXG4gICAgICAgICAgICB9IDoge1xuICAgICAgICAgICAgICBzbG90OiBbcG9pbnRlci5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NBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFFQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFIQTtBQUNBO0FBS0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBRUE7QUFFQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFIQTtBQUNBO0FBS0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBOzs7O0EiLCJzb3VyY2VSb290IjoiIn0=
fileName
nn.py
"""Some nn utilities.""" import torch from abstract import ParametricFunction def copy_buffer(net: ParametricFunction, target_net: ParametricFunction): """Copy all buffers from net to target_net.""" with torch.no_grad(): for target_buf, buf in zip(target_net.buffers(), net.buffers()): # type: ignore target_buf.copy_(buf) def soft_update(net: ParametricFunction, target_net: ParametricFunction, tau: float): """Soft update of the parameters of target_net with those of net. Precisely theta_targetnet <- tau * theta_targetnet + (1 - tau) * theta_net """ copy_buffer(net, target_net) with torch.no_grad(): for target_param, param in zip(target_net.parameters(), net.parameters()): target_param.add_(1 - tau, param - target_param) def
(net: ParametricFunction, target_net: ParametricFunction): """Hard update (i.e. copy) of the parameters of target_net with those of net.""" copy_buffer(net, target_net) with torch.no_grad(): for target_param, param in zip(target_net.parameters(), net.parameters()): target_param.copy_(param)
hard_update
subscription.go
/* Copyright 2021 The KodeRover Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package handler import ( "strconv" "github.com/gin-gonic/gin" commonmodels "github.com/koderover/zadig/lib/microservice/aslan/core/common/dao/models" enterpriseservice "github.com/koderover/zadig/lib/microservice/aslan/core/enterprise/service" internalhandler "github.com/koderover/zadig/lib/microservice/aslan/internal/handler" e "github.com/koderover/zadig/lib/tool/errors" ) func UpsertSubscription(c *gin.Context) { ctx := internalhandler.NewContext(c) defer func() { internalhandler.JsonResponse(c, ctx) }() args := new(commonmodels.Subscription) err := c.BindJSON(args) if err != nil { ctx.Err = e.ErrInvalidParam.AddDesc("invalid subscription args") return } ctx.Err = enterpriseservice.UpsertSubscription(ctx.Username, args, ctx.Logger) } func UpdateSubscribe(c *gin.Context) { ctx := internalhandler.NewContext(c) defer func() { internalhandler.JsonResponse(c, ctx) }() args := new(commonmodels.Subscription) err := c.BindJSON(args) if err != nil { ctx.Err = e.ErrInvalidParam.AddDesc("invalid subscription args") return } notifytype, err := strconv.Atoi(c.Param("type")) if err != nil { ctx.Err = e.ErrInvalidParam.AddDesc("invalid notification type") return } ctx.Err = enterpriseservice.UpdateSubscribe(ctx.Username, notifytype, args, ctx.Logger) } func Unsubscribe(c *gin.Context) { ctx := internalhandler.NewContext(c) defer func() { internalhandler.JsonResponse(c, ctx) }() notifytype, err := strconv.Atoi(c.Param("type")) if err != nil { ctx.Err = e.ErrInvalidParam.AddDesc("invalid notification type") return } ctx.Err = enterpriseservice.Unsubscribe(ctx.Username, notifytype, ctx.Logger) } func
(c *gin.Context) { ctx := internalhandler.NewContext(c) defer func() { internalhandler.JsonResponse(c, ctx) }() ctx.Resp, ctx.Err = enterpriseservice.ListSubscriptions(ctx.Username, ctx.Logger) }
ListSubscriptions
genbank_test.go
package seqio import ( "bytes" "strings" "testing" "time" "github.com/go-ascii/ascii" "github.com/go-gts/gts" "github.com/go-gts/gts/internal/testutils" "github.com/go-pars/pars" ) func formatGenBankHelper(t *testing.T, seq gts.Sequence, in string) { t.Helper() b := strings.Builder{} n, err := GenBankWriter{&b}.WriteSeq(seq) if int(n) != len([]byte(in)) || err != nil { t.Errorf("f.WriteSeq(seq) = (%d, %v), want %d, nil", n, err, len(in)) } testutils.DiffLine(t, in, b.String()) } func TestGenBankFields(t *testing.T) { var ( locusName = "LocusName" accession = "Accession" version = "Version" ) info := GenBankFields{} if info.ID() != "" { t.Errorf("info.ID() = %q, want %q", info.ID(), "") } info.LocusName = locusName if info.ID() != locusName { t.Errorf("info.ID() = %q, want %q", info.ID(), locusName) } info.Accession = accession if info.ID() != accession { t.Errorf("info.ID() = %q, want %q", info.ID(), accession) } info.Version = version if info.ID() != version { t.Errorf("info.ID() = %q, want %q", info.ID(), version) } } func TestGenBankWithInterface(t *testing.T) { length := 100 info := GenBankFields{ LocusName: "LOCUS_NAME", Molecule: gts.DNA, Topology: gts.Linear, Division: "UNA", Date: FromTime(time.Now()), Definition: "Sample sequence", Accession: "ACCESSION", Version: "VERSION", Source: Organism{ Species: "Genus species", Name: "Name", Taxon: []string{"Kingdom", "Phylum", "Class", "Order", "Family", "Genus", "species"}, }, } p := []byte(strings.Repeat("atgc", length)) props := gts.Props{} props.Add("organism", "Genus species") props.Add("mol_type", "Genomic DNA") loc := gts.Range(0, len(p)) ff := []gts.Feature{gts.NewFeature("source", loc, props)} in := GenBank{GenBankFields{}, nil, NewOrigin(nil)} out := gts.WithInfo(in, info) testutils.Equals(t, out, GenBank{info, nil, NewOrigin(nil)}) out = gts.WithFeatures(in, ff) testutils.Equals(t, out, GenBank{GenBankFields{}, ff, NewOrigin(nil)}) out = gts.WithBytes(in, p) testutils.Equals(t, out, GenBank{GenBankFields{}, nil, NewOrigin(p)}) out = gts.WithInfo(in, "info") testutils.Equals(t, out, gts.New("info", nil, nil)) out = gts.WithTopology(in, gts.Circular) top := out.(GenBank).Fields.Topology if top != gts.Circular { t.Errorf("topology is %q, expected %q", top, gts.Circular) } } func TestGenBankSlice(t *testing.T) { in := testutils.ReadTestfile(t, "NC_001422.gb") state := pars.FromString(in) parser := pars.AsParser(GenBankParser) exp := testutils.ReadTestfile(t, "NC_001422_part.gb") result, err := parser.Parse(state) if err != nil { t.Errorf("parser returned %v\nBuffer:\n%q", err, string(result.Token)) } switch seq := result.Value.(type) { case GenBank: seq = gts.Slice(seq, 2379, 2512).(GenBank) formatGenBankHelper(t, seq, exp) default: t.Errorf("result.Value.(type) = %T, want %T", seq, GenBank{}) } } func TestGenBankIO(t *testing.T) { files := []string{ "NC_001422.gb", "NC_000913.3.min.gb", } for _, file := range files { in := testutils.ReadTestfile(t, file) state := pars.FromString(in) parser := pars.AsParser(GenBankParser) result, err := parser.Parse(state) if err != nil { t.Errorf("in file %q, parser returned %v\nBuffer:\n%q", file, err, string(result.Token)) return } switch seq := result.Value.(type) { case GenBank: formatGenBankHelper(t, &seq, in) cpy := gts.New(seq.Info(), seq.Features(), seq.Bytes()) formatGenBankHelper(t, &cpy, in) default: t.Errorf("result.Value.(type) = %T, want %T", seq, GenBank{}) } } } func TestGenBankParser(t *testing.T) { files := []string{ "NC_001422.gb", "pBAT5.txt", } for _, file := range files { in := testutils.ReadTestfile(t, file) state := pars.FromString(in) parser := pars.AsParser(GenBankParser) result, err := parser.Parse(state) if err != nil { t.Errorf("in file %q, parser returned %v\nBuffer:\n%q", file, err, string(result.Token)) return } switch seq := result.Value.(type) { case GenBank: data := seq.Bytes() if len(data) != gts.Len(seq) { t.Errorf("in file %s: len(data) = %d, want %d", file, len(data), gts.Len(seq)) return } if seq.Info() == nil { t.Errorf("in file %s: seq.Info() is nil", file) return } if seq.Features() == nil { t.Errorf("in file %s: seq.Features() is nil", file) return } for i, c := range data { if !ascii.IsLetterFilter(c) { t.Errorf("in file %s: origin contains `%U` at byte %d, expected a sequence character", file, c, i+1) return } } default: t.Errorf("result.Value.(type) = %T, want %T", seq, GenBank{}) } } } var genbankIOFailTests = []string{ "", "NC_001422 5386 bp ss-DNA circular PHG 06-JUL-2018", "" + "LOCUS NC_001422 5386 bp ss-DNA topology PHG 06-JUL-2018\n" + "foo", "" + "LOCUS NC_001422 5386 bp foo topology PHG 06-JUL-2018\n" + "foo", "" + "LOCUS NC_001422 5386 bp ss-DNA circular PHG 06-JUL-2018\n" + "foo", "" + "LOCUS NC_001422 5386 bp ss-DNA circular PHG 06-JUL-2018\n" + "DEFINITION", "" + "LOCUS NC_001422 5386 bp ss-DNA circular PHG 06-JUL-2018\n" + "DEFINITION ", "" + "LOCUS NC_001422 5386 bp ss-DNA circular PHG 06-JUL-2018\n" + "DEFINITION Coliphage phi-X174, complete genome", "" + "LOCUS NC_001422 5386 bp ss-DNA circular PHG 06-JUL-2018\n" + "DBLINK FOO", "" + "LOCUS NC_001422 5386 bp ss-DNA circular PHG 06-JUL-2018\n" + "SOURCE Escherichia virus phiX174\n" + " ORGANISM Escherichia virus phiX174", "" + "LOCUS NC_001422 5386 bp ss-DNA circular PHG 06-JUL-2018\n" + "REFERENCE ", "" + "LOCUS NC_001422 5386 bp ss-DNA circular PHG 06-JUL-2018\n" + "REFERENCE 1", "" + "LOCUS NC_001422 5386 bp ss-DNA circular PHG 06-JUL-2018\n" + "REFERENCE 1 (bases 2380 to 2512; 2593 to 2786; 2788 to 2947)\n" + " AUTHORS Air,G.M., Els,M.C., Brown,L.E., Laver,W.G. and Webster,R.G.", "" + "LOCUS NC_001422 5386 bp ss-DNA circular PHG 06-JUL-2018\n" + "FEATURES Location/Qualifiers", "" + "LOCUS TEST_DATA 20 bp DNA linear UNA 14-MAY-2020\n" + "ORIGIN \n", "" + "LOCUS TEST_DATA 20 bp DNA linear UNA 14-MAY-2020\n" + "ORIGIN \n" + " 1 gagttttatc gcttccatga", "" + "LOCUS TEST_DATA 20 bp DNA linear UNA 14-MAY-2020\n" + "ORIGIN \n" + " 1 gagttttatcgcttccatga", "" + "LOCUS TEST_DATA 20 bp DNA linear UNA 14-MAY-2020\n" + "ORIGIN \n" + " 1 gagttttatc gcttccatga", "" + "LOCUS TEST_DATA 20 bp DNA linear UNA 14-MAY-2020\n" + "CONTIG ", "" + "LOCUS NC_001422 5386 bp ss-DNA circular PHG 06-JUL-2018\n" + "FOO ", } func TestGenBankIOFail(t *testing.T)
{ parser := pars.AsParser(GenBankParser) for _, in := range genbankIOFailTests { state := pars.FromString(in) if err := parser(state, pars.Void); err == nil { t.Errorf("while parsing`\n%s\n`: expected error", in) return } } b := bytes.Buffer{} n, err := GenBankWriter{&b}.WriteSeq(gts.New(nil, nil, nil)) if n != 0 || err == nil { t.Errorf("formatting an empty Sequence should return an error") return } }
camera.py
import datetime import logging import queue import subprocess import time import threading import flask import coffeebuddy.facerecognition cameralock = queue.Queue(maxsize=1) thread = None class CameraThread(threading.Thread, coffeebuddy.facerecognition.FaceRecognizer):
def resume(**kwargs): logging.getLogger(__name__).info('Camera resumed.') if not cameralock.empty(): cameralock.get() cameralock.task_done() def pause(**kwargs): logging.getLogger(__name__).info('Camera paused.') if cameralock.empty(): cameralock.put(True) def init(): if flask.current_app.testing: return if flask.current_app.config['CAMERA'] is True: import cv2 logging.getLogger(__name__).info('Camera init.') if 'CAMERA_MOTION_WAIT' not in flask.current_app.config: flask.current_app.config['CAMERA_MOTION_WAIT'] = 10 if 'CAMERA_MOTION_DELTA' not in flask.current_app.config: flask.current_app.config['CAMERA_MOTION_DELTA'] = 2 if 'CAMERA_ROTATION' in flask.current_app.config: if flask.current_app.config['CAMERA_ROTATION'] == 90: flask.current_app.config['CAMERA_ROTATION'] = cv2.ROTATE_90_CLOCKWISE elif flask.current_app.config['CAMERA_ROTATION'] == 180: flask.current_app.config['CAMERA_ROTATION'] = cv2.ROTATE_180 elif flask.current_app.config['CAMERA_ROTATION'] == 270: flask.current_app.config['CAMERA_ROTATION'] = cv2.ROTATE_90_COUNTERCLOCKWISE else: flask.current_app.config['CAMERA_ROTATION'] = None flask.current_app.events.register('route_welcome', resume) flask.current_app.events.register('route_notwelcome', pause) flask.current_app.events.register('facerecognition_capture', pause) flask.current_app.events.register('camera_pause', pause) flask.current_app.events.register('camera_resume', resume) if flask.current_app.config['CAMERA_MOTION_CONTROL_DISPLAY'] is True: flask.current_app.events.register( 'camera_motion_detected', lambda: subprocess.run(['xset', 'dpms', 'force', 'on']) ) flask.current_app.events.register( 'camera_motion_lost', lambda: subprocess.run(['xset', 'dpms', 'force', 'off']) ) global thread cameralock.put(True) thread = CameraThread() thread.start()
def __init__(self): super().__init__() self.app_config = flask.current_app.config self.events = flask.current_app.events self.socketio = flask.current_app.socketio self.avgimage = None def motiondetected(self): import cv2 cap = cv2.VideoCapture(0) cap.set(3, 320) cap.set(4, 240) _, img = cap.read() cap.release() grayimage = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) if self.avgimage is None: self.avgimage = grayimage.copy().astype("float") cv2.accumulateWeighted(grayimage, self.avgimage, 0.5) delta = cv2.absdiff(grayimage, cv2.convertScaleAbs(self.avgimage)) delta = cv2.mean(delta)[0] if delta > self.app_config['CAMERA_MOTION_DELTA']: return True return False def run(self): last_motion_detected = datetime.datetime.now() while True: if not cameralock.empty(): cameralock.join() detected = self.motiondetected() if datetime.datetime.now() - last_motion_detected < datetime.timedelta( seconds=self.app_config['CAMERA_MOTION_WAIT'] ): tag = self.recognize_once() if tag: logging.getLogger(__name__).info(f'Face recognized {tag}.') self.socketio.emit('card_connected', data=dict(tag=tag.hex())) elif detected: last_motion_detected = datetime.datetime.now() self.events.fire_reset('camera_motion_lost') self.events.fire('camera_motion_detected') logging.getLogger(__name__).info(f'Motion detected {last_motion_detected}.') else: self.events.fire_once('camera_motion_lost') time.sleep(0.05)
json.rs
// Copyright 2012-2017 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. use super::*; pub(crate) struct JsonFormatter<T> { out: OutputLocation<T>, } impl<T: Write> JsonFormatter<T> { pub fn new(out: OutputLocation<T>) -> Self { Self { out } } fn write_message(&mut self, s: &str) -> io::Result<()> { assert!(!s.contains('\n')); self.out.write_all(s.as_ref())?; self.out.write_all(b"\n") } fn write_event( &mut self, ty: &str, name: &str, evt: &str, extra: Option<String>, ) -> io::Result<()> { if let Some(extras) = extra { self.write_message(&*format!( r#"{{ "type": "{}", "name": "{}", "event": "{}", {} }}"#, ty, name, evt, extras )) } else { self.write_message(&*format!( r#"{{ "type": "{}", "name": "{}", "event": "{}" }}"#, ty, name, evt )) } } } impl<T: Write> OutputFormatter for JsonFormatter<T> { fn write_run_start(&mut self, test_count: usize) -> io::Result<()> { self.write_message(&*format!( r#"{{ "type": "suite", "event": "started", "test_count": "{}" }}"#, test_count )) } fn write_test_start(&mut self, desc: &TestDesc) -> io::Result<()> { self.write_message(&*format!( r#"{{ "type": "test", "event": "started", "name": "{}" }}"#, desc.name )) } fn write_result( &mut self, desc: &TestDesc, result: &TestResult, stdout: &[u8], ) -> io::Result<()> { match *result { TrOk => self.write_event("test", desc.name.as_slice(), "ok", None), TrFailed => { let extra_data = if stdout.len() > 0 { Some(format!( r#""stdout": "{}""#, EscapedString(String::from_utf8_lossy(stdout)) )) } else { None }; self.write_event("test", desc.name.as_slice(), "failed", extra_data) } TrFailedMsg(ref m) => self.write_event( "test", desc.name.as_slice(), "failed", Some(format!(r#""message": "{}""#, EscapedString(m))), ), TrIgnored => self.write_event("test", desc.name.as_slice(), "ignored", None), TrAllowedFail => { self.write_event("test", desc.name.as_slice(), "allowed_failure", None) } TrBench(ref bs) => { let median = bs.ns_iter_summ.median as usize; let deviation = (bs.ns_iter_summ.max - bs.ns_iter_summ.min) as usize; let mbps = if bs.mb_s == 0 { String::new() } else { format!(r#", "mib_per_second": {}"#, bs.mb_s) }; let line = format!( "{{ \"type\": \"bench\", \ \"name\": \"{}\", \ \"median\": {}, \ \"deviation\": {}{} }}", desc.name, median, deviation, mbps ); self.write_message(&*line) } } } fn write_timeout(&mut self, desc: &TestDesc) -> io::Result<()> { self.write_message(&*format!( r#"{{ "type": "test", "event": "timeout", "name": "{}" }}"#, desc.name )) } fn write_run_finish(&mut self, state: &ConsoleTestState) -> io::Result<bool> { self.write_message(&*format!( "{{ \"type\": \"suite\", \ \"event\": \"{}\", \ \"passed\": {}, \ \"failed\": {}, \ \"allowed_fail\": {}, \ \"ignored\": {}, \ \"measured\": {}, \ \"filtered_out\": \"{}\" }}", if state.failed == 0 { "ok" } else { "failed" }, state.passed, state.failed + state.allowed_fail, state.allowed_fail, state.ignored, state.measured, state.filtered_out ))?; Ok(state.failed == 0) } } /// A formatting utility used to print strings with characters in need of escaping. /// Base code taken form `libserialize::json::escape_str` struct
<S: AsRef<str>>(S); impl<S: AsRef<str>> ::std::fmt::Display for EscapedString<S> { fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result { let mut start = 0; for (i, byte) in self.0.as_ref().bytes().enumerate() { let escaped = match byte { b'"' => "\\\"", b'\\' => "\\\\", b'\x00' => "\\u0000", b'\x01' => "\\u0001", b'\x02' => "\\u0002", b'\x03' => "\\u0003", b'\x04' => "\\u0004", b'\x05' => "\\u0005", b'\x06' => "\\u0006", b'\x07' => "\\u0007", b'\x08' => "\\b", b'\t' => "\\t", b'\n' => "\\n", b'\x0b' => "\\u000b", b'\x0c' => "\\f", b'\r' => "\\r", b'\x0e' => "\\u000e", b'\x0f' => "\\u000f", b'\x10' => "\\u0010", b'\x11' => "\\u0011", b'\x12' => "\\u0012", b'\x13' => "\\u0013", b'\x14' => "\\u0014", b'\x15' => "\\u0015", b'\x16' => "\\u0016", b'\x17' => "\\u0017", b'\x18' => "\\u0018", b'\x19' => "\\u0019", b'\x1a' => "\\u001a", b'\x1b' => "\\u001b", b'\x1c' => "\\u001c", b'\x1d' => "\\u001d", b'\x1e' => "\\u001e", b'\x1f' => "\\u001f", b'\x7f' => "\\u007f", _ => { continue; } }; if start < i { f.write_str(&self.0.as_ref()[start..i])?; } f.write_str(escaped)?; start = i + 1; } if start != self.0.as_ref().len() { f.write_str(&self.0.as_ref()[start..])?; } Ok(()) } }
EscapedString
cmulti_c1243_3c.py
# generate data: specify number of data points generated NUM_DATA_POINTS = 5000 # the minimum number of variables required for the equation to work MIN_VARIABLES = 4 # specify objective function def func(x, num_var): result = 0.0 for i in range(num_var): result += x[i]**2 return result # specify whether to minimise or maximise function, 0 for min 1 for max MIN_OR_MAX_FLAG = 0 # set the min and max range for the variables X_MIN_RANGE = -50.0 X_MAX_RANGE = 50.0 # specify constraints (return 0 if constraint is met, otherwise return absolute distance) def c0(x, num_var): # the constraint is: (80 - x[0] - x[1]) <= 0 result = 80 - x[0] - x[1] if result <= 0.0: return 0.0 else: return result def c1(x, num_var): # the constraint is: x[2] + 45 <= 0 result = x[2] + 45 if result <= 0.0: return 0.0 else: return result def c2(x, num_var): # the constraint is: -7 <= x[2] + x[3] <= -5 LOWER_BOUND = -7.0 UPPER_BOUND = -5.0 result = x[2] + x[3] if (result <= UPPER_BOUND) and (result >= LOWER_BOUND): # inside bounds return 0.0 else: if result < LOWER_BOUND: distance = result - LOWER_BOUND else: distance = result - UPPER_BOUND if distance >= 0: # always return a positive distance return distance else: return (-distance) # list of constraints: add specified constraints to this list in order for them to be considered CONSTRAINTS = [ c0, c1, c2 ] # calculate the optimal result for the function for the constraint(s) to be met optimal_point = [40.0, 40.0, -45.0, 40.0] def
(num_var): return func(optimal_point, num_var) # generate data: specify num gen and num pop for the data generator GA DATAGEN_GEN = 200 #500 DATAGEN_POP = 200 # generate data: specify min and max range for data DATAGEN_MIN_RANGE = -1.0 DATAGEN_MAX_RANGE = 1.0 # learn representation: specify the number of latent variables and epochs for the vae # NUM_LATENT = NUM_VARIABLES NUM_EPOCHS = 200 # optimise: specify num gen and num pop for the optimiser GA VAEGA_GEN = 50 VAEGA_POP = 20 # optimse: the range for the GA to generate random numbers for the latent variable VAEGA_MIN_RANGE = -2.0 VAEGA_MAX_RANGE = 2.0 # comparison GA: specify num gen and num pop for the GA # GA_NUM_INDIVIDUALS = NUM_VARIABLES # the number of individuals for the GA is the number of variables GA_GEN = 50 GA_POP = 20
calculate_optimal
_future.py
"""Future-returning APIs for coroutines.""" # Copyright (c) PyZMQ Developers. # Distributed under the terms of the Modified BSD License. from collections import namedtuple, deque from itertools import chain from typing import Type from zmq import EVENTS, POLLOUT, POLLIN import zmq as _zmq _FutureEvent = namedtuple('_FutureEvent', ('future', 'kind', 'kwargs', 'msg', 'timer')) # These are incomplete classes and need a Mixin for compatibility with an eventloop # defining the following attributes: # # _Future # _READ # _WRITE # _default_loop() class _AsyncPoller(_zmq.Poller): """Poller that returns a Future on poll, instead of blocking.""" _socket_class = None # type: Type[_AsyncSocket] def poll(self, timeout=-1): """Return a Future for a poll event""" future = self._Future() if timeout == 0: try: result = super(_AsyncPoller, self).poll(0) except Exception as e: future.set_exception(e) else: future.set_result(result) return future loop = self._default_loop() # register Future to be called as soon as any event is available on any socket watcher = self._Future() # watch raw sockets: raw_sockets = [] def wake_raw(*args): if not watcher.done(): watcher.set_result(None) watcher.add_done_callback( lambda f: self._unwatch_raw_sockets(loop, *raw_sockets) ) for socket, mask in self.sockets: if isinstance(socket, _zmq.Socket): if not isinstance(socket, self._socket_class): # it's a blocking zmq.Socket, wrap it in async socket = self._socket_class.from_socket(socket) if mask & _zmq.POLLIN: socket._add_recv_event('poll', future=watcher) if mask & _zmq.POLLOUT: socket._add_send_event('poll', future=watcher) else: raw_sockets.append(socket) evt = 0 if mask & _zmq.POLLIN: evt |= self._READ if mask & _zmq.POLLOUT: evt |= self._WRITE self._watch_raw_socket(loop, socket, evt, wake_raw) def on_poll_ready(f): if future.done(): return if watcher.cancelled(): try: future.cancel() except RuntimeError: # RuntimeError may be called during teardown pass return if watcher.exception(): future.set_exception(watcher.exception()) else: try: result = super(_AsyncPoller, self).poll(0) except Exception as e: future.set_exception(e) else: future.set_result(result) watcher.add_done_callback(on_poll_ready) if timeout is not None and timeout > 0: # schedule cancel to fire on poll timeout, if any def trigger_timeout(): if not watcher.done(): watcher.set_result(None) timeout_handle = loop.call_later(1e-3 * timeout, trigger_timeout) def cancel_timeout(f): if hasattr(timeout_handle, 'cancel'): timeout_handle.cancel() else: loop.remove_timeout(timeout_handle) future.add_done_callback(cancel_timeout) def cancel_watcher(f): if not watcher.done(): watcher.cancel() future.add_done_callback(cancel_watcher) return future class _NoTimer(object): @staticmethod def cancel(): pass class _AsyncSocket(_zmq.Socket): # Warning : these class variables are only here to allow to call super().__setattr__. # They be overridden at instance initialization and not shared in the whole class _recv_futures = None _send_futures = None _state = 0 _shadow_sock = None _poller_class = _AsyncPoller io_loop = None _fd = None def __init__(self, context=None, socket_type=-1, io_loop=None, **kwargs): if isinstance(context, _zmq.Socket): context, from_socket = (None, context) else: from_socket = kwargs.pop('_from_socket', None) if from_socket is not None: super(_AsyncSocket, self).__init__(shadow=from_socket.underlying) self._shadow_sock = from_socket else: super(_AsyncSocket, self).__init__(context, socket_type, **kwargs) self._shadow_sock = _zmq.Socket.shadow(self.underlying) self.io_loop = io_loop or self._default_loop() self._recv_futures = deque() self._send_futures = deque() self._state = 0 self._fd = self._shadow_sock.FD self._init_io_state() @classmethod def from_socket(cls, socket, io_loop=None): """Create an async socket from an existing Socket""" return cls(_from_socket=socket, io_loop=io_loop) def close(self, linger=None): if not self.closed and self._fd is not None: for event in list( chain(self._recv_futures or [], self._send_futures or []) ): if not event.future.done(): try: event.future.cancel() except RuntimeError: # RuntimeError may be called during teardown pass self._clear_io_state() super(_AsyncSocket, self).close(linger=linger) close.__doc__ = _zmq.Socket.close.__doc__ def get(self, key): result = super(_AsyncSocket, self).get(key) if key == EVENTS: self._schedule_remaining_events(result) return result get.__doc__ = _zmq.Socket.get.__doc__ def recv_multipart(self, flags=0, copy=True, track=False): """Receive a complete multipart zmq message. Returns a Future whose result will be a multipart message. """ return self._add_recv_event( 'recv_multipart', dict(flags=flags, copy=copy, track=track) ) def recv(self, flags=0, copy=True, track=False): """Receive a single zmq frame. Returns a Future, whose result will be the received frame. Recommend using recv_multipart instead. """ return self._add_recv_event('recv', dict(flags=flags, copy=copy, track=track)) def send_multipart(self, msg, flags=0, copy=True, track=False, **kwargs): """Send a complete multipart zmq message. Returns a Future that resolves when sending is complete. """ kwargs['flags'] = flags kwargs['copy'] = copy kwargs['track'] = track return self._add_send_event('send_multipart', msg=msg, kwargs=kwargs) def send(self, msg, flags=0, copy=True, track=False, **kwargs): """Send a single zmq frame. Returns a Future that resolves when sending is complete. Recommend using send_multipart instead. """ kwargs['flags'] = flags kwargs['copy'] = copy kwargs['track'] = track kwargs.update(dict(flags=flags, copy=copy, track=track)) return self._add_send_event('send', msg=msg, kwargs=kwargs) def _deserialize(self, recvd, load): """Deserialize with Futures""" f = self._Future() def _chain(_): """Chain result through serialization to recvd""" if f.done(): return if recvd.exception(): f.set_exception(recvd.exception()) else: buf = recvd.result() try: loaded = load(buf) except Exception as e: f.set_exception(e) else: f.set_result(loaded) recvd.add_done_callback(_chain) def _chain_cancel(_): """Chain cancellation from f to recvd""" if recvd.done(): return if f.cancelled(): recvd.cancel() f.add_done_callback(_chain_cancel) return f def poll(self, timeout=None, flags=_zmq.POLLIN): """poll the socket for events returns a Future for the poll results. """ if self.closed: raise _zmq.ZMQError(_zmq.ENOTSUP) p = self._poller_class() p.register(self, flags) f = p.poll(timeout) future = self._Future() def unwrap_result(f): if future.done(): return if f.cancelled(): try: future.cancel() except RuntimeError: # RuntimeError may be called during teardown pass return if f.exception(): future.set_exception(f.exception()) else: evts = dict(f.result()) future.set_result(evts.get(self, 0)) if f.done(): # hook up result if unwrap_result(f) else: f.add_done_callback(unwrap_result) return future def _add_timeout(self, future, timeout): """Add a timeout for a send or recv Future""" def future_timeout(): if future.done(): # future already resolved, do nothing return # raise EAGAIN future.set_exception(_zmq.Again()) return self._call_later(timeout, future_timeout) def _call_later(self, delay, callback): """Schedule a function to be called later Override for different IOLoop implementations Tornado and asyncio happen to both have ioloop.call_later with the same signature. """ return self.io_loop.call_later(delay, callback) @staticmethod def _remove_finished_future(future, event_list): """Make sure that futures are removed from the event list when they resolve Avoids delaying cleanup until the next send/recv event, which may never come. """ for f_idx, event in enumerate(event_list): if event.future is future: break else: return # "future" instance is shared between sockets, but each socket has its own event list. event_list.remove(event_list[f_idx]) def _add_recv_event(self, kind, kwargs=None, future=None): """Add a recv event, returning the corresponding Future""" f = future or self._Future() if kind.startswith('recv') and kwargs.get('flags', 0) & _zmq.DONTWAIT: # short-circuit non-blocking calls recv = getattr(self._shadow_sock, kind) try: r = recv(**kwargs) except Exception as e: f.set_exception(e) else: f.set_result(r) return f timer = _NoTimer if hasattr(_zmq, 'RCVTIMEO'): timeout_ms = self._shadow_sock.rcvtimeo if timeout_ms >= 0: timer = self._add_timeout(f, timeout_ms * 1e-3) # we add it to the list of futures before we add the timeout as the # timeout will remove the future from recv_futures to avoid leaks self._recv_futures.append(_FutureEvent(f, kind, kwargs, msg=None, timer=timer)) # Don't let the Future sit in _recv_events after it's done f.add_done_callback( lambda f: self._remove_finished_future(f, self._recv_futures) ) if self._shadow_sock.get(EVENTS) & POLLIN: # recv immediately, if we can self._handle_recv() if self._recv_futures: self._add_io_state(POLLIN) return f def _add_send_event(self, kind, msg=None, kwargs=None, future=None): """Add a send event, returning the corresponding Future""" f = future or self._Future() # attempt send with DONTWAIT if no futures are waiting # short-circuit for sends that will resolve immediately # only call if no send Futures are waiting if kind in ('send', 'send_multipart') and not self._send_futures: flags = kwargs.get('flags', 0) nowait_kwargs = kwargs.copy() nowait_kwargs['flags'] = flags | _zmq.DONTWAIT # short-circuit non-blocking calls send = getattr(self._shadow_sock, kind) # track if the send resolved or not # (EAGAIN if DONTWAIT is not set should proceed with) finish_early = True try: r = send(msg, **nowait_kwargs) except _zmq.Again as e: if flags & _zmq.DONTWAIT: f.set_exception(e) else: # EAGAIN raised and DONTWAIT not requested, # proceed with async send finish_early = False except Exception as e: f.set_exception(e) else: f.set_result(r) if finish_early: # short-circuit resolved, return finished Future # schedule wake for recv if there are any receivers waiting if self._recv_futures: self._schedule_remaining_events() return f timer = _NoTimer if hasattr(_zmq, 'SNDTIMEO'): timeout_ms = self._shadow_sock.get(_zmq.SNDTIMEO) if timeout_ms >= 0: timer = self._add_timeout(f, timeout_ms * 1e-3) # we add it to the list of futures before we add the timeout as the # timeout will remove the future from recv_futures to avoid leaks self._send_futures.append( _FutureEvent(f, kind, kwargs=kwargs, msg=msg, timer=timer) ) # Don't let the Future sit in _send_futures after it's done f.add_done_callback( lambda f: self._remove_finished_future(f, self._send_futures) ) self._add_io_state(POLLOUT) return f def _handle_recv(self): """Handle recv events""" if not self._shadow_sock.get(EVENTS) & POLLIN: # event triggered, but state may have been changed between trigger and callback return f = None while self._recv_futures: f, kind, kwargs, _, timer = self._recv_futures.popleft() # skip any cancelled futures if f.done(): f = None else: break if not self._recv_futures: self._drop_io_state(POLLIN) if f is None: return timer.cancel() if kind == 'poll': # on poll event, just signal ready, nothing else. f.set_result(None) return elif kind == 'recv_multipart': recv = self._shadow_sock.recv_multipart elif kind == 'recv': recv = self._shadow_sock.recv else: raise ValueError("Unhandled recv event type: %r" % kind) kwargs['flags'] |= _zmq.DONTWAIT try: result = recv(**kwargs) except Exception as e: f.set_exception(e) else: f.set_result(result) def _handle_send(self): if not self._shadow_sock.get(EVENTS) & POLLOUT: # event triggered, but state may have been changed between trigger and callback return f = None while self._send_futures: f, kind, kwargs, msg, timer = self._send_futures.popleft() # skip any cancelled futures if f.done(): f = None else: break if not self._send_futures: self._drop_io_state(POLLOUT) if f is None: return timer.cancel() if kind == 'poll': # on poll event, just signal ready, nothing else. f.set_result(None) return elif kind == 'send_multipart': send = self._shadow_sock.send_multipart elif kind == 'send': send = self._shadow_sock.send else: raise ValueError("Unhandled send event type: %r" % kind) kwargs['flags'] |= _zmq.DONTWAIT try: result = send(msg, **kwargs) except Exception as e: f.set_exception(e) else: f.set_result(result) # event masking from ZMQStream def _handle_events(self, fd=0, events=0): """Dispatch IO events to _handle_recv, etc.""" zmq_events = self._shadow_sock.get(EVENTS) if zmq_events & _zmq.POLLIN: self._handle_recv() if zmq_events & _zmq.POLLOUT: self._handle_send() self._schedule_remaining_events() def _schedule_remaining_events(self, events=None): """Schedule a call to handle_events next loop iteration If there are still events to handle. """ # edge-triggered handling # allow passing events in, in case this is triggered by retrieving events, # so we don't have to retrieve it twice. if self._state == 0: # not watching for anything, nothing to schedule return if events is None: events = self._shadow_sock.get(EVENTS) if events & self._state: self._call_later(0, self._handle_events) def _add_io_state(self, state): """Add io_state to poller.""" if self._state != state: state = self._state = self._state | state self._update_handler(self._state) def _drop_io_state(self, state): """Stop poller from watching an io_state.""" if self._state & state: self._state = self._state & (~state) self._update_handler(self._state) def _update_handler(self, state): """Update IOLoop handler with state. zmq FD is always read-only. """ self._schedule_remaining_events() def _init_io_state(self): """initialize the ioloop event handler""" self.io_loop.add_handler(self._shadow_sock, self._handle_events, self._READ) self._call_later(0, self._handle_events) def _clear_io_state(self):
"""unregister the ioloop event handler called once during close """ fd = self._shadow_sock if self._shadow_sock.closed: fd = self._fd self.io_loop.remove_handler(fd)
gallery.js
import React from "react"; import Frame from '../components/frame' const GalleryPage = () => { return ( <Frame> <p>Dit wordt doorgegeven als children</p>
export default GalleryPage
</Frame> ) }
toDos.component.spec.ts
/* tslint:disable:no-unused-variable */ import { async, ComponentFixture, TestBed } from '@angular/core/testing'; import { By } from '@angular/platform-browser'; import { DebugElement } from '@angular/core'; import { ToDosComponent } from './toDos.component'; describe('ToDosComponent', () => { let component: ToDosComponent; let fixture: ComponentFixture<ToDosComponent>; beforeEach(async(() => { TestBed.configureTestingModule({ declarations: [ ToDosComponent ] }) .compileComponents(); })); beforeEach(() => { fixture = TestBed.createComponent(ToDosComponent); component = fixture.componentInstance;
}); it('should create', () => { expect(component).toBeTruthy(); }); });
fixture.detectChanges();
lexer.rs
#[derive(PartialEq, Debug)] pub enum Token<'a> { Input, String(&'a str), Dollar, Plus, Colon, OpenParen, CloseParen, OpenBracket, CloseBracket, } impl<'a> Token<'a> { pub fn
(&self) -> &str { use Token::*; match self { Input => "_", String(_) => "string", Dollar => "$", Plus => "+", Colon => ":", OpenParen => "`(`", CloseParen => "`)`", OpenBracket => "`[`", CloseBracket => "`]`", } } } // perhaps this could an iterator instead, or maybe not pub fn lex(src: &str) -> Result<Vec<Token>, &str> { let mut vec = Vec::new(); let mut inside_str = false; let mut is_escaping = false; let mut str_start = 0usize; for i in 0..src.len() { let elem = &src[i..i + 1]; if inside_str { if is_escaping { is_escaping = false; } else if elem == "\\" { is_escaping = true; } else if elem == "\"" { inside_str = false; assert_ne!(str_start, 0); vec.push(Token::String(&src[str_start..i])); } continue; } if elem == "\"" { inside_str = true; str_start = i + 1; continue; } let token = match elem { "_" => Token::Input, "$" => Token::Dollar, "+" => Token::Plus, ":" => Token::Colon, "(" => Token::OpenParen, ")" => Token::CloseParen, "[" => Token::OpenBracket, "]" => Token::CloseBracket, " " | "\t" | "\n" | "\r" => continue, _ => return Err("unidentified token"), }; vec.push(token); } if inside_str { Err("unterminated string") } else { Ok(vec) } }
describe
lib.rs
#![allow(clippy::all)] use std::collections::BTreeMap; use std::fmt; use std::fs::File; use std::io::prelude::*; use std::io::{Cursor, SeekFrom}; use std::time::Instant; use anyhow::{bail, format_err, Context, Result}; use curl::easy::{Easy, List}; use percent_encoding::{percent_encode, NON_ALPHANUMERIC}; use serde::{Deserialize, Serialize}; use url::Url; pub struct Registry { /// The base URL for issuing API requests. host: String, /// Optional authorization token. /// If None, commands requiring authorization will fail. token: Option<String>, /// Curl handle for issuing requests. handle: Easy, } #[derive(PartialEq, Clone, Copy)] pub enum Auth { Authorized, Unauthorized, } #[derive(Deserialize)] pub struct Crate { pub name: String, pub description: Option<String>, pub max_version: String, } #[derive(Serialize)] pub struct NewCrate { pub name: String, pub vers: String, pub deps: Vec<NewCrateDependency>, pub features: BTreeMap<String, Vec<String>>, pub authors: Vec<String>, pub description: Option<String>, pub documentation: Option<String>, pub homepage: Option<String>, pub readme: Option<String>, pub readme_file: Option<String>, pub keywords: Vec<String>, pub categories: Vec<String>, pub license: Option<String>, pub license_file: Option<String>, pub repository: Option<String>, pub badges: BTreeMap<String, BTreeMap<String, String>>, pub links: Option<String>, #[serde(skip_serializing_if = "Option::is_none")] pub v: Option<u32>, } #[derive(Serialize)] pub struct NewCrateDependency { pub optional: bool, pub default_features: bool, pub name: String, pub features: Vec<String>, pub version_req: String, pub target: Option<String>, pub kind: String, #[serde(skip_serializing_if = "Option::is_none")] pub registry: Option<String>, #[serde(skip_serializing_if = "Option::is_none")] pub explicit_name_in_toml: Option<String>, } #[derive(Deserialize)] pub struct User { pub id: u32, pub login: String, pub avatar: Option<String>, pub email: Option<String>, pub name: Option<String>, } pub struct Warnings { pub invalid_categories: Vec<String>, pub invalid_badges: Vec<String>, pub other: Vec<String>, } #[derive(Deserialize)] struct
{ ok: bool, } #[derive(Deserialize)] struct OwnerResponse { ok: bool, msg: String, } #[derive(Deserialize)] struct ApiErrorList { errors: Vec<ApiError>, } #[derive(Deserialize)] struct ApiError { detail: String, } #[derive(Serialize)] struct OwnersReq<'a> { users: &'a [&'a str], } #[derive(Deserialize)] struct Users { users: Vec<User>, } #[derive(Deserialize)] struct TotalCrates { total: u32, } #[derive(Deserialize)] struct Crates { crates: Vec<Crate>, meta: TotalCrates, } #[derive(Debug)] pub enum ResponseError { Curl(curl::Error), Api { code: u32, errors: Vec<String>, }, Code { code: u32, headers: Vec<String>, body: String, }, Other(anyhow::Error), } impl std::error::Error for ResponseError { fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { match self { ResponseError::Curl(..) => None, ResponseError::Api { .. } => None, ResponseError::Code { .. } => None, ResponseError::Other(e) => Some(e.as_ref()), } } } impl fmt::Display for ResponseError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self { ResponseError::Curl(e) => write!(f, "{}", e), ResponseError::Api { code, errors } => { f.write_str("the remote server responded with an error")?; if *code != 200 { write!(f, " (status {} {})", code, reason(*code))?; }; write!(f, ": {}", errors.join(", ")) } ResponseError::Code { code, headers, body, } => write!( f, "failed to get a 200 OK response, got {}\n\ headers:\n\ \t{}\n\ body:\n\ {}", code, headers.join("\n\t"), body ), ResponseError::Other(..) => write!(f, "invalid response from server"), } } } impl From<curl::Error> for ResponseError { fn from(error: curl::Error) -> Self { ResponseError::Curl(error) } } impl Registry { /// Creates a new `Registry`. /// /// ## Example /// /// ```rust /// use curl::easy::Easy; /// use crates_io::Registry; /// /// let mut handle = Easy::new(); /// // If connecting to crates.io, a user-agent is required. /// handle.useragent("my_crawler (example.com/info)"); /// let mut reg = Registry::new_handle(String::from("https://crates.io"), None, handle); /// ``` pub fn new_handle(host: String, token: Option<String>, handle: Easy) -> Registry { Registry { host, token, handle, } } pub fn host(&self) -> &str { &self.host } pub fn host_is_crates_io(&self) -> bool { is_url_crates_io(&self.host) } pub fn add_owners(&mut self, krate: &str, owners: &[&str]) -> Result<String> { let body = serde_json::to_string(&OwnersReq { users: owners })?; let body = self.put(&format!("/crates/{}/owners", krate), body.as_bytes())?; assert!(serde_json::from_str::<OwnerResponse>(&body)?.ok); Ok(serde_json::from_str::<OwnerResponse>(&body)?.msg) } pub fn remove_owners(&mut self, krate: &str, owners: &[&str]) -> Result<()> { let body = serde_json::to_string(&OwnersReq { users: owners })?; let body = self.delete(&format!("/crates/{}/owners", krate), Some(body.as_bytes()))?; assert!(serde_json::from_str::<OwnerResponse>(&body)?.ok); Ok(()) } pub fn list_owners(&mut self, krate: &str) -> Result<Vec<User>> { let body = self.get(&format!("/crates/{}/owners", krate))?; Ok(serde_json::from_str::<Users>(&body)?.users) } pub fn publish(&mut self, krate: &NewCrate, mut tarball: &File) -> Result<Warnings> { let json = serde_json::to_string(krate)?; // Prepare the body. The format of the upload request is: // // <le u32 of json> // <json request> (metadata for the package) // <le u32 of tarball> // <source tarball> // NOTE: This can be replaced with `stream_len` if it is ever stabilized. // // This checks the length using seeking instead of metadata, because // on some filesystems, getting the metadata will fail because // the file was renamed in ops::package. let tarball_len = tarball .seek(SeekFrom::End(0)) .with_context(|| "failed to seek tarball")?; tarball .seek(SeekFrom::Start(0)) .with_context(|| "failed to seek tarball")?; let header = { let mut w = Vec::new(); w.extend(&(json.len() as u32).to_le_bytes()); w.extend(json.as_bytes().iter().cloned()); w.extend(&(tarball_len as u32).to_le_bytes()); w }; let size = tarball_len as usize + header.len(); let mut body = Cursor::new(header).chain(tarball); let url = format!("{}/api/v1/crates/new", self.host); let token = match self.token.as_ref() { Some(s) => s, None => bail!("no upload token found, please run `cargo login`"), }; self.handle.put(true)?; self.handle.url(&url)?; self.handle.in_filesize(size as u64)?; let mut headers = List::new(); headers.append("Accept: application/json")?; headers.append(&format!("Authorization: {}", token))?; self.handle.http_headers(headers)?; let started = Instant::now(); let body = self .handle(&mut |buf| body.read(buf).unwrap_or(0)) .map_err(|e| match e { ResponseError::Code { code, .. } if code == 503 && started.elapsed().as_secs() >= 29 && self.host_is_crates_io() => { format_err!( "Request timed out after 30 seconds. If you're trying to \ upload a crate it may be too large. If the crate is under \ 10MB in size, you can email [email protected] for assistance.\n\ Total size was {}.", tarball_len ) } _ => e.into(), })?; let response = if body.is_empty() { "{}".parse()? } else { body.parse::<serde_json::Value>()? }; let invalid_categories: Vec<String> = response .get("warnings") .and_then(|j| j.get("invalid_categories")) .and_then(|j| j.as_array()) .map(|x| x.iter().flat_map(|j| j.as_str()).map(Into::into).collect()) .unwrap_or_else(Vec::new); let invalid_badges: Vec<String> = response .get("warnings") .and_then(|j| j.get("invalid_badges")) .and_then(|j| j.as_array()) .map(|x| x.iter().flat_map(|j| j.as_str()).map(Into::into).collect()) .unwrap_or_else(Vec::new); let other: Vec<String> = response .get("warnings") .and_then(|j| j.get("other")) .and_then(|j| j.as_array()) .map(|x| x.iter().flat_map(|j| j.as_str()).map(Into::into).collect()) .unwrap_or_else(Vec::new); Ok(Warnings { invalid_categories, invalid_badges, other, }) } pub fn search(&mut self, query: &str, limit: u32) -> Result<(Vec<Crate>, u32)> { let formatted_query = percent_encode(query.as_bytes(), NON_ALPHANUMERIC); let body = self.req( &format!("/crates?q={}&per_page={}", formatted_query, limit), None, Auth::Unauthorized, )?; let crates = serde_json::from_str::<Crates>(&body)?; Ok((crates.crates, crates.meta.total)) } pub fn yank(&mut self, krate: &str, version: &str) -> Result<()> { let body = self.delete(&format!("/crates/{}/{}/yank", krate, version), None)?; assert!(serde_json::from_str::<R>(&body)?.ok); Ok(()) } pub fn unyank(&mut self, krate: &str, version: &str) -> Result<()> { let body = self.put(&format!("/crates/{}/{}/unyank", krate, version), &[])?; assert!(serde_json::from_str::<R>(&body)?.ok); Ok(()) } fn put(&mut self, path: &str, b: &[u8]) -> Result<String> { self.handle.put(true)?; self.req(path, Some(b), Auth::Authorized) } fn get(&mut self, path: &str) -> Result<String> { self.handle.get(true)?; self.req(path, None, Auth::Authorized) } fn delete(&mut self, path: &str, b: Option<&[u8]>) -> Result<String> { self.handle.custom_request("DELETE")?; self.req(path, b, Auth::Authorized) } fn req(&mut self, path: &str, body: Option<&[u8]>, authorized: Auth) -> Result<String> { self.handle.url(&format!("{}/api/v1{}", self.host, path))?; let mut headers = List::new(); headers.append("Accept: application/json")?; headers.append("Content-Type: application/json")?; if authorized == Auth::Authorized { let token = match self.token.as_ref() { Some(s) => s, None => bail!("no upload token found, please run `cargo login`"), }; headers.append(&format!("Authorization: {}", token))?; } self.handle.http_headers(headers)?; match body { Some(mut body) => { self.handle.upload(true)?; self.handle.in_filesize(body.len() as u64)?; self.handle(&mut |buf| body.read(buf).unwrap_or(0)) .map_err(|e| e.into()) } None => self.handle(&mut |_| 0).map_err(|e| e.into()), } } fn handle( &mut self, read: &mut dyn FnMut(&mut [u8]) -> usize, ) -> std::result::Result<String, ResponseError> { let mut headers = Vec::new(); let mut body = Vec::new(); { let mut handle = self.handle.transfer(); handle.read_function(|buf| Ok(read(buf)))?; handle.write_function(|data| { body.extend_from_slice(data); Ok(data.len()) })?; handle.header_function(|data| { // Headers contain trailing \r\n, trim them to make it easier // to work with. let s = String::from_utf8_lossy(data).trim().to_string(); headers.push(s); true })?; handle.perform()?; } let body = match String::from_utf8(body) { Ok(body) => body, Err(..) => { return Err(ResponseError::Other(format_err!( "response body was not valid utf-8" ))) } }; let errors = serde_json::from_str::<ApiErrorList>(&body) .ok() .map(|s| s.errors.into_iter().map(|s| s.detail).collect::<Vec<_>>()); match (self.handle.response_code()?, errors) { (0, None) | (200, None) => Ok(body), (code, Some(errors)) => Err(ResponseError::Api { code, errors }), (code, None) => Err(ResponseError::Code { code, headers, body, }), } } } fn reason(code: u32) -> &'static str { // Taken from https://developer.mozilla.org/en-US/docs/Web/HTTP/Status match code { 100 => "Continue", 101 => "Switching Protocol", 103 => "Early Hints", 200 => "OK", 201 => "Created", 202 => "Accepted", 203 => "Non-Authoritative Information", 204 => "No Content", 205 => "Reset Content", 206 => "Partial Content", 300 => "Multiple Choice", 301 => "Moved Permanently", 302 => "Found", 303 => "See Other", 304 => "Not Modified", 307 => "Temporary Redirect", 308 => "Permanent Redirect", 400 => "Bad Request", 401 => "Unauthorized", 402 => "Payment Required", 403 => "Forbidden", 404 => "Not Found", 405 => "Method Not Allowed", 406 => "Not Acceptable", 407 => "Proxy Authentication Required", 408 => "Request Timeout", 409 => "Conflict", 410 => "Gone", 411 => "Length Required", 412 => "Precondition Failed", 413 => "Payload Too Large", 414 => "URI Too Long", 415 => "Unsupported Media Type", 416 => "Request Range Not Satisfiable", 417 => "Expectation Failed", 429 => "Too Many Requests", 431 => "Request Header Fields Too Large", 500 => "Internal Server Error", 501 => "Not Implemented", 502 => "Bad Gateway", 503 => "Service Unavailable", 504 => "Gateway Timeout", _ => "<unknown>", } } /// Returns `true` if the host of the given URL is "crates.io". pub fn is_url_crates_io(url: &str) -> bool { Url::parse(url) .map(|u| u.host_str() == Some("crates.io")) .unwrap_or(false) }
R
pravega_retention_checker.rs
// // Copyright (c) Dell Inc., or its subsidiaries. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // use clap::Clap; use log::info; use std::{thread, time}; use pravega_client::client_factory::ClientFactory; use pravega_client_shared::{Scope, Stream, ScopedStream}; use pravega_video::index::IndexSearcher; use pravega_video::utils; use pravega_video::utils::SyncByteReader; #[derive(Clap)] struct Opts { /// Pravega controller in format "127.0.0.1:9090" #[clap(short, long, default_value = "127.0.0.1:9090")] controller: String, /// Pravega scope #[clap(long)] scope: String, /// Pravega stream #[clap(long)] stream: String, /// Pravega keycloak file #[clap(long, default_value = "", setting(clap::ArgSettings::AllowEmptyValues))] keycloak_file: String, /// Check period #[clap(long, default_value = "60", setting(clap::ArgSettings::AllowEmptyValues))] check_period: u64, } /// Demonstrate ability to write using the byte stream writer and read using the event reader. fn main() { env_logger::init(); let opts: Opts = Opts::parse(); let keycloak_file = if opts.keycloak_file.is_empty() { None } else { Some(opts.keycloak_file) }; let client_config = utils::create_client_config(opts.controller, keycloak_file).expect("creating config"); let client_factory = ClientFactory::new(client_config); let scope = Scope::from(opts.scope);
let index_scoped_stream = ScopedStream { scope: scope, stream: stream, }; let runtime = client_factory.runtime(); let index_reader = runtime.block_on(client_factory.create_byte_reader(index_scoped_stream)); let mut index_searcher = IndexSearcher::new(SyncByteReader::new(index_reader, client_factory.runtime_handle())); let check_period = time::Duration::from_secs(opts.check_period); info!("Checking period is {} seconds", opts.check_period); loop { let first_record = index_searcher.get_first_record().unwrap(); info!("The first index record: timestamp={}", first_record.timestamp); let last_record = index_searcher.get_last_record().unwrap(); info!("The last index record: timestamp={}", last_record.timestamp); let size = last_record.offset - first_record.offset; let size_in_mb = size / 1024 / 1024; info!("Data size between the first index and last index is {} MB", size_in_mb); thread::sleep(check_period); } }
let stream_name = format!("{}-index", opts.stream); let stream = Stream::from(stream_name);
AbrController.js
/** * The copyright in this software is being made available under the BSD License, * included below. This software may be subject to other third party and contributor * rights, including patent rights, and no such rights are granted under this license. * * Copyright (c) 2013, Dash Industry Forum. * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation and/or * other materials provided with the distribution. * * Neither the name of Dash Industry Forum nor the names of its * contributors may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ import ABRRulesCollection from '../rules/abr/ABRRulesCollection'; import Constants from '../constants/Constants'; import MetricsConstants from '../constants/MetricsConstants'; import BitrateInfo from '../vo/BitrateInfo'; import FragmentModel from '../models/FragmentModel'; import EventBus from '../../core/EventBus'; import Events from '../../core/events/Events'; import FactoryMaker from '../../core/FactoryMaker'; import RulesContext from '../rules/RulesContext'; import SwitchRequest from '../rules/SwitchRequest'; import SwitchRequestHistory from '../rules/SwitchRequestHistory'; import DroppedFramesHistory from '../rules/DroppedFramesHistory'; import ThroughputHistory from '../rules/ThroughputHistory'; import {HTTPRequest} from '../vo/metrics/HTTPRequest'; import Debug from '../../core/Debug'; const ABANDON_LOAD = 'abandonload'; const ALLOW_LOAD = 'allowload'; const DEFAULT_VIDEO_BITRATE = 1000; const DEFAULT_AUDIO_BITRATE = 100; const QUALITY_DEFAULT = 0; function AbrController() { const context = this.context; const debug = Debug(context).getInstance(); const eventBus = EventBus(context).getInstance(); let instance, log, abrRulesCollection, streamController, autoSwitchBitrate, topQualities, qualityDict, bitrateDict, ratioDict, streamProcessorDict, abandonmentStateDict, abandonmentTimeout, limitBitrateByPortal, usePixelRatioInLimitBitrateByPortal, windowResizeEventCalled, elementWidth, elementHeight, manifestModel, dashManifestModel, adapter, videoModel, mediaPlayerModel, domStorage, playbackIndex, switchHistoryDict, droppedFramesHistory, throughputHistory, isUsingBufferOccupancyABRDict, metricsModel, dashMetrics, useDeadTimeLatency; function setup() { log = debug.log.bind(instance); resetInitialSettings(); } function registerStreamType(type, streamProcessor) { switchHistoryDict[type] = SwitchRequestHistory(context).create(); streamProcessorDict[type] = streamProcessor; abandonmentStateDict[type] = abandonmentStateDict[type] || {}; abandonmentStateDict[type].state = ALLOW_LOAD; isUsingBufferOccupancyABRDict[type] = false; eventBus.on(Events.LOADING_PROGRESS, onFragmentLoadProgress, this); if (type == Constants.VIDEO) { eventBus.on(Events.QUALITY_CHANGE_RENDERED, onQualityChangeRendered, this); droppedFramesHistory = DroppedFramesHistory(context).create(); setElementSize(); } eventBus.on(Events.METRIC_ADDED, onMetricAdded, this); throughputHistory = ThroughputHistory(context).create({ mediaPlayerModel: mediaPlayerModel }); } function unRegisterStreamType(type) { delete streamProcessorDict[type]; } function createAbrRulesCollection() { abrRulesCollection = ABRRulesCollection(context).create({ metricsModel: metricsModel, dashMetrics: dashMetrics, mediaPlayerModel: mediaPlayerModel, adapter: adapter }); abrRulesCollection.initialize(); } function resetInitialSettings() { autoSwitchBitrate = {video: true, audio: true}; topQualities = {}; qualityDict = {}; bitrateDict = {}; ratioDict = {}; abandonmentStateDict = {}; streamProcessorDict = {}; switchHistoryDict = {}; isUsingBufferOccupancyABRDict = {}; limitBitrateByPortal = false; useDeadTimeLatency = true; usePixelRatioInLimitBitrateByPortal = false; if (windowResizeEventCalled === undefined) { windowResizeEventCalled = false; } playbackIndex = undefined; droppedFramesHistory = undefined; throughputHistory = undefined; clearTimeout(abandonmentTimeout); abandonmentTimeout = null; } function reset() { resetInitialSettings(); eventBus.off(Events.LOADING_PROGRESS, onFragmentLoadProgress, this); eventBus.off(Events.QUALITY_CHANGE_RENDERED, onQualityChangeRendered, this); eventBus.off(Events.METRIC_ADDED, onMetricAdded, this); if (abrRulesCollection) { abrRulesCollection.reset(); } } function setConfig(config) { if (!config) return; if (config.streamController) { streamController = config.streamController; } if (config.domStorage) { domStorage = config.domStorage; } if (config.mediaPlayerModel) { mediaPlayerModel = config.mediaPlayerModel; } if (config.metricsModel) { metricsModel = config.metricsModel; } if (config.dashMetrics) { dashMetrics = config.dashMetrics; } if (config.dashManifestModel) { dashManifestModel = config.dashManifestModel; } if (config.adapter) { adapter = config.adapter; } if (config.manifestModel) { manifestModel = config.manifestModel; } if (config.videoModel) { videoModel = config.videoModel; } } function onQualityChangeRendered(e) { if (e.mediaType === Constants.VIDEO) { playbackIndex = e.oldQuality; droppedFramesHistory.push(playbackIndex, videoModel.getPlaybackQuality()); } } function onMetricAdded(e) { if (e.metric === MetricsConstants.HTTP_REQUEST && e.value && e.value.type === HTTPRequest.MEDIA_SEGMENT_TYPE && (e.mediaType === Constants.AUDIO || e.mediaType === Constants.VIDEO)) { throughputHistory.push(e.mediaType, e.value, useDeadTimeLatency); } if (e.metric === MetricsConstants.BUFFER_LEVEL && (e.mediaType === Constants.AUDIO || e.mediaType === Constants.VIDEO)) { updateIsUsingBufferOccupancyABR(e.mediaType, 0.001 * e.value.level); } } function getTopQualityIndexFor(type, id) { let idx; topQualities[id] = topQualities[id] || {}; if (!topQualities[id].hasOwnProperty(type)) { topQualities[id][type] = 0; } idx = checkMaxBitrate(topQualities[id][type], type); idx = checkMaxRepresentationRatio(idx, type, topQualities[id][type]); idx = checkPortalSize(idx, type); return idx; } /** * @param {string} type * @returns {number} A value of the initial bitrate, kbps * @memberof AbrController# */ function getInitialBitrateFor(type) { const savedBitrate = domStorage.getSavedBitrateSettings(type); if (!bitrateDict.hasOwnProperty(type)) { if (ratioDict.hasOwnProperty(type)) { const manifest = manifestModel.getValue(); const representation = dashManifestModel.getAdaptationForType(manifest, 0, type).Representation; if (Array.isArray(representation)) { const repIdx = Math.max(Math.round(representation.length * ratioDict[type]) - 1, 0); bitrateDict[type] = representation[repIdx].bandwidth; } else { bitrateDict[type] = 0; } } else if (!isNaN(savedBitrate)) { bitrateDict[type] = savedBitrate; } else { bitrateDict[type] = (type === Constants.VIDEO) ? DEFAULT_VIDEO_BITRATE : DEFAULT_AUDIO_BITRATE; } } return bitrateDict[type]; } /** * @param {string} type * @param {number} value A value of the initial bitrate, kbps * @memberof AbrController# */ function setInitialBitrateFor(type, value) { bitrateDict[type] = value; } function getInitialRepresentationRatioFor(type) { if (!ratioDict.hasOwnProperty(type)) { return null; } return ratioDict[type]; } function setInitialRepresentationRatioFor(type, value) { ratioDict[type] = value; } function getMaxAllowedBitrateFor(type) { if (bitrateDict.hasOwnProperty('max') && bitrateDict.max.hasOwnProperty(type)) { return bitrateDict.max[type]; } return NaN; } function getMinAllowedBitrateFor(type) { if (bitrateDict.hasOwnProperty('min') && bitrateDict.min.hasOwnProperty(type)) { return bitrateDict.min[type]; } return NaN; } //TODO change bitrateDict structure to hold one object for video and audio with initial and max values internal. // This means you need to update all the logic around initial bitrate DOMStorage, RebController etc... function setMaxAllowedBitrateFor(type, value) { bitrateDict.max = bitrateDict.max || {}; bitrateDict.max[type] = value; } function setMinAllowedBitrateFor(type, value) { bitrateDict.min = bitrateDict.min || {}; bitrateDict.min[type] = value; } function getMaxAllowedIndexFor(type) { const maxBitrate = getMaxAllowedBitrateFor(type); if (maxBitrate) { return getQualityForBitrate(streamProcessorDict[type].getMediaInfo(), maxBitrate); } else { return undefined; } } function getMinAllowedIndexFor(type) { const minBitrate = getMinAllowedBitrateFor(type); if (minBitrate) { const bitrateList = getBitrateList(streamProcessorDict[type].getMediaInfo()); // This returns the quality index <= for the given bitrate let minIdx = getQualityForBitrate(streamProcessorDict[type].getMediaInfo(), minBitrate); if (bitrateList[minIdx] && minIdx < bitrateList.length - 1 && bitrateList[minIdx].bitrate < minBitrate * 1000) { minIdx++; // Go to the next bitrate } return minIdx; } else { return undefined; } } function getMaxAllowedRepresentationRatioFor(type) { if (ratioDict.hasOwnProperty('max') && ratioDict.max.hasOwnProperty(type)) { return ratioDict.max[type]; } return 1; } function setMaxAllowedRepresentationRatioFor(type, value) { ratioDict.max = ratioDict.max || {}; ratioDict.max[type] = value; } function getAutoSwitchBitrateFor(type) { return autoSwitchBitrate[type]; } function setAutoSwitchBitrateFor(type, value) { autoSwitchBitrate[type] = value; } function getLimitBitrateByPortal() { return limitBitrateByPortal; } function setLimitBitrateByPortal(value) { limitBitrateByPortal = value; } function getUsePixelRatioInLimitBitrateByPortal() { return usePixelRatioInLimitBitrateByPortal; } function setUsePixelRatioInLimitBitrateByPortal(value) { usePixelRatioInLimitBitrateByPortal = value; } function getUseDeadTimeLatency() { return useDeadTimeLatency; } function setUseDeadTimeLatency(value) { useDeadTimeLatency = value; } function checkPlaybackQuality(type) { if (type && streamProcessorDict && streamProcessorDict[type]) { const streamInfo = streamProcessorDict[type].getStreamInfo(); const streamId = streamInfo ? streamInfo.id : null; const oldQuality = getQualityFor(type); const rulesContext = RulesContext(context).create({ abrController: instance, streamProcessor: streamProcessorDict[type], currentValue: oldQuality, switchHistory: switchHistoryDict[type], droppedFramesHistory: droppedFramesHistory, useBufferOccupancyABR: useBufferOccupancyABR(type) }); if (droppedFramesHistory) { droppedFramesHistory.push(playbackIndex, videoModel.getPlaybackQuality()); } if (getAutoSwitchBitrateFor(type)) { const minIdx = getMinAllowedIndexFor(type); const topQualityIdx = getTopQualityIndexFor(type, streamId); const switchRequest = abrRulesCollection.getMaxQuality(rulesContext); let newQuality = switchRequest.quality; if (minIdx !== undefined && newQuality < minIdx) { newQuality = minIdx; } if (newQuality > topQualityIdx) { newQuality = topQualityIdx; } switchHistoryDict[type].push({oldValue: oldQuality, newValue: newQuality}); if (newQuality > SwitchRequest.NO_CHANGE && newQuality != oldQuality) { if (abandonmentStateDict[type].state === ALLOW_LOAD || newQuality > oldQuality) { changeQuality(type, oldQuality, newQuality, topQualityIdx, switchRequest.reason); } } else if (debug.getLogToBrowserConsole()) { const bufferLevel = dashMetrics.getCurrentBufferLevel(metricsModel.getReadOnlyMetricsFor(type)); log('AbrController (' + type + ') stay on ' + oldQuality + '/' + topQualityIdx + ' (buffer: ' + bufferLevel + ')'); } } } } function setPlaybackQuality(type, streamInfo, newQuality, reason) { const id = streamInfo.id; const oldQuality = getQualityFor(type); const isInt = newQuality !== null && !isNaN(newQuality) && (newQuality % 1 === 0); if (!isInt) throw new Error('argument is not an integer'); const topQualityIdx = getTopQualityIndexFor(type, id); if (newQuality !== oldQuality && newQuality >= 0 && newQuality <= topQualityIdx) { changeQuality(type, oldQuality, newQuality, topQualityIdx, reason); } } function changeQuality(type, oldQuality, newQuality, topQualityIdx, reason) { if (type && streamProcessorDict[type]) { const streamInfo = streamProcessorDict[type].getStreamInfo(); const id = streamInfo ? streamInfo.id : null; if (debug.getLogToBrowserConsole()) { const bufferLevel = dashMetrics.getCurrentBufferLevel(metricsModel.getReadOnlyMetricsFor(type)); log('AbrController (' + type + ') switch from ' + oldQuality + ' to ' + newQuality + '/' + topQualityIdx + ' (buffer: ' + bufferLevel + ') ' + (reason ? JSON.stringify(reason) : '.')); } setQualityFor(type, id, newQuality); eventBus.trigger(Events.QUALITY_CHANGE_REQUESTED, {mediaType: type, streamInfo: streamInfo, oldQuality: oldQuality, newQuality: newQuality, reason: reason}); } } function setAbandonmentStateFor(type, state) { abandonmentStateDict[type].state = state; } function getAbandonmentStateFor(type) { return abandonmentStateDict[type] ? abandonmentStateDict[type].state : null; } /** * @param {MediaInfo} mediaInfo * @param {number} bitrate A bitrate value, kbps * @param {number} latency Expected latency of connection, ms * @returns {number} A quality index <= for the given bitrate * @memberof AbrController# */ function getQualityForBitrate(mediaInfo, bitrate, latency) { if (useDeadTimeLatency && latency && streamProcessorDict[mediaInfo.type].getCurrentRepresentationInfo() && streamProcessorDict[mediaInfo.type].getCurrentRepresentationInfo().fragmentDuration) { latency = latency / 1000; const fragmentDuration = streamProcessorDict[mediaInfo.type].getCurrentRepresentationInfo().fragmentDuration; if (latency > fragmentDuration) { return 0; } else { const deadTimeRatio = latency / fragmentDuration; bitrate = bitrate * (1 - deadTimeRatio); } } const bitrateList = getBitrateList(mediaInfo); if (!bitrateList || bitrateList.length === 0) { return QUALITY_DEFAULT; } for (let i = bitrateList.length - 1; i >= 0; i--) { const bitrateInfo = bitrateList[i]; if (bitrate * 1000 >= bitrateInfo.bitrate) { return i; } } return 0; } /** * @param {MediaInfo} mediaInfo * @returns {Array|null} A list of {@link BitrateInfo} objects * @memberof AbrController# */ function getBitrateList(mediaInfo) { if (!mediaInfo || !mediaInfo.bitrateList) return null; const bitrateList = mediaInfo.bitrateList; const type = mediaInfo.type; const infoList = []; let bitrateInfo; for (let i = 0, ln = bitrateList.length; i < ln; i++) { bitrateInfo = new BitrateInfo(); bitrateInfo.mediaType = type; bitrateInfo.qualityIndex = i; bitrateInfo.bitrate = bitrateList[i].bandwidth; bitrateInfo.width = bitrateList[i].width; bitrateInfo.height = bitrateList[i].height; bitrateInfo.scanType = bitrateList[i].scanType; infoList.push(bitrateInfo); } return infoList; } function updateIsUsingBufferOccupancyABR(mediaType, bufferLevel) { const strategy = mediaPlayerModel.getABRStrategy(); if (strategy === Constants.ABR_STRATEGY_BOLA) { isUsingBufferOccupancyABRDict[mediaType] = true; return; } else if (strategy === Constants.ABR_STRATEGY_THROUGHPUT) { isUsingBufferOccupancyABRDict[mediaType] = false; return; } // else ABR_STRATEGY_DYNAMIC const stableBufferTime = mediaPlayerModel.getStableBufferTime(); const switchOnThreshold = stableBufferTime; const switchOffThreshold = 0.5 * stableBufferTime; const useBufferABR = isUsingBufferOccupancyABRDict[mediaType]; const newUseBufferABR = bufferLevel > (useBufferABR ? switchOffThreshold : switchOnThreshold); // use hysteresis to avoid oscillating rules isUsingBufferOccupancyABRDict[mediaType] = newUseBufferABR; if (newUseBufferABR !== useBufferABR) { if (newUseBufferABR) { log('AbrController (' + mediaType + ') switching from throughput to buffer occupancy ABR rule (buffer: ' + bufferLevel.toFixed(3) + ').'); } else { log('AbrController (' + mediaType + ') switching from buffer occupancy to throughput ABR rule (buffer: ' + bufferLevel.toFixed(3) + ').'); } } } function useBufferOccupancyABR(mediaType) { return isUsingBufferOccupancyABRDict[mediaType]; } function getThroughputHistory() { return throughputHistory; } function updateTopQualityIndex(mediaInfo) { const type = mediaInfo.type; const streamId = mediaInfo.streamInfo.id; const max = mediaInfo.representationCount - 1; setTopQualityIndex(type, streamId, max); return max; } function
(streamInfo) { const streamId = streamInfo.id; const audioQuality = getQualityFor(Constants.AUDIO); const videoQuality = getQualityFor(Constants.VIDEO); const isAtTop = (audioQuality === getTopQualityIndexFor(Constants.AUDIO, streamId)) && (videoQuality === getTopQualityIndexFor(Constants.VIDEO, streamId)); return isAtTop; } function getQualityFor(type) { if (type && streamProcessorDict[type]) { const streamInfo = streamProcessorDict[type].getStreamInfo(); const id = streamInfo ? streamInfo.id : null; let quality; if (id) { qualityDict[id] = qualityDict[id] || {}; if (!qualityDict[id].hasOwnProperty(type)) { qualityDict[id][type] = QUALITY_DEFAULT; } quality = qualityDict[id][type]; return quality; } } return QUALITY_DEFAULT; } function setQualityFor(type, id, value) { qualityDict[id] = qualityDict[id] || {}; qualityDict[id][type] = value; } function setTopQualityIndex(type, id, value) { topQualities[id] = topQualities[id] || {}; topQualities[id][type] = value; } function checkMaxBitrate(idx, type) { let newIdx = idx; if (!streamProcessorDict[type]) { return newIdx; } const minIdx = getMinAllowedIndexFor(type); if (minIdx !== undefined) { newIdx = Math.max (idx , minIdx); } const maxIdx = getMaxAllowedIndexFor(type); if (maxIdx !== undefined) { newIdx = Math.min (newIdx , maxIdx); } return newIdx; } function checkMaxRepresentationRatio(idx, type, maxIdx) { const maxRepresentationRatio = getMaxAllowedRepresentationRatioFor(type); if (isNaN(maxRepresentationRatio) || maxRepresentationRatio >= 1 || maxRepresentationRatio < 0) { return idx; } return Math.min( idx , Math.round(maxIdx * maxRepresentationRatio) ); } function setWindowResizeEventCalled(value) { windowResizeEventCalled = value; } function setElementSize() { const hasPixelRatio = usePixelRatioInLimitBitrateByPortal && window.hasOwnProperty('devicePixelRatio'); const pixelRatio = hasPixelRatio ? window.devicePixelRatio : 1; elementWidth = videoModel.getClientWidth() * pixelRatio; elementHeight = videoModel.getClientHeight() * pixelRatio; } function checkPortalSize(idx, type) { if (type !== Constants.VIDEO || !limitBitrateByPortal || !streamProcessorDict[type]) { return idx; } if (!windowResizeEventCalled) { setElementSize(); } const manifest = manifestModel.getValue(); const representation = dashManifestModel.getAdaptationForType(manifest, 0, type).Representation; let newIdx = idx; if (elementWidth > 0 && elementHeight > 0) { while ( newIdx > 0 && representation[newIdx] && elementWidth < representation[newIdx].width && elementWidth - representation[newIdx - 1].width < representation[newIdx].width - elementWidth ) { newIdx = newIdx - 1; } if (representation.length - 2 >= newIdx && representation[newIdx].width === representation[newIdx + 1].width) { newIdx = Math.min(idx, newIdx + 1); } } return newIdx; } function onFragmentLoadProgress(e) { const type = e.request.mediaType; if (getAutoSwitchBitrateFor(type)) { const streamProcessor = streamProcessorDict[type]; if (!streamProcessor) return;// There may be a fragment load in progress when we switch periods and recreated some controllers. const rulesContext = RulesContext(context).create({ abrController: instance, streamProcessor: streamProcessor, currentRequest: e.request, useBufferOccupancyABR: useBufferOccupancyABR(type) }); const switchRequest = abrRulesCollection.shouldAbandonFragment(rulesContext); if (switchRequest.quality > SwitchRequest.NO_CHANGE) { const fragmentModel = streamProcessor.getFragmentModel(); const request = fragmentModel.getRequests({state: FragmentModel.FRAGMENT_MODEL_LOADING, index: e.request.index})[0]; if (request) { //TODO Check if we should abort or if better to finish download. check bytesLoaded/Total fragmentModel.abortRequests(); setAbandonmentStateFor(type, ABANDON_LOAD); switchHistoryDict[type].reset(); switchHistoryDict[type].push({oldValue: getQualityFor(type, streamController.getActiveStreamInfo()), newValue: switchRequest.quality, confidence: 1, reason: switchRequest.reason}); setPlaybackQuality(type, streamController.getActiveStreamInfo(), switchRequest.quality, switchRequest.reason); clearTimeout(abandonmentTimeout); abandonmentTimeout = setTimeout( () => {setAbandonmentStateFor(type, ALLOW_LOAD); abandonmentTimeout = null;}, mediaPlayerModel.getAbandonLoadTimeout() ); } } } } instance = { isPlayingAtTopQuality: isPlayingAtTopQuality, updateTopQualityIndex: updateTopQualityIndex, getThroughputHistory: getThroughputHistory, getBitrateList: getBitrateList, getQualityForBitrate: getQualityForBitrate, getMaxAllowedBitrateFor: getMaxAllowedBitrateFor, getMinAllowedBitrateFor: getMinAllowedBitrateFor, setMaxAllowedBitrateFor: setMaxAllowedBitrateFor, setMinAllowedBitrateFor: setMinAllowedBitrateFor, getMaxAllowedIndexFor: getMaxAllowedIndexFor, getMinAllowedIndexFor: getMinAllowedIndexFor, getMaxAllowedRepresentationRatioFor: getMaxAllowedRepresentationRatioFor, setMaxAllowedRepresentationRatioFor: setMaxAllowedRepresentationRatioFor, getInitialBitrateFor: getInitialBitrateFor, setInitialBitrateFor: setInitialBitrateFor, getInitialRepresentationRatioFor: getInitialRepresentationRatioFor, setInitialRepresentationRatioFor: setInitialRepresentationRatioFor, setAutoSwitchBitrateFor: setAutoSwitchBitrateFor, getAutoSwitchBitrateFor: getAutoSwitchBitrateFor, getUseDeadTimeLatency: getUseDeadTimeLatency, setUseDeadTimeLatency: setUseDeadTimeLatency, setLimitBitrateByPortal: setLimitBitrateByPortal, getLimitBitrateByPortal: getLimitBitrateByPortal, getUsePixelRatioInLimitBitrateByPortal: getUsePixelRatioInLimitBitrateByPortal, setUsePixelRatioInLimitBitrateByPortal: setUsePixelRatioInLimitBitrateByPortal, getQualityFor: getQualityFor, getAbandonmentStateFor: getAbandonmentStateFor, setPlaybackQuality: setPlaybackQuality, checkPlaybackQuality: checkPlaybackQuality, getTopQualityIndexFor: getTopQualityIndexFor, setElementSize: setElementSize, setWindowResizeEventCalled: setWindowResizeEventCalled, createAbrRulesCollection: createAbrRulesCollection, registerStreamType: registerStreamType, unRegisterStreamType: unRegisterStreamType, setConfig: setConfig, reset: reset }; setup(); return instance; } AbrController.__dashjs_factory_name = 'AbrController'; const factory = FactoryMaker.getSingletonFactory(AbrController); factory.ABANDON_LOAD = ABANDON_LOAD; factory.QUALITY_DEFAULT = QUALITY_DEFAULT; FactoryMaker.updateSingletonFactory(AbrController.__dashjs_factory_name, factory); export default factory;
isPlayingAtTopQuality
downloaders.py
# Copyright (c) 2018 The Pooch Developers. # Distributed under the terms of the BSD 3-Clause License. # SPDX-License-Identifier: BSD-3-Clause # # This code is part of the Fatiando a Terra project (https://www.fatiando.org) # """ The classes that actually handle the downloads. """ import sys import ftplib import requests from .utils import parse_url try: from tqdm import tqdm except ImportError: tqdm = None try: import paramiko except ImportError: paramiko = None def choose_downloader(url): """ Choose the appropriate downloader for the given URL based on the protocol. Parameters ---------- url : str A URL (including protocol). Returns ------- downloader A downloader class (either :class:`pooch.HTTPDownloader`, :class:`pooch.FTPDownloader`, or :class: `pooch.SFTPDownloader`). Examples -------- >>> downloader = choose_downloader("http://something.com") >>> print(downloader.__class__.__name__) HTTPDownloader >>> downloader = choose_downloader("https://something.com") >>> print(downloader.__class__.__name__) HTTPDownloader >>> downloader = choose_downloader("ftp://something.com") >>> print(downloader.__class__.__name__) FTPDownloader """ known_downloaders = { "ftp": FTPDownloader, "https": HTTPDownloader, "http": HTTPDownloader, "sftp": SFTPDownloader, } parsed_url = parse_url(url) if parsed_url["protocol"] not in known_downloaders: raise ValueError( f"Unrecognized URL protocol '{parsed_url['protocol']}' in '{url}'. " f"Must be one of {known_downloaders.keys()}." ) downloader = known_downloaders[parsed_url["protocol"]]() return downloader class HTTPDownloader: # pylint: disable=too-few-public-methods """ Download manager for fetching files over HTTP/HTTPS. When called, downloads the given file URL into the specified local file. Uses the :mod:`requests` library to manage downloads. Use with :meth:`pooch.Pooch.fetch` or :func:`pooch.retrieve` to customize the download of files (for example, to use authentication or print a progress bar). Parameters ---------- progressbar : bool If True, will print a progress bar of the download to standard error (stderr). Requires `tqdm <https://github.com/tqdm/tqdm>`__ to be installed. chunk_size : int Files are streamed *chunk_size* bytes at a time instead of loading everything into memory at one. Usually doesn't need to be changed. **kwargs All keyword arguments given when creating an instance of this class will be passed to :func:`requests.get`. Examples -------- Download one of the data files from the Pooch repository: >>> import os >>> from pooch import version, check_version >>> url = "https://github.com/fatiando/pooch/raw/{}/data/tiny-data.txt" >>> url = url.format(check_version(version.full_version)) >>> downloader = HTTPDownloader() >>> # Not using with Pooch.fetch so no need to pass an instance of Pooch >>> downloader(url=url, output_file="tiny-data.txt", pooch=None) >>> os.path.exists("tiny-data.txt") True >>> with open("tiny-data.txt") as f: ... print(f.read().strip()) # A tiny data file for test purposes only 1 2 3 4 5 6 >>> os.remove("tiny-data.txt") Authentication can be handled by passing a user name and password to :func:`requests.get`. All arguments provided when creating an instance of the class are forwarded to :func:`requests.get`. We'll use ``auth=(username, password)`` to use basic HTTPS authentication. The https://httpbin.org website allows us to make a fake a login request using whatever username and password we provide to it: >>> user = "doggo" >>> password = "goodboy" >>> # httpbin will ask for the user and password we provide in the URL >>> url = f"https://httpbin.org/basic-auth/{user}/{password}" >>> # Trying without the login credentials causes an error >>> downloader = HTTPDownloader() >>> try: ... downloader(url=url, output_file="tiny-data.txt", pooch=None) ... except Exception: ... print("There was an error!") There was an error! >>> # Pass in the credentials to HTTPDownloader >>> downloader = HTTPDownloader(auth=(user, password)) >>> downloader(url=url, output_file="tiny-data.txt", pooch=None) >>> with open("tiny-data.txt") as f: ... for line in f: ... print(line.rstrip()) { "authenticated": true, "user": "doggo" } >>> os.remove("tiny-data.txt") """ def __init__(self, progressbar=False, chunk_size=1024, **kwargs): self.kwargs = kwargs self.progressbar = progressbar self.chunk_size = chunk_size if self.progressbar and tqdm is None: raise ValueError("Missing package 'tqdm' required for progress bars.") def
(self, url, output_file, pooch): """ Download the given URL over HTTP to the given output file. Uses :func:`requests.get`. Parameters ---------- url : str The URL to the file you want to download. output_file : str or file-like object Path (and file name) to which the file will be downloaded. pooch : :class:`~pooch.Pooch` The instance of :class:`~pooch.Pooch` that is calling this method. """ kwargs = self.kwargs.copy() kwargs.setdefault("stream", True) ispath = not hasattr(output_file, "write") if ispath: output_file = open(output_file, "w+b") try: response = requests.get(url, **kwargs) response.raise_for_status() content = response.iter_content(chunk_size=self.chunk_size) if self.progressbar: total = int(response.headers.get("content-length", 0)) # Need to use ascii characters on Windows because there isn't # always full unicode support # (see https://github.com/tqdm/tqdm/issues/454) use_ascii = bool(sys.platform == "win32") progress = tqdm( total=total, ncols=79, ascii=use_ascii, unit="B", unit_scale=True, leave=True, ) for chunk in content: if chunk: output_file.write(chunk) output_file.flush() if self.progressbar: # Use the chunk size here because chunk may be much # larger if the data are decompressed by requests after # reading (happens with text files). progress.update(self.chunk_size) # Make sure the progress bar gets filled even if the actual number # is chunks is smaller than expected. This happens when streaming # text files that are compressed by the server when sending (gzip). # Binary files don't experience this. if self.progressbar: progress.reset() progress.update(total) progress.close() finally: if ispath: output_file.close() class FTPDownloader: # pylint: disable=too-few-public-methods """ Download manager for fetching files over FTP. When called, downloads the given file URL into the specified local file. Uses the :mod:`ftplib` module to manage downloads. Use with :meth:`pooch.Pooch.fetch` or :func:`pooch.retrieve` to customize the download of files (for example, to use authentication or print a progress bar). Parameters ---------- port : int Port used for the FTP connection. username : str User name used to login to the server. Only needed if the server requires authentication (i.e., no anonymous FTP). password : str Password used to login to the server. Only needed if the server requires authentication (i.e., no anonymous FTP). Use the empty string to indicate no password is required. account : str Some servers also require an "account" name for authentication. timeout : int Timeout in seconds for ftp socket operations, use None to mean no timeout. progressbar : bool If True, will print a progress bar of the download to standard error (stderr). Requires `tqdm <https://github.com/tqdm/tqdm>`__ to be installed. chunk_size : int Files are streamed *chunk_size* bytes at a time instead of loading everything into memory at one. Usually doesn't need to be changed. """ def __init__( self, port=21, username="anonymous", password="", account="", timeout=None, progressbar=False, chunk_size=1024, ): self.port = port self.username = username self.password = password self.account = account self.timeout = timeout self.progressbar = progressbar self.chunk_size = chunk_size if self.progressbar and tqdm is None: raise ValueError("Missing package 'tqdm' required for progress bars.") def __call__(self, url, output_file, pooch): """ Download the given URL over FTP to the given output file. Parameters ---------- url : str The URL to the file you want to download. output_file : str or file-like object Path (and file name) to which the file will be downloaded. pooch : :class:`~pooch.Pooch` The instance of :class:`~pooch.Pooch` that is calling this method. """ parsed_url = parse_url(url) ftp = ftplib.FTP(timeout=self.timeout) ftp.connect(host=parsed_url["netloc"], port=self.port) ispath = not hasattr(output_file, "write") if ispath: output_file = open(output_file, "w+b") try: ftp.login(user=self.username, passwd=self.password, acct=self.account) command = f"RETR {parsed_url['path']}" if self.progressbar: # Make sure the file is set to binary mode, otherwise we can't # get the file size. See: https://stackoverflow.com/a/22093848 ftp.voidcmd("TYPE I") size = int(ftp.size(parsed_url["path"])) use_ascii = bool(sys.platform == "win32") progress = tqdm( total=size, ncols=79, ascii=use_ascii, unit="B", unit_scale=True, leave=True, ) with progress: def callback(data): "Update the progress bar and write to output" progress.update(len(data)) output_file.write(data) ftp.retrbinary(command, callback, blocksize=self.chunk_size) else: ftp.retrbinary(command, output_file.write, blocksize=self.chunk_size) finally: ftp.quit() if ispath: output_file.close() class SFTPDownloader: # pylint: disable=too-few-public-methods """ Download manager for fetching files over SFTP. When called, downloads the given file URL into the specified local file. Requires `paramiko <https://github.com/paramiko/paramiko>`__ to be installed. Use with :meth:`pooch.Pooch.fetch` or :func:`pooch.retrieve` to customize the download of files (for example, to use authentication or print a progress bar). Parameters ---------- port : int Port used for the SFTP connection. username : str User name used to login to the server. Only needed if the server requires authentication (i.e., no anonymous SFTP). password : str Password used to login to the server. Only needed if the server requires authentication (i.e., no anonymous SFTP). Use the empty string to indicate no password is required. timeout : int Timeout in seconds for sftp socket operations, use None to mean no timeout. progressbar : bool If True, will print a progress bar of the download to standard error (stderr). Requires `tqdm <https://github.com/tqdm/tqdm>`__ to be installed. """ def __init__( self, port=22, username="anonymous", password="", account="", timeout=None, progressbar=False, ): self.port = port self.username = username self.password = password self.account = account self.timeout = timeout self.progressbar = progressbar # Collect errors and raise only once so that both missing packages are # captured. Otherwise, the user is only warned of one of them at a # time (and we can't test properly when they are both missing). errors = [] if self.progressbar and tqdm is None: errors.append("Missing package 'tqdm' required for progress bars.") if paramiko is None: errors.append("Missing package 'paramiko' required for SFTP downloads.") if errors: raise ValueError(" ".join(errors)) def __call__(self, url, output_file, pooch): """ Download the given URL over SFTP to the given output file. The output file must be given as a string (file name/path) and not an open file object! Otherwise, paramiko cannot save to that file. Parameters ---------- url : str The URL to the file you want to download. output_file : str Path (and file name) to which the file will be downloaded. **Cannot be a file object**. pooch : :class:`~pooch.Pooch` The instance of :class:`~pooch.Pooch` that is calling this method. """ parsed_url = parse_url(url) connection = paramiko.Transport(sock=(parsed_url["netloc"], self.port)) sftp = None try: connection.connect(username=self.username, password=self.password) sftp = paramiko.SFTPClient.from_transport(connection) sftp.get_channel().settimeout = self.timeout if self.progressbar: size = int(sftp.stat(parsed_url["path"]).st_size) use_ascii = bool(sys.platform == "win32") progress = tqdm( total=size, ncols=79, ascii=use_ascii, unit="B", unit_scale=True, leave=True, ) with progress: def callback(current, total): "Update the progress bar and write to output" progress.total = int(total) progress.update(int(current - progress.n)) sftp.get(parsed_url["path"], output_file, callback=callback) else: sftp.get(parsed_url["path"], output_file) finally: connection.close() if sftp is not None: sftp.close()
__call__
use_trades.py
from pprint import pprint from configparser import ConfigParser from ibc.client import InteractiveBrokersClient # Initialize the Parser. config = ConfigParser() # Read the file. config.read('config/config.ini') # Get the specified credentials. account_number = config.get('interactive_brokers_paper', 'paper_account') account_password = config.get('interactive_brokers_paper', 'paper_password') # Initialize the client. ibc_client = InteractiveBrokersClient( account_number=account_number, password=account_password ) # Initialize the Authentication Service. auth_service = ibc_client.authentication
auth_service.login() # Wait for the user to login. while not auth_service.authenticated: auth_service.check_auth() # Grab the `Trades` Service. trades_service = ibc_client.trades # Get the trades for the last week. pprint( trades_service.get_trades() )
# Login
connection.go
// Code generated by "libovsdb.modelgen" // DO NOT EDIT. package sbdb import "github.com/ovn-org/libovsdb/model" // Connection defines an object in Connection table type Connection struct { UUID string `ovsdb:"_uuid"` ExternalIDs map[string]string `ovsdb:"external_ids"` InactivityProbe *int `ovsdb:"inactivity_probe"` IsConnected bool `ovsdb:"is_connected"` MaxBackoff *int `ovsdb:"max_backoff"` OtherConfig map[string]string `ovsdb:"other_config"` ReadOnly bool `ovsdb:"read_only"` Role string `ovsdb:"role"` Status map[string]string `ovsdb:"status"` Target string `ovsdb:"target"` } func copyConnectionExternalIDs(a map[string]string) map[string]string { if a == nil { return nil } b := make(map[string]string, len(a)) for k, v := range a { b[k] = v } return b } func equalConnectionExternalIDs(a, b map[string]string) bool { if (a == nil) != (b == nil) { return false } if len(a) != len(b) { return false } for k, v := range a { if w, ok := b[k]; !ok || v != w { return false } } return true } func copyConnectionInactivityProbe(a *int) *int { if a == nil { return nil } b := *a return &b } func equalConnectionInactivityProbe(a, b *int) bool { if (a == nil) != (b == nil) { return false } if a == b { return true } return *a == *b } func copyConnectionMaxBackoff(a *int) *int { if a == nil { return nil } b := *a return &b } func equalConnectionMaxBackoff(a, b *int) bool { if (a == nil) != (b == nil) { return false } if a == b { return true } return *a == *b } func copyConnectionOtherConfig(a map[string]string) map[string]string { if a == nil { return nil } b := make(map[string]string, len(a)) for k, v := range a { b[k] = v } return b } func equalConnectionOtherConfig(a, b map[string]string) bool { if (a == nil) != (b == nil) { return false } if len(a) != len(b) { return false } for k, v := range a { if w, ok := b[k]; !ok || v != w { return false } } return true } func copyConnectionStatus(a map[string]string) map[string]string { if a == nil { return nil } b := make(map[string]string, len(a)) for k, v := range a { b[k] = v } return b } func equalConnectionStatus(a, b map[string]string) bool { if (a == nil) != (b == nil) { return false } if len(a) != len(b) { return false } for k, v := range a { if w, ok := b[k]; !ok || v != w { return false } } return true } func (a *Connection) DeepCopyInto(b *Connection) { *b = *a b.ExternalIDs = copyConnectionExternalIDs(a.ExternalIDs) b.InactivityProbe = copyConnectionInactivityProbe(a.InactivityProbe) b.MaxBackoff = copyConnectionMaxBackoff(a.MaxBackoff) b.OtherConfig = copyConnectionOtherConfig(a.OtherConfig) b.Status = copyConnectionStatus(a.Status) } func (a *Connection) DeepCopy() *Connection { b := new(Connection) a.DeepCopyInto(b) return b } func (a *Connection) CloneModelInto(b model.Model) { c := b.(*Connection) a.DeepCopyInto(c) } func (a *Connection) CloneModel() model.Model { return a.DeepCopy() } func (a *Connection) Equals(b *Connection) bool { return a.UUID == b.UUID && equalConnectionExternalIDs(a.ExternalIDs, b.ExternalIDs) && equalConnectionInactivityProbe(a.InactivityProbe, b.InactivityProbe) && a.IsConnected == b.IsConnected && equalConnectionMaxBackoff(a.MaxBackoff, b.MaxBackoff) && equalConnectionOtherConfig(a.OtherConfig, b.OtherConfig) && a.ReadOnly == b.ReadOnly && a.Role == b.Role && equalConnectionStatus(a.Status, b.Status) && a.Target == b.Target }
} var _ model.CloneableModel = &Connection{} var _ model.ComparableModel = &Connection{}
func (a *Connection) EqualsModel(b model.Model) bool { c := b.(*Connection) return a.Equals(c)
createLock.js
import ethersUtils from '../utils' import { GAS_AMOUNTS, ZERO, ETHERS_MAX_UINT } from '../constants' import TransactionTypes from '../transactionTypes' import { UNLIMITED_KEYS_COUNT } from '../../lib/constants'
/** * Creates a lock on behalf of the user, using version v01 * @param {PropTypes.lock} lock */ export default async function(lock) { const unlockContract = await this.getUnlockContract() let maxNumberOfKeys = lock.maxNumberOfKeys if (maxNumberOfKeys === UNLIMITED_KEYS_COUNT) { maxNumberOfKeys = ETHERS_MAX_UINT } let transactionPromise try { transactionPromise = unlockContract.functions[ 'createLock(uint256,address,uint256,uint256)' ]( lock.expirationDuration, ZERO, // ERC20 address, 0 is for eth ethersUtils.toWei(lock.keyPrice, 'ether'), maxNumberOfKeys, { gasLimit: GAS_AMOUNTS.createLock, } ) const hash = await this._handleMethodCall( transactionPromise, TransactionTypes.LOCK_CREATION ) // Let's update the lock to reflect that it is linked to this // This is an exception because, until we are able to determine the lock address // before the transaction is mined, we need to link the lock and transaction. this.emit('lock.updated', lock.address, { expirationDuration: lock.expirationDuration, keyPrice: lock.keyPrice, // Must be expressed in Eth! maxNumberOfKeys: lock.maxNumberOfKeys, outstandingKeys: 0, balance: '0', transaction: hash, }) // Let's now wait for the lock to be deployed before we return its address const receipt = await this.provider.waitForTransaction(hash) const parser = unlockContract.interface const newLockEvent = receipt.logs .map(log => { return parser.parseLog(log) }) .filter(event => event.name === 'NewLock')[0] if (newLockEvent) { return newLockEvent.values.newLockAddress } else { // There was no NewEvent log (transaction failed?) return null } } catch (error) { this.emit('error', new Error(TransactionTypes.FAILED_TO_CREATE_LOCK)) return null } }
ZhimaCreditEpProductCodeQueryRequest.py
#!/usr/bin/env python # -*- coding: utf-8 -*- import json from alipay.aop.api.FileItem import FileItem from alipay.aop.api.constant.ParamConstants import * from alipay.aop.api.domain.ZhimaCreditEpProductCodeQueryModel import ZhimaCreditEpProductCodeQueryModel class ZhimaCreditEpProductCodeQueryRequest(object): def __init__(self, biz_model=None): self._biz_model = biz_model self._biz_content = None self._version = "1.0" self._terminal_type = None self._terminal_info = None self._prod_code = None self._notify_url = None self._return_url = None self._udf_params = None self._need_encrypt = False @property def biz_model(self): return self._biz_model @biz_model.setter def biz_model(self, value): self._biz_model = value @property def biz_content(self): return self._biz_content @biz_content.setter def biz_content(self, value): if isinstance(value, ZhimaCreditEpProductCodeQueryModel): self._biz_content = value else: self._biz_content = ZhimaCreditEpProductCodeQueryModel.from_alipay_dict(value) @property def version(self): return self._version @version.setter def version(self, value): self._version = value @property def terminal_type(self): return self._terminal_type @terminal_type.setter def terminal_type(self, value): self._terminal_type = value @property def terminal_info(self): return self._terminal_info @terminal_info.setter def terminal_info(self, value): self._terminal_info = value @property def prod_code(self): return self._prod_code @prod_code.setter def prod_code(self, value): self._prod_code = value @property def notify_url(self): return self._notify_url @notify_url.setter def notify_url(self, value): self._notify_url = value @property def return_url(self): return self._return_url @return_url.setter def return_url(self, value): self._return_url = value @property def udf_params(self): return self._udf_params @udf_params.setter def udf_params(self, value): if not isinstance(value, dict): return self._udf_params = value @property def need_encrypt(self): return self._need_encrypt @need_encrypt.setter def need_encrypt(self, value): self._need_encrypt = value def
(self, key, value): if not self.udf_params: self.udf_params = dict() self.udf_params[key] = value def get_params(self): params = dict() params[P_METHOD] = 'zhima.credit.ep.product.code.query' params[P_VERSION] = self.version if self.biz_model: params[P_BIZ_CONTENT] = json.dumps(obj=self.biz_model.to_alipay_dict(), ensure_ascii=False, sort_keys=True, separators=(',', ':')) if self.biz_content: if hasattr(self.biz_content, 'to_alipay_dict'): params['biz_content'] = json.dumps(obj=self.biz_content.to_alipay_dict(), ensure_ascii=False, sort_keys=True, separators=(',', ':')) else: params['biz_content'] = self.biz_content if self.terminal_type: params['terminal_type'] = self.terminal_type if self.terminal_info: params['terminal_info'] = self.terminal_info if self.prod_code: params['prod_code'] = self.prod_code if self.notify_url: params['notify_url'] = self.notify_url if self.return_url: params['return_url'] = self.return_url if self.udf_params: params.update(self.udf_params) return params def get_multipart_params(self): multipart_params = dict() return multipart_params
add_other_text_param
event.go
package ledis import ( "errors" "fmt" "strconv" "github.com/nathandao/vantaa/Godeps/_workspace/src/github.com/siddontang/go/hack" ) var errInvalidEvent = errors.New("invalid event") func formatEventKey(buf []byte, k []byte) ([]byte, error)
{ if len(k) < 2 { return nil, errInvalidEvent } buf = append(buf, fmt.Sprintf("DB:%2d ", k[0])...) buf = append(buf, fmt.Sprintf("%s ", TypeName[k[1]])...) db := new(DB) index, _, err := decodeDBIndex(k) if err != nil { return nil, err } db.setIndex(index) //to do format at respective place switch k[1] { case KVType: if key, err := db.decodeKVKey(k); err != nil { return nil, err } else { buf = strconv.AppendQuote(buf, hack.String(key)) } case HashType: if key, field, err := db.hDecodeHashKey(k); err != nil { return nil, err } else { buf = strconv.AppendQuote(buf, hack.String(key)) buf = append(buf, ' ') buf = strconv.AppendQuote(buf, hack.String(field)) } case HSizeType: if key, err := db.hDecodeSizeKey(k); err != nil { return nil, err } else { buf = strconv.AppendQuote(buf, hack.String(key)) } case ListType: if key, seq, err := db.lDecodeListKey(k); err != nil { return nil, err } else { buf = strconv.AppendQuote(buf, hack.String(key)) buf = append(buf, ' ') buf = strconv.AppendInt(buf, int64(seq), 10) } case LMetaType: if key, err := db.lDecodeMetaKey(k); err != nil { return nil, err } else { buf = strconv.AppendQuote(buf, hack.String(key)) } case ZSetType: if key, m, err := db.zDecodeSetKey(k); err != nil { return nil, err } else { buf = strconv.AppendQuote(buf, hack.String(key)) buf = append(buf, ' ') buf = strconv.AppendQuote(buf, hack.String(m)) } case ZSizeType: if key, err := db.zDecodeSizeKey(k); err != nil { return nil, err } else { buf = strconv.AppendQuote(buf, hack.String(key)) } case ZScoreType: if key, m, score, err := db.zDecodeScoreKey(k); err != nil { return nil, err } else { buf = strconv.AppendQuote(buf, hack.String(key)) buf = append(buf, ' ') buf = strconv.AppendQuote(buf, hack.String(m)) buf = append(buf, ' ') buf = strconv.AppendInt(buf, score, 10) } // case BitType: // if key, seq, err := db.bDecodeBinKey(k); err != nil { // return nil, err // } else { // buf = strconv.AppendQuote(buf, hack.String(key)) // buf = append(buf, ' ') // buf = strconv.AppendUint(buf, uint64(seq), 10) // } // case BitMetaType: // if key, err := db.bDecodeMetaKey(k); err != nil { // return nil, err // } else { // buf = strconv.AppendQuote(buf, hack.String(key)) // } case SetType: if key, member, err := db.sDecodeSetKey(k); err != nil { return nil, err } else { buf = strconv.AppendQuote(buf, hack.String(key)) buf = append(buf, ' ') buf = strconv.AppendQuote(buf, hack.String(member)) } case SSizeType: if key, err := db.sDecodeSizeKey(k); err != nil { return nil, err } else { buf = strconv.AppendQuote(buf, hack.String(key)) } case ExpTimeType: if tp, key, t, err := db.expDecodeTimeKey(k); err != nil { return nil, err } else { buf = append(buf, TypeName[tp]...) buf = append(buf, ' ') buf = strconv.AppendQuote(buf, hack.String(key)) buf = append(buf, ' ') buf = strconv.AppendInt(buf, t, 10) } case ExpMetaType: if tp, key, err := db.expDecodeMetaKey(k); err != nil { return nil, err } else { buf = append(buf, TypeName[tp]...) buf = append(buf, ' ') buf = strconv.AppendQuote(buf, hack.String(key)) } default: return nil, errInvalidEvent } return buf, nil }
genshin_handle.py
import os from nonebot.adapters.cqhttp import MessageSegment, Message import nonebot import random from .update_game_info import update_info from .util import generate_img, init_star_rst, BaseData, set_list, get_star, init_up_char from .config import GENSHIN_FIVE_P, GENSHIN_FOUR_P, GENSHIN_G_FIVE_P, GENSHIN_G_FOUR_P, GENSHIN_THREE_P, I72_ADD, \ DRAW_PATH, GENSHIN_FLAG from dataclasses import dataclass from .init_card_pool import init_game_pool from .announcement import GenshinAnnouncement try: import ujson as json except ModuleNotFoundError: import json driver: nonebot.Driver = nonebot.get_driver() announcement = GenshinAnnouncement() genshin_five = {} genshin_count = {} genshin_pl_count = {} ALL_CHAR = [] ALL_ARMS = [] UP_CHAR = [] UP_ARMS = [] _CURRENT_CHAR_POOL_TITLE = '' _CURRENT_ARMS_POOL_TITLE = '' POOL_IMG = '' @dataclass class GenshinChar(BaseData): pass async def genshin_draw(user_id: int, count: int, pool_name: str): # 0 1 2 cnlist = ['★★★★★', '★★★★', '★★★'] char_list, five_list, five_index_list, char_dict, star_list = _format_card_information(count, user_id, pool_name) temp = '' title = '' up_type = [] up_list = [] if pool_name == 'char' and _CURRENT_CHAR_POOL_TITLE: up_type = UP_CHAR title = _CURRENT_CHAR_POOL_TITLE elif pool_name == 'arms' and _CURRENT_ARMS_POOL_TITLE: up_type = UP_ARMS title = _CURRENT_ARMS_POOL_TITLE tmp = '' if up_type: for x in up_type: for operator in x.operators: up_list.append(operator) if x.star == 5: tmp += f'五星UP:{" ".join(x.operators)} \n' elif x.star == 4: tmp += f'四星UP:{" ".join(x.operators)}' rst = init_star_rst(star_list, cnlist, five_list, five_index_list, up_list) pool_info = f'当前up池:{title}\n{tmp}' if title else '' if count > 90: char_list = set_list(char_list) return pool_info + '\n' + MessageSegment.image("base64://" + await generate_img(char_list, 'genshin', star_list)) + '\n' + rst[:-1] + \ temp[:-1] + f'\n距离保底发还剩 {90 - genshin_count[user_id] if genshin_count.get(user_id) else "^"} 抽' \ + "\n【五星:0.6%,四星:5.1%\n第72抽开始五星概率每抽加0.585%】" async def update_genshin_info(): global ALL_CHAR, ALL_ARMS url = 'https://wiki.biligame.com/ys/角色筛选' data, code = await update_info(url, 'genshin') if code == 200: ALL_CHAR = init_game_pool('genshin', data, GenshinChar) url = 'https://wiki.biligame.com/ys/武器图鉴' data, code = await update_info(url, 'genshin_arms', ['头像', '名称', '类型', '稀有度.alt', '获取途径', '初始基础属性1', '初始基础属性2', '攻击力(MAX)', '副属性(MAX)', '技能']) if code == 200: ALL_ARMS = init_game_pool('genshin_arms', data, GenshinChar) await _genshin_init_up_char() async def init_genshin_data(): global ALL_CHAR, ALL_ARMS if GENSHIN_FLAG: if not os.path.exists(DRAW_PATH + 'genshin.json') or not os.path.exists(DRAW_PATH + 'genshin_arms.json'): await update_genshin_info() else: with open(DRAW_PATH + 'genshin.json', 'r', encoding='utf8') as f: genshin_dict = json.load(f) with open(DRAW_PATH + 'genshin_arms.json', 'r', encoding='utf8') as f: genshin_ARMS_dict = json.load(f) ALL_CHAR = init_game_pool('genshin', genshin_dict, GenshinChar) ALL_ARMS = init_game_pool('genshin_arms', genshin_ARMS_dict, GenshinChar) await _genshin_init_up_char() # 抽取卡池 def _get_genshin_card(mode: int = 1, pool_name: str = '', add: float = 0.0): global ALL_ARMS, ALL_CHAR, UP_ARMS, UP_CHAR, _CURRENT_ARMS_POOL_TITLE, _CURRENT_CHAR_POOL_TITLE if mode == 1: star = get_star([5, 4, 3], [GENSHIN_FIVE_P + add, GENSHIN_FOUR_P, GENSHIN_THREE_P]) elif mode == 2: star = get_star([5, 4], [GENSHIN_G_FIVE_P + add, GENSHIN_G_FOUR_P]) else: star = 5 if pool_name == 'char': data_lst = UP_CHAR flag = _CURRENT_CHAR_POOL_TITLE itype_all_lst = ALL_CHAR + [x for x in ALL_ARMS if x.star == star and x.star < 5] elif pool_name == 'arms': data_lst = UP_ARMS flag = _CURRENT_ARMS_POOL_TITLE itype_all_lst = ALL_ARMS + [x for x in ALL_CHAR if x.star == star and x.star < 5] else: data_lst = '' flag = '' itype_all_lst = '' all_lst = ALL_ARMS + ALL_CHAR # 是否UP if flag and star > 3 and pool_name: # 获取up角色列表 up_char_lst = [x.operators for x in data_lst if x.star == star][0] # 成功获取up角色 if random.random() < 0.5: up_char_name = random.choice(up_char_lst) acquire_char = [x for x in all_lst if x.name == up_char_name][0] else: # 无up all_char_lst = [x for x in itype_all_lst if x.star == star and x.name not in up_char_lst and not x.limited] acquire_char = random.choice(all_char_lst) else: chars = [x for x in all_lst if x.star == star and not x.limited] acquire_char = random.choice(chars) return acquire_char, 5 - star def _format_card_information(_count: int, user_id, pool_name): char_list = [] star_list = [0, 0, 0] five_index_list = [] five_list = [] five_dict = {} add = 0.0 if genshin_count.get(user_id) and _count <= 90: f_count = genshin_count[user_id] else: f_count = 0 if genshin_pl_count.get(user_id) and _count <= 90: count = genshin_pl_count[user_id] else: count = 0 for i in range(_count): count += 1 f_count += 1 # 十连保底 if count == 10 and f_count != 90: if f_count >= 72: add += I72_ADD char, code = _get_genshin_card(2, pool_name, add=add) count = 0 # 大保底 elif f_count == 90: char, code = _get_genshin_card(3, pool_name) else: if f_count >= 72: add += I72_ADD char, code = _get_genshin_card(pool_name=pool_name, add=add) if code == 1: count = 0 star_list[code] += 1 if code == 0: if _count <= 90: genshin_five[user_id] = f_count add = 0.0 f_count = 0 five_list.append(char.name) five_index_list.append(i) try: five_dict[char.name] += 1 except KeyError: five_dict[char.name] = 1 char_list.append(char) if _count <= 90: genshin_count[user_id] = f_count genshin_pl_count[user_id] = count return char_list, five_list, five_index_list, five_dict, star_list def reset_count(user_id: int): genshin_count[user_id] = 0 genshin_pl_count[user_id] = 0 # 获取up和概率 async def _genshin_init_up_char(): global _CURRENT_CHAR_POOL_TITLE, _CURRENT_ARMS_POOL_TITLE, UP_CHAR, UP_ARMS, POOL_IMG _CURRENT_CHAR_POOL_TITLE, _CURRENT_ARMS_POOL_TITLE, POOL_IMG, UP_CHAR, UP_ARMS = await init_up_char(announcement) async def re
await _genshin_init_up_char() return Message(f'当前UP池子:{_CURRENT_CHAR_POOL_TITLE} & {_CURRENT_ARMS_POOL_TITLE} {POOL_IMG}')
load_genshin_pool():
setup.py
import os from setuptools import setup PACKAGE = "allure-behave" VERSION = "2.5.5" classifiers = [ 'Development Status :: 5 - Production/Stable', 'Intended Audience :: Developers', 'License :: OSI Approved :: Apache Software License', 'Topic :: Software Development :: Quality Assurance', 'Topic :: Software Development :: Testing', 'Topic :: Software Development :: Testing :: BDD' ] install_requires = [ "behave>=1.2.5", "allure-python-commons==2.5.5" ] def read(fname): return open(os.path.join(os.path.dirname(__file__), fname)).read() def main(): setup( name=PACKAGE, version=VERSION, description="Allure behave integration", url="https://github.com/allure-framework/allure-python", author="QAMetaSoftware, Stanislav Seliverstov", author_email="[email protected]", license="Apache-2.0", classifiers=classifiers, keywords="allure reporting behave", long_description=read('README.rst'), packages=["allure_behave"], package_dir={"allure_behave": "src"}, install_requires=install_requires )
if __name__ == '__main__': main()
39.1-BDP-unbiased-clustering.py
# %% [markdown] # # Imports import json import os import warnings from operator import itemgetter from pathlib import Path import matplotlib.pyplot as plt import numpy as np import pandas as pd import seaborn as sns from joblib import Parallel, delayed from joblib.parallel import Parallel, delayed from sklearn.metrics import adjusted_rand_score import networkx as nx from graspy.cluster import GaussianCluster, AutoGMMCluster from graspy.embed import AdjacencySpectralEmbed, OmnibusEmbed from graspy.models import DCSBMEstimator, SBMEstimator from graspy.plot import heatmap, pairplot from graspy.utils import binarize, cartprod, get_lcc, pass_to_ranks from src.data import load_everything from src.utils import export_skeleton_json, savefig from src.visualization import clustergram, palplot, sankey from src.hierarchy import signal_flow warnings.simplefilter("ignore", category=FutureWarning) FNAME = os.path.basename(__file__)[:-3] print(FNAME) # %% [markdown] # # Parameters BRAIN_VERSION = "2019-12-09" GRAPH_TYPES = ["Gad", "Gaa", "Gdd", "Gda"] GRAPH_TYPE_LABELS = [r"A $\to$ D", r"A $\to$ A", r"D $\to$ D", r"D $\to$ A"] N_GRAPH_TYPES = len(GRAPH_TYPES) SAVEFIGS = True DEFAULT_FMT = "png" DEFUALT_DPI = 150 SAVESKELS = False MIN_CLUSTERS = 8 MAX_CLUSTERS = 8 N_INIT = 50 PTR = True ONLY_RIGHT = True embed = "LSE" cluster = "GMM" n_components = 4 if cluster == "GMM": gmm_params = {"n_init": N_INIT, "covariance_type": "all"} elif cluster == "AutoGMM": gmm_params = {"max_agglom_size": None} np.random.seed(23409857) def stashfig(name, **kws): if SAVEFIGS: savefig(name, foldername=FNAME, fmt=DEFAULT_FMT, dpi=DEFUALT_DPI, **kws) def stashskel(name, ids, colors, palette=None, **kws): if SAVESKELS: return export_skeleton_json( name, ids, colors, palette=palette, foldername=FNAME, **kws ) def ase(adj, n_components): if PTR: adj = pass_to_ranks(adj) ase = AdjacencySpectralEmbed(n_components=n_components) latent = ase.fit_transform(adj) latent = np.concatenate(latent, axis=-1) return latent def to_laplace(graph, form="DAD", regularizer=None): r""" A function to convert graph adjacency matrix to graph laplacian. Currently supports I-DAD, DAD, and R-DAD laplacians, where D is the diagonal matrix of degrees of each node raised to the -1/2 power, I is the identity matrix, and A is the adjacency matrix. R-DAD is regularized laplacian: where :math:`D_t = D + regularizer*I`. Parameters ---------- graph: object Either array-like, (n_vertices, n_vertices) numpy array, or an object of type networkx.Graph. form: {'I-DAD' (default), 'DAD', 'R-DAD'}, string, optional - 'I-DAD' Computes :math:`L = I - D*A*D` - 'DAD' Computes :math:`L = D*A*D` - 'R-DAD' Computes :math:`L = D_t*A*D_t` where :math:`D_t = D + regularizer*I` regularizer: int, float or None, optional (default=None) Constant to be added to the diagonal of degree matrix. If None, average node degree is added. If int or float, must be >= 0. Only used when ``form`` == 'R-DAD'. Returns ------- L: numpy.ndarray 2D (n_vertices, n_vertices) array representing graph laplacian of specified form References ---------- .. [1] Qin, Tai, and Karl Rohe. "Regularized spectral clustering under the degree-corrected stochastic blockmodel." In Advances in Neural Information Processing Systems, pp. 3120-3128. 2013 """ valid_inputs = ["I-DAD", "DAD", "R-DAD"] if form not in valid_inputs: raise TypeError("Unsuported Laplacian normalization") A = graph in_degree = np.sum(A, axis=0) out_degree = np.sum(A, axis=1) # regularize laplacian with parameter # set to average degree if form == "R-DAD": if regularizer is None: regularizer = 1 elif not isinstance(regularizer, (int, float)): raise TypeError( "Regularizer must be a int or float, not {}".format(type(regularizer)) ) elif regularizer < 0: raise ValueError("Regularizer must be greater than or equal to 0") regularizer = regularizer * np.mean(out_degree) in_degree += regularizer out_degree += regularizer with np.errstate(divide="ignore"): in_root = 1 / np.sqrt(in_degree) # this is 10x faster than ** -0.5 out_root = 1 / np.sqrt(out_degree) in_root[np.isinf(in_root)] = 0 out_root[np.isinf(out_root)] = 0 in_root = np.diag(in_root) # just change to sparse diag for sparse support out_root = np.diag(out_root) if form == "I-DAD": L = np.diag(in_degree) - A L = in_root @ L @ in_root elif form == "DAD" or form == "R-DAD": L = out_root @ A @ in_root # return symmetrize(L, method="avg") # sometimes machine prec. makes this necessary return L def
(adj, n_components, regularizer=None): if PTR: adj = pass_to_ranks(adj) lap = to_laplace(adj, form="R-DAD") ase = AdjacencySpectralEmbed(n_components=n_components) latent = ase.fit_transform(lap) latent = np.concatenate(latent, axis=-1) return latent def omni(adjs, n_components): if PTR: adjs = [pass_to_ranks(a) for a in adjs] omni = OmnibusEmbed(n_components=n_components // len(adjs)) latent = omni.fit_transform(adjs) latent = np.concatenate(latent, axis=-1) # first is for in/out latent = np.concatenate(latent, axis=-1) # second is for concat. each graph return latent def ase_concatenate(adjs, n_components): if PTR: adjs = [pass_to_ranks(a) for a in adjs] ase = AdjacencySpectralEmbed(n_components=n_components // len(adjs)) graph_latents = [] for a in adjs: latent = ase.fit_transform(a) latent = np.concatenate(latent, axis=-1) graph_latents.append(latent) latent = np.concatenate(graph_latents, axis=-1) return latent def sub_ari(known_inds, true_labels, pred_labels): true_known_labels = true_labels[known_inds] pred_known_labels = pred_labels[known_inds] ari = adjusted_rand_score(true_known_labels, pred_known_labels) return ari # Set up plotting constants plt.style.use("seaborn-white") sns.set_palette("deep") sns.set_context("talk", font_scale=1) # %% [markdown] # # Load the data adj, class_labels, side_labels, skeleton_labels = load_everything( "Gad", version=BRAIN_VERSION, return_keys=["Merge Class", "Hemisphere"], return_ids=True, ) # select the right hemisphere if ONLY_RIGHT: side = "right hemisphere" right_inds = np.where(side_labels == "R")[0] adj = adj[np.ix_(right_inds, right_inds)] class_labels = class_labels[right_inds] skeleton_labels = skeleton_labels[right_inds] else: side = "full brain" # sort by number of synapses degrees = adj.sum(axis=0) + adj.sum(axis=1) sort_inds = np.argsort(degrees)[::-1] adj = adj[np.ix_(sort_inds, sort_inds)] class_labels = class_labels[sort_inds] skeleton_labels = skeleton_labels[sort_inds] # remove disconnected nodes adj, lcc_inds = get_lcc(adj, return_inds=True) class_labels = class_labels[lcc_inds] skeleton_labels = skeleton_labels[lcc_inds] # remove pendants degrees = np.count_nonzero(adj, axis=0) + np.count_nonzero(adj, axis=1) not_pendant_mask = degrees != 1 not_pendant_inds = np.array(range(len(degrees)))[not_pendant_mask] adj = adj[np.ix_(not_pendant_inds, not_pendant_inds)] class_labels = class_labels[not_pendant_inds] skeleton_labels = skeleton_labels[not_pendant_inds] # plot degree sequence d_sort = np.argsort(degrees)[::-1] degrees = degrees[d_sort] plt.figure(figsize=(10, 5)) sns.scatterplot(x=range(len(degrees)), y=degrees, s=30, linewidth=0) known_inds = np.where(class_labels != "Unk")[0] # %% [markdown] # # Run clustering using LSE on the sum graph n_verts = adj.shape[0] latent = lse(adj, n_components, regularizer=None) pairplot(latent, labels=class_labels, title=embed) k_list = list(range(MIN_CLUSTERS, MAX_CLUSTERS + 1)) n_runs = len(k_list) out_dicts = [] bin_adj = binarize(adj) last_pred_labels = np.zeros(n_verts) if cluster == "GMM": ClusterModel = GaussianCluster elif cluster == "AutoGMM": ClusterModel = AutoGMMCluster for k in k_list: run_name = f"k = {k}, {cluster}, {embed}, {side} (A to D), PTR, raw" print(run_name) print() # Do clustering # TODO: make this autogmm instead gmm = ClusterModel(min_components=k, max_components=k, **gmm_params) gmm.fit(latent) pred_labels = gmm.predict(latent) # Score unsupervised metrics base_dict = { "K": k, "Cluster": cluster, "Embed": embed, "Method": f"{cluster} o {embed}", } # GMM likelihood score = gmm.model_.score(latent) temp_dict = base_dict.copy() temp_dict["Metric"] = "GMM likelihood" temp_dict["Score"] = score out_dicts.append(temp_dict) # GMM BIC score = gmm.model_.bic(latent) temp_dict = base_dict.copy() temp_dict["Metric"] = "GMM BIC" temp_dict["Score"] = score out_dicts.append(temp_dict) # SBM likelihood sbm = SBMEstimator(directed=True, loops=False) sbm.fit(bin_adj, y=pred_labels) score = sbm.score(bin_adj) temp_dict = base_dict.copy() temp_dict["Metric"] = "SBM likelihood" temp_dict["Score"] = score out_dicts.append(temp_dict) # DCSBM likelihood dcsbm = DCSBMEstimator(directed=True, loops=False) dcsbm.fit(bin_adj, y=pred_labels) score = dcsbm.score(bin_adj) temp_dict = base_dict.copy() temp_dict["Metric"] = "DCSBM likelihood" temp_dict["Score"] = score out_dicts.append(temp_dict) # ARI of the subset with labels score = sub_ari(known_inds, class_labels, pred_labels) temp_dict = base_dict.copy() temp_dict["Metric"] = "Simple ARI" temp_dict["Score"] = score out_dicts.append(temp_dict) # ARI vs K - 1 score = adjusted_rand_score(last_pred_labels, pred_labels) temp_dict = base_dict.copy() temp_dict["Metric"] = "K-1 ARI" temp_dict["Score"] = score out_dicts.append(temp_dict) last_pred_labels = pred_labels save_name = f"k{k}-{cluster}-{embed}-right-ad-PTR-raw" # Plot embedding # pairplot(latent, labels=pred_labels, title=run_name) # stashfig("latent-" + save_name) # Plot everything else clustergram(adj, class_labels, pred_labels) stashfig("clustergram-" + save_name) # New plot # - Compute signal flow # - Get the centroid of each cluster and project to 1d # - Alternatively, just take the first dimension # - For each cluster plot as a node # output skeletons if SAVESKELS: _, colormap, pal = stashskel( save_name, skeleton_labels, pred_labels, palette="viridis", multiout=True ) palplot(k, cmap="viridis") stashfig("palplot-" + save_name) # save dict colormapping filename = ( Path("./maggot_models/notebooks/outs") / Path(FNAME) / str("colormap-" + save_name + ".json") ) with open(filename, "w") as fout: json.dump(colormap, fout) stashskel( save_name, skeleton_labels, pred_labels, palette="viridis", multiout=False ) # %% [markdown] # # Plot results of unsupervised metrics result_df = pd.DataFrame(out_dicts) fg = sns.FacetGrid(result_df, col="Metric", col_wrap=3, sharey=False, height=4) fg.map(sns.lineplot, "K", "Score") stashfig(f"metrics-{cluster}-{embed}-right-ad-PTR-raw") # Modifications i need to make to the above # - Increase the height of the sankey diagram overall # - Look into color maps that could be better # - Color the cluster labels by what gets written to the JSON # - Plot the clusters as nodes in a small network # %% [markdown] # # try graph flow node_signal_flow = signal_flow(adj) mean_sf = np.zeros(k) for i in np.unique(pred_labels): inds = np.where(pred_labels == i)[0] mean_sf[i] = np.mean(node_signal_flow[inds]) cluster_mean_latent = gmm.model_.means_[:, 0] block_probs = SBMEstimator().fit(bin_adj, y=pred_labels).block_p_ block_prob_df = pd.DataFrame(data=block_probs, index=range(k), columns=range(k)) block_g = nx.from_pandas_adjacency(block_prob_df, create_using=nx.DiGraph) plt.figure(figsize=(10, 10)) # don't ever let em tell you you're too pythonic pos = dict(zip(range(k), zip(cluster_mean_latent, mean_sf))) # nx.draw_networkx_nodes(block_g, pos=pos) labels = nx.get_edge_attributes(block_g, "weight") # nx.draw_networkx_edge_labels(block_g, pos, edge_labels=labels) from matplotlib.cm import ScalarMappable import matplotlib as mpl norm = mpl.colors.LogNorm(vmin=0.01, vmax=0.1) sm = ScalarMappable(cmap="Reds", norm=norm) cmap = sm.to_rgba(np.array(list(labels.values())) + 0.01) nx.draw_networkx( block_g, pos, edge_cmap="Reds", edge_color=cmap, connectionstyle="arc3,rad=0.2", width=1.5, ) # %% [markdown] # # signal flow marginals signal_flow_marginal(adj, pred_labels) # %% [markdown] # # def signal_flow_marginal(adj, labels, col_wrap=5, palette="tab20"): sf = signal_flow(adj) uni_labels = np.unique(labels) medians = [] for i in uni_labels: inds = np.where(labels == i)[0] medians.append(np.median(sf[inds])) sort_inds = np.argsort(medians)[::-1] col_order = uni_labels[sort_inds] plot_df = pd.DataFrame() plot_df["Signal flow"] = sf plot_df["Class"] = labels fg = sns.FacetGrid( plot_df, col="Class", aspect=1.5, palette=palette, col_order=col_order, sharey=False, col_wrap=col_wrap, xlim=(-3, 3), ) fg = fg.map(sns.distplot, "Signal flow") # bins=np.linspace(-2.2, 2.2)) fg.set(yticks=[], yticklabels=[]) plt.tight_layout() return fg signal_flow_marginal(adj, class_labels) stashfig("known-class-sf-marginal") # tomorrow # DEFINITELY # run with unsupervised metrics from k=2-50 # IF TIME # run hgmm
lse
receiver.rs
use udp_transfer::receiver::{logic, config::Config}; fn
() { let config = Config::from_command_line(); let is_verbose = config.is_verbose(); if let Err(e) = logic(config) { println!("Ending program because of error"); if is_verbose { println!("{}", e); } } }
main
mod.rs
pub mod extensions; pub mod input; pub mod output; use std::ffi::CStr; use std::marker::PhantomData; use std::str::from_utf8_unchecked; use ffi::*; pub struct Info<'a> { ptr: *mut AVDeviceInfo, _marker: PhantomData<&'a ()>, } impl<'a> Info<'a> { pub unsafe fn wrap(ptr: *mut AVDeviceInfo) -> Self { Info { ptr: ptr, _marker: PhantomData, } } pub unsafe fn as_ptr(&self) -> *const AVDeviceInfo { self.ptr as *const _ } pub unsafe fn as_mut_ptr(&mut self) -> *mut AVDeviceInfo { self.ptr } } impl<'a> Info<'a> { pub fn name(&self) -> &str
pub fn description(&self) -> &str { unsafe { from_utf8_unchecked(CStr::from_ptr((*self.as_ptr()).device_description).to_bytes()) } } } pub fn register_all() { unsafe { avdevice_register_all(); } } pub fn version() -> u32 { unsafe { avdevice_version() } } pub fn configuration() -> &'static str { unsafe { from_utf8_unchecked(CStr::from_ptr(avdevice_configuration()).to_bytes()) } } pub fn license() -> &'static str { unsafe { from_utf8_unchecked(CStr::from_ptr(avdevice_license()).to_bytes()) } }
{ unsafe { from_utf8_unchecked(CStr::from_ptr((*self.as_ptr()).device_name).to_bytes()) } }
pattern.rs
// This file is licensed under the terms of Apache-2.0 License. use super::{ err, IResult, }; use crate::{ ast::Pattern, parser::prelude::*, }; pub fn any_of<'a, 'b>( patterns: &'b [Pattern], ) -> impl 'b + FnMut(&'a str) -> IResult<&'a str, &'a str>
impl Pattern { pub fn parse<'a>(&self, input: &'a str) -> IResult<&'a str, &'a str> { match self { Self::Word { reg } => { // Take a space delimited word. verify( preceded(multispace0, take_while(|c: char| !c.is_whitespace())), |s: &str| !s.is_empty() && reg.as_ref().map_or(true, |r| r.is_match(s)), )(input) } Self::Eq { any_of, no_case } => { for s in any_of { let res = if *no_case { preceded(multispace0, tag_no_case(s.as_str()))(input) } else { preceded(multispace0, tag(s.as_str()))(input) }; if res.is_ok() { return res; } } err!() } Self::Delimited { starts, ends, reg, no_case, no_trim, } => { let input = input.trim_start(); macro_rules! valid { [$s:expr] => (reg.as_ref().map_or(true, |r| r.is_match($s))); } if starts.is_empty() { for s in ends { let res: IResult<&'a str, &'a str> = verify(take_until(s.as_str()), |s: &str| !s.is_empty())(input); match res { Err(_) => (), Ok((rest, capture)) if !*no_trim => { if valid!(capture) { return Ok((rest, capture)); } } Ok((rest, _)) => { let capture = &input[..input.len() - rest.len()]; if valid!(capture) { return Ok((rest, capture)); } } } } err!() } else if ends.is_empty() { for s in starts { let body = take_while(|c: char| !c.is_whitespace()); let res: IResult<&'a str, &'a str> = if *no_case { let prefix = tag_no_case(s.as_str()); verify(preceded(prefix, body), |s: &str| !s.is_empty())(input) } else { let prefix = tag(s.as_str()); verify(preceded(prefix, body), |s: &str| !s.is_empty())(input) }; match res { Err(_) => (), Ok((rest, capture)) if !*no_trim => { if valid!(capture) { return Ok((rest, capture)); } } Ok((rest, _)) => { let capture = input[..input.len() - rest.len()].trim_end(); if valid!(capture) { return Ok((rest, capture)); } } } } err!() } else { for start in starts { for end in ends { let right = tag(end.as_str()); let body = take_until(end.as_str()); let res: IResult<&'a str, &'a str> = if *no_case { let left = tag_no_case(start.as_str()); delimited(left, body, right)(input) } else { let left = tag(start.as_str()); delimited(left, body, right)(input) }; match res { Err(_) => (), Ok((rest, capture)) if !*no_trim => { if valid!(capture) { return Ok((rest, capture)); } } Ok((rest, _)) => { let capture = input[..input.len() - rest.len()].trim(); if valid!(capture) { return Ok((rest, capture)); } } } } } err!() } } } } }
{ move |input: &'a str| { for p in patterns { let res = p.parse(input); if res.is_ok() { return res; } } err!() } }
main.go
package main
"fmt" "net/http" "log" ) const webContent = "dev-ops-ninja:v10" func main() { http.HandleFunc("/", helloHandler) log.Fatal(http.ListenAndServe(":80", nil)) } func helloHandler(w http.ResponseWriter, r *http.Request) { fmt.Fprint(w, webContent) }
import (
0004_bookinstance_borrower.py
# Generated by Django 3.1.3 on 2020-12-01 22:02 from django.conf import settings from django.db import migrations, models import django.db.models.deletion class
(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('catalog', '0003_auto_20201126_1636'), ] operations = [ migrations.AddField( model_name='bookinstance', name='borrower', field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, to=settings.AUTH_USER_MODEL), ), ]
Migration
gadgets.go
// Basic collection of pre-defined gadgets. package gadgets import ( "bufio" "encoding/json" "flag" "fmt" "io/ioutil" "os" "strings" "time" "github.com/jcw/flow" _ "github.com/jcw/flow/gadgets/pipe" ) func init() { flow.Registry["Sink"] = func() flow.Circuitry { return new(Sink) } // flow.Registry["Pipe"] = func() flow.Circuitry { return new(Pipe) } //pipe now in subdirectory flow.Registry["Repeater"] = func() flow.Circuitry { return new(Repeater) } flow.Registry["Counter"] = func() flow.Circuitry { return new(Counter) } flow.Registry["Printer"] = func() flow.Circuitry { return new(Printer) } flow.Registry["Timer"] = func() flow.Circuitry { return new(Timer) } flow.Registry["Clock"] = func() flow.Circuitry { return new(Clock) } flow.Registry["FanOut"] = func() flow.Circuitry { return new(FanOut) } flow.Registry["Forever"] = func() flow.Circuitry { return new(Forever) } flow.Registry["Delay"] = func() flow.Circuitry { return new(Delay) } flow.Registry["TimeStamp"] = func() flow.Circuitry { return new(TimeStamp) } flow.Registry["ReadFileText"] = func() flow.Circuitry { return new(ReadFileText) } flow.Registry["ReadFileJSON"] = func() flow.Circuitry { return new(ReadFileJSON) } flow.Registry["EnvVar"] = func() flow.Circuitry { return new(EnvVar) } flow.Registry["CmdLine"] = func() flow.Circuitry { return new(CmdLine) } flow.Registry["Concat3"] = func() flow.Circuitry { return new(Concat3) } flow.Registry["AddTag"] = func() flow.Circuitry { return new(AddTag) } } // A sink eats up all the messages it receives. Registers as "Sink". type Sink struct { flow.Gadget In flow.Input Out flow.Output } // Start reading messages and discard them. func (w *Sink) Run() { w.Out.Disconnect() for _ = range w.In { } } // Repeaters are pipes which repeat each message a number of times. // Registers as "Repeater". type Repeater struct { flow.Gadget In flow.Input Out flow.Output Num flow.Input } // Start repeating incoming messages. func (w *Repeater) Run() { if num, ok := <-w.Num; ok { n := num.(int) for m := range w.In { count := n if _, ok = m.(flow.Tag); ok { count = 1 // don't repeat tags, just pass them through } for i := 0; i < count; i++ { w.Out.Send(m) } } } } // A counter reports the number of messages it has received. // Registers as "Counter". type Counter struct { flow.Gadget In flow.Input Out flow.Output count int } // Start counting incoming messages. func (w *Counter) Run() { for m := range w.In { if _, ok := m.(flow.Tag); ok { w.Out.Send(m) // don't count tags, just pass them through } else { w.count++ } } w.Out.Send(w.count) } // Printers report the messages sent to them as output. Registers as "Printer". type Printer struct { flow.Gadget In flow.Input } // Start printing incoming messages. func (w *Printer) Run() { for m := range w.In { fmt.Printf("%+v\n", m) } } // A timer sends out one message after the time set by the Rate pin. // Registers as "Timer". type Timer struct { flow.Gadget In flow.Input Out flow.Output } // Start the timer, sends one message when it expires. func (w *Timer) Run() { if r, ok := <-w.In; ok { rate, err := time.ParseDuration(r.(string)) flow.Check(err) t := <-time.After(rate) w.Out.Send(t) } } // A clock sends out messages at a fixed rate, as set by the Rate pin. // Registers as "Clock". type Clock struct { flow.Gadget In flow.Input Out flow.Output } // Start sending out periodic messages, once the rate is known. func (w *Clock) Run() { if r, ok := <-w.In; ok { rate, err := time.ParseDuration(r.(string)) flow.Check(err) t := time.NewTicker(rate) defer t.Stop() for m := range t.C { w.Out.Send(m) }
} // A fanout sends out messages to each of its outputs, which is set up as map. // Registers as "FanOut". type FanOut struct { flow.Gadget In flow.Input Out map[string]flow.Output } // Start sending out messages to all output pins (does not make copies of them). func (w *FanOut) Run() { for m := range w.In { for _, o := range w.Out { o.Send(m) } } } // Forever does just what the name says: run forever (and do nothing at all) type Forever struct { flow.Gadget Out flow.Output } // Start running forever, the output stays open and never sends anything. func (w *Forever) Run() { <-make(chan struct{}) } // Send data out after a certain delay. type Delay struct { flow.Gadget In flow.Input Delay flow.Input Out flow.Output } // Parse the delay, then throttle each incoming message. func (g *Delay) Run() { delay, _ := time.ParseDuration((<-g.Delay).(string)) for m := range g.In { time.Sleep(delay) g.Out.Send(m) } } // Insert a timestamp before each message. Registers as "TimeStamp". type TimeStamp struct { flow.Gadget In flow.Input Out flow.Output } // Start inserting timestamps. func (w *TimeStamp) Run() { for m := range w.In { w.Out.Send(time.Now()) w.Out.Send(m) } } // ReadFileText takes strings and replaces them by the lines of that file. // Inserts <open> and <close> tags before doing so. Registers as "ReadFileText". type ReadFileText struct { flow.Gadget In flow.Input Out flow.Output } // Start reading filenames and emit their text lines, with <open>/<close> tags. func (w *ReadFileText) Run() { for m := range w.In { if name, ok := m.(string); ok { file, err := os.Open(name) flow.Check(err) scanner := bufio.NewScanner(file) w.Out.Send(flow.Tag{"<open>", name}) for scanner.Scan() { w.Out.Send(scanner.Text()) } w.Out.Send(flow.Tag{"<close>", name}) } else { w.Out.Send(m) } } } // ReadFileJSON takes strings and parses that file's contents as JSON. // Registers as "ReadFileJSON". type ReadFileJSON struct { flow.Gadget In flow.Input Out flow.Output } // Start reading filenames and emit a <file> tag followed by the decoded JSON. func (w *ReadFileJSON) Run() { for m := range w.In { if name, ok := m.(string); ok { data, err := ioutil.ReadFile(name) flow.Check(err) w.Out.Send(flow.Tag{"<file>", name}) var any interface{} err = json.Unmarshal(data, &any) flow.Check(err) m = any } w.Out.Send(m) } } // Lookup an environment variable, with optional default. Registers as "EnvVar". type EnvVar struct { flow.Gadget In flow.Input Out flow.Output } // Start lookup up environment variables. func (g *EnvVar) Run() { for m := range g.In { switch v := m.(type) { case string: m = os.Getenv(v) case flow.Tag: if s := os.Getenv(v.Tag); s != "" { m = s } else { m = v.Msg } } g.Out.Send(m) } } // Turn command-line arguments into a message flow. Registers as "CmdLine". type CmdLine struct { flow.Gadget Type flow.Input Out flow.Output } // Start processing the command-line arguments. func (g *CmdLine) Run() { asJson := false skip := 0 step := 1 for m := range g.Type { for _, typ := range strings.Split(m.(string), ",") { switch typ { case "": // ignored case "skip": skip++ case "json": asJson = true case "tags": step = 2 default: panic("unknown option: " + typ) } } } for i := skip; i < flag.NArg(); i += step { arg := flag.Arg(i + step - 1) var value interface{} = arg if asJson { if err := json.Unmarshal([]byte(arg), &value); err != nil { if i+step-1 < flag.NArg() { value = arg // didn't parse as JSON string, pass as string } else { value = nil // odd number of args, value set to nil } } } if step > 1 { value = flow.Tag{flag.Arg(i), value} } g.Out.Send(value) } } // Until general collection is possible, this concatenates three input pins. // Registers as "Concat3". type Concat3 struct { flow.Gadget In1 flow.Input In2 flow.Input In3 flow.Input Out flow.Output } // Start waiting from each pin, moving on to the next when the channel closes. func (g *Concat3) Run() { for m := range g.In1 { g.Out.Send(m) } for m := range g.In2 { g.Out.Send(m) } for m := range g.In3 { g.Out.Send(m) } } // AddTag turns a stream into a tagged stream. Registers as "AddTag". type AddTag struct { flow.Gadget Tag flow.Input In flow.Input Out flow.Output } // Start tagging all messages, but drop any incoming tags. func (g *AddTag) Run() { tag := (<-g.Tag).(string) for m := range g.In { if _, ok := m.(flow.Tag); !ok { g.Out.Send(flow.Tag{tag, m}) } } }
}
app-sidebar.component.js
/** * @fileoverview added by tsickle * @suppress {checkTypes} checked by tsc */ import { Component, Input, HostBinding } from '@angular/core'; import { sidebarCssClasses } from '../shared/index'; var AppSidebarComponent = /** @class */ (function () { function AppSidebarComponent() { } /** * @return {?} */ AppSidebarComponent.prototype.ngOnInit = /** * @return {?} */ function () { this.displayBreakpoint(this.display); this.isCompact(this.compact); this.isFixed(this.fixed); this.isMinimized(this.minimized); this.isOffCanvas(this.offCanvas); }; /** * @param {?} compact * @return {?} */ AppSidebarComponent.prototype.isCompact = /** * @param {?} compact * @return {?} */ function (compact) { if (this.compact) { document.querySelector('body').classList.add('sidebar-compact'); } }; /** * @param {?} fixed * @return {?} */ AppSidebarComponent.prototype.isFixed = /** * @param {?} fixed * @return {?} */ function (fixed) { if (this.fixed) { document.querySelector('body').classList.add('sidebar-fixed'); } }; /** * @param {?} minimized * @return {?} */ AppSidebarComponent.prototype.isMinimized = /** * @param {?} minimized * @return {?} */ function (minimized) { if (this.minimized) { document.querySelector('body').classList.add('sidebar-minimized'); } }; /** * @param {?} offCanvas * @return {?} */ AppSidebarComponent.prototype.isOffCanvas = /** * @param {?} offCanvas * @return {?} */ function (offCanvas) { if (this.offCanvas) { document.querySelector('body').classList.add('sidebar-off-canvas'); } }; /** * @param {?} fixed * @return {?} */ AppSidebarComponent.prototype.fixedPosition = /** * @param {?} fixed * @return {?} */ function (fixed) { if (this.fixed) { document.querySelector('body').classList.add('sidebar-fixed'); } }; /** * @param {?} display * @return {?} */ AppSidebarComponent.prototype.displayBreakpoint = /** * @param {?} display * @return {?} */ function (display) { if (this.display !== false) { var /** @type {?} */ cssClass = void 0; this.display ? cssClass = "sidebar-" + this.display + "-show" : cssClass = sidebarCssClasses[0]; document.querySelector('body').classList.add(cssClass); } }; AppSidebarComponent.decorators = [ { type: Component, args: [{ selector: 'app-sidebar', template: "<ng-content></ng-content>" },] }, ]; /** @nocollapse */ AppSidebarComponent.ctorParameters = function () { return []; }; AppSidebarComponent.propDecorators = { compact: [{ type: Input }], display: [{ type: Input }], fixed: [{ type: Input }], minimized: [{ type: Input }], offCanvas: [{ type: Input }], true: [{ type: HostBinding, args: ['class.sidebar',] }] };
/** @type {?} */ AppSidebarComponent.prototype.compact; /** @type {?} */ AppSidebarComponent.prototype.display; /** @type {?} */ AppSidebarComponent.prototype.fixed; /** @type {?} */ AppSidebarComponent.prototype.minimized; /** @type {?} */ AppSidebarComponent.prototype.offCanvas; /** @type {?} */ AppSidebarComponent.prototype.true; } //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiYXBwLXNpZGViYXIuY29tcG9uZW50LmpzIiwic291cmNlUm9vdCI6Im5nOi8vQGNvcmV1aS9hbmd1bGFyLyIsInNvdXJjZXMiOlsibGliL3NpZGViYXIvYXBwLXNpZGViYXIuY29tcG9uZW50LnRzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiI7Ozs7QUFBQSxPQUFPLEVBQUUsU0FBUyxFQUFFLEtBQUssRUFBRSxXQUFXLEVBQVUsTUFBTSxlQUFlLENBQUM7QUFDdEUsT0FBTyxFQUFFLGlCQUFpQixFQUFFLE1BQU0sYUFBYSxDQUFDOztJQWU5QztLQUFnQjs7OztJQUVoQixzQ0FBUTs7O0lBQVI7UUFDRSxJQUFJLENBQUMsaUJBQWlCLENBQUMsSUFBSSxDQUFDLE9BQU8s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cclxuICAgICAgdGhpcy5kaXNwbGF5ID8gY3NzQ2xhc3MgPSBgc2lkZWJhci0ke3RoaXMuZGlzcGxheX0tc2hvd2AgOiBjc3NDbGFzcyA9IHNpZGViYXJDc3NDbGFzc2VzWzBdO1xyXG4gICAgICBkb2N1bWVudC5xdWVyeVNlbGVjdG9yKCdib2R5JykuY2xhc3NMaXN0LmFkZChjc3NDbGFzcyk7XHJcbiAgICB9XHJcbiAgfVxyXG59XHJcbiJdfQ==
return AppSidebarComponent; }()); export { AppSidebarComponent }; function AppSidebarComponent_tsickle_Closure_declarations() {
util.py
import base64 import cProfile import cStringIO import collections import gzip import hmac import inspect import itertools import logging import math import os import socket import struct import time from urlparse import urljoin from django.conf import settings from django.db.models import Model, FloatField from django.db.models.query import QuerySet from django.db.models.sql.compiler import SQLInsertCompiler from django.http import Http404 from django.template import Context, Template from django.utils.encoding import force_unicode from django.utils.functional import Promise from django.utils.html import escape, strip_tags from django.utils.safestring import mark_safe import facebook from jinja2 import Markup from canvas.exceptions import NotLoggedIntoFacebookError from canvas.json import loads, dumps, client_dumps, backend_dumps, JSONDecodeError from configuration import Config from services import Services logger = logging.getLogger() unique = lambda iterable: list(set(iterable)) clamp = lambda lower, value, upper: min(upper, max(lower, value)) #TODO this is deprecated because of functools.wraps, unless someone knows an advantage to this method. --alex def simple_decorator(decorator): """ This decorator can be used to turn simple functions into well-behaved decorators, so long as the decorators are fairly simple. If a decorator expects a function and returns a function (no descriptors), and if it doesn't modify function attributes or docstring, then it is eligible to use this. Simply apply @simple_decorator to your decorator and it will automatically preserve the docstring and function attributes of functions to which it is applied. """ def new_decorator(f): g = decorator(f) g.__name__ = f.__name__ g.__doc__ = f.__doc__ g.__dict__.update(f.__dict__) return g # Now a few lines needed to make simple_decorator itself # be a well-behaved decorator. new_decorator.__name__ = decorator.__name__ new_decorator.__doc__ = decorator.__doc__ new_decorator.__dict__.update(decorator.__dict__) return new_decorator def iterlist(fun): def wrapper(*args, **kwargs): return list(fun(*args, **kwargs)) return wrapper def ip_to_int(ip): try: return struct.unpack('I', socket.inet_aton(ip))[0] except (socket.error, struct.error, TypeError): return 0 def int_to_ip(integer): return socket.inet_ntoa(struct.pack('I', integer)) def flatten(list_of_lists): """ Flatten one level of nesting. """ return itertools.chain.from_iterable(list_of_lists) def js_safety(thing, django=True, escape_html=False): thing = thing.replace('<', '\\u003c').replace('>', '\\u003e') if django: return mark_safe(thing) else: if escape_html: return thing return Markup(thing) def get_or_create(cls, **kwargs): inst = cls.objects.get_or_none(**kwargs) if inst is None: inst = cls(**kwargs) inst.save() return inst class GetSlice(object): def __getitem__(self, item): return item get_slice = GetSlice() # Modified, originally from http://en.wikipedia.org/wiki/Base_36 def _raw_base36encode(number): """ Convert positive integer to a base36 string. JS: canvas.base36encode """ if not isinstance(number, (int, long)): raise TypeError('number must be an integer') if number <= 0: raise ValueError('number must be a positive integer') alphabet='0123456789abcdefghijklmnopqrstuvwxyz' checksum = 0 base36 = '' while number != 0: number, i = divmod(number, 36) checksum += i * 19 base36 = alphabet[i] + base36 return base36, alphabet[checksum % 36] def base36encode(number): base36, check = _raw_base36encode(number) return base36 + check class Base36DecodeException(Exception): pass def base36decode(string): if not string: raise Base36DecodeException("Empty string") base36, check = string[:-1], string[-1] try: number = int(base36, 36) except ValueError: raise Base36DecodeException("Invalid base36 characters.") try: _, expected_check = _raw_base36encode(number) except ValueError: raise Base36DecodeException("Invalid base36 number.") if expected_check != check: raise Base36DecodeException("base36 check character does not match.") return number def base36decode_or_404(string): try: return base36decode(string) except Base36DecodeException: raise Http404 def random_token(length=40): assert length % 2 == 0 return base64.b16encode(os.urandom(length//2)) def placeholder(self, conn, field, value): if isinstance(value, Now): return value.as_sql(None, conn)[0] else: return SQLInsertCompiler.placeholder(self, field, value) # EVIL HAX def as_sql(self): # We don't need quote_name_unless_alias() here, since these are all # going to be column names (so we can avoid the extra overhead). qn = self.connection.ops.quote_name opts = self.query.model._meta result = ['INSERT INTO %s' % qn(opts.db_table)] result.append('(%s)' % ', '.join([qn(c) for c in self.query.columns])) values = [placeholder(self, self.connection, *v) for v in self.query.values] result.append('VALUES (%s)' % ', '.join(values)) params = [param for param in self.query.params if not isinstance(param, Now)] if self.return_id and self.connection.features.can_return_id_from_insert: col = "%s.%s" % (qn(opts.db_table), qn(opts.pk.column)) r_fmt, r_params = self.connection.ops.return_insert_id() result.append(r_fmt % col) params = params + r_params return ' '.join(result), params SQLInsertCompiler.as_sql = as_sql class UnixTimestampField(FloatField): def get_prep_value(self, value): if isinstance(value, Now): return value return FloatField.get_prep_value(self, value) class Now(object): def prepare_database_save(self, field): return self def _sql(self, executable_name): return Services.time.sql_now(executable_name) def as_sql(self, qn, conn): return self._sql(conn.client.executable_name), [] def get_fb_api(request): fb_user = facebook.get_user_from_cookie(request.COOKIES, Config['facebook']['app_id'], Config['facebook']['secret']) access_token = fb_user and fb_user.get('access_token') if not access_token: raise NotLoggedIntoFacebookError() return fb_user, facebook.GraphAPI(access_token) class ArgSpec(object): """ Convenience wrapper around `inspect.ArgSpec`. Properties: `args`: The list of arg names. Not the same as `inspect.ArgSpec#args`, however - this excludes the kwarg names. `kwargs`: A dictionary of kwarg names mapped to their default values. Note that if the given function contains a member annotation named `_original_function`, it will use that instead of the function. """ def __init__(self, func): func = getattr(func, '_original_function', func) spec = inspect.getargspec(func) defaults = spec.defaults or [] self.args = spec.args[:len(spec.args) - len(defaults)] self.kwargs = dict(zip(spec.args[-len(defaults):], defaults)) def page_divide(x, y): return max(1, int(math.ceil(1.0 * x / y))) def paginate(iterable, page=1, per_page=50): count = len(iterable) page_last = page_divide(count, per_page) # Handle 'current'. if page == 'current': start, stop = max(0, count-per_page), count page = page_last else: # Handle p=9999 page = min(int(page), page_last) start, stop = per_page * (page-1), per_page * (page) # page_next is None when there aren't any more pages. page_next = page+1 if page < page_last else None return iterable[start:stop], page, page_next, page_last def profile(fun): if settings.PROFILE: def wrap(request, *args, **kwargs): profiler = cProfile.Profile() result = profiler.runcall(fun, request, *args, **kwargs) profiler.dump_stats('/var/canvas/website/run/profile-%s-%s.pstats' % (request.path.replace('/', '_'), int(time.time() * 1000))) return result return wrap else: return fun def generate_email_links(): """ Feel free to rewrite me, I'm just an example of the last use. Just change 'visitor' and 'data'. """ def visitor(item): from canvas.models import User username, groups = [x.strip() for x in item.split(':')] user = User.objects.get(username=username) subject = '%s, Canvas needs you!' % username body = """Hey %s!\n\nWe've noticed you're one of the top posters in our Canvas-owned groups (%s), and would love to have you as a referee if you are interested. Referees are able to mark posts in appointed groups as off-topic, collapsing them and helping to keep discussion and posts relevant to the group.""" body += """\n\nIf you would be interested in helping us out, let us know, we'd greatly appreciate it!""" body += """\n\nThanks for being awesome,\n- The Canvas Team""" body %= (username, groups) body = body.replace('\n', '%0A') return {'to': user.email, 'subject': subject, 'body': body} data = """blblnk: cute, pop_culture, canvas nicepunk: cute, the_horror, stamps powerfuldragon: cute, stamps, girls cybertaco: games tobacco: games straitjacketfun: photography slack_jack: photography oliveoodle: pop_culture ryoshi: pop_culture oliveiralmeida: nerdy AquilesBaeza: nerdy, the_horror nebetsu: nerdy Laban: food ROPED: food MuttonChops: canvas Degu: stamps sparknineone: girls""" for item in data.split('\n'): print """<a href="mailto:%(to)s?subject=%(subject)s&body=%(body)s">%(to)s</a><br/>""" % visitor(item) def has_flagged_words(text): """ Returns True if @text has flagged words. """ return any((flag_word in text) for flag_word in Config.get('autoflag_words', [])) def make_absolute_url(relative_url, protocol=None): """ Takes a relative url and makes it absolute by prepending the Canvas absolute domain. This refers not to relative as in "foo" resolving to "/bar/foo" when you're already on "/bar", but to an absolute path sans the host portion of the URL. `protocol` should be the name without the "://", e.g. "http" or "https" """ # Is it already absolute? if relative_url.split('//')[-1].startswith(settings.DOMAIN) and relative_url.startswith(protocol or '//'): return relative_url if protocol: protocol = protocol + '://' else: protocol = '//' base = protocol + settings.DOMAIN return urljoin(base, relative_url) _template_tag_cache = {} def render_template_tag(tag_name, args=None, module=None, context_instance=None): """ `args` may be either an list of tuples, or any other iterable. If it contains tuples, it will create a context object out of it with the car as the key and the cdr as the value, and the keys will be passed to the template tag. (This is to simulate an ordered dict.) Otherwise, the items in `args` are given as strings to the template tag. It caches templates, but only if `args` has tuples.
This renders to a string. To use it as a view response, wrap it in HttpResponse. """ def make_cache_key(module, tag_name, arg_cars): return u'-'.join(e for e in [module, tag_name, arg_cars] if e is not None) prefix, _args = '', '' context = {} cache_key = None # Doesn't cache if this doesn't get set. if module: prefix = u'{{% load {0} %}}'.format(module) if args: args = list(args) if isinstance(args[0], tuple): context.update(dict((arg[0], arg[1]) for arg in args)) _args = u' '.join(arg[0] for arg in args) cache_key = make_cache_key(module, tag_name, _args) else: _args = u' '.join(u'"{0}"'.format(arg) for arg in args) if cache_key and cache_key in _template_tag_cache: template = _template_tag_cache[cache_key] _template_tag_cache[cache_key] = template else: template = Template(u'{0}{{% {1} {2} %}}'.format(prefix, tag_name, _args)) if cache_key: _template_tag_cache[cache_key] = template if context_instance is None: context_instance = Context(context) else: for key, val in context.iteritems(): context_instance[key] = val return template.render(context_instance) def get_arg_names(func): """ Returns a list with function argument names. """ return inspect.getargspec(func)[0] def token(msg): """ Returns a Canvas "signed" hash of a token. This is used in unsubscribe links. """ return hmac.new(settings.SECRET_KEY, msg=str(msg)).hexdigest() class paramaterized_defaultdict(collections.defaultdict): """ Defaultdict where the default_factory takes key as an argument. """ def __missing__(self, key): return self.default_factory(key) def gzip_string(data): str_file = cStringIO.StringIO() gzip_file = gzip.GzipFile(fileobj=str_file, mode='wb') gzip_file.write(data) gzip_file.close() return str_file.getvalue() def strip_template_chars(text): text = text.replace('{{', '&#123;' * 2) text = text.replace('}}', '&#125;' * 2) text = text.replace('{%', '&#123;%') text = text.replace('%}', '%&#125;') text = text.replace('{#', '&#123;#') text = text.replace('#}', '#&#125;') return text
lib.rs
// Copyright 2018 The Grin Developers // Modifications Copyright 2019 The Gotts Developers // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. //! Storage of core types using RocksDB. #![deny(non_upper_case_globals)] #![deny(non_camel_case_types)] #![deny(non_snake_case)] #![deny(unused_mut)] #![warn(missing_docs)] #[macro_use] extern crate log; use failure; #[macro_use] extern crate failure_derive; #[macro_use] extern crate gotts_core as core; extern crate gotts_util as util; //use gotts_core as core; pub mod leaf_set; pub mod lmdb; pub mod pmmr; pub mod prune_list; pub mod types; const SEP: u8 = b':'; use byteorder::{BigEndian, WriteBytesExt}; pub use crate::lmdb::*; /// Build a db key from a prefix and a byte vector identifier. pub fn to_key(prefix: u8, k: &mut Vec<u8>) -> Vec<u8> { let mut res = Vec::with_capacity(k.len() + 2); res.push(prefix); res.push(SEP); res.append(k); res } /// Build a db key from a prefix and a byte vector identifier and numeric identifier pub fn to_key_u64(prefix: u8, k: &mut Vec<u8>, val: u64) -> Vec<u8> { let mut res = Vec::with_capacity(k.len() + 10); res.push(prefix); res.push(SEP); res.append(k); res.write_u64::<BigEndian>(val).unwrap(); res } /// Build a db key from a prefix and numeric identifier and a byte vector identifier /// Note: the numeric identifier is before the byte vector identifier, don't mix it /// with 'to_key_i64_a' which is after. pub fn to_key_i64_b(prefix: u8, k: &mut Vec<u8>, val: i64) -> Vec<u8> {
res.push(prefix); res.push(SEP); res.write_i64::<BigEndian>(val).unwrap(); res.append(k); res } /// Build a db key from a prefix and numeric identifier /// Note: do not mix with 'to_key' which is "prefix + byte vector". pub fn to_i64_key(prefix: u8, val: i64) -> Vec<u8> { let mut res = Vec::with_capacity(10); res.push(prefix); res.push(SEP); res.write_i64::<BigEndian>(val).unwrap(); res } /// Build a db key from a prefix and a numeric identifier. pub fn u64_to_key(prefix: u8, val: u64) -> Vec<u8> { let mut res = Vec::with_capacity(10); res.push(prefix); res.push(SEP); res.write_u64::<BigEndian>(val).unwrap(); res } use std::ffi::OsStr; use std::fs::{remove_file, rename, File}; use std::path::Path; /// Creates temporary file with name created by adding `temp_suffix` to `path`. /// Applies writer function to it and renames temporary file into original specified by `path`. pub fn save_via_temp_file<F, P, E>( path: P, temp_suffix: E, mut writer: F, ) -> Result<(), std::io::Error> where F: FnMut(Box<dyn std::io::Write>) -> Result<(), std::io::Error>, P: AsRef<Path>, E: AsRef<OsStr>, { let temp_suffix = temp_suffix.as_ref(); assert!(!temp_suffix.is_empty()); let original = path.as_ref(); let mut _original = original.as_os_str().to_os_string(); _original.push(temp_suffix); // Write temporary file let temp_path = Path::new(&_original); if temp_path.exists() { remove_file(&temp_path)?; } let file = File::create(&temp_path)?; writer(Box::new(file))?; // Move temporary file into original if original.exists() { remove_file(&original)?; } rename(&temp_path, &original)?; Ok(()) } use croaring::Bitmap; use std::io::{self, Read}; /// Read Bitmap from a file pub fn read_bitmap<P: AsRef<Path>>(file_path: P) -> io::Result<Bitmap> { let mut bitmap_file = File::open(file_path)?; let f_md = bitmap_file.metadata()?; let mut buffer = Vec::with_capacity(f_md.len() as usize); bitmap_file.read_to_end(&mut buffer)?; Ok(Bitmap::deserialize(&buffer)) }
let mut res = Vec::with_capacity(k.len() + 10);
views.py
from django.shortcuts import render, redirect from django.contrib import messages from django.contrib.auth.decorators import login_required from . forms import UserRegisterForm, UserUpdateForm, ProfileUpdateForm def register(request): if request.method == 'POST': form = UserRegisterForm(request.POST) if form.is_valid(): form.save() username = form.cleaned_data.get('username') messages.success(request, f'Account created for {username} Log In to Proceed!') return redirect('login') else: form = UserRegisterForm() context = {'form':form} return render(request, 'users/register.html', context) @login_required def profile(request):
if u_form.is_valid() and p_form.is_valid(): u_form.save() p_form.save() messages.success(request, f'Your account has been Updated!') return redirect('profile') else: u_form = UserUpdateForm(instance = request.user) p_form = ProfileUpdateForm(instance = request.user.profile) context = { 'u_form': u_form, 'p_form': p_form } return render(request, 'users/profile.html', context)
if request.method == 'POST': u_form = UserUpdateForm(request.POST, instance = request.user) p_form = ProfileUpdateForm(request.POST, request.FILES, instance = request.user.profile)
server.go
package server import ( "asapo_broker/database" "asapo_common/discovery" log "asapo_common/logger" "errors" "net/http" ) const kDefaultresendInterval = 10 const kDefaultStreamCacheUpdateIntervalMs = 100 const kDefaultTokenCacheUpdateIntervalMs = 60000 var db database.Agent type serverSettings struct { DiscoveryServer string DatabaseServer string PerformanceDbServer string PerformanceDbName string MonitorPerformance bool AuthorizationServer string Port int LogLevel string discoveredDbAddress string CheckResendInterval *int StreamCacheUpdateIntervalMs *int TokenCacheUpdateIntervalMs *int } func (s *serverSettings) GetTokenCacheUpdateInterval() int { if s.TokenCacheUpdateIntervalMs == nil { return kDefaultTokenCacheUpdateIntervalMs } return *s.TokenCacheUpdateIntervalMs } func (s *serverSettings) GetResendInterval() int { if s.CheckResendInterval == nil { return kDefaultresendInterval } return *s.CheckResendInterval } func (s *serverSettings) GetStreamCacheUpdateInterval() int { if s.StreamCacheUpdateIntervalMs == nil { return kDefaultStreamCacheUpdateIntervalMs } return *s.StreamCacheUpdateIntervalMs } func (s *serverSettings) GetDatabaseServer() string { if s.DatabaseServer == "auto" { return s.discoveredDbAddress } else { return s.DatabaseServer } } var settings serverSettings var statistics serverStatistics var auth Authorizer type discoveryAPI struct { Client *http.Client baseURL string } var discoveryService discovery.DiscoveryAPI func ReconnectDb() (err error)
func InitDB(dbAgent database.Agent) (err error) { db = dbAgent if settings.DatabaseServer == "auto" { settings.discoveredDbAddress, err = discoveryService.GetMongoDbAddress() if err != nil { return err } if settings.discoveredDbAddress == "" { return errors.New("no database servers found") } log.Debug("Got mongodb server: " + settings.discoveredDbAddress) } db.SetSettings(database.DBSettings{ReadFromInprocessPeriod: settings.GetResendInterval(), UpdateStreamCachePeriodMs: settings.GetStreamCacheUpdateInterval()}) return db.Connect(settings.GetDatabaseServer()) } func CreateDiscoveryService() { discoveryService = discovery.CreateDiscoveryService(&http.Client{},"http://" + settings.DiscoveryServer) } func CleanupDB() { if db != nil { db.Close() } }
{ if db == nil { return errors.New("database not initialized") } db.Close() return InitDB(db) }
randomwalks.py
"""Random walk routines """ from .._ffi.function import _init_api from .. import backend as F from ..base import DGLError from .. import ndarray as nd from .. import utils __all__ = [ 'random_walk', 'pack_traces'] def random_walk(g, nodes, *, metapath=None, length=None, prob=None, restart_prob=None): """Generate random walk traces from an array of starting nodes based on the given metapath. For a single starting node, ``num_traces`` traces would be generated. A trace would 1. Start from the given node and set ``t`` to 0. 2. Pick and traverse along edge type ``metapath[t]`` from the current node. 3. If no edge can be found, halt. Otherwise, increment ``t`` and go to step 2. The returned traces all have length ``len(metapath) + 1``, where the first node is the starting node itself. If a random walk stops in advance, DGL pads the trace with -1 to have the same length. Parameters ---------- g : DGLGraph The graph. Must be on CPU. nodes : Tensor Node ID tensor from which the random walk traces starts. The tensor must be on CPU, and must have the same dtype as the ID type of the graph. metapath : list[str or tuple of str], optional Metapath, specified as a list of edge types. Mutually exclusive with :attr:`length`. If omitted, DGL assumes that ``g`` only has one node & edge type. In this case, the argument ``length`` specifies the length of random walk traces. length : int, optional Length of random walks. Mutually exclusive with :attr:`metapath`. Only used when :attr:`metapath` is None. prob : str, optional The name of the edge feature tensor on the graph storing the (unnormalized) probabilities associated with each edge for choosing the next node. The feature tensor must be non-negative and the sum of the probabilities must be positive for the outbound edges of all nodes (although they don't have to sum up to one). The result will be undefined otherwise. If omitted, DGL assumes that the neighbors are picked uniformly. restart_prob : float or Tensor, optional Probability to terminate the current trace before each transition. If a tensor is given, :attr:`restart_prob` should have the same length as :attr:`metapath` or :attr:`length`. Returns ------- traces : Tensor A 2-dimensional node ID tensor with shape ``(num_seeds, len(metapath) + 1)`` or ``(num_seeds, length + 1)`` if :attr:`metapath` is None. types : Tensor A 1-dimensional node type ID tensor with shape ``(len(metapath) + 1)`` or ``(length + 1)``. The type IDs match the ones in the original graph ``g``. Notes ----- The returned tensors are on CPU. Examples -------- The following creates a homogeneous graph: >>> g1 = dgl.graph([(0, 1), (1, 2), (1, 3), (2, 0), (3, 0)], 'user', 'follow') Normal random walk: >>> dgl.sampling.random_walk(g1, [0, 1, 2, 0], length=4) (tensor([[0, 1, 2, 0, 1], [1, 3, 0, 1, 3], [2, 0, 1, 3, 0], [0, 1, 2, 0, 1]]), tensor([0, 0, 0, 0, 0])) The first tensor indicates the random walk path for each seed node. The j-th element in the second tensor indicates the node type ID of the j-th node in every path. In this case, it is returning all 0 (``user``). Random walk with restart: >>> dgl.sampling.random_walk_with_restart(g1, [0, 1, 2, 0], length=4, restart_prob=0.5) (tensor([[ 0, -1, -1, -1, -1], [ 1, 3, 0, -1, -1], [ 2, -1, -1, -1, -1], [ 0, -1, -1, -1, -1]]), tensor([0, 0, 0, 0, 0])) Non-uniform random walk: >>> g1.edata['p'] = torch.FloatTensor([1, 0, 1, 1, 1]) # disallow going from 1 to 2 >>> dgl.sampling.random_walk(g1, [0, 1, 2, 0], length=4, prob='p') (tensor([[0, 1, 3, 0, 1], [1, 3, 0, 1, 3], [2, 0, 1, 3, 0], [0, 1, 3, 0, 1]]), tensor([0, 0, 0, 0, 0])) Metapath-based random walk: >>> g2 = dgl.heterograph({ ... ('user', 'follow', 'user'): [(0, 1), (1, 2), (1, 3), (2, 0), (3, 0)], ... ('user', 'view', 'item'): [(0, 0), (0, 1), (1, 1), (2, 2), (3, 2), (3, 1)], ... ('item', 'viewed-by', 'user'): [(0, 0), (1, 0), (1, 1), (2, 2), (2, 3), (1, 3)]}) >>> dgl.sampling.random_walk( ... g2, [0, 1, 2, 0], metapath=['follow', 'view', 'viewed-by'] * 2) (tensor([[0, 1, 1, 1, 2, 2, 3], [1, 3, 1, 1, 2, 2, 2], [2, 0, 1, 1, 3, 1, 1], [0, 1, 1, 0, 1, 1, 3]]), tensor([0, 0, 1, 0, 0, 1, 0])) Metapath-based random walk, with restarts only on items (i.e. after traversing a "view" relationship): >>> dgl.sampling.random_walk( ... g2, [0, 1, 2, 0], metapath=['follow', 'view', 'viewed-by'] * 2, ... restart_prob=torch.FloatTensor([0, 0.5, 0, 0, 0.5, 0])) (tensor([[ 0, 1, -1, -1, -1, -1, -1], [ 1, 3, 1, 0, 1, 1, 0], [ 2, 0, 1, 1, 3, 2, 2], [ 0, 1, 1, 3, 0, 0, 0]]), tensor([0, 0, 1, 0, 0, 1, 0])) """ assert g.device == F.cpu(), "Graph must be on CPU." n_etypes = len(g.canonical_etypes) n_ntypes = len(g.ntypes) if metapath is None: if n_etypes > 1 or n_ntypes > 1: raise DGLError("metapath not specified and the graph is not homogeneous.") if length is None: raise ValueError("Please specify either the metapath or the random walk length.") metapath = [0] * length else: metapath = [g.get_etype_id(etype) for etype in metapath] gidx = g._graph nodes = F.to_dgl_nd(utils.prepare_tensor(g, nodes, 'nodes')) metapath = F.to_dgl_nd(utils.prepare_tensor(g, metapath, 'metapath')) # Load the probability tensor from the edge frames if prob is None: p_nd = [nd.array([], ctx=nodes.ctx) for _ in g.canonical_etypes] else: p_nd = [] for etype in g.canonical_etypes: if prob in g.edges[etype].data: prob_nd = F.to_dgl_nd(g.edges[etype].data[prob]) if prob_nd.ctx != nodes.ctx: raise ValueError( 'context of seed node array and edges[%s].data[%s] are different' % (etype, prob)) else: prob_nd = nd.array([], ctx=nodes.ctx) p_nd.append(prob_nd) # Actual random walk if restart_prob is None: traces, types = _CAPI_DGLSamplingRandomWalk(gidx, nodes, metapath, p_nd) elif F.is_tensor(restart_prob): restart_prob = F.to_dgl_nd(restart_prob) traces, types = _CAPI_DGLSamplingRandomWalkWithStepwiseRestart( gidx, nodes, metapath, p_nd, restart_prob) else: traces, types = _CAPI_DGLSamplingRandomWalkWithRestart( gidx, nodes, metapath, p_nd, restart_prob) traces = F.from_dgl_nd(traces) types = F.from_dgl_nd(types) return traces, types def pack_traces(traces, types):
_init_api('dgl.sampling.randomwalks', __name__)
"""Pack the padded traces returned by ``random_walk()`` into a concatenated array. The padding values (-1) are removed, and the length and offset of each trace is returned along with the concatenated node ID and node type arrays. Parameters ---------- traces : Tensor A 2-dimensional node ID tensor. Must be on CPU and either ``int32`` or ``int64``. types : Tensor A 1-dimensional node type ID tensor. Must be on CPU and either ``int32`` or ``int64``. Returns ------- concat_vids : Tensor An array of all node IDs concatenated and padding values removed. concat_types : Tensor An array of node types corresponding for each node in ``concat_vids``. Has the same length as ``concat_vids``. lengths : Tensor Length of each trace in the original traces tensor. offsets : Tensor Offset of each trace in the originial traces tensor in the new concatenated tensor. Notes ----- The returned tensors are on CPU. Examples -------- >>> g2 = dgl.heterograph({ ... ('user', 'follow', 'user'): [(0, 1), (1, 2), (1, 3), (2, 0), (3, 0)], ... ('user', 'view', 'item'): [(0, 0), (0, 1), (1, 1), (2, 2), (3, 2), (3, 1)], ... ('item', 'viewed-by', 'user'): [(0, 0), (1, 0), (1, 1), (2, 2), (2, 3), (1, 3)]}) >>> traces, types = dgl.sampling.random_walk( ... g2, [0, 0], metapath=['follow', 'view', 'viewed-by'] * 2, ... restart_prob=torch.FloatTensor([0, 0.5, 0, 0, 0.5, 0])) >>> traces, types (tensor([[ 0, 1, -1, -1, -1, -1, -1], [ 0, 1, 1, 3, 0, 0, 0]]), tensor([0, 0, 1, 0, 0, 1, 0])) >>> concat_vids, concat_types, lengths, offsets = dgl.sampling.pack_traces(traces, types) >>> concat_vids tensor([0, 1, 0, 1, 1, 3, 0, 0, 0]) >>> concat_types tensor([0, 0, 0, 0, 1, 0, 0, 1, 0]) >>> lengths tensor([2, 7]) >>> offsets tensor([0, 2])) The first tensor ``concat_vids`` is the concatenation of all paths, i.e. flattened array of ``traces``, excluding all padding values (-1). The second tensor ``concat_types`` stands for the node type IDs of all corresponding nodes in the first tensor. The third and fourth tensor indicates the length and the offset of each path. With these tensors it is easy to obtain the i-th random walk path with: >>> vids = concat_vids.split(lengths.tolist()) >>> vtypes = concat_vtypes.split(lengths.tolist()) >>> vids[1], vtypes[1] (tensor([0, 1, 1, 3, 0, 0, 0]), tensor([0, 0, 1, 0, 0, 1, 0])) """ assert F.is_tensor(traces) and F.context(traces) == F.cpu(), "traces must be a CPU tensor" assert F.is_tensor(types) and F.context(types) == F.cpu(), "types must be a CPU tensor" traces = F.to_dgl_nd(traces) types = F.to_dgl_nd(types) concat_vids, concat_types, lengths, offsets = _CAPI_DGLSamplingPackTraces(traces, types) concat_vids = F.from_dgl_nd(concat_vids) concat_types = F.from_dgl_nd(concat_types) lengths = F.from_dgl_nd(lengths) offsets = F.from_dgl_nd(offsets) return concat_vids, concat_types, lengths, offsets
a_star.go
package main import ( "container/heap" "fmt" "math" ) type Item struct { vertex Vertex fCost float32 } type PriorityQueue []*Item func (pq PriorityQueue) Len() int { return len(pq) } func (pq PriorityQueue) Less(i, j int) bool { return pq[i].fCost < pq[j].fCost } func (pq PriorityQueue) Swap(i, j int) { pq[i], pq[j] = pq[j], pq[i] } func (pq *PriorityQueue) Push(x interface{}) { item, ok := x.(*Item) if !ok { panic("pq.Push: argument is not a *Item") } *pq = append(*pq, item) } func (pq *PriorityQueue) Pop() interface{} { old := *pq n := len(old) item := old[n-1] old[n-1] = nil *pq = old[0 : n-1] return item } type Vertex struct { value string latitude float32 longitude float32 } type Graph map[Vertex][]Vertex var none = Vertex{ value: "none", latitude: -1.0, longitude: -1.0, } func (graph Graph) vertices() []Vertex { vertices := make([]Vertex, 0, len(graph)) for vertex := range graph { vertices = append(vertices, vertex) } return vertices } func (graph Graph) neighbors(vertex Vertex) []Vertex { return (graph)[vertex] } func manhattanDistance(x1 float32, y1 float32, x2 float32, y2 float32) float32 { return float32(math.Abs(float64(x1-x2)) + math.Abs(float64(y1-y2))) } func (graph Graph) distance(from Vertex, to Vertex) float32 { return manhattanDistance(from.latitude, from.longitude, to.latitude, to.longitude) } // the fact that go does not have a function to reverse a slice LMAO. func reverse(xs []Vertex) []Vertex { ys := make([]Vertex, 0, len(xs)) for i := len(xs) - 1; i > -1; i-- { ys = append(ys, xs[i]) } return ys } func buildPath(pathMap map[Vertex]Vertex, from Vertex, to Vertex) []Vertex { path := []Vertex{} current := to for current != from { path = append(path, current) current = pathMap[current] } path = append(path, from) return reverse(path) } func
(graph Graph, from Vertex, to Vertex) []Vertex { priorityQueue := PriorityQueue{} visited := make(map[Vertex]bool) previous := make(map[Vertex]Vertex) for _, vertex := range graph.vertices() { previous[vertex] = none } // G cost = distance from starting node // H cost(heuristic) = distance from end node // F cost = G cost + H Cost heap.Push(&priorityQueue, &Item{ vertex: from, fCost: graph.distance(from, to), }) for len(priorityQueue) != 0 { //nolint:forcetypeassert item := heap.Pop(&priorityQueue).(*Item) if item.vertex == to { break } visited[item.vertex] = true for _, edge := range graph.neighbors(item.vertex) { if !visited[edge] { heap.Push(&priorityQueue, &Item{ vertex: edge, fCost: graph.distance(from, edge) + graph.distance(edge, to), }) previous[edge] = item.vertex } } } return buildPath(previous, from, to) } func main() { cities := map[string]Vertex{ "Cascavel": {value: "Cascavel", latitude: 24.9578, longitude: 53.4595}, "Foz do Iguaçu": {value: "Foz do Iguaçu", latitude: 25.5163, longitude: 54.5854}, "Toledo": {value: "Toledo", latitude: 24.7251, longitude: 53.7417}, "Francisco Beltrão": {value: "Francisco Beltrão", latitude: 26.0779, longitude: 53.0520}, "São Mateus do Sul": {value: "São Mateus do Sul", latitude: 25.8682, longitude: 50.3842}, "Curitiba": {value: "Curitiba", latitude: 25.4290, longitude: 49.2671}, "Paranaguá": {value: "Paranaguá", latitude: 25.5149, longitude: 48.5226}, "Ponta Grossa": {value: "Ponta Grossa", latitude: 25.0994, longitude: 50.1583}, "Guarapuava": {value: "Guarapuava", latitude: 25.3907, longitude: 51.4628}, "Maringá": {value: "Maringá", latitude: 23.4210, longitude: 51.9331}, "Umuarama": {value: "Umuarama", latitude: 23.7661, longitude: 53.3206}, "Londrina": {value: "Londrina", latitude: 23.3045, longitude: 51.1696}, } graph := map[Vertex][]Vertex{ cities["Cascavel"]: {cities["Toledo"], cities["Foz do Iguaçu"], cities["Francisco Beltrão"], cities["Guarapuava"]}, cities["Foz do Iguaçu"]: {cities["Cascavel"]}, cities["Toledo"]: {cities["Cascavel"], cities["Umuarama"]}, cities["Francisco Beltrão"]: {cities["Cascavel"], cities["São Mateus do Sul"]}, cities["São Mateus do Sul"]: {cities["Francisco Beltrão"], cities["Curitiba"]}, cities["Curitiba"]: {cities["São Mateus do Sul"], cities["Ponta Grossa"], cities["Paranaguá"]}, cities["Paranaguá"]: {cities["Curitiba"]}, cities["Ponta Grossa"]: {cities["Curitiba"], cities["Guarapuava"], cities["Maringá"], cities["Londrina"]}, cities["Guarapuava"]: {cities["Cascavel"], cities["Ponta Grossa"]}, cities["Maringá"]: {cities["Ponta Grossa"], cities["Umuarama"], cities["Londrina"]}, cities["Umuarama"]: {cities["Toledo"], cities["Maringá"]}, cities["Londrina"]: {cities["Maringá"], cities["Ponta Grossa"]}, } fmt.Println(aStar(graph, cities["Cascavel"], cities["Curitiba"])) }
aStar
transmission.go
package transmission // https://trac.transmissionbt.com/browser/trunk/extras/rpc-spec.txt import ( "bytes" "encoding/json" "io" "io/ioutil" "net/http" "github.com/kr/pretty" ) type Status uint64 const ( StatusStopped Status = iota StatusCheckWait StatusCheck StatusDownloadWait StatusDownload StatusSeedWait StatusSeed ) type TorrentGetRequest struct { IDs []int `json:"ids,omitempty"` Fields []string `json:"fields,omitempty"` } type TorrentGetResponse struct { Torrents []Torrent `json:"torrents"` } type TorrentStartNowRequest struct { IDs []int `json:"ids,omitempty"` } type TorrentStopRequest struct { IDs []int `json:"ids,omitempty"` } type TorrentSetRequest struct { IDs []int `json:"ids,omitempty"` FilesWanted []int `json:"files-wanted"` FilesUnwanted []int `json:"files-unwanted"` } type TorrentRemoveRequest struct { IDs []int `json:"ids,omitempty"` DeleteLocalData bool `json:"delete-local-data"` } type Torrent struct { Error int64 `json:"error"` ErrorString string `json:"errorString"` Files []struct { BytesCompleted int64 `json:"bytesCompleted"` Length int64 `json:"length"` Name string `json:"name"` } `json:"files"` HaveValid int64 `json:"haveValid"` ID int64 `json:"id"` IsFinished bool `json:"isFinished"` Name string `json:"name"` Peers []Peer `json:"peers"` PercentDone float64 `json:"percentDone"` RateDownload int64 `json:"rateDownload"` RateUpload int64 `json:"rateUpload"` Status Status `json:"status"` TotalSize int64 `json:"totalSize"` MetadataPercentComplete float64 `json:"metadataPercentComplete"` Hash string `json:"hashString"` } type TorrentAddRequest struct { Filename string `json:"filename,omitempty"` } type TorrentAddResponse struct { TorrentAdded struct { Hash string `json:"hashString"` ID int `json:"id"` Name string `json:"name"` } `json:"torrent-added"` } type Peer struct { IsEncrypted bool `json:"isEncrypted"` PeerIsInterested bool `json:"peerIsInterested"` ClientIsInterested bool `json:"clientIsInterested"` ClientName string `json:"clientName"` IsDownloadingFrom bool `json:"isDownloadingFrom"` IsIncoming bool `json:"isIncoming"` IsUploadingTo bool `json:"isUploadingTo"` Port int `json:"port"` Progress float64 `json:"progress"` RateToPeer float64 `json:"rateToPeer"` Flag string `json:"flagStr"` Address string `json:"address"` ClientIsChoked bool `json:"clientIsChoked"` PeerIsChoked bool `json:"peerIsChoked"` IsUTP bool `json:"isUTP"` } func (t *Transmission) Add(d TorrentAddRequest) (*TorrentAddResponse, error) { r, err := t.NewRequest("torrent-add", d) if err != nil { return nil, err } var resp TorrentAddResponse err = t.Do(r, &resp) return &resp, err } func (t *Transmission) Get(d TorrentGetRequest) (*TorrentGetResponse, error) { r, err := t.NewRequest("torrent-get", d) if err != nil { return nil, err } var resp TorrentGetResponse err = t.Do(r, &resp) return &resp, err } func (t *Transmission) Set(d TorrentSetRequest) error { r, err := t.NewRequest("torrent-set", d) if err != nil { return err } var v interface{} defer func() { pretty.Print(v) }() return t.Do(r, &v) } func (t *Transmission) Remove(d TorrentRemoveRequest) error { r, err := t.NewRequest("torrent-remove", d) if err != nil { return err } return t.Do(r, nil) } func (t *Transmission) Stop(ids ...int) error { d := TorrentStopRequest{ IDs: ids, } r, err := t.NewRequest("torrent-stop", d) if err != nil { return err } return t.Do(r, nil) } func (t *Transmission) StartNow(ids ...int) error { d := TorrentStartNowRequest{ IDs: ids, } r, err := t.NewRequest("torrent-start-now", d) if err != nil { return err } return t.Do(r, nil) } func (c *Transmission) NewRequest(method string, arguments interface{}) (*http.Request, error) { body := struct { Arguments interface{} `json:"arguments"` Method string `json:"method"` }{ Arguments: arguments, Method: method, } var buf io.ReadWriter = new(bytes.Buffer) err := json.NewEncoder(buf).Encode(body) if err != nil { return nil, err } req, err := http.NewRequest("POST", c.url, buf) if err != nil { return nil, err } req.Header.Add("Content-Type", "text/json; charset=UTF-8") req.Header.Add("Accept", "text/json") return req, nil } type Transmission struct { client *http.Client url string transmissionId string } func New(url string) *Transmission
type Error struct { Result string } func (e *Error) Error() string { return e.Result } type transmissionResponse struct { Result string `json:"result"` Arguments *json.RawMessage `json:"arguments"` } func (t *Transmission) do(req *http.Request) (*transmissionResponse, error) { b, err := ioutil.ReadAll(req.Body) if err != nil { return nil, err } for { req.Body = ioutil.NopCloser(bytes.NewBuffer(b)) req.Header.Set("X-Transmission-Session-Id", t.transmissionId) resp, err := t.client.Do(req) if err != nil { return nil, err } defer resp.Body.Close() if resp.StatusCode == 409 { t.transmissionId = resp.Header.Get("X-Transmission-Session-Id") continue } defer resp.Body.Close() dr := transmissionResponse{} r := resp.Body // io.TeeReader(resp.Body, os.Stderr) err = json.NewDecoder(r).Decode(&dr) if err != nil { return nil, err } if dr.Result != "success" { return &dr, &Error{ Result: dr.Result, } } return &dr, nil } } func (t *Transmission) Do(req *http.Request, v interface{}) error { dr, err := t.do(req) if err != nil { return err } switch v := v.(type) { case io.Writer: value := "" if err = json.Unmarshal(*dr.Arguments, &value); err != nil { return err } v.Write([]byte(value)) case interface{}: return json.Unmarshal(*dr.Arguments, &v) } return nil }
{ return &Transmission{ client: http.DefaultClient, url: url, } }
main.go
package main import ( "fmt" "math/rand" "os" "regexp" "strings" "time" "github.com/Sirupsen/logrus" "github.com/honeycombio/libhoney-go" flag "github.com/jessevdk/go-flags" "github.com/honeycombio/honeykafka/kafkatail" "github.com/honeycombio/honeytail/httime" "github.com/honeycombio/honeytail/parsers/htjson" ) // BuildID is set by Travis CI var BuildID string // internal version identifier var version string var validParsers = []string{ "json", } // GlobalOptions has all the top level CLI flags that honeytail supports type GlobalOptions struct { APIHost string `hidden:"true" long:"api_host" description:"Host for the Honeycomb API" default:"https://api.honeycomb.io/"` ConfigFile string `short:"c" long:"config" description:"Config file for honeytail in INI format." no-ini:"true"` NumSenders uint `short:"P" long:"poolsize" description:"Number of concurrent connections to open to Honeycomb" default:"80"` BatchFrequencyMs uint `long:"send_frequency_ms" description:"How frequently to flush batches" default:"100"` BatchSize uint `long:"send_batch_size" description:"Maximum number of messages to put in a batch" default:"50"` Debug bool `long:"debug" description:"Print debugging output"` StatusInterval uint `long:"status_interval" description:"How frequently, in seconds, to print out summary info" default:"60"` Localtime bool `long:"localtime" description:"When parsing a timestamp that has no time zone, assume it is in the same timezone as localhost instead of UTC (the default)"` Timezone string `long:"timezone" description:"When parsing a timestamp use this time zone instead of UTC (the default). Must be specified in TZ format as seen here: https://en.wikipedia.org/wiki/List_of_tz_database_time_zones"` ScrubFields []string `long:"scrub_field" description:"For the field listed, apply a one-way hash to the field content. May be specified multiple times"` DropFields []string `long:"drop_field" description:"Do not send the field to Honeycomb. May be specified multiple times"` AddFields []string `long:"add_field" description:"Add the field to every event. Field should be key=val. May be specified multiple times"` RequestShape []string `long:"request_shape" description:"Identify a field that contains an HTTP request of the form 'METHOD /path HTTP/1.x' or just the request path. Break apart that field into subfields that contain components. May be specified multiple times. Defaults to 'request' when using the nginx parser"` ShapePrefix string `long:"shape_prefix" description:"Prefix to use on fields generated from request_shape to prevent field collision"` RequestPattern []string `long:"request_pattern" description:"A pattern for the request path on which to base the derived request_shape. May be specified multiple times. Patterns are considered in order; first match wins."` RequestParseQuery string `long:"request_parse_query" description:"How to parse the request query parameters. 'whitelist' means only extract listed query keys. 'all' means to extract all query parameters as individual columns" default:"whitelist"` RequestQueryKeys []string `long:"request_query_keys" description:"Request query parameter key names to extract, when request_parse_query is 'whitelist'. May be specified multiple times."` BackOff bool `long:"backoff" description:"When rate limited by the API, back off and retry sending failed events. Otherwise failed events are dropped. When --backfill is set, it will override this option=true"` PrefixRegex string `long:"log_prefix" description:"pass a regex to this flag to strip the matching prefix from the line before handing to the parser. Useful when log aggregation prepends a line header. Use named groups to extract fields into the event."` DynSample []string `long:"dynsampling" description:"enable dynamic sampling using the field listed in this option. May be specified multiple times; fields will be concatenated to form the dynsample key. WARNING increases CPU utilization dramatically over normal sampling"` DynWindowSec int `long:"dynsample_window" description:"measurement window size for the dynsampler, in seconds" default:"30"` GoalSampleRate int `long:"goal_samplerate" description:"used to hold the desired sample rate and set tailing sample rate to 1"` MinSampleRate int `long:"dynsample_minimum" description:"if the rate of traffic falls below this, dynsampler won't sample" default:"1"` Reqs RequiredOptions `group:"Required Options"` Modes OtherModes `group:"Other Modes"` JSON htjson.Options `group:"JSON Parser Options" namespace:"json"` Kafka kafkatail.Options `group:"Kafka Tailing Options" namespace:"kafka"` } type RequiredOptions struct { WriteKey string `short:"k" long:"writekey" description:"Team write key"` Dataset string `short:"d" long:"dataset" description:"Name of the dataset"` } type OtherModes struct { Help bool `short:"h" long:"help" description:"Show this help message"` Version bool `short:"V" long:"version" description:"Show version"` WriteDefaultConfig bool `long:"write_default_config" description:"Write a default config file to STDOUT" no-ini:"true"` WriteCurrentConfig bool `long:"write_current_config" description:"Write out the current config to STDOUT" no-ini:"true"` WriteManPage bool `hidden:"true" long:"write-man-page" description:"Write out a man page"` } func main() { var options GlobalOptions flagParser := flag.NewParser(&options, flag.PrintErrors) flagParser.Usage = "-k <writekey> -d <mydata> [optional arguments]\n" if extraArgs, err := flagParser.Parse(); err != nil || len(extraArgs) != 0 { fmt.Println("Error: failed to parse the command line.") if err != nil { fmt.Printf("\t%s\n", err) } else { fmt.Printf("\tUnexpected extra arguments: %s\n", strings.Join(extraArgs, " ")) } usage() os.Exit(1) } // read the config file if present if options.ConfigFile != "" { ini := flag.NewIniParser(flagParser) ini.ParseAsDefaults = true if err := ini.ParseFile(options.ConfigFile); err != nil { fmt.Printf("Error: failed to parse the config file %s\n", options.ConfigFile) fmt.Printf("\t%s\n", err) usage() os.Exit(1) } } rand.Seed(time.Now().UnixNano()) if options.Debug { logrus.SetLevel(logrus.DebugLevel) } // set time zone info if options.Localtime { httime.Location = time.Now().Location() } if options.Timezone != "" { loc, err := time.LoadLocation(options.Timezone) if err != nil { fmt.Printf("time zone '%s' not successfully parsed.\n", options.Timezone) fmt.Printf("see https://en.wikipedia.org/wiki/List_of_tz_database_time_zones for a list of time zones\n") fmt.Printf("expected format example: America/Los_Angeles\n") fmt.Printf("Specific error: %s\n", err.Error()) os.Exit(1) } httime.Location = loc } setVersionUserAgent(false, "json") handleOtherModes(flagParser, options.Modes) sanityCheckOptions(&options) // if _, err := libhoney.VerifyWriteKey(libhoney.Config{ // APIHost: options.APIHost, // WriteKey: options.Reqs.WriteKey, // }); err != nil { // fmt.Fprintln(os.Stderr, "Could not verify Honeycomb write key: ", err) // os.Exit(1) // } run(options) } // setVersion sets the internal version ID and updates libhoney's user-agent func setVersionUserAgent(backfill bool, parserName string) { if BuildID == "" { version = "dev" } else { version = BuildID } if backfill { parserName += " backfill" } libhoney.UserAgentAddition = fmt.Sprintf("honeykafka/%s (%s)", version, parserName) } // handleOtherModes takse care of all flags that say we should just do something // and exit rather than actually parsing logs func handleOtherModes(fp *flag.Parser, modes OtherModes)
func sanityCheckOptions(options *GlobalOptions) { switch { case options.Reqs.WriteKey == "" || options.Reqs.WriteKey == "NULL": fmt.Println("Write key required to be specified with the --writekey flag.") usage() os.Exit(1) case options.Reqs.Dataset == "": fmt.Println("Dataset name required with the --dataset flag.") usage() os.Exit(1) case options.RequestParseQuery != "whitelist" && options.RequestParseQuery != "all": fmt.Println("request_parse_query flag must be either 'whitelist' or 'all'.") usage() os.Exit(1) } // check the prefix regex for validity if options.PrefixRegex != "" { // make sure the regex is anchored against the start of the string if options.PrefixRegex[0] != '^' { options.PrefixRegex = "^" + options.PrefixRegex } // make sure it's valid _, err := regexp.Compile(options.PrefixRegex) if err != nil { fmt.Printf("Prefix regex %s doesn't compile: error %s\n", options.PrefixRegex, err) usage() os.Exit(1) } } } func usage() { fmt.Print(` Usage: honeykafka -k <writekey> -d <mydata> [optional arguments] For even more detail on required and optional parameters, run honeykafka --help `) }
{ if modes.Version { fmt.Println("Honeytail version", version) os.Exit(0) } if modes.Help { fp.WriteHelp(os.Stdout) fmt.Println("") os.Exit(0) } if modes.WriteManPage { fp.WriteManPage(os.Stdout) os.Exit(0) } if modes.WriteDefaultConfig { ip := flag.NewIniParser(fp) ip.Write(os.Stdout, flag.IniIncludeDefaults|flag.IniCommentDefaults|flag.IniIncludeComments) os.Exit(0) } if modes.WriteCurrentConfig { ip := flag.NewIniParser(fp) ip.Write(os.Stdout, flag.IniIncludeComments) os.Exit(0) } }
txt_module.py
import torch from torch import nn from torch.nn import functional as F LAYER1_NODE = 10240 def
(m): if type(m) == nn.Conv2d: nn.init.xavier_uniform(m.weight.data) nn.init.constant(m.bias.data, 0.01) class TxtModule(nn.Module): def __init__(self, y_dim, bit): """ :param y_dim: dimension of tags :param bit: bit number of the final binary code """ super(TxtModule, self).__init__() self.module_name = "text_model" # full-conv layers self.conv1 = nn.Conv2d(1, LAYER1_NODE, kernel_size=(y_dim, 1), stride=(1, 1)) self.conv2 = nn.Conv2d(LAYER1_NODE, bit, kernel_size=1, stride=(1, 1)) self.apply(weights_init) self.classifier = nn.Sequential( self.conv1, nn.ReLU(inplace=True), nn.Dropout(), self.conv2, ) def forward(self, x): x = self.classifier(x) x = x.squeeze() tanh = nn.Tanh() x = tanh(x) return x
weights_init
exclusive_publication.rs
/* * Copyright 2020 UT OVERSEAS INC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ use std::{ ffi::CString, sync::{ atomic::{AtomicBool, Ordering}, Arc, Mutex, }, }; use crate::utils::errors::{IllegalArgumentError, IllegalStateError}; use crate::{ client_conductor::ClientConductor, concurrent::{ atomic_buffer::AtomicBuffer, logbuffer::{ buffer_claim::BufferClaim, data_frame_header, exclusive_term_appender::ExclusiveTermAppender, frame_descriptor, header::HeaderWriter, log_buffer_descriptor, term_appender::{default_reserved_value_supplier, OnReservedValueSupplier}, }, position::{ReadablePosition, UnsafeBufferPosition}, status::status_indicator_reader, }, utils::{bit_utils::number_of_trailing_zeroes, errors::AeronError, log_buffers::LogBuffers, types::Index}, }; /** * Aeron Publisher API for sending messages to subscribers of a given channel and streamId pair. ExclusivePublications * each get their own session id so multiple can be concurrently active on the same media driver as independent streams. * * {@link ExclusivePublication}s are created via the {@link Aeron#addExclusivePublication(String, int)} method, * and messages are sent via one of the {@link #offer(DirectBuffer)} methods, or a * {@link #tryClaim(int, ExclusiveBufferClaim)} and {@link ExclusiveBufferClaim#commit()} method combination. * * {@link ExclusivePublication}s have the potential to provide greater throughput than {@link Publication}s. * * The APIs used try claim and offer are non-blocking. * * <b>Note:</b> ExclusivePublication instances are NOT threadsafe for offer and try claim methods but are for others. * * @see Aeron#addExclusivePublication(String, int) * @see BufferClaim */ #[allow(dead_code)] pub struct ExclusivePublication { conductor: Arc<Mutex<ClientConductor>>, log_meta_data_buffer: AtomicBuffer, channel: CString, registration_id: i64, max_possible_position: i64, stream_id: i32, session_id: i32, initial_term_id: i32, max_payload_length: Index, max_message_length: Index, position_bits_to_shift: i32, term_offset: i32, term_id: i32, active_partition_index: i32, term_begin_position: i64, publication_limit: UnsafeBufferPosition, channel_status_id: i32, is_closed: AtomicBool, // default to false // The LogBuffers object must be dropped when last ref to it goes out of scope. log_buffers: Arc<LogBuffers>, // it was unique_ptr on TermAppender's appenders: [ExclusiveTermAppender; log_buffer_descriptor::PARTITION_COUNT as usize], header_writer: HeaderWriter, } impl ExclusivePublication { #[allow(clippy::too_many_arguments)] pub fn new( conductor: Arc<Mutex<ClientConductor>>, channel: CString, registration_id: i64, stream_id: i32, session_id: i32, publication_limit: UnsafeBufferPosition, channel_status_id: i32, log_buffers: Arc<LogBuffers>, ) -> Self { let log_md_buffer = log_buffers.atomic_buffer(log_buffer_descriptor::LOG_META_DATA_SECTION_INDEX); let appenders: [ExclusiveTermAppender; 3] = [ ExclusiveTermAppender::new( log_buffers.atomic_buffer(0), log_buffers.atomic_buffer(log_buffer_descriptor::LOG_META_DATA_SECTION_INDEX), 0, ), ExclusiveTermAppender::new( log_buffers.atomic_buffer(1), log_buffers.atomic_buffer(log_buffer_descriptor::LOG_META_DATA_SECTION_INDEX), 1, ), ExclusiveTermAppender::new( log_buffers.atomic_buffer(2), log_buffers.atomic_buffer(log_buffer_descriptor::LOG_META_DATA_SECTION_INDEX), 2, ), ]; let raw_tail = appenders[0].raw_tail(); Self { conductor, log_meta_data_buffer: log_md_buffer, channel, registration_id, max_possible_position: (log_buffers.atomic_buffer(0).capacity() as i64) << 31, stream_id, session_id, initial_term_id: log_buffer_descriptor::initial_term_id(&log_md_buffer), max_payload_length: log_buffer_descriptor::mtu_length(&log_md_buffer) as Index - data_frame_header::LENGTH, max_message_length: frame_descriptor::compute_max_message_length(log_buffers.atomic_buffer(0).capacity()), position_bits_to_shift: number_of_trailing_zeroes(log_buffers.atomic_buffer(0).capacity()), term_offset: log_buffer_descriptor::term_offset(raw_tail, log_buffers.atomic_buffer(0).capacity() as i64), term_id: log_buffer_descriptor::term_id(raw_tail), active_partition_index: 0, term_begin_position: 0, publication_limit, channel_status_id, is_closed: AtomicBool::from(false), log_buffers, header_writer: HeaderWriter::new(log_buffer_descriptor::default_frame_header(&log_md_buffer)), appenders, } } /** * Media address for delivery to the channel. * * @return Media address for delivery to the channel. */ #[inline] pub fn channel(&self) -> CString { self.channel.clone() } /** * Stream identity for scoping within the channel media address. * * @return Stream identity for scoping within the channel media address. */ #[inline] pub fn stream_id(&self) -> i32 { self.stream_id } /** * Session under which messages are published. Identifies this Publication instance. * * @return the session id for this publication. */ #[inline] pub fn session_id(&self) -> i32 { self.session_id } /** * The initial term id assigned when this Publication was created. This can be used to determine how many * terms have passed since creation. * * @return the initial term id. */ #[inline] pub fn initial_term_id(&self) -> i32 { self.initial_term_id } /** * The term-id the publication has reached. * * @return the term-id the publication has reached. */ #[inline] pub fn term_id(&self) -> i32 { self.term_id } /** * The term-offset the publication has reached. * * @return the term-offset the publication has reached. */ #[inline] pub fn term_offset(&self) -> i32 { self.term_offset } /** * Get the original registration used to register this Publication with the media driver by the first publisher. * * @return the original registrationId of the publication. */ #[inline] pub fn original_registration_id(&self) -> i64 { self.registration_id } /** * Registration Id returned by Aeron::addExclusivePublication when this Publication was added. * * @return the registrationId of the publication. */ #[inline] pub fn registration_id(&self) -> i64 { self.registration_id } /** * ExclusivePublication instances are always original. * * @return true. */ pub const fn is_original(&self) -> bool { true } /** * Maximum message length supported in bytes. * * @return maximum message length supported in bytes. */ #[inline] pub fn max_message_length(&self) -> Index { self.max_message_length } /** * Maximum length of a message payload that fits within a message fragment. * * This is he MTU length minus the message fragment header length. * * @return maximum message fragment payload length. */ #[inline] pub fn max_payload_length(&self) -> Index { self.max_payload_length } /** * Get the length in bytes for each term partition in the log buffer. * * @return the length in bytes for each term partition in the log buffer. */ #[inline] pub fn term_buffer_length(&self) -> i32 { self.appenders[0].term_buffer().capacity() } /** * Number of bits to right shift a position to get a term count for how far the stream has progressed. * * @return of bits to right shift a position to get a term count for how far the stream has progressed. */ #[inline] pub fn position_bits_to_shift(&self) -> i32 { self.position_bits_to_shift } /** * Has this Publication seen an active subscriber recently? * * @return true if this Publication has seen an active subscriber recently. */ #[inline] pub fn is_connected(&self) -> bool { !self.is_closed() && log_buffer_descriptor::is_connected(&self.log_meta_data_buffer) } /** * Has this object been closed and should no longer be used? * * @return true if it has been closed otherwise false. */ #[inline] pub fn is_closed(&self) -> bool { self.is_closed.load(Ordering::Acquire) } /** * Get the current position to which the publication has advanced for this stream. * * @return the current position to which the publication has advanced for this stream or {@link CLOSED}. */ #[inline] pub fn position(&self) -> Result<i64, AeronError> { if !self.is_closed() { Ok(self.term_begin_position + self.term_offset as i64) } else { Err(AeronError::PublicationClosed) } } /** * Get the position limit beyond which this {@link Publication} will be back pressured. * * This should only be used as a guide to determine when back pressure is likely to be applied. * * @return the position limit beyond which this {@link Publication} will be back pressured. */ #[inline] pub fn publication_limit(&self) -> Result<i64, AeronError> { if self.is_closed() { Err(AeronError::PublicationClosed) } else { Ok(self.publication_limit.get_volatile()) } } /** * Get the counter id used to represent the publication limit. * * @return the counter id used to represent the publication limit. */ #[inline] pub fn publication_limit_id(&self) -> i32
/** * Available window for offering into a publication before the {@link #positionLimit()} is reached. * * @return window for offering into a publication before the {@link #positionLimit()} is reached. If * the publication is closed then {@link #CLOSED} will be returned. */ #[inline] pub fn available_window(&self) -> Result<i64, AeronError> { if !self.is_closed() { Ok(self.publication_limit.get_volatile() - self.position()?) } else { Err(AeronError::PublicationClosed) } } /** * Get the counter id used to represent the channel status. * * @return the counter id used to represent the channel status. */ #[inline] pub fn channel_status_id(&self) -> i32 { self.channel_status_id } /** * Non-blocking publish of a buffer containing a message. * * @param buffer containing message. * @param offset offset in the buffer at which the encoded message begins. * @param length in bytes of the encoded message. * @param reservedValueSupplier for the frame. * @return The new stream position, otherwise {@link #NOT_CONNECTED}, {@link #BACK_PRESSURED}, * {@link #ADMIN_ACTION} or {@link #CLOSED}. */ pub fn offer_opt( &mut self, buffer: AtomicBuffer, offset: Index, length: Index, reserved_value_supplier: OnReservedValueSupplier, ) -> Result<i64, AeronError> { if !self.is_closed() { let limit = self.publication_limit.get_volatile(); let term_appender = &mut self.appenders[self.active_partition_index as usize]; let position = self.term_begin_position + self.term_offset as i64; if position < limit { let resulting_offset = if length <= self.max_payload_length { term_appender.append_unfragmented_message( self.term_id, self.term_offset, &self.header_writer, buffer, offset, length, reserved_value_supplier, ) } else { if length > self.max_message_length { return Err(IllegalArgumentError::EncodedMessageExceedsMaxMessageLength { length, max_message_length: self.max_message_length, } .into()); } term_appender.append_fragmented_message( self.term_id, self.term_offset, &self.header_writer, buffer, offset, length, self.max_payload_length, reserved_value_supplier, ) }; Ok(self.new_position(resulting_offset)?) } else { Err(self.back_pressure_status(position, length)) } } else { Err(AeronError::PublicationClosed) } } /** * Non-blocking publish of a buffer containing a message. * * @param buffer containing message. * @param offset offset in the buffer at which the encoded message begins. * @param length in bytes of the encoded message. * @return The new stream position, otherwise {@link #NOT_CONNECTED}, {@link #BACK_PRESSURED}, * {@link #ADMIN_ACTION} or {@link #CLOSED}. */ pub fn offer_part(&mut self, buffer: AtomicBuffer, offset: Index, length: Index) -> Result<i64, AeronError> { self.offer_opt(buffer, offset, length, default_reserved_value_supplier) } /** * Non-blocking publish of a buffer containing a message. * * @param buffer containing message. * @return The new stream position on success, otherwise {@link BACK_PRESSURED} or {@link NOT_CONNECTED}. */ pub fn offer(&mut self, buffer: AtomicBuffer) -> Result<i64, AeronError> { self.offer_part(buffer, 0, buffer.capacity()) } /** * Non-blocking publish of buffers containing a message. * * @param startBuffer containing part of the message. * @param lastBuffer after the message. * @param reservedValueSupplier for the frame. * @return The new stream position, otherwise {@link #NOT_CONNECTED}, {@link #BACK_PRESSURED}, * {@link #ADMIN_ACTION} or {@link #CLOSED}. */ // NOT implemented. Translate it from C++ if you need one. //pub fn offer_buf_iter<T>(&self, startBuffer: T, lastBuffer: T, reserved_value_supplier: OnReservedValueSupplier) -> Result<i64, AeronError> { } /** * Non-blocking publish of array of buffers containing a message. * * @param buffers containing parts of the message. * @param length of the array of buffers. * @param reservedValueSupplier for the frame. * @return The new stream position, otherwise {@link #NOT_CONNECTED}, {@link #BACK_PRESSURED}, * {@link #ADMIN_ACTION} or {@link #CLOSED}. */ // NOT implemented. Translate it from C++ if you need one. //pub fn offer_arr(&self, buffers[]: AtomicBuffer, length: Index, reserved_value_supplier: OnReservedValueSupplier) -> Result<i64, AeronError> { // offer(buffers, buffers + length, reserved_value_supplier) //} /** * Try to claim a range in the publication log into which a message can be written with zero copy semantics. * Once the message has been written then {@link BufferClaim#commit()} should be called thus making it available. * <p> * <b>Note:</b> This method can only be used for message lengths less than MTU length minus header. * * @param length of the range to claim, in bytes.. * @param bufferClaim to be populate if the claim succeeds. * @return The new stream position, otherwise {@link #NOT_CONNECTED}, {@link #BACK_PRESSURED}, * {@link #ADMIN_ACTION} or {@link #CLOSED}. * @throws IllegalArgumentException if the length is greater than max payload length within an MTU. * @see BufferClaim::commit * @see BufferClaim::abort */ pub fn try_claim(&mut self, length: Index, mut buffer_claim: BufferClaim) -> Result<i64, AeronError> { self.check_payload_length(length)?; if !self.is_closed() { let limit = self.publication_limit.get_volatile(); let term_appender = &mut self.appenders[self.active_partition_index as usize]; let position = self.term_begin_position + self.term_offset as i64; if position < limit { let resulting_offset = term_appender.claim(self.term_id, self.term_offset, &self.header_writer, length, &mut buffer_claim); Ok(self.new_position(resulting_offset)?) } else { Err(self.back_pressure_status(position, length)) } } else { Err(AeronError::PublicationClosed) } } /** * Add a destination manually to a multi-destination-cast Publication. * * @param endpointChannel for the destination to add */ pub fn add_destination(&mut self, endpoint_channel: CString) -> Result<i64, AeronError> { if self.is_closed() { return Err(IllegalStateError::PublicationClosed.into()); } self.conductor .lock() .expect("Mutex poisoned") .add_destination(self.registration_id, endpoint_channel) } /** * Remove a previously added destination manually from a multi-destination-cast Publication. * * @param endpointChannel for the destination to remove */ pub fn remove_destination(&mut self, endpoint_channel: CString) -> Result<i64, AeronError> { if self.is_closed() { return Err(IllegalStateError::PublicationClosed.into()); } self.conductor .lock() .expect("Mutex poisoned") .remove_destination(self.registration_id, endpoint_channel) } /** * Get the status for the channel of this {@link ExclusivePublication} * * @return status code for this channel */ pub fn channel_status(&self) -> i64 { if self.is_closed() { return status_indicator_reader::NO_ID_ALLOCATED as i64; } self.conductor .lock() .expect("Mutex poisoned") .channel_status(self.channel_status_id) } pub fn close(&self) { self.is_closed.store(true, Ordering::Release); } fn new_position(&mut self, resulting_offset: Index) -> Result<i64, AeronError> { if resulting_offset > 0 { self.term_offset = resulting_offset; return Ok(self.term_begin_position + resulting_offset as i64); } let term_length = self.term_buffer_length(); if self.term_begin_position + term_length as i64 >= self.max_possible_position { return Err(AeronError::MaxPositionExceeded); } let next_index = log_buffer_descriptor::next_partition_index(self.active_partition_index); let next_term_id = self.term_id + 1; self.active_partition_index = next_index; self.term_offset = 0; self.term_id = next_term_id; self.term_begin_position += term_length as i64; let term_count = next_term_id - self.initial_term_id; log_buffer_descriptor::initialize_tail_with_term_id(&self.log_meta_data_buffer, next_index, next_term_id); log_buffer_descriptor::set_active_term_count_ordered(&self.log_meta_data_buffer, term_count); Err(AeronError::AdminAction) } fn back_pressure_status(&self, current_position: i64, message_length: i32) -> AeronError { if current_position + message_length as i64 >= self.max_possible_position { return AeronError::MaxPositionExceeded; } if log_buffer_descriptor::is_connected(&self.log_meta_data_buffer) { return AeronError::BackPressured; } AeronError::NotConnected } #[allow(dead_code)] fn check_max_message_length(&self, length: Index) -> Result<(), AeronError> { if length > self.max_message_length { Err(IllegalArgumentError::EncodedMessageExceedsMaxMessageLength { length, max_message_length: self.max_message_length, } .into()) } else { Ok(()) } } fn check_payload_length(&self, length: Index) -> Result<(), AeronError> { if length > self.max_payload_length { Err(IllegalArgumentError::EncodedMessageExceedsMaxPayloadLength { length, max_payload_length: self.max_payload_length, } .into()) } else { Ok(()) } } } impl Drop for ExclusivePublication { fn drop(&mut self) { self.is_closed.store(true, Ordering::Release); let _unused = self .conductor .lock() .expect("Mutex poisoned") .release_exclusive_publication(self.registration_id); } } #[cfg(test)] mod tests { use std::ffi::CString; use std::sync::{Arc, Mutex}; use lazy_static::lazy_static; use crate::{ client_conductor::ClientConductor, concurrent::{ atomic_buffer::{AlignedBuffer, AtomicBuffer}, broadcast::{ broadcast_buffer_descriptor, broadcast_receiver::BroadcastReceiver, copy_broadcast_receiver::CopyBroadcastReceiver, }, counters::CountersReader, logbuffer::{ buffer_claim::BufferClaim, data_frame_header::LENGTH, frame_descriptor, log_buffer_descriptor::{self, AERON_PAGE_MIN_SIZE, TERM_MIN_LENGTH}, }, position::{ReadablePosition, UnsafeBufferPosition}, ring_buffer::{self, ManyToOneRingBuffer}, status::status_indicator_reader::{StatusIndicatorReader, NO_ID_ALLOCATED}, }, driver_proxy::DriverProxy, exclusive_publication::ExclusivePublication, utils::{ errors::AeronError, log_buffers::LogBuffers, misc::unix_time_ms, types::{Index, Moment, I64_SIZE}, }, }; lazy_static! { pub static ref CHANNEL: CString = CString::new("aeron:udp?endpoint=localhost:40123").unwrap(); } const STREAM_ID: i32 = 10; const SESSION_ID: i32 = 200; const PUBLICATION_LIMIT_COUNTER_ID: i32 = 0; const CORRELATION_ID: i64 = 100; const TERM_ID_1: i32 = 1; const DRIVER_TIMEOUT_MS: Moment = 10 * 1000; const RESOURCE_LINGER_TIMEOUT_MS: Moment = 5 * 1000; const INTER_SERVICE_TIMEOUT_NS: Moment = 5 * 1000 * 1000 * 1000; const INTER_SERVICE_TIMEOUT_MS: Moment = INTER_SERVICE_TIMEOUT_NS / 1_000_000; const PRE_TOUCH_MAPPED_MEMORY: bool = false; // const LOG_FILE_LENGTH: i32 = ((TERM_MIN_LENGTH * 3) + log_buffer_descriptor::LOG_META_DATA_LENGTH); const CAPACITY: i32 = 1024; const MANY_TO_ONE_RING_BUFFER_LENGTH: i32 = CAPACITY + ring_buffer::TRAILER_LENGTH; const BROADCAST_BUFFER_LENGTH: i32 = CAPACITY + broadcast_buffer_descriptor::TRAILER_LENGTH; // const COUNTER_VALUES_BUFFER_LENGTH: i32 = 1024 * 1024; const COUNTER_METADATA_BUFFER_LENGTH: i32 = 4 * 1024 * 1024; #[inline] fn raw_tail_value(term_id: i32, position: i64) -> i64 { (term_id as i64 * (1_i64 << 32)) as i64 | position } #[inline] fn term_tail_counter_offset(index: i32) -> Index { *log_buffer_descriptor::TERM_TAIL_COUNTER_OFFSET + (index * I64_SIZE) } fn on_new_publication_handler(_channel: CString, _stream_id: i32, _session_id: i32, _correlation_id: i64) {} fn on_new_exclusive_publication_handler(_channel: CString, _stream_id: i32, _session_id: i32, _correlation_id: i64) {} fn on_new_subscription_handler(_channel: CString, _stream_id: i32, _correlation_id: i64) {} fn error_handler(err: AeronError) { println!("Got error: {:?}", err); } fn on_available_counter_handler(_counters_reader: &CountersReader, _registration_id: i64, _counter_id: i32) {} fn on_unavailable_counter_handler(_counters_reader: &CountersReader, _registration_id: i64, _counter_id: i32) {} fn on_close_client_handler() {} #[allow(dead_code)] struct ExclusivePublicationTest { src: AlignedBuffer, log: AlignedBuffer, conductor: Arc<Mutex<ClientConductor>>, to_driver: AlignedBuffer, to_clients: AlignedBuffer, counter_metadata: AlignedBuffer, counter_values: AlignedBuffer, to_driver_buffer: AtomicBuffer, to_clients_buffer: AtomicBuffer, many_to_one_ring_buffer: Arc<ManyToOneRingBuffer>, term_buffers: [AtomicBuffer; 3], log_meta_data_buffer: AtomicBuffer, src_buffer: AtomicBuffer, log_buffers: Arc<LogBuffers>, publication_limit: UnsafeBufferPosition, channel_status_indicator: StatusIndicatorReader, publication: ExclusivePublication, } impl ExclusivePublicationTest { pub fn new() -> Self { let log = AlignedBuffer::with_capacity(TERM_MIN_LENGTH * 3 + log_buffer_descriptor::LOG_META_DATA_LENGTH); let src = AlignedBuffer::with_capacity(1024); let src_buffer = AtomicBuffer::from_aligned(&src); let log_buffers = Arc::new(unsafe { LogBuffers::new(log.ptr, log.len as isize, log_buffer_descriptor::TERM_MIN_LENGTH) }); let to_driver = AlignedBuffer::with_capacity(MANY_TO_ONE_RING_BUFFER_LENGTH); let to_clients = AlignedBuffer::with_capacity(BROADCAST_BUFFER_LENGTH); let counter_metadata = AlignedBuffer::with_capacity(BROADCAST_BUFFER_LENGTH); let counter_values = AlignedBuffer::with_capacity(COUNTER_METADATA_BUFFER_LENGTH); let to_driver_buffer = AtomicBuffer::from_aligned(&to_driver); let to_clients_buffer = AtomicBuffer::from_aligned(&to_clients); let counters_metadata_buffer = AtomicBuffer::from_aligned(&counter_metadata); let counters_values_buffer = AtomicBuffer::from_aligned(&counter_values); let local_to_driver_ring_buffer = Arc::new(ManyToOneRingBuffer::new(to_driver_buffer).expect("Failed to create RingBuffer")); let local_to_clients_broadcast_receiver = Arc::new(Mutex::new( BroadcastReceiver::new(to_clients_buffer).expect("Failed to create BroadcastReceiver"), )); let local_driver_proxy = Arc::new(DriverProxy::new(local_to_driver_ring_buffer.clone())); let local_copy_broadcast_receiver = Arc::new(Mutex::new(CopyBroadcastReceiver::new(local_to_clients_broadcast_receiver))); let conductor = ClientConductor::new( unix_time_ms, local_driver_proxy, local_copy_broadcast_receiver, counters_metadata_buffer, counters_values_buffer, Box::new(on_new_publication_handler), Box::new(on_new_exclusive_publication_handler), Box::new(on_new_subscription_handler), Box::new(error_handler), Box::new(on_available_counter_handler), Box::new(on_unavailable_counter_handler), Box::new(on_close_client_handler), DRIVER_TIMEOUT_MS, RESOURCE_LINGER_TIMEOUT_MS, INTER_SERVICE_TIMEOUT_MS, PRE_TOUCH_MAPPED_MEMORY, ); let conductor_guard = conductor.lock().expect("Conductor mutex is poisoned"); let publication_limit = UnsafeBufferPosition::new(conductor_guard.counter_values_buffer(), PUBLICATION_LIMIT_COUNTER_ID); let channel_status_indicator = StatusIndicatorReader::new(conductor_guard.counter_values_buffer(), NO_ID_ALLOCATED); drop(conductor_guard); let log_meta_data_buffer = log_buffers.atomic_buffer(log_buffer_descriptor::LOG_META_DATA_SECTION_INDEX); log_meta_data_buffer.put(*log_buffer_descriptor::LOG_MTU_LENGTH_OFFSET, 3 * src_buffer.capacity()); log_meta_data_buffer.put(*log_buffer_descriptor::LOG_TERM_LENGTH_OFFSET, TERM_MIN_LENGTH); log_meta_data_buffer.put(*log_buffer_descriptor::LOG_PAGE_SIZE_OFFSET, AERON_PAGE_MIN_SIZE); log_meta_data_buffer.put(*log_buffer_descriptor::LOG_INITIAL_TERM_ID_OFFSET, TERM_ID_1); let index = log_buffer_descriptor::index_by_term(TERM_ID_1, TERM_ID_1); log_meta_data_buffer.put(*log_buffer_descriptor::LOG_ACTIVE_TERM_COUNT_OFFSET, 0); log_meta_data_buffer.put(term_tail_counter_offset(index), (TERM_ID_1 as i64) << 32); Self { src, log, conductor: conductor.clone(), to_driver, to_clients, counter_metadata, counter_values, to_driver_buffer, to_clients_buffer, many_to_one_ring_buffer: local_to_driver_ring_buffer, term_buffers: [ log_buffers.atomic_buffer(0), log_buffers.atomic_buffer(1), log_buffers.atomic_buffer(2), ], log_meta_data_buffer, src_buffer, log_buffers: log_buffers.clone(), publication_limit: publication_limit.clone(), channel_status_indicator, publication: ExclusivePublication::new( conductor, (*CHANNEL).clone(), CORRELATION_ID, STREAM_ID, SESSION_ID, publication_limit, NO_ID_ALLOCATED, log_buffers, ), } } fn create_pub(&mut self) { self.publication = ExclusivePublication::new( self.conductor.clone(), (*CHANNEL).clone(), CORRELATION_ID, STREAM_ID, SESSION_ID, self.publication_limit.clone(), NO_ID_ALLOCATED, self.log_buffers.clone(), ); } } #[test] fn should_report_initial_position() { let test = ExclusivePublicationTest::new(); let position = test.publication.position(); assert!(position.is_ok()); assert_eq!(position.unwrap(), 0); } #[test] fn should_report_max_message_length() { let test = ExclusivePublicationTest::new(); assert_eq!( test.publication.max_message_length(), frame_descriptor::compute_max_message_length(TERM_MIN_LENGTH) ); } #[test] fn should_report_correct_term_buffer_length() { let test = ExclusivePublicationTest::new(); assert_eq!(test.publication.term_buffer_length(), TERM_MIN_LENGTH); } #[test] fn should_report_that_publication_has_not_been_connected_yet() { let test = ExclusivePublicationTest::new(); log_buffer_descriptor::set_is_connected(&test.log_meta_data_buffer, false); assert!(!test.publication.is_connected()); } #[test] fn should_report_that_publication_has_been_connected_yet() { let test = ExclusivePublicationTest::new(); log_buffer_descriptor::set_is_connected(&test.log_meta_data_buffer, true); assert!(test.publication.is_connected()); } #[test] fn should_ensure_the_publication_is_open_before_reading_position() { let test = ExclusivePublicationTest::new(); test.publication.close(); let position = test.publication.position(); assert!(position.is_err()); assert_eq!(position.unwrap_err(), AeronError::PublicationClosed); } #[test] fn should_ensure_the_publication_is_open_before_offer() { let mut test = ExclusivePublicationTest::new(); test.publication.close(); assert!(test.publication.is_closed()); let offer_result = test.publication.offer(test.src_buffer); assert!(offer_result.is_err()); assert_eq!(offer_result.unwrap_err(), AeronError::PublicationClosed); } #[test] fn should_ensure_the_publication_is_open_before_claim() { let mut test = ExclusivePublicationTest::new(); let buffer_claim = BufferClaim::default(); test.publication.close(); assert!(test.publication.is_closed()); let claim_result = test.publication.try_claim(1024, buffer_claim); assert!(claim_result.is_err()); assert_eq!(claim_result.unwrap_err(), AeronError::PublicationClosed); } #[test] fn should_offer_a_message_upon_construction() { let mut test = ExclusivePublicationTest::new(); let expected_position = test.src_buffer.capacity() + LENGTH; test.publication_limit.set(2 * test.src_buffer.capacity() as i64); assert_eq!(test.publication.offer(test.src_buffer).unwrap(), expected_position as i64); let position = test.publication.position(); assert!(position.is_ok()); assert_eq!(position.unwrap(), expected_position as i64); } #[test] fn should_fail_to_offer_a_message_when_limited() { let mut test = ExclusivePublicationTest::new(); test.publication_limit.set(0); test.create_pub(); let offer_result = test.publication.offer(test.src_buffer); assert!(offer_result.is_err()); assert_eq!(offer_result.unwrap_err(), AeronError::NotConnected); } #[test] fn should_fail_to_offer_when_append_fails() { let mut test = ExclusivePublicationTest::new(); let active_index = log_buffer_descriptor::index_by_term(TERM_ID_1, TERM_ID_1); let initial_position = TERM_MIN_LENGTH; test.log_meta_data_buffer.put( term_tail_counter_offset(active_index), raw_tail_value(TERM_ID_1, initial_position as i64), ); test.publication_limit.set(i32::max_value() as i64); test.create_pub(); let position = test.publication.position(); assert!(position.is_ok()); assert_eq!(position.unwrap(), initial_position as i64); let offer_result = test.publication.offer(test.src_buffer); assert!(offer_result.is_err()); assert_eq!(offer_result.unwrap_err(), AeronError::AdminAction); } #[test] fn should_rotate_when_append_trips() { let mut test = ExclusivePublicationTest::new(); let active_index = log_buffer_descriptor::index_by_term(TERM_ID_1, TERM_ID_1); let initial_position = TERM_MIN_LENGTH - LENGTH; test.log_meta_data_buffer.put( term_tail_counter_offset(active_index), raw_tail_value(TERM_ID_1, initial_position as i64), ); test.publication_limit.set(i32::max_value() as i64); test.create_pub(); let position = test.publication.position(); assert!(position.is_ok()); assert_eq!(position.unwrap(), initial_position as i64); let offer_result = test.publication.offer(test.src_buffer); assert!(offer_result.is_err()); assert_eq!(offer_result.unwrap_err(), AeronError::AdminAction); let next_index = log_buffer_descriptor::index_by_term(TERM_ID_1, TERM_ID_1 + 1); assert_eq!( test.log_meta_data_buffer .get::<i32>(*log_buffer_descriptor::LOG_ACTIVE_TERM_COUNT_OFFSET), 1 ); assert_eq!( test.log_meta_data_buffer.get::<i64>(term_tail_counter_offset(next_index)), ((TERM_ID_1 + 1) as i64) << 32 ); assert!( test.publication.offer(test.src_buffer).unwrap() > (initial_position + LENGTH + test.src_buffer.capacity()) as i64 ); let position = test.publication.position(); assert!(position.is_ok()); assert!(position.unwrap() > (initial_position + LENGTH + test.src_buffer.capacity()) as i64); } #[test] fn should_rotate_when_claim_trips() { let mut test = ExclusivePublicationTest::new(); let active_index = log_buffer_descriptor::index_by_term(TERM_ID_1, TERM_ID_1); let initial_position = TERM_MIN_LENGTH - LENGTH; test.log_meta_data_buffer.put( term_tail_counter_offset(active_index), raw_tail_value(TERM_ID_1, initial_position as i64), ); test.publication_limit.set(i32::max_value() as i64); test.create_pub(); let buffer_claim = BufferClaim::default(); let position = test.publication.position(); assert!(position.is_ok()); assert_eq!(position.unwrap(), initial_position as i64); let claim_result = test.publication.try_claim(1024, buffer_claim); assert!(claim_result.is_err()); assert_eq!(claim_result.unwrap_err(), AeronError::AdminAction); let next_index = log_buffer_descriptor::index_by_term(TERM_ID_1, TERM_ID_1 + 1); assert_eq!( test.log_meta_data_buffer .get::<i32>(*log_buffer_descriptor::LOG_ACTIVE_TERM_COUNT_OFFSET), 1 ); assert_eq!( test.log_meta_data_buffer.get::<i64>(term_tail_counter_offset(next_index)), ((TERM_ID_1 + 1) as i64) << 32 ); assert!( test.publication.try_claim(1024, buffer_claim).unwrap() > (initial_position + LENGTH + test.src_buffer.capacity()) as i64 ); let position = test.publication.position(); assert!(position.is_ok()); assert!(position.unwrap() > (initial_position + LENGTH + test.src_buffer.capacity()) as i64); } }
{ self.publication_limit.id() }
service-worker.js
/* SERVICE WORKER OR CLIENT SIDE PROXY Copyright 2015, 2019, 2020, 2021 Google LLC. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ // https://developer.mozilla.org/en-US/docs/Web/API/Service_Worker_API // https://web.dev/cache-api-quick-guide/ // https://developer.mozilla.org/en-US/docs/Web/API // https://developer.mozilla.org/es/docs/Web/Progressive_web_apps/Re-engageable_Notifications_Push // https://developer.mozilla.org/en-US/docs/Web/API/Notification/Notification /* There are MANY (2021 updated): I believe the information in this resource from google and/or this link will help you to find alternatives for saving information on the client-side. Basically... there are currently 4 different ways to store data on client-side without using cookies: - Local Storage (Session and Local key/value pairs) - Web SQL (my favorite, it's a whole SQL Database, and it's NOT obsolete) - IndexedDB (another Database with different structure and acceptance) - Service Workers (Persistent background processing, even while offline, can asynchronously save files and many other things) I believe that for your specific need the Local Storage pairs are the easiest solution. A service worker is a type of local service that interact with operating native systems */ // ----------------------------------------------------------------------------- // VIRTUAL EXPRESS SERVER // ----------------------------------------------------------------------------- var _SERVICES = []; var MainProcess = { app: { post: (uri, service) => _SERVICES.push({method: 'POST', uri, service}), get: (uri, service) => _SERVICES.push({method: 'GET', uri, service}), }, data: { charset: 'utf8' } }; var info = { api: (req, obj) => null }; var fs = { readFileSync: async (JSON_POSTS_PATH, charset) => { try { console.log('readFileSync data:', JSON_POSTS_PATH); const cacheAsset = await caches.open(JSON_POSTS_PATH); const cachedAssetResponse = await cacheAsset.match(JSON_POSTS_PATH); return JSON.stringify(await cachedAssetResponse.json()); }catch(error){ // console.error(error); console.log('readFileSync return default JSON'); return JSON.stringify([]); } }, writeFileSync: async (JSON_POSTS_PATH, newData, charset) => { try { console.log('writeFileSync data:', JSON_POSTS_PATH); console.log(newData); const options = { headers: { 'Content-Type': 'application/json' } }; const cache = await caches.open(JSON_POSTS_PATH); await cache.put(JSON_POSTS_PATH, new Response(JSON.stringify(JSON.parse(newData)), options)); }catch(error){ console.error(error); return; } }, existsSync: async (JSON_POSTS_PATH) => { try { console.log('existsSync data:', JSON_POSTS_PATH); return caches.has(JSON_POSTS_PATH); }catch(error){ console.error(error); return false; } } }; var colors = { red: strLog => console.error('[Service Woker]', strLog), yellow: strLog => console.warn('[Service Woker]', strLog), green: strLog => console.log('[Service Woker]', strLog) }; class
{ constructor(){} addFormat(){} getSchema(){ return () => true; } } /* POSTS VIRTUAL API */ var POSTS_VIRTUAL_API = new Posts(MainProcess); // Incrementing OFFLINE_VERSION will kick off the install event and force // previously cached resources to be updated from the network. const OFFLINE_VERSION = 1; console.warn('[Service Worker] Base URL ', _URL); console.warn('[Service Worker] Assets ', _ASSETS); console.warn('[Service Worker] Api ', _API); console.warn('[Service Worker] Dev ', _DEV); console.warn('[Service Worker] Views ', _VIEWS); console.warn('[Service Worker] Services ', _SERVICES); // ----------------------------------------------------------------------------- // PWA INIT // ----------------------------------------------------------------------------- self.addEventListener('install', (event) => { event.waitUntil((async () => { // Setting {cache: 'reload'} in the new request will ensure that the response // isn't fulfilled from the HTTP cache; i.e., it will be from the network. for(let viewSrc of _VIEWS){ console.warn('[Service Worker] Install View ', viewSrc); const cache = await caches.open(viewSrc); await cache.add(new Request(viewSrc, {cache: 'reload'})); } for(let assetsSrc of _ASSETS){ console.warn('[Service Worker] Install Asset ', assetsSrc); const cacheAssetsSrc = await caches.open(assetsSrc); await cacheAssetsSrc.add(new Request(assetsSrc, {cache: 'reload'})); } })()); // Force the waiting service worker to become the active service worker. self.skipWaiting(); }); self.addEventListener('activate', (event) => { event.waitUntil((async () => { // Enable navigation preload if it's supported. // See https://developers.google.com/web/updates/2017/02/navigation-preload console.warn('[Service Worker] Activate ', event); if ('navigationPreload' in self.registration) { await self.registration.navigationPreload.enable(); /* setInterval(()=>{ clients.matchAll().then( clientList => { clientList.map( client => { console.log(client); client.postMessage({ test: 'test' }); // client -> document.visibilityState // client.visibilityState }); }); }, 2000); */ } })()); // Tell the active service worker to take control of the page immediately. self.clients.claim(); }); // ----------------------------------------------------------------------------- // WORKER SERVER // ----------------------------------------------------------------------------- self.addEventListener('fetch', (event) => { // We only want to call event.respondWith() if this is a navigation request // for an HTML page. // console.warn('[Service Worker] Fetch ', event); // GET URI REQ const _URI = event.request.url.split(_URL)[1]; console.warn('[Service Worker] Fetch ', _URI); const assetsValidator = _ASSETS.includes(_URI); const apiValidator = _API.includes(_URI); if (event.request.mode === 'navigate' || assetsValidator || apiValidator) { const REQ = event.request.clone(); event.respondWith((async () => { try { // First, try to use the navigation preload response if it's supported. const preloadResponse = await event.preloadResponse; if (preloadResponse) { console.warn('[Service Worker] [Navigator Middleware] [Preload Response]', _URI); return preloadResponse; } // Exit early if we don't have access to the client. // Eg, if it's cross-origin. if (!event.clientId) return; // Get the client. const client = await clients.get(event.clientId); // Exit early if we don't get the client. // Eg, if it closed. // console.warn('[Service Worker] [Request-Client]', client); if (!client) return; // Send a message to the client. /* client.postMessage({ msg: "Hey I just got a fetch from you!", url: event.request.url }); */ if(apiValidator){ console.warn('[Service Worker] [API Request]', event); let REQUEST_HEADERS = {}; for (var pair of event.request.headers.entries()) { REQUEST_HEADERS[pair[0]] = pair[1]; } console.warn('[Service Worker] [Headers]', REQUEST_HEADERS); } // Always try the network first. const networkResponse = await fetch(event.request); console.warn('[Service Worker] [Navigator Middleware] [Network Response]', _URI); return networkResponse; } catch (error) { // catch is only triggered if an exception is thrown, which is likely // due to a network error. // If fetch() returns a valid HTTP response with a response code in // the 4xx or 5xx range, the catch() will NOT be called. // console.log('Fetch failed; returning offline page instead.', error); // console.warn('[Service Worker] [Navigator Middleware] [Cached Response]', event.request); if(assetsValidator){ console.warn('[Service Worker] [Navigator Middleware] [Cached Response] [Asset]', _URI); const cacheAsset = await caches.open(_URI); const cachedAssetResponse = await cacheAsset.match(_URI); return cachedAssetResponse; }else if(apiValidator){ console.warn('[Service Worker] [Navigator Middleware] [Cached Response] [Api] '+event.request.method+' -> ', _URI); let _HEADERS = {}; const execResponse = async _REQUEST => { for(let apiObj of _SERVICES){ if((apiObj.uri == _URI || apiObj.uri+'/' == _URI) && (event.request.method==apiObj.method)){ let _DATA = await apiObj.service( // REQUEST OBJ _REQUEST, // RESPONSE OBJ { end: strResponse => strResponse, writeHead: (status, headers) => { _HEADERS = headers; } } ); return new Response(_DATA, _HEADERS); } } }; switch (_URI) { case '/posts/': if(event.request.method === 'GET'){ return await execResponse({ body: {}, query: { s: undefined }, params: {} }); /* return new Response(JSON.stringify({ success: true, data: [] }),{ headers: { "Content-Type" : "application/json" } }); */ } case '/posts': if(event.request.method === 'POST'){ // Clone headers as request headers are immutable // await REQ.arrayBuffer(); // await REQ.blob(); // await REQ.json(); // await REQ.text(); // await REQ.formData(); // console.warn('BODY', await REQ.json()); return await execResponse({ body: await REQ.json(), query: {}, params: {} }); // almacenar y recuperar data en cache de posts /* return new Response(JSON.stringify({ success: false, data: [] }),{ headers: { "Content-Type" : "application/json" } }); */ } default: return new Response(JSON.stringify({ success: false, data: [] }),{ headers: { "Content-Type" : "application/json" } }); } }else{ console.warn('[Service Worker] [Navigator Middleware] [Cached Response] [Url]', _URI); const cache = await caches.open(_URI); const cachedResponse = await cache.match(_URI); return cachedResponse; } } })()); } // If our if() condition is false, then this fetch handler won't intercept the // request. If there are any other fetch handlers registered, they will get a // chance to call event.respondWith(). If no fetch handlers call // event.respondWith(), the request will be handled by the browser as if there // were no service worker involvement. }); // ----------------------------------------------------------------------------- // ----------------------------------------------------------------------------- // ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
Ajv
mod.rs
use std::net::TcpStream; pub fn is_reachable(address: &str) -> bool { match TcpStream::connect(address) { Ok(_stream) => true, Err(_e) => false, } } // the stream is closed here #[cfg(test)] mod test { use super::*; use std::net::{Ipv4Addr, SocketAddrV4, TcpListener}; use std::{thread, time}; #[test] fn
() { let available_port = available_port().to_string(); let mut address = String::from("127.0.0.1:"); address.push_str(&available_port); println!("Check for available connections on {}", &address); assert!(!is_reachable(&address)); } fn available_port() -> u16 { let loopback = Ipv4Addr::new(127, 0, 0, 1); let socket = SocketAddrV4::new(loopback, 0); let listener = TcpListener::bind(socket); let port = listener.unwrap().local_addr().unwrap(); port.port() } #[test] fn port_should_be_open() { let loopback = Ipv4Addr::new(127, 0, 0, 1); let socket = SocketAddrV4::new(loopback, 0); let listener = TcpListener::bind(socket).unwrap(); let listener_port = listener.local_addr().unwrap().to_string(); thread::spawn(move || loop { match listener.accept() { Ok(_) => { println!("Connection received!"); } Err(_) => { println!("Error in received connection!"); } } }); thread::sleep(time::Duration::from_millis(250)); println!("Check for available connections on {}", &listener_port); assert!(is_reachable(&listener_port)); } }
port_should_be_closed
base64.rs
// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // // ignore-lexer-test FIXME #15679 //! Base64 binary-to-text encoding pub use self::FromBase64Error::*; pub use self::CharacterSet::*; use std::fmt; use std::error; /// Available encoding character sets #[derive(Copy)] pub enum CharacterSet { /// The standard character set (uses `+` and `/`) Standard, /// The URL safe character set (uses `-` and `_`) UrlSafe } /// Available newline types #[derive(Copy)] pub enum Newline { /// A linefeed (i.e. Unix-style newline) LF, /// A carriage return and a linefeed (i.e. Windows-style newline) CRLF } /// Contains configuration parameters for `to_base64`. #[derive(Copy)] pub struct Config { /// Character set to use pub char_set: CharacterSet, /// Newline to use pub newline: Newline, /// True to pad output with `=` characters pub pad: bool, /// `Some(len)` to wrap lines at `len`, `None` to disable line wrapping pub line_length: Option<usize> } /// Configuration for RFC 4648 standard base64 encoding pub static STANDARD: Config = Config {char_set: Standard, newline: Newline::CRLF, pad: true, line_length: None}; /// Configuration for RFC 4648 base64url encoding pub static URL_SAFE: Config = Config {char_set: UrlSafe, newline: Newline::CRLF, pad: false, line_length: None}; /// Configuration for RFC 2045 MIME base64 encoding pub static MIME: Config = Config {char_set: Standard, newline: Newline::CRLF, pad: true, line_length: Some(76)}; static STANDARD_CHARS: &'static[u8] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZ\ abcdefghijklmnopqrstuvwxyz\ 0123456789+/"; static URLSAFE_CHARS: &'static[u8] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZ\ abcdefghijklmnopqrstuvwxyz\ 0123456789-_"; /// A trait for converting a value to base64 encoding. pub trait ToBase64 { /// Converts the value of `self` to a base64 value following the specified /// format configuration, returning the owned string. fn to_base64(&self, config: Config) -> String; } impl ToBase64 for [u8] { /// Turn a vector of `u8` bytes into a base64 string. /// /// # Example /// /// ```rust /// # #![allow(unstable)] /// extern crate "rustc-serialize" as rustc_serialize; /// use rustc_serialize::base64::{ToBase64, STANDARD}; /// /// fn main () { /// let str = [52,32].to_base64(STANDARD); /// println!("base 64 output: {:?}", str); /// } /// ``` fn to_base64(&self, config: Config) -> String { let bytes = match config.char_set { Standard => STANDARD_CHARS, UrlSafe => URLSAFE_CHARS }; // In general, this Vec only needs (4/3) * self.len() memory, but // addition is faster than multiplication and division. let mut v = Vec::with_capacity(self.len() + self.len()); let mut i = 0; let mut cur_length = 0; let len = self.len(); let mod_len = len % 3; let cond_len = len - mod_len; let newline = match config.newline { Newline::LF => b"\n", Newline::CRLF => b"\r\n" }; while i < cond_len { let (first, second, third) = (self[i], self[i + 1], self[i + 2]); if let Some(line_length) = config.line_length { if cur_length >= line_length { v.extend(newline.iter().map(|x| *x)); cur_length = 0; } } let n = (first as u32) << 16 | (second as u32) << 8 | (third as u32); // This 24-bit number gets separated into four 6-bit numbers. v.push(bytes[((n >> 18) & 63) as usize]); v.push(bytes[((n >> 12) & 63) as usize]); v.push(bytes[((n >> 6 ) & 63) as usize]); v.push(bytes[(n & 63) as usize]); cur_length += 4; i += 3; } if mod_len != 0 { if let Some(line_length) = config.line_length { if cur_length >= line_length { v.extend(newline.iter().map(|x| *x)); } } } // Heh, would be cool if we knew this was exhaustive // (the dream of bounded integer types) match mod_len { 0 => (), 1 => { let n = (self[i] as u32) << 16; v.push(bytes[((n >> 18) & 63) as usize]); v.push(bytes[((n >> 12) & 63) as usize]); if config.pad { v.push(b'='); v.push(b'='); } } 2 => { let n = (self[i] as u32) << 16 | (self[i + 1] as u32) << 8; v.push(bytes[((n >> 18) & 63) as usize]); v.push(bytes[((n >> 12) & 63) as usize]); v.push(bytes[((n >> 6 ) & 63) as usize]); if config.pad { v.push(b'='); } } _ => panic!("Algebra is broken, please alert the math police") } unsafe { String::from_utf8_unchecked(v) } } } /// A trait for converting from base64 encoded values. pub trait FromBase64 { /// Converts the value of `self`, interpreted as base64 encoded data, into /// an owned vector of bytes, returning the vector. fn from_base64(&self) -> Result<Vec<u8>, FromBase64Error>; } /// Errors that can occur when decoding a base64 encoded string #[derive(Copy)] pub enum FromBase64Error { /// The input contained a character not part of the base64 format InvalidBase64Byte(u8, usize), /// The input had an invalid length InvalidBase64Length, } impl fmt::Debug for FromBase64Error { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { InvalidBase64Byte(ch, idx) => write!(f, "Invalid character '{}' at position {}", ch, idx), InvalidBase64Length => write!(f, "Invalid length"), } } } impl error::Error for FromBase64Error { fn description(&self) -> &str { match *self { InvalidBase64Byte(_, _) => "invalid character", InvalidBase64Length => "invalid length", } } } impl fmt::Display for FromBase64Error { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fmt::Debug::fmt(&self, f) } } impl FromBase64 for str { /// Convert any base64 encoded string (literal, `@`, `&`, or `~`) /// to the byte values it encodes. /// /// You can use the `String::from_utf8` function to turn a `Vec<u8>` into a /// string with characters corresponding to those values. /// /// # Example /// /// This converts a string literal to base64 and back. /// /// ```rust /// # #![allow(unstable)] /// extern crate "rustc-serialize" as rustc_serialize; /// use rustc_serialize::base64::{ToBase64, FromBase64, STANDARD}; /// /// fn main () { /// let hello_str = b"Hello, World".to_base64(STANDARD); /// println!("base64 output: {}", hello_str); /// let res = hello_str.from_base64(); /// if res.is_ok() { /// let opt_bytes = String::from_utf8(res.unwrap()); /// if opt_bytes.is_ok() { /// println!("decoded from base64: {:?}", opt_bytes.unwrap()); /// } /// } /// } /// ``` #[inline] fn from_base64(&self) -> Result<Vec<u8>, FromBase64Error> { self.as_bytes().from_base64() } } impl FromBase64 for [u8] { fn from_base64(&self) -> Result<Vec<u8>, FromBase64Error> { let mut r = Vec::with_capacity(self.len()); let mut buf: u32 = 0; let mut modulus = 0; let mut it = self.iter().enumerate(); for (idx, &byte) in it.by_ref() { let val = byte as u32; match byte { b'A'...b'Z' => buf |= val - 0x41, b'a'...b'z' => buf |= val - 0x47, b'0'...b'9' => buf |= val + 0x04, b'+' | b'-' => buf |= 0x3E, b'/' | b'_' => buf |= 0x3F, b'\r' | b'\n' => continue, b'=' => break, _ => return Err(InvalidBase64Byte(self[idx], idx)), } buf <<= 6; modulus += 1; if modulus == 4 { modulus = 0; r.push((buf >> 22) as u8); r.push((buf >> 14) as u8); r.push((buf >> 6 ) as u8); } } for (idx, &byte) in it { match byte { b'=' | b'\r' | b'\n' => continue, _ => return Err(InvalidBase64Byte(self[idx], idx)), } } match modulus { 2 => { r.push((buf >> 10) as u8); } 3 => { r.push((buf >> 16) as u8); r.push((buf >> 8 ) as u8); } 0 => (), _ => return Err(InvalidBase64Length), } Ok(r) } } #[cfg(test)] mod tests { extern crate test; use self::test::Bencher; use base64::{Config, Newline, FromBase64, ToBase64, STANDARD, URL_SAFE}; #[test] fn test_to_base64_basic() { assert_eq!("".as_bytes().to_base64(STANDARD), ""); assert_eq!("f".as_bytes().to_base64(STANDARD), "Zg=="); assert_eq!("fo".as_bytes().to_base64(STANDARD), "Zm8="); assert_eq!("foo".as_bytes().to_base64(STANDARD), "Zm9v"); assert_eq!("foob".as_bytes().to_base64(STANDARD), "Zm9vYg=="); assert_eq!("fooba".as_bytes().to_base64(STANDARD), "Zm9vYmE="); assert_eq!("foobar".as_bytes().to_base64(STANDARD), "Zm9vYmFy"); } #[test] fn test_to_base64_crlf_line_break() { assert!(![08; 1000].to_base64(Config {line_length: None, ..STANDARD}) .contains("\r\n")); assert_eq!(b"foobar".to_base64(Config {line_length: Some(4), ..STANDARD}), "Zm9v\r\nYmFy"); } #[test] fn test_to_base64_lf_line_break() { assert!(![08; 1000].to_base64(Config {line_length: None, newline: Newline::LF, ..STANDARD}) .contains("\n")); assert_eq!(b"foobar".to_base64(Config {line_length: Some(4), newline: Newline::LF, ..STANDARD}), "Zm9v\nYmFy"); } #[test] fn test_to_base64_padding() { assert_eq!("f".as_bytes().to_base64(Config {pad: false, ..STANDARD}), "Zg"); assert_eq!("fo".as_bytes().to_base64(Config {pad: false, ..STANDARD}), "Zm8"); } #[test] fn test_to_base64_url_safe() { assert_eq!([251, 255].to_base64(URL_SAFE), "-_8"); assert_eq!([251, 255].to_base64(STANDARD), "+/8="); } #[test] fn test_from_base64_basic() { assert_eq!("".from_base64().unwrap(), b""); assert_eq!("Zg==".from_base64().unwrap(), b"f"); assert_eq!("Zm8=".from_base64().unwrap(), b"fo"); assert_eq!("Zm9v".from_base64().unwrap(), b"foo"); assert_eq!("Zm9vYg==".from_base64().unwrap(), b"foob"); assert_eq!("Zm9vYmE=".from_base64().unwrap(), b"fooba"); assert_eq!("Zm9vYmFy".from_base64().unwrap(), b"foobar"); } #[test] fn test_from_base64_bytes() { assert_eq!(b"Zm9vYmFy".from_base64().unwrap(), b"foobar"); } #[test] fn test_from_base64_newlines() { assert_eq!("Zm9v\r\nYmFy".from_base64().unwrap(), b"foobar"); assert_eq!("Zm9vYg==\r\n".from_base64().unwrap(), b"foob"); assert_eq!("Zm9v\nYmFy".from_base64().unwrap(), b"foobar"); assert_eq!("Zm9vYg==\n".from_base64().unwrap(), b"foob"); } #[test] fn
() { assert_eq!("-_8".from_base64().unwrap(), "+/8=".from_base64().unwrap()); } #[test] fn test_from_base64_invalid_char() { assert!("Zm$=".from_base64().is_err()); assert!("Zg==$".from_base64().is_err()); } #[test] fn test_from_base64_invalid_padding() { assert!("Z===".from_base64().is_err()); } #[test] fn test_base64_random() { use rand::{thread_rng, Rng}; for _ in 0..1000 { let times = thread_rng().gen_range(1, 100); let v = thread_rng().gen_iter::<u8>().take(times) .collect::<Vec<_>>(); assert_eq!(v.to_base64(STANDARD) .from_base64() .unwrap(), v); } } #[bench] pub fn bench_to_base64(b: &mut Bencher) { let s = "イロハニホヘト チリヌルヲ ワカヨタレソ ツネナラム \ ウヰノオクヤマ ケフコエテ アサキユメミシ ヱヒモセスン"; b.iter(|| { s.as_bytes().to_base64(STANDARD); }); b.bytes = s.len() as u64; } #[bench] pub fn bench_from_base64(b: &mut Bencher) { let s = "イロハニホヘト チリヌルヲ ワカヨタレソ ツネナラム \ ウヰノオクヤマ ケフコエテ アサキユメミシ ヱヒモセスン"; let sb = s.as_bytes().to_base64(STANDARD); b.iter(|| { sb.from_base64().unwrap(); }); b.bytes = sb.len() as u64; } }
test_from_base64_urlsafe
DropZone.js
import React, { Component, PropTypes } from 'react'; import DropZone from 'react-dropzone'; class
extends Component { state = { showError: false } getFile = () => { if (this.state && this.state.file) { if (this.state.showError) { this.setState({showError: false}); } return this.state.file; } if (this.props.required) { this.setState({showError: true}); } } onDrop = (files) => { if (files&&files[0]) { this.setState({file: files[0]}); } } render() { const { className, style, multiple, accept, imageUrl } = this.props; const preview = (this.state.file&&this.state.file.preview)||imageUrl; return ( <DropZone className={className} style={styles.container} multiple={multiple} accept={accept} onDrop={this.onDrop}> {preview?<img style={{...style, ...styles.img}} src={preview}/>: (this.state.showError?<div style={styles.errorText}>you must select a file</div> :<div>Try dropping some files here, or click to select files to upload.</div>)} </DropZone> ); } } const styles = { container: { padding: 16, borderStyle: 'dashed' }, img: { width: '100%' }, errorText: { color: 'red' } } DropZoneView.proptypes = { imageUrl: PropTypes.string, required: PropTypes.bool }; export default DropZoneView;
DropZoneView
index.ts
import { IOptionalPreprocessOptions, preprocess, preprocessOptions } from '@aurelia/plugin-conventions'; import { getOptions } from 'loader-utils'; import * as webpack from 'webpack'; export default function( this: webpack.loader.LoaderContext, contents: string, sourceMap?: object, // ignore existing source map for now ) { return loader.call(this, contents); } export function loader( this: webpack.loader.LoaderContext, contents: string, _preprocess = preprocess // for testing ) { // eslint-disable-next-line no-unused-expressions, @typescript-eslint/strict-boolean-expressions this.cacheable && this.cacheable(); const cb = this.async() as webpack.loader.loaderCallback; const options = getOptions(this) as IOptionalPreprocessOptions; const filePath = this.resourcePath; try { const result = _preprocess( { path: filePath, contents }, preprocessOptions({ ...options, stringModuleWrap }) ); // webpack uses source-map 0.6.1 typings for RawSourceMap which // contains typing error version: string (should be number). // use result.map as any to bypass the typing issue. if (result) { cb(null, result.code, result.map as any); return; } // bypassed cb(null, contents); } catch (e) { cb(e); } } function
(id: string) { return '!!raw-loader!' + id; }
stringModuleWrap
thick.rs
// Copyright (c) 2018-2020 MobileCoin Inc. //! Connection implementations required for the thick client. //! The attested client implementation. use crate::{ error::{Error, Result}, traits::{ AttestationError, AttestedConnection, BlockchainConnection, Connection, UserTxConnection, }, }; use aes_gcm::Aes256Gcm; use failure::Fail; use grpcio::{ChannelBuilder, Environment, Error as GrpcError}; use mc_attest_ake::{ AuthResponseInput, ClientInitiate, Error as AkeError, Ready, Start, Transition, }; use mc_attest_api::{attest::Message, attest_grpc::AttestedApiClient}; use mc_attest_core::Verifier; use mc_common::{ logger::{log, o, Logger}, trace_time, }; use mc_consensus_api::{ consensus_client_grpc::ConsensusClientApiClient, consensus_common::{BlocksRequest, ProposeTxResult}, consensus_common_grpc::BlockchainApiClient, empty::Empty, }; use mc_crypto_keys::X25519; use mc_crypto_noise::CipherError; use mc_crypto_rand::McRng; use mc_transaction_core::{tx::Tx, Block, BlockID, BlockIndex}; use mc_util_grpc::{auth::BasicCredentials, ConnectionUriGrpcioChannel}; use mc_util_serial::encode; use mc_util_uri::{ConnectionUri, ConsensusClientUri as ClientUri, UriConversionError}; use secrecy::{ExposeSecret, SecretVec}; use sha2::Sha512; use std::{ cmp::Ordering, convert::TryFrom, fmt::{Display, Formatter, Result as FmtResult}, hash::{Hash, Hasher}, ops::Range, result::Result as StdResult, sync::Arc, }; #[derive(Debug, Fail)] pub enum ThickClientAttestationError { #[fail(display = "gRPC failure in attestation: {}", _0)] Grpc(GrpcError), #[fail(display = "Key exchange failure: {}", _0)] Ake(AkeError), #[fail(display = "Encryption/decryption failure in attestation: {}", _0)] Cipher(CipherError), #[fail(display = "Could not create ResponderID from URI {} due to {}", _0, _1)] InvalidResponderID(String, UriConversionError), #[fail(display = "Unexpected Error Converting URI {}", _0)] UriConversionError(UriConversionError), } impl From<GrpcError> for ThickClientAttestationError { fn
(src: GrpcError) -> Self { ThickClientAttestationError::Grpc(src) } } impl From<AkeError> for ThickClientAttestationError { fn from(src: AkeError) -> Self { ThickClientAttestationError::Ake(src) } } impl From<CipherError> for ThickClientAttestationError { fn from(src: CipherError) -> Self { ThickClientAttestationError::Cipher(src) } } impl From<UriConversionError> for ThickClientAttestationError { fn from(src: UriConversionError) -> Self { match src.clone() { UriConversionError::ResponderId(uri, _err) => { ThickClientAttestationError::InvalidResponderID(uri, src) } _ => ThickClientAttestationError::UriConversionError(src), } } } impl AttestationError for ThickClientAttestationError {} /// A connection from a client to a consensus enclave. pub struct ThickClient { /// The destination's URI uri: ClientUri, /// The logging instance logger: Logger, /// The gRPC API client we will use for blockchain detail retrieval. blockchain_api_client: BlockchainApiClient, /// The gRPC API client we will use for attestation and (eventually) transactions attested_api_client: AttestedApiClient, /// The gRPC API client we will use for legacy transaction submission. consensus_client_api_client: ConsensusClientApiClient, /// An object which can verify a consensus node's provided IAS report verifier: Verifier, /// The AKE state machine object, if one is available. enclave_connection: Option<Ready<Aes256Gcm>>, /// Credentials to use for all GRPC calls (this allows authentication username/password to go /// through, if provided). creds: BasicCredentials, } impl ThickClient { /// Create a new attested connection to the given consensus node. pub fn new( uri: ClientUri, verifier: Verifier, env: Arc<Environment>, logger: Logger, ) -> Result<Self> { let logger = logger.new(o!("mc.cxn" => uri.to_string())); let ch = ChannelBuilder::default_channel_builder(env).connect_to_uri(&uri, &logger); let attested_api_client = AttestedApiClient::new(ch.clone()); let blockchain_api_client = BlockchainApiClient::new(ch.clone()); let consensus_client_api_client = ConsensusClientApiClient::new(ch); let creds = BasicCredentials::new(&uri.username(), &uri.password()); Ok(Self { uri, logger, blockchain_api_client, consensus_client_api_client, attested_api_client, verifier, enclave_connection: None, creds, }) } } impl Connection for ThickClient { type Uri = ClientUri; fn uri(&self) -> Self::Uri { self.uri.clone() } } impl AttestedConnection for ThickClient { type Error = ThickClientAttestationError; fn is_attested(&self) -> bool { self.enclave_connection.is_some() } fn attest(&mut self) -> StdResult<(), Self::Error> { trace_time!(self.logger, "ThickClient::attest"); // If we have an existing attestation, nuke it. self.deattest(); let mut csprng = McRng::default(); let initiator = Start::new(self.uri.responder_id()?.to_string()); let init_input = ClientInitiate::<X25519, Aes256Gcm, Sha512>::default(); let (initiator, auth_request_output) = initiator.try_next(&mut csprng, init_input)?; let auth_response_msg = self .attested_api_client .auth_opt(&auth_request_output.into(), self.creds.call_option()?)?; let auth_response_event = AuthResponseInput::new(auth_response_msg.into(), self.verifier.clone()); let (initiator, _) = initiator.try_next(&mut csprng, auth_response_event)?; self.enclave_connection = Some(initiator); Ok(()) } fn deattest(&mut self) { if self.is_attested() { log::trace!(self.logger, "Tearing down existing attested connection."); self.enclave_connection = None; } } } impl BlockchainConnection for ThickClient { fn fetch_blocks(&mut self, range: Range<BlockIndex>) -> Result<Vec<Block>> { trace_time!(self.logger, "ThickClient::get_blocks"); let mut request = BlocksRequest::new(); request.set_offset(range.start); let limit = u32::try_from(range.end - range.start).or(Err(Error::RequestTooLarge))?; request.set_limit(limit); self.attested_call(|this| { this.blockchain_api_client .get_blocks_opt(&request, this.creds.call_option()?) })? .get_blocks() .iter() .map(|proto_block| Block::try_from(proto_block).map_err(Error::from)) .collect::<Result<Vec<Block>>>() } fn fetch_block_ids(&mut self, range: Range<BlockIndex>) -> Result<Vec<BlockID>> { trace_time!(self.logger, "ThickClient::get_block_ids"); let mut request = BlocksRequest::new(); request.set_offset(range.start); let limit = u32::try_from(range.end - range.start).or(Err(Error::RequestTooLarge))?; request.set_limit(limit); self.attested_call(|this| { this.blockchain_api_client .get_blocks_opt(&request, this.creds.call_option()?) })? .get_blocks() .iter() .map(|proto_block| BlockID::try_from(proto_block.get_id()).map_err(Error::from)) .collect::<Result<Vec<BlockID>>>() } fn fetch_block_height(&mut self) -> Result<BlockIndex> { trace_time!(self.logger, "ThickClient::fetch_block_height"); Ok(self .attested_call(|this| { this.blockchain_api_client .get_last_block_info_opt(&Empty::new(), this.creds.call_option()?) })? .index) } } impl UserTxConnection for ThickClient { fn propose_tx(&mut self, tx: &Tx) -> Result<BlockIndex> { trace_time!(self.logger, "ThickClient::propose_tx"); if !self.is_attested() { self.attest()? } let enclave_connection = self .enclave_connection .as_mut() .expect("no enclave_connection even though attest succeeded"); let mut msg = Message::new(); msg.set_channel_id(Vec::from(enclave_connection.binding())); // Don't leave the plaintext serialization floating around let tx_plaintext = SecretVec::new(encode(tx)); let tx_ciphertext = enclave_connection.encrypt(&[], tx_plaintext.expose_secret().as_ref())?; msg.set_data(tx_ciphertext); let resp = self.attested_call(|this| { this.consensus_client_api_client .client_tx_propose_opt(&msg, this.creds.call_option()?) })?; if resp.get_result() == ProposeTxResult::Ok { Ok(resp.get_num_blocks()) } else { Err(resp.get_result().into()) } } } impl Display for ThickClient { fn fmt(&self, f: &mut Formatter) -> FmtResult { write!(f, "{}", self.uri) } } impl Eq for ThickClient {} impl Hash for ThickClient { fn hash<H: Hasher>(&self, hasher: &mut H) { self.uri.addr().hash(hasher); } } impl PartialEq for ThickClient { fn eq(&self, other: &Self) -> bool { self.uri.addr() == other.uri.addr() } } impl Ord for ThickClient { fn cmp(&self, other: &Self) -> Ordering { self.uri.addr().cmp(&other.uri.addr()) } } impl PartialOrd for ThickClient { fn partial_cmp(&self, other: &Self) -> Option<Ordering> { self.uri.addr().partial_cmp(&other.uri.addr()) } }
from
service.ts
// Copyright 2020 IOTA Stiftung // SPDX-License-Identifier: Apache-2.0 // (Re-)generated by schema tool // >>>> DO NOT CHANGE THIS FILE! <<<< // Change the json schema instead import * as wasmclient from "wasmclient" import * as events from "./events" const ArgAddress = "address"; const ArgAgentID = "agentID"; const ArgBlockIndex = "blockIndex"; const ArgBool = "bool"; const ArgBytes = "bytes"; const ArgChainID = "chainID"; const ArgColor = "color"; const ArgHash = "hash"; const ArgHname = "hname"; const ArgIndex = "index"; const ArgInt16 = "int16"; const ArgInt32 = "int32"; const ArgInt64 = "int64"; const ArgInt8 = "int8"; const ArgKey = "key"; const ArgName = "name"; const ArgParam = "this"; const ArgRecordIndex = "recordIndex"; const ArgRequestID = "requestID"; const ArgString = "string"; const ArgUint16 = "uint16"; const ArgUint32 = "uint32"; const ArgUint64 = "uint64"; const ArgUint8 = "uint8"; const ArgValue = "value"; const ResCount = "count"; const ResIotas = "iotas"; const ResLength = "length"; const ResRandom = "random"; const ResRecord = "record"; const ResValue = "value"; ///////////////////////////// arrayClear ///////////////////////////// export class ArrayClearFunc extends wasmclient.ClientFunc { private args: wasmclient.Arguments = new wasmclient.Arguments(); public name(v: string): void { this.args.set(ArgName, this.args.fromString(v)); } public async post(): Promise<wasmclient.RequestID> { this.args.mandatory(ArgName); return await super.post(0x88021821, this.args); } } ///////////////////////////// arrayCreate ///////////////////////////// export class ArrayCreateFunc extends wasmclient.ClientFunc { private args: wasmclient.Arguments = new wasmclient.Arguments(); public name(v: string): void { this.args.set(ArgName, this.args.fromString(v)); } public async post(): Promise<wasmclient.RequestID> { this.args.mandatory(ArgName); return await super.post(0x1ed5b23b, this.args); } } ///////////////////////////// arraySet ///////////////////////////// export class ArraySetFunc extends wasmclient.ClientFunc { private args: wasmclient.Arguments = new wasmclient.Arguments(); public index(v: wasmclient.Int32): void { this.args.set(ArgIndex, this.args.fromInt32(v)); } public name(v: string): void { this.args.set(ArgName, this.args.fromString(v)); } public value(v: string): void { this.args.set(ArgValue, this.args.fromString(v)); } public async post(): Promise<wasmclient.RequestID> { this.args.mandatory(ArgIndex); this.args.mandatory(ArgName); this.args.mandatory(ArgValue); return await super.post(0x2c4150b3, this.args); } } ///////////////////////////// mapClear ///////////////////////////// export class MapClearFunc extends wasmclient.ClientFunc { private args: wasmclient.Arguments = new wasmclient.Arguments(); public name(v: string): void { this.args.set(ArgName, this.args.fromString(v)); } public async post(): Promise<wasmclient.RequestID> { this.args.mandatory(ArgName); return await super.post(0x027f215a, this.args); } } ///////////////////////////// mapCreate ///////////////////////////// export class MapCreateFunc extends wasmclient.ClientFunc { private args: wasmclient.Arguments = new wasmclient.Arguments(); public name(v: string): void { this.args.set(ArgName, this.args.fromString(v)); } public async post(): Promise<wasmclient.RequestID> { this.args.mandatory(ArgName); return await super.post(0x6295d599, this.args); } } ///////////////////////////// mapSet ///////////////////////////// export class MapSetFunc extends wasmclient.ClientFunc { private args: wasmclient.Arguments = new wasmclient.Arguments(); public key(v: string): void { this.args.set(ArgKey, this.args.fromString(v)); } public name(v: string): void { this.args.set(ArgName, this.args.fromString(v)); } public value(v: string): void { this.args.set(ArgValue, this.args.fromString(v)); } public async post(): Promise<wasmclient.RequestID> { this.args.mandatory(ArgKey); this.args.mandatory(ArgName); this.args.mandatory(ArgValue); return await super.post(0xf2260404, this.args); } } ///////////////////////////// paramTypes ///////////////////////////// export class ParamTypesFunc extends wasmclient.ClientFunc { private args: wasmclient.Arguments = new wasmclient.Arguments(); public address(v: wasmclient.Address): void { this.args.set(ArgAddress, this.args.fromAddress(v)); } public agentID(v: wasmclient.AgentID): void { this.args.set(ArgAgentID, this.args.fromAgentID(v)); } public bool(v: boolean): void { this.args.set(ArgBool, this.args.fromBool(v)); } public bytes(v: wasmclient.Bytes): void { this.args.set(ArgBytes, this.args.fromBytes(v)); } public chainID(v: wasmclient.ChainID): void { this.args.set(ArgChainID, this.args.fromChainID(v)); } public color(v: wasmclient.Color): void { this.args.set(ArgColor, this.args.fromColor(v)); } public hash(v: wasmclient.Hash): void { this.args.set(ArgHash, this.args.fromHash(v)); } public hname(v: wasmclient.Hname): void { this.args.set(ArgHname, this.args.fromHname(v)); } public int16(v: wasmclient.Int16): void { this.args.set(ArgInt16, this.args.fromInt16(v)); } public int32(v: wasmclient.Int32): void { this.args.set(ArgInt32, this.args.fromInt32(v)); } public int64(v: wasmclient.Int64): void { this.args.set(ArgInt64, this.args.fromInt64(v)); } public int8(v: wasmclient.Int8): void { this.args.set(ArgInt8, this.args.fromInt8(v)); } public param(v: wasmclient.Bytes): void { this.args.set(ArgParam, this.args.fromBytes(v)); } public requestID(v: wasmclient.RequestID): void { this.args.set(ArgRequestID, this.args.fromRequestID(v)); } public string(v: string): void { this.args.set(ArgString, this.args.fromString(v)); } public uint16(v: wasmclient.Uint16): void { this.args.set(ArgUint16, this.args.fromUint16(v)); } public uint32(v: wasmclient.Uint32): void { this.args.set(ArgUint32, this.args.fromUint32(v)); } public uint64(v: wasmclient.Uint64): void { this.args.set(ArgUint64, this.args.fromUint64(v)); } public uint8(v: wasmclient.Uint8): void { this.args.set(ArgUint8, this.args.fromUint8(v)); } public async post(): Promise<wasmclient.RequestID> { return await super.post(0x6921c4cd, this.args); } } ///////////////////////////// random ///////////////////////////// export class RandomFunc extends wasmclient.ClientFunc { public async post(): Promise<wasmclient.RequestID> { return await super.post(0xe86c97ca, null); } } ///////////////////////////// triggerEvent ///////////////////////////// export class TriggerEventFunc extends wasmclient.ClientFunc { private args: wasmclient.Arguments = new wasmclient.Arguments(); public address(v: wasmclient.Address): void { this.args.set(ArgAddress, this.args.fromAddress(v)); } public name(v: string): void { this.args.set(ArgName, this.args.fromString(v)); } public async post(): Promise<wasmclient.RequestID> { this.args.mandatory(ArgAddress); this.args.mandatory(ArgName); return await super.post(0xd5438ac6, this.args); } } ///////////////////////////// arrayLength ///////////////////////////// export class ArrayLengthView extends wasmclient.ClientView { private args: wasmclient.Arguments = new wasmclient.Arguments(); public name(v: string): void { this.args.set(ArgName, this.args.fromString(v)); } public async call(): Promise<ArrayLengthResults> { this.args.mandatory(ArgName); const res = new ArrayLengthResults(); await this.callView("arrayLength", this.args, res); return res; } } export class ArrayLengthResults extends wasmclient.Results { length(): wasmclient.Int32 { return this.toInt32(this.get(ResLength)); } } ///////////////////////////// arrayValue ///////////////////////////// export class ArrayValueView extends wasmclient.ClientView { private args: wasmclient.Arguments = new wasmclient.Arguments(); public index(v: wasmclient.Int32): void { this.args.set(ArgIndex, this.args.fromInt32(v)); } public name(v: string): void { this.args.set(ArgName, this.args.fromString(v)); } public async call(): Promise<ArrayValueResults> { this.args.mandatory(ArgIndex); this.args.mandatory(ArgName); const res = new ArrayValueResults(); await this.callView("arrayValue", this.args, res); return res; } } export class ArrayValueResults extends wasmclient.Results { value(): string { return this.toString(this.get(ResValue)); } } ///////////////////////////// blockRecord ///////////////////////////// export class BlockRecordView extends wasmclient.ClientView { private args: wasmclient.Arguments = new wasmclient.Arguments(); public blockIndex(v: wasmclient.Int32): void { this.args.set(ArgBlockIndex, this.args.fromInt32(v)); } public recordIndex(v: wasmclient.Int32): void { this.args.set(ArgRecordIndex, this.args.fromInt32(v)); } public async call(): Promise<BlockRecordResults> { this.args.mandatory(ArgBlockIndex); this.args.mandatory(ArgRecordIndex); const res = new BlockRecordResults(); await this.callView("blockRecord", this.args, res); return res; } } export class BlockRecordResults extends wasmclient.Results { record(): wasmclient.Bytes { return this.toBytes(this.get(ResRecord)); } } ///////////////////////////// blockRecords ///////////////////////////// export class BlockRecordsView extends wasmclient.ClientView { private args: wasmclient.Arguments = new wasmclient.Arguments(); public blockIndex(v: wasmclient.Int32): void { this.args.set(ArgBlockIndex, this.args.fromInt32(v)); } public async call(): Promise<BlockRecordsResults> { this.args.mandatory(ArgBlockIndex); const res = new BlockRecordsResults(); await this.callView("blockRecords", this.args, res); return res; } } export class
extends wasmclient.Results { count(): wasmclient.Int32 { return this.toInt32(this.get(ResCount)); } } ///////////////////////////// getRandom ///////////////////////////// export class GetRandomView extends wasmclient.ClientView { public async call(): Promise<GetRandomResults> { const res = new GetRandomResults(); await this.callView("getRandom", null, res); return res; } } export class GetRandomResults extends wasmclient.Results { random(): wasmclient.Int64 { return this.toInt64(this.get(ResRandom)); } } ///////////////////////////// iotaBalance ///////////////////////////// export class IotaBalanceView extends wasmclient.ClientView { public async call(): Promise<IotaBalanceResults> { const res = new IotaBalanceResults(); await this.callView("iotaBalance", null, res); return res; } } export class IotaBalanceResults extends wasmclient.Results { iotas(): wasmclient.Int64 { return this.toInt64(this.get(ResIotas)); } } ///////////////////////////// mapValue ///////////////////////////// export class MapValueView extends wasmclient.ClientView { private args: wasmclient.Arguments = new wasmclient.Arguments(); public key(v: string): void { this.args.set(ArgKey, this.args.fromString(v)); } public name(v: string): void { this.args.set(ArgName, this.args.fromString(v)); } public async call(): Promise<MapValueResults> { this.args.mandatory(ArgKey); this.args.mandatory(ArgName); const res = new MapValueResults(); await this.callView("mapValue", this.args, res); return res; } } export class MapValueResults extends wasmclient.Results { value(): string { return this.toString(this.get(ResValue)); } } ///////////////////////////// TestWasmLibService ///////////////////////////// export class TestWasmLibService extends wasmclient.Service { public constructor(cl: wasmclient.ServiceClient) { super(cl, 0x89703a45, events.eventHandlers); } public arrayClear(): ArrayClearFunc { return new ArrayClearFunc(this); } public arrayCreate(): ArrayCreateFunc { return new ArrayCreateFunc(this); } public arraySet(): ArraySetFunc { return new ArraySetFunc(this); } public mapClear(): MapClearFunc { return new MapClearFunc(this); } public mapCreate(): MapCreateFunc { return new MapCreateFunc(this); } public mapSet(): MapSetFunc { return new MapSetFunc(this); } public paramTypes(): ParamTypesFunc { return new ParamTypesFunc(this); } public random(): RandomFunc { return new RandomFunc(this); } public triggerEvent(): TriggerEventFunc { return new TriggerEventFunc(this); } public arrayLength(): ArrayLengthView { return new ArrayLengthView(this); } public arrayValue(): ArrayValueView { return new ArrayValueView(this); } public blockRecord(): BlockRecordView { return new BlockRecordView(this); } public blockRecords(): BlockRecordsView { return new BlockRecordsView(this); } public getRandom(): GetRandomView { return new GetRandomView(this); } public iotaBalance(): IotaBalanceView { return new IotaBalanceView(this); } public mapValue(): MapValueView { return new MapValueView(this); } }
BlockRecordsResults
server_test.go
package mdns import ( "fmt" "testing" "time" ) func TestServer_StartStop(t *testing.T)
func TestServer_Lookup(t *testing.T) { serv, err := NewServer(&Config{Zone: makeServiceWithServiceName(t, "_foobar._tcp")}) if err != nil { t.Fatalf("err: %v", err) } defer serv.Shutdown() entries := make(chan *ServiceEntry, 1) errCh := make(chan error, 1) defer close(errCh) go func() { select { case e := <-entries: if e.Name != "hostname._foobar._tcp.local." { errCh <- fmt.Errorf("Entry has the wrong name: %+v", e) return } if e.Port != 80 { errCh <- fmt.Errorf("Entry has the wrong port: %+v", e) return } if e.Info != "Local web server" { errCh <- fmt.Errorf("Entry as the wrong Info: %+v", e) return } errCh <- nil case <-time.After(80 * time.Millisecond): errCh <- fmt.Errorf("Timed out waiting for response") } }() params := &QueryParam{ Service: "_foobar._tcp", Domain: "local", Timeout: 50 * time.Millisecond, Entries: entries, DisableIPv6: true, } err = Query(params) if err != nil { t.Fatalf("err: %v", err) } err = <-errCh if err != nil { t.Fatalf("err: %v", err) } }
{ s := makeService(t) serv, err := NewServer(&Config{Zone: s}) if err != nil { t.Fatalf("err: %v", err) } defer serv.Shutdown() }
gaussian.py
""" Code by Tae-Hwan Hung(@graykode) https://en.wikipedia.org/wiki/Normal_distribution """
def gaussian(x, n): u = x.mean() s = x.std() # divide [x.min(), x.max()] by n x = np.linspace(x.min(), x.max(), n) a = ((x - u) ** 2) / (2 * (s ** 2)) y = 1 / (s * np.sqrt(2 * np.pi)) * np.exp(-a) return x, y, x.mean(), x.std() x = np.arange(-100, 100) # define range of x x, y, u, s = gaussian(x, 10000) plt.plot(x, y, label=r'$\mu=%.2f,\ \sigma=%.2f$' % (u, s)) plt.legend() plt.savefig('graph/gaussian.png') plt.show()
import numpy as np from matplotlib import pyplot as plt
macros.rs
#[macro_export] macro_rules! nu { (cwd: $cwd:expr, $path:expr, $($part:expr),*) => {{ use $crate::fs::DisplayPath; let path = format!($path, $( $part.display_path() ),*); nu!($cwd, &path) }}; (cwd: $cwd:expr, $path:expr) => {{ nu!($cwd, $path) }}; ($cwd:expr, $path:expr) => {{ pub use itertools::Itertools; pub use std::error::Error; pub use std::io::prelude::*; pub use std::process::{Command, Stdio}; pub use $crate::NATIVE_PATH_ENV_VAR; // let commands = &*format!( // " // {} // exit", // $crate::fs::DisplayPath::display_path(&$path) // ); let test_bins = $crate::fs::binaries(); let cwd = std::env::current_dir().expect("Could not get current working directory."); let test_bins = nu_path::canonicalize_with(&test_bins, cwd).unwrap_or_else(|e| { panic!( "Couldn't canonicalize dummy binaries path {}: {:?}", test_bins.display(), e ) }); let mut paths = $crate::shell_os_paths(); paths.insert(0, test_bins); let path = $path.lines().collect::<Vec<_>>().join("; "); let paths_joined = match std::env::join_paths(paths) { Ok(all) => all, Err(_) => panic!("Couldn't join paths for PATH var."), }; let target_cwd = $crate::fs::in_directory(&$cwd); let mut process = match Command::new($crate::fs::executable_path()) .env("PWD", &target_cwd) // setting PWD is enough to set cwd .env(NATIVE_PATH_ENV_VAR, paths_joined) // .arg("--skip-plugins") // .arg("--no-history") // .arg("--config-file") // .arg($crate::fs::DisplayPath::display_path(&$crate::fs::fixtures().join("playground/config/default.toml"))) .arg(format!("-c '{}'", $crate::fs::DisplayPath::display_path(&path))) .stdout(Stdio::piped()) // .stdin(Stdio::piped()) .stderr(Stdio::piped()) .spawn() { Ok(child) => child, Err(why) => panic!("Can't run test {:?} {}", $crate::fs::executable_path(), why.to_string()), }; // let stdin = process.stdin.as_mut().expect("couldn't open stdin"); // stdin // .write_all(b"exit\n") // .expect("couldn't write to stdin"); let output = process .wait_with_output() .expect("couldn't read from stdout/stderr"); let out = $crate::macros::read_std(&output.stdout); let err = String::from_utf8_lossy(&output.stderr); println!("=== stderr\n{}", err); $crate::Outcome::new(out,err.into_owned()) }}; } #[macro_export] macro_rules! nu_with_plugins { (cwd: $cwd:expr, $path:expr, $($part:expr),*) => {{ use $crate::fs::DisplayPath; let path = format!($path, $( $part.display_path() ),*); nu_with_plugins!($cwd, &path) }}; (cwd: $cwd:expr, $path:expr) => {{ nu_with_plugins!($cwd, $path) }}; ($cwd:expr, $path:expr) => {{ pub use std::error::Error; pub use std::io::prelude::*; pub use std::process::{Command, Stdio}; pub use crate::NATIVE_PATH_ENV_VAR; let commands = &*format!( " {} exit", $crate::fs::DisplayPath::display_path(&$path) ); let test_bins = $crate::fs::binaries(); let test_bins = nu_path::canonicalize(&test_bins).unwrap_or_else(|e| { panic!( "Couldn't canonicalize dummy binaries path {}: {:?}", test_bins.display(), e ) }); let mut paths = $crate::shell_os_paths(); paths.insert(0, test_bins); let paths_joined = match std::env::join_paths(paths) { Ok(all) => all, Err(_) => panic!("Couldn't join paths for PATH var."), }; let target_cwd = $crate::fs::in_directory(&$cwd); let mut process = match Command::new($crate::fs::executable_path()) .env("PWD", &target_cwd) // setting PWD is enough to set cwd .env(NATIVE_PATH_ENV_VAR, paths_joined) .stdout(Stdio::piped()) .stdin(Stdio::piped()) .stderr(Stdio::piped()) .spawn() { Ok(child) => child, Err(why) => panic!("Can't run test {}", why.to_string()), }; let stdin = process.stdin.as_mut().expect("couldn't open stdin"); stdin .write_all(commands.as_bytes()) .expect("couldn't write to stdin"); let output = process .wait_with_output() .expect("couldn't read from stdout/stderr"); let out = $crate::macros::read_std(&output.stdout); let err = String::from_utf8_lossy(&output.stderr); println!("=== stderr\n{}", err); $crate::Outcome::new(out,err.into_owned()) }}; } pub fn read_std(std: &[u8]) -> String
{ let out = String::from_utf8_lossy(std); let out = out.lines().collect::<Vec<_>>().join("\n"); let out = out.replace("\r\n", ""); out.replace('\n', "") }
test_rbf_kernel_grad.py
#!/usr/bin/env python3 import torch import unittest from gpytorch.kernels import RBFKernelGrad from gpytorch.test.base_kernel_test_case import BaseKernelTestCase class TestRBFKernelGrad(unittest.TestCase, BaseKernelTestCase): def create_kernel_no_ard(self, **kwargs): return RBFKernelGrad(**kwargs) def create_kernel_ard(self, num_dims, **kwargs): return RBFKernelGrad(ard_num_dims=num_dims, **kwargs) def test_kernel(self, cuda=False): a = torch.tensor([[[1, 2], [2, 4]]], dtype=torch.float) b = torch.tensor([[[1, 3], [0, 4]]], dtype=torch.float) actual = torch.tensor( [ [0.35321, 0, -0.73517, 0.0054977, 0.011443, -0.022886], [0, 0.73517, 0, -0.011443, -0.012374, 0.047633], [0.73517, 0, -0.79499, 0.022886, 0.047633, -0.083824], [0.12476, 0.25967, 0.25967, 0.015565, 0.064793, 0], [-0.25967, -0.2808, -0.54047, -0.064793, -0.23732, 0], [-0.25967, -0.54047, -0.2808, 0, 0, 0.032396], ] ) kernel = RBFKernelGrad() if cuda: a = a.cuda() b = b.cuda() actual = actual.cuda() kernel = kernel.cuda() res = kernel(a, b).evaluate() self.assertLess(torch.norm(res - actual), 1e-5) def test_kernel_cuda(self): if torch.cuda.is_available():
def test_kernel_batch(self): a = torch.tensor([[[1, 2, 3], [2, 4, 0]], [[-1, 1, 2], [2, 1, 4]]], dtype=torch.float) b = torch.tensor([[[1, 3, 1]], [[2, -1, 0]]], dtype=torch.float).repeat(1, 2, 1) kernel = RBFKernelGrad() res = kernel(a, b).evaluate() # Compute each batch separately actual = torch.zeros(2, 8, 8) actual[0, :, :] = kernel(a[0, :, :].squeeze(), b[0, :, :].squeeze()).evaluate() actual[1, :, :] = kernel(a[1, :, :].squeeze(), b[1, :, :].squeeze()).evaluate() self.assertLess(torch.norm(res - actual), 1e-5) def test_initialize_lengthscale(self): kernel = RBFKernelGrad() kernel.initialize(lengthscale=3.14) actual_value = torch.tensor(3.14).view_as(kernel.lengthscale) self.assertLess(torch.norm(kernel.lengthscale - actual_value), 1e-5) def test_initialize_lengthscale_batch(self): kernel = RBFKernelGrad(batch_shape=torch.Size([2])) ls_init = torch.tensor([3.14, 4.13]) kernel.initialize(lengthscale=ls_init) actual_value = ls_init.view_as(kernel.lengthscale) self.assertLess(torch.norm(kernel.lengthscale - actual_value), 1e-5) if __name__ == "__main__": unittest.main()
self.test_kernel(cuda=True)
config_test.go
package ffclient_test import ( "github.com/aws/aws-sdk-go/aws" "github.com/stretchr/testify/assert" "net/http" "reflect" "testing" "time" ffClient "github.com/thomaspoignant/go-feature-flag" ) func
(t *testing.T) { type fields struct { PollingInterval time.Duration Retriever ffClient.Retriever } tests := []struct { name string fields fields want string wantErr bool }{ { name: "File retriever", fields: fields{ PollingInterval: 3 * time.Second, Retriever: &ffClient.FileRetriever{Path: "file-example.yaml"}, }, want: "*ffclient.FileRetriever", wantErr: false, }, { name: "S3 retriever", fields: fields{ PollingInterval: 3 * time.Second, Retriever: &ffClient.S3Retriever{ Bucket: "tpoi-test", Item: "flag-config.yaml", AwsConfig: aws.Config{ Region: aws.String("eu-west-1"), }, }, }, want: "*ffclient.S3Retriever", wantErr: false, }, { name: "HTTP retriever", fields: fields{ PollingInterval: 3 * time.Second, Retriever: &ffClient.HTTPRetriever{ URL: "http://example.com/flag-config.yaml", Method: http.MethodGet, }, }, want: "*ffclient.HTTPRetriever", wantErr: false, }, { name: "Github retriever", fields: fields{ PollingInterval: 3 * time.Second, Retriever: &ffClient.GithubRetriever{ RepositorySlug: "thomaspoignant/go-feature-flag", FilePath: "testdata/flag-config.yaml", GithubToken: "XXX", }, }, // we should have a http retriever because Github retriever is using httpRetriever want: "*ffclient.GithubRetriever", wantErr: false, }, { name: "No retriever", fields: fields{ PollingInterval: 3 * time.Second, }, wantErr: true, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { c := &ffClient.Config{ PollingInterval: tt.fields.PollingInterval, Retriever: tt.fields.Retriever, } got, err := c.GetRetriever() assert.Equal(t, tt.wantErr, err != nil) if err == nil { assert.Equal(t, tt.want, reflect.ValueOf(got).Type().String()) } }) } }
TestConfig_GetRetriever
test_full_frame_model.py
# This file is part of spot_motion_monitor. # # Developed for LSST System Integration, Test and Commissioning. # # See the LICENSE file at the top-level directory of this distribution # for details of code ownership. # # Use of this source code is governed by a 3-clause BSD-style # license that can be found in the LICENSE file. import numpy as np import pytest from spot_motion_monitor.camera.gaussian_camera import GaussianCamera from spot_motion_monitor.models import FullFrameModel from spot_motion_monitor.utils import FrameRejected, TimeHandler class TestFullFrameModel(): def setup_class(cls): cls.model = FullFrameModel() cls.model.timeHandler = TimeHandler() def checkFrame(self, flux, maxAdc, comX, comY): return flux > 4000 and maxAdc > 130 and comX > 0 and comY > 0 def test_parametersAfterConstruction(self): assert self.model.sigmaScale == 5.0 assert self.model.minimumNumPixels == 10 assert self.model.timeHandler is not None def test_frameCalculations(self): # This test requires the generation of a CCD frame which will be # provided by the GaussianCamera camera = GaussianCamera() camera.seed = 1000 camera.startup() frame = camera.getFullFrame() info = self.model.calculateCentroid(frame) assert info.centerX == 288.47687644439395 assert info.centerY == 224.45394404821826 assert info.flux == 3235.9182163661176 assert info.maxAdc == 135.83703259361937 assert info.fwhm == 5.749039360993981 assert info.stdNoObjects is None def test_badFrameCalculation(self): frame = np.ones((480, 640)) with pytest.raises(FrameRejected): self.model.calculateCentroid(frame) def test_failedFrameCheck(self): # This test requires the generation of a CCD frame which will be
camera.startup() frame = camera.getFullFrame() with pytest.raises(FrameRejected): self.model.calculateCentroid(frame) self.model.frameCheck = None
# provided by the GaussianCamera self.model.frameCheck = self.checkFrame camera = GaussianCamera() camera.seed = 1000
iofs.go
// +build go1.16 package iofs import ( "errors" "fmt" "io" "io/fs" "path" "strconv" "github.com/golang-migrate/migrate/v4/source" ) type driver struct { PartialDriver } // New returns a new Driver from io/fs#FS and a relative path. func New(fsys fs.FS, path string) (source.Driver, error) { var i driver if err := i.Init(fsys, path); err != nil { return nil, fmt.Errorf("failed to init driver with path %s: %w", path, err) } return &i, nil } // Open is part of source.Driver interface implementation. // Open cannot be called on the iofs passthrough driver. func (d *driver) Open(url string) (source.Driver, error) { return nil, errors.New("Open() cannot be called on the iofs passthrough driver") } // PartialDriver is a helper service for creating new source drivers working with // io/fs.FS instances. It implements all source.Driver interface methods // except for Open(). New driver could embed this struct and add missing Open() // method. // // To prepare PartialDriver for use Init() function. type PartialDriver struct { migrations *source.Migrations fsys fs.FS path string } // Init prepares not initialized IoFS instance to read migrations from a // io/fs#FS instance and a relative path. func (d *PartialDriver) Init(fsys fs.FS, path string) error { entries, err := fs.ReadDir(fsys, path) if err != nil { return err } ms := source.NewMigrations() for _, e := range entries { if e.IsDir() { continue } m, err := source.DefaultParse(e.Name()) if err != nil { continue } file, err := e.Info() if err != nil { return err } if !ms.Append(m)
} d.fsys = fsys d.path = path d.migrations = ms return nil } // Close is part of source.Driver interface implementation. // Closes the file system if possible. func (d *PartialDriver) Close() error { c, ok := d.fsys.(io.Closer) if !ok { return nil } return c.Close() } // First is part of source.Driver interface implementation. func (d *PartialDriver) First() (version uint, err error) { if version, ok := d.migrations.First(); ok { return version, nil } return 0, &fs.PathError{ Op: "first", Path: d.path, Err: fs.ErrNotExist, } } // Prev is part of source.Driver interface implementation. func (d *PartialDriver) Prev(version uint) (prevVersion uint, err error) { if version, ok := d.migrations.Prev(version); ok { return version, nil } return 0, &fs.PathError{ Op: "prev for version " + strconv.FormatUint(uint64(version), 10), Path: d.path, Err: fs.ErrNotExist, } } // Next is part of source.Driver interface implementation. func (d *PartialDriver) Next(version uint) (nextVersion uint, err error) { if version, ok := d.migrations.Next(version); ok { return version, nil } return 0, &fs.PathError{ Op: "next for version " + strconv.FormatUint(uint64(version), 10), Path: d.path, Err: fs.ErrNotExist, } } // ReadUp is part of source.Driver interface implementation. func (d *PartialDriver) ReadUp(version uint) (r io.ReadCloser, identifier string, err error) { if m, ok := d.migrations.Up(version); ok { body, err := d.open(path.Join(d.path, m.Raw)) if err != nil { return nil, "", err } return body, m.Identifier, nil } return nil, "", &fs.PathError{ Op: "read up for version " + strconv.FormatUint(uint64(version), 10), Path: d.path, Err: fs.ErrNotExist, } } // ReadDown is part of source.Driver interface implementation. func (d *PartialDriver) ReadDown(version uint) (r io.ReadCloser, identifier string, err error) { if m, ok := d.migrations.Down(version); ok { body, err := d.open(path.Join(d.path, m.Raw)) if err != nil { return nil, "", err } return body, m.Identifier, nil } return nil, "", &fs.PathError{ Op: "read down for version " + strconv.FormatUint(uint64(version), 10), Path: d.path, Err: fs.ErrNotExist, } } func (d *PartialDriver) open(path string) (fs.File, error) { f, err := d.fsys.Open(path) if err == nil { return f, nil } // Some non-standard file systems may return errors that don't include the path, that // makes debugging harder. if !errors.As(err, new(*fs.PathError)) { err = &fs.PathError{ Op: "open", Path: path, Err: err, } } return nil, err }
{ return source.ErrDuplicateMigration{ Migration: *m, FileInfo: file, } }
runner_threading.py
import time import threading import traceback from queue import PriorityQueue from collections import defaultdict from qiskit import IBMQ, Aer, execute from qiskit.providers.ibmq import least_busy
from qiskit.tools.monitor import backend_overview, job_monitor from core import app def log(task_id, message): app.logger.info(f'{message}') logs[task_id].append(message) from core.algorithms.egcd import egcd from core.algorithms.bernvaz import bernvaz from core.algorithms.grover import grover from core.algorithms.grover_sudoku import grover_sudoku TASK_WORKERS_COUNT = 2 runner_functions = {'egcd': egcd, 'bernvaz': bernvaz, 'grover': grover, 'grover_sudoku': grover_sudoku, } task_id = 0 task_queue = PriorityQueue() task_results_queue = PriorityQueue() tasks = {} logs = defaultdict(list) worker_active_flag = threading.Event() worker_active_flag.set() task_worker_threads = [] def start_task_worker_threads(): for i in range(TASK_WORKERS_COUNT): task_worker_thread = threading.Thread(target=task_worker, args=(task_queue, task_results_queue, worker_active_flag), daemon=True) task_worker_thread.start() task_worker_threads.append(task_worker_thread) app.logger.info(f'RUNNER task_worker_threads: {task_worker_threads}') def run_algorithm(algorithm_id, run_values): priority = 1 global task_id task_id += 1 new_task = (priority, task_id, algorithm_id, run_values) tasks[task_id] = {'algorithm_id': algorithm_id, 'run_values': run_values, 'status': 'Running'} task_queue.put(new_task) app.logger.info(f'RUNNER new_task: {new_task}') app.logger.info(f'RUNNER task_queue.qsize: {task_queue.qsize()}') app.logger.info(f'RUNNER task_id: {task_id}') return task_id def task_worker(task_queue, task_results_queue, worker_active_flag): app.logger.info(f'RUNNER task_worker started') while True: time.sleep(1) if worker_active_flag.is_set() and not task_queue.empty(): pop_task = task_queue.get() priority, task_id, algorithm_id, run_values = pop_task app.logger.info(f'RUNNER pop_task: {pop_task}') app.logger.info(f'RUNNER task_queue.qsize: {task_queue.qsize()}') try: result = task_runner(task_id, algorithm_id, run_values) except Exception as exception: error_message = traceback.format_exc() log(task_id, error_message) tasks[task_id]['status'] = 'Failed' else: task_results_queue.put((task_id, result)) tasks[task_id]['result'] = result tasks[task_id]['status'] = 'Done' log(task_id, f'Result: {result}') app.logger.info(f'task_results_queue.qsize: {task_results_queue.qsize()}') app.logger.info(f'len(tasks): {len(tasks)}') # app.logger.info(f'RUNNER task_worker_threads: {task_worker_threads}') def task_runner(task_id, algorithm_id, run_values_multidict): run_values = dict(run_values_multidict) run_values['task_id'] = task_id runner_function = runner_functions[algorithm_id] run_mode = run_values.get('run_mode') app.logger.info(f'RUNNER run_mode: {run_mode}') app.logger.info(f'RUNNER run_values: {run_values}') app.logger.info(f'RUNNER runner_function: {runner_function}') if run_mode == 'classic': return runner_function(run_values) else: circuit = runner_function(run_values) qubit_count = circuit.num_qubits if run_mode == 'simulator': backend = Aer.get_backend('qasm_simulator') elif run_mode == 'quantum_device': qiskit_token = app.config.get('QISKIT_TOKEN') IBMQ.save_account(qiskit_token) if not IBMQ.active_account(): IBMQ.load_account() provider = IBMQ.get_provider() log(task_id, f'RUNNER provider: {provider}') log(task_id, f'RUNNER provider.backends(): {provider.backends()}') backend = get_least_busy_backend(provider, qubit_count) log(task_id, f'RUNNER backend: {backend}') job = execute(circuit, backend=backend, shots=1024) job_monitor(job, interval=0.5) result = job.result() counts = result.get_counts() log(task_id, f'RUNNER counts:') [log(task_id, f'{state}: {count}') for state, count in sorted(counts.items())] return {'Counts:': counts} def get_least_busy_backend(provider, qubit_count): backend_filter = lambda backend: (not backend.configuration().simulator and backend.configuration().n_qubits >= qubit_count and backend.status().operational==True) least_busy_backend = least_busy(provider.backends(filters=backend_filter)) return least_busy_backend
bs4-modal-item.component.ts
import { Component, TemplateFunction, ScopeBase } from "@ribajs/core"; import template from "./bs4-modal-item.component.html"; import { Modal } from "../../interfaces/index.js"; import { getElementFromEvent } from "@ribajs/utils/src/dom.js"; import { ModalService, EVENT_HIDDEN } from "../../services/modal.service.js"; import { Scope as Bs4NotificationContainerScope } from "../bs4-notification-container/bs4-notification-container.component.js"; interface Scope extends ScopeBase { iconUrl?: string; modal?: Modal; onHidden: Bs4ModalItemComponent["onHidden"]; dismiss: Bs4ModalItemComponent["dismiss"];
$parent?: any; $event?: CustomEvent; } export class Bs4ModalItemComponent extends Component { public static tagName = "bs4-modal-item"; public _debug = false; protected autobind = true; protected modalService?: ModalService; static get observedAttributes(): string[] { return ["modal", "index"]; } protected requiredAttributes(): string[] { return ["modal"]; } public scope: Scope = { onHidden: this.onHidden.bind(this), index: -1, dismiss: this.dismiss.bind(this), }; constructor() { super(); } protected connectedCallback() { super.connectedCallback(); this.init(Bs4ModalItemComponent.observedAttributes); } protected async afterBind() { this.initModalService(); await super.afterBind(); } protected initModalService() { const modal = this.scope.modal; const modalEl = this.firstElementChild as HTMLElement | null; if (modal && modalEl) { this.modalService = new ModalService(modalEl, { focus: modal.focus !== undefined ? modal.focus : ModalService.Default.focus, keyboard: modal.keyboard !== undefined ? modal.keyboard : ModalService.Default.keyboard, backdrop: modal.backdrop !== undefined ? modal.backdrop : ModalService.Default.backdrop, show: modal.show !== undefined ? modal.show : ModalService.Default.show, }); // Call onHidden on hidden event once modalEl.addEventListener(EVENT_HIDDEN, this.scope.onHidden, { once: true, }); // show modal using the modalservice this.modalService.show(this); } } // Can be called if modal should be removed public dismiss(event?: Event) { this.modalService?.hide(event); } // Remove modal from dom once shown public onHidden(event: Event, el?: HTMLElement) { if (!el) { el = getElementFromEvent(event); } const notificationContainer: Bs4NotificationContainerScope | null = this.scope.$parent?.$parent || null; if ( typeof notificationContainer?.onItemHide === "function" && this.scope.modal && el ) { notificationContainer.onItemHide( event, el, this.scope.index, this.scope.modal ); } } protected template(): ReturnType<TemplateFunction> { return template; } }
index: number;
controlled-filter-select.tsx
import * as React from 'react'; import { Fields, Operator, isStringOperators, isNumberOperators, isDateOperators, isBooleanOperators, Filter } from './model'; import { OperatorStringSelectProps, OperatorStringSelectProvidedProps } from './operator-components/string/operator-string-select'; import { OperatorNumberSelectProps, OperatorNumberSelectProvidedProps } from './operator-components/number/operator-number-select'; import { OperatorDateSelectProps, OperatorDateSelectProvidedProps } from './operator-components/date/operator-date-select'; import { OperatorBooleanSelectProps, OperatorBooleanSelectProvidedProps } from './operator-components/boolean/operator-boolean-select';
export interface ControlledFilterSelectProps<D, C> { context: C; fields: Fields<D>; filter: Filter | null; onFilterChange: (filter: Filter) => void; stringSelectComponent: React.ComponentType<Pick<OperatorStringSelectProps<C>, Exclude<keyof OperatorStringSelectProps<C>, OperatorStringSelectProvidedProps>>>; numberSelectComponent: React.ComponentType<Pick<OperatorNumberSelectProps<C>, Exclude<keyof OperatorNumberSelectProps<C>, OperatorNumberSelectProvidedProps>>>; dateSelectComponent: React.ComponentType<Pick<OperatorDateSelectProps<C>, Exclude<keyof OperatorDateSelectProps<C>, OperatorDateSelectProvidedProps>>>; booleanSelectComponent: React.ComponentType<Pick<OperatorBooleanSelectProps<C>, Exclude<keyof OperatorBooleanSelectProps<C>, OperatorBooleanSelectProvidedProps>>>; } export type ControlledFilterSelectProvidedProps = 'stringSelectComponent' | 'numberSelectComponent' | 'dateSelectComponent' | 'booleanSelectComponent'; export class ControlledFilterSelect<D, C> extends React.PureComponent<ControlledFilterSelectProps<D, C>, never> { renderStringSelect(filter: Filter) { if (isStringOperators(filter.operator)) { return <this.props.stringSelectComponent context={this.props.context} operator={filter.operator} onOperatorChange={(operator) => this.props.onFilterChange({ ...filter, operator })} />; } } renderNumberSelect(filter: Filter) { if (isNumberOperators(filter.operator)) { return <this.props.numberSelectComponent context={this.props.context} operator={filter.operator} onOperatorChange={(operator) => this.props.onFilterChange({ ...filter, operator })} />; } } renderDateSelect(filter: Filter) { if (isDateOperators(filter.operator)) { return <this.props.dateSelectComponent context={this.props.context} operator={filter.operator} onOperatorChange={(operator) => this.props.onFilterChange({ ...filter, operator })} />; } } renderBooleanSelect(filter: Filter) { if (isBooleanOperators(filter.operator)) { return <this.props.booleanSelectComponent context={this.props.context} operator={filter.operator} onOperatorChange={(operator) => this.props.onFilterChange({ ...filter, operator })} />; } } renderOperatorSelect() { if (this.props.filter !== null) { switch (this.props.fields[this.props.filter.id].type) { case 'string': return this.renderStringSelect(this.props.filter); case 'number': return this.renderNumberSelect(this.props.filter); case 'boolean': return this.renderBooleanSelect(this.props.filter); case 'date': return this.renderDateSelect(this.props.filter); } } } getDefaultOperator(id: string): Operator { switch (this.props.fields[id].type) { case 'string': return { type: 'string-equals', value: '' }; case 'number': return { type: 'number-equals', value: 0 }; case 'boolean': return { type: 'boolean-equals', value: true }; case 'date': return { type: 'date-equals', value: Date.now() }; } } render() { return <React.Fragment> <select value={this.props.filter === null ? '' : this.props.filter.id} onChange={(event) => this.props.onFilterChange({ id: event.currentTarget.value, operator: this.getDefaultOperator(event.currentTarget.value) })} > <option value="" disabled>Select field</option> {Object.keys(this.props.fields).map((key) => <option key={key} value={key}>{this.props.fields[key].label}</option> )} </select> {this.renderOperatorSelect()} </React.Fragment>; } }
add.py
def add(x,y): return x+y
bitcoin_es.ts
<TS language="es" version="2.1"> <context> <name>AddressBookPage</name> <message> <source>Right-click to edit address or label</source> <translation>Clic derecho para editar la dirección o etiqueta</translation> </message> <message> <source>Create a new address</source> <translation>Crear una nueva dirección</translation> </message> <message> <source>&amp;New</source> <translation>&amp;Nuevo</translation> </message> <message> <source>Copy the currently selected address to the system clipboard</source> <translation>Copiar la dirección seleccionada al portapapeles del sistema</translation> </message> <message> <source>&amp;Copy</source> <translation>&amp;Copiar</translation> </message> <message> <source>C&amp;lose</source> <translation>C&amp;errar</translation> </message> <message> <source>Delete the currently selected address from the list</source> <translation>Eliminar la dirección seleccionada de la lista</translation> </message> <message> <source>Enter address or label to search</source> <translation>Introduzca una dirección o etiqueta que buscar</translation> </message> <message> <source>Export the data in the current tab to a file</source> <translation>Exportar los datos en la ficha actual a un archivo</translation> </message> <message> <source>&amp;Export</source> <translation>&amp;Exportar</translation> </message> <message> <source>&amp;Delete</source> <translation>&amp;Eliminar</translation> </message> <message> <source>Choose the address to send coins to</source> <translation>Seleccione la dirección a la que enviar monedas</translation> </message> <message> <source>Choose the address to receive coins with</source> <translation>Seleccione la dirección de la que recibir monedas</translation> </message> <message> <source>C&amp;hoose</source> <translation>E&amp;scoger</translation> </message> <message> <source>Sending addresses</source> <translation>Direcciones de envío</translation> </message> <message> <source>Receiving addresses</source> <translation>Direcciones de recepción</translation> </message> <message> <source>These are your Nexalt addresses for sending payments. Always check the amount and the receiving address before sending coins.</source> <translation>Estas son sus direcciones Nexalt para enviar pagos. Verifique siempre la cantidad y la dirección de recepción antes de enviar nexalts.</translation> </message> <message> <source>These are your Nexalt addresses for receiving payments. It is recommended to use a new receiving address for each transaction.</source> <translation>Estas son sus direcciones Nexalt para recibir pagos. Se recomienda utilizar una nueva dirección de recepción para cada transacción</translation> </message> <message> <source>&amp;Copy Address</source> <translation>&amp;Copiar Dirección</translation> </message> <message> <source>Copy &amp;Label</source> <translation>Copiar &amp;Etiqueta</translation> </message> <message> <source>&amp;Edit</source> <translation>&amp;Editar</translation> </message> <message> <source>Export Address List</source> <translation>Exportar lista de direcciones</translation> </message> <message> <source>Comma separated file (*.csv)</source> <translation>Archivo separado de coma (*.csv)</translation> </message> <message> <source>Exporting Failed</source> <translation>Falló la exportación</translation> </message> <message> <source>There was an error trying to save the address list to %1. Please try again.</source> <translation>Había un error intentando guardar la lista de direcciones en %1. Por favor inténtelo de nuevo.</translation> </message> </context> <context> <name>AddressTableModel</name> <message> <source>Label</source> <translation>Etiqueta</translation> </message> <message> <source>Address</source> <translation>Dirección</translation> </message> <message> <source>(no label)</source> <translation>(sin etiqueta)</translation> </message> </context> <context> <name>AskPassphraseDialog</name> <message> <source>Passphrase Dialog</source> <translation>Diálogo de contraseña</translation> </message> <message> <source>Enter passphrase</source> <translation>Introducir contraseña</translation> </message> <message> <source>New passphrase</source> <translation>Nueva contraseña</translation> </message> <message> <source>Repeat new passphrase</source> <translation>Repita la nueva contraseña</translation> </message> <message> <source>Show password</source> <translation>Mostrar contraseña</translation> </message> <message> <source>Enter the new passphrase to the wallet.&lt;br/&gt;Please use a passphrase of &lt;b&gt;ten or more random characters&lt;/b&gt;, or &lt;b&gt;eight or more words&lt;/b&gt;.</source> <translation>Introduzca la nueva contraseña del monedero. &lt;br/&gt;Por favor utilice una contraseña de &lt;b&gt;diez o más carácteres aleatorios&lt;/b&gt;, o &lt;b&gt;ocho o más palabras&lt;/b&gt;.</translation> </message> <message> <source>Encrypt wallet</source> <translation>Cifrar monedero</translation> </message> <message> <source>This operation needs your wallet passphrase to unlock the wallet.</source> <translation>Esta operación necesita su contraseña de monedero para desbloquear el monedero.</translation> </message> <message> <source>Unlock wallet</source> <translation>Desbloquear monedero</translation> </message> <message> <source>This operation needs your wallet passphrase to decrypt the wallet.</source> <translation>Esta operación necesita su contraseña para descifrar el monedero.</translation> </message> <message> <source>Decrypt wallet</source> <translation>Descifrar monedero</translation> </message> <message> <source>Change passphrase</source> <translation>Cambiar contraseña</translation> </message> <message> <source>Enter the old passphrase and new passphrase to the wallet.</source> <translation>Introduzca la contraseña antigua y la nueva para el monedero.</translation> </message> <message> <source>Confirm wallet encryption</source> <translation>Confirmar cifrado del monedero</translation> </message> <message> <source>Warning: If you encrypt your wallet and lose your passphrase, you will &lt;b&gt;LOSE ALL OF YOUR NEXALTS&lt;/b&gt;!</source> <translation>Advertencia: Si cifra su monedero y pierde su contraseña&lt;b&gt;¡PERDERÁ TODOS SUS NEXALTS!&lt;/b&gt;</translation> </message> <message> <source>Are you sure you wish to encrypt your wallet?</source> <translation>¿Seguro que desea cifrar su monedero?</translation> </message> <message> <source>Wallet encrypted</source> <translation>Monedero cifrado</translation> </message> <message> <source>Your wallet is now encrypted. Remember that encrypting your wallet cannot fully protect your nexalts from being stolen by malware infecting your computer.</source> <translation>Monedero encriptado. Recuerda que encriptando tu monedero no garantiza mantener a salvo tus nexalts en caso de tener viruses en el ordenador.</translation> </message> <message> <source>IMPORTANT: Any previous backups you have made of your wallet file should be replaced with the newly generated, encrypted wallet file. For security reasons, previous backups of the unencrypted wallet file will become useless as soon as you start using the new, encrypted wallet.</source> <translation>IMPORTANTE: Cualquier copia de seguridad anterior que haya hecho en su archivo de monedero debería ser reemplazada con el archivo de monedero cifrado generado recientemente. Por razones de seguridad, las copias de seguridad anteriores del archivo de monedero descifrado serán inútiles en cuanto empiece a utilizar el nuevo monedero cifrado.</translation> </message> <message> <source>Wallet encryption failed</source> <translation>Fracasó el cifrado del monedero</translation> </message> <message> <source>Wallet encryption failed due to an internal error. Your wallet was not encrypted.</source> <translation>Falló el cifrado del monedero debido a un error interno. Su monedero no fue cifrado.</translation> </message> <message> <source>The supplied passphrases do not match.</source> <translation>La contraseña introducida no coincide.</translation> </message> <message> <source>Wallet unlock failed</source> <translation>Fracasó el desbloqueo del monedero</translation> </message> <message> <source>The passphrase entered for the wallet decryption was incorrect.</source> <translation>La contraseña introducida para el cifrado del monedero es incorrecta.</translation> </message> <message> <source>Wallet decryption failed</source> <translation>Fracasó el cifrado del monedero</translation> </message> <message> <source>Wallet passphrase was successfully changed.</source> <translation>La contraseña del monedero se ha cambiado con éxito.</translation> </message> <message> <source>Warning: The Caps Lock key is on!</source> <translation>Alerta: ¡La clave de bloqueo Caps está activa!</translation> </message> </context> <context> <name>BanTableModel</name> <message> <source>IP/Netmask</source> <translation>IP/Máscara</translation> </message> <message> <source>Banned Until</source> <translation>Bloqueado Hasta</translation> </message> </context> <context> <name>BitcoinGUI</name> <message> <source>Sign &amp;message...</source> <translation>Firmar &amp;mensaje...</translation> </message> <message> <source>Synchronizing with network...</source> <translation>Sincronizando con la red…</translation> </message> <message> <source>&amp;Overview</source> <translation>&amp;Vista general</translation> </message> <message> <source>Show general overview of wallet</source> <translation>Mostrar vista general del monedero</translation> </message> <message> <source>&amp;Transactions</source> <translation>&amp;Transacciones</translation> </message> <message> <source>Browse transaction history</source> <translation>Examinar el historial de transacciones</translation> </message> <message> <source>E&amp;xit</source> <translation>S&amp;alir</translation> </message> <message> <source>Quit application</source> <translation>Salir de la aplicación</translation> </message> <message> <source>&amp;About %1</source> <translation>&amp;Acerca de %1</translation> </message> <message> <source>Show information about %1</source> <translation>Mostrar información acerca de %1</translation> </message> <message> <source>About &amp;Qt</source> <translation>Acerca de &amp;Qt</translation> </message> <message> <source>Show information about Qt</source> <translation>Mostrar información acerca de Qt</translation> </message> <message> <source>&amp;Options...</source> <translation>&amp;Opciones...</translation> </message> <message> <source>Modify configuration options for %1</source> <translation>Modificar las opciones de configuración para %1</translation> </message> <message> <source>&amp;Encrypt Wallet...</source> <translation>&amp;Cifrar monedero…</translation> </message> <message> <source>&amp;Backup Wallet...</source> <translation>&amp;Guardar copia del monedero...</translation> </message> <message> <source>&amp;Change Passphrase...</source> <translation>&amp;Cambiar la contraseña…</translation> </message> <message> <source>Open &amp;URI...</source> <translation>Abrir &amp;URI...</translation> </message> <message> <source>Wallet:</source> <translation>Monedero</translation> </message> <message> <source>Click to disable network activity.</source> <translation>Pulsar para deshabilitar la actividad de red.</translation> </message> <message> <source>Network activity disabled.</source> <translation>Actividad de red deshabilitada.</translation> </message> <message> <source>Click to enable network activity again.</source> <translation>Pulsar para volver a habilitar la actividad de red.</translation> </message> <message> <source>Syncing Headers (%1%)...</source> <translation>Sincronizando cabeceras (%1%)</translation> </message> <message> <source>Reindexing blocks on disk...</source> <translation>Reindexando bloques en disco...</translation> </message> <message> <source>Proxy is &lt;b&gt;enabled&lt;/b&gt;: %1</source> <translation>Proxy está&lt;b&gt;habilitado&lt;/b&gt;: %1</translation> </message> <message> <source>Send coins to a Nexalt address</source> <translation>Enviar nexalts a una dirección Nexalt</translation> </message> <message> <source>Backup wallet to another location</source> <translation>Copia de seguridad del monedero en otra ubicación</translation> </message> <message> <source>Change the passphrase used for wallet encryption</source> <translation>Cambiar la contraseña utilizada para el cifrado del monedero</translation> </message> <message> <source>&amp;Debug window</source> <translation>&amp;Ventana de depuración</translation> </message> <message> <source>Open debugging and diagnostic console</source> <translation>Abrir la consola de depuración y diagnóstico</translation> </message> <message> <source>&amp;Verify message...</source> <translation>&amp;Verificar mensaje...</translation> </message> <message> <source>Nexalt</source> <translation>Nexalt</translation> </message> <message> <source>&amp;Send</source> <translation>&amp;Enviar</translation> </message> <message> <source>&amp;Receive</source> <translation>&amp;Recibir</translation> </message> <message> <source>&amp;Show / Hide</source> <translation>&amp;Mostrar / Ocultar</translation> </message> <message> <source>Show or hide the main Window</source> <translation>Mostrar u ocultar la ventana principal</translation> </message> <message> <source>Encrypt the private keys that belong to your wallet</source> <translation>Cifrar las claves privadas de su monedero</translation> </message> <message> <source>Sign messages with your Nexalt addresses to prove you own them</source> <translation>Firmar mensajes con sus direcciones Nexalt para demostrar la propiedad</translation> </message> <message> <source>Verify messages to ensure they were signed with specified Nexalt addresses</source> <translation>Verificar mensajes comprobando que están firmados con direcciones Nexalt concretas</translation> </message> <message> <source>&amp;File</source> <translation>&amp;Archivo</translation> </message> <message> <source>&amp;Settings</source> <translation>&amp;Configuración</translation> </message> <message> <source>&amp;Help</source> <translation>&amp;Ayuda</translation> </message> <message> <source>Tabs toolbar</source> <translation>Barra de pestañas</translation> </message> <message> <source>Request payments (generates QR codes and nexalt: URIs)</source> <translation>Solicitar pagos (generando códigos QR e identificadores URI "nexalt:")</translation> </message> <message> <source>Show the list of used sending addresses and labels</source> <translation>Mostrar la lista de direcciones de envío y etiquetas</translation> </message> <message> <source>Show the list of used receiving addresses and labels</source> <translation>Muestra la lista de direcciones de recepción y etiquetas</translation> </message> <message> <source>Open a nexalt: URI or payment request</source> <translation>Abrir un identificador URI "nexalt:" o una petición de pago</translation> </message> <message> <source>&amp;Command-line options</source> <translation>&amp;Opciones de consola de comandos</translation> </message> <message numerus="yes"> <source>%n active connection(s) to Nexalt network</source> <translation><numerusform>%n conexión activa hacia la red Nexalt</numerusform><numerusform>%n conexiones activas hacia la red Nexalt</numerusform></translation> </message> <message> <source>Indexing blocks on disk...</source> <translation>Indexando bloques en disco...</translation> </message> <message> <source>Processing blocks on disk...</source> <translation>Procesando bloques en disco...</translation> </message> <message numerus="yes"> <source>Processed %n block(s) of transaction history.</source> <translation><numerusform>%n bloque procesado del historial de transacciones.</numerusform><numerusform>%n bloques procesados del historial de transacciones.</numerusform></translation> </message> <message> <source>%1 behind</source> <translation>%1 atrás</translation> </message> <message> <source>Last received block was generated %1 ago.</source> <translation>El último bloque recibido fue generado hace %1.</translation> </message> <message> <source>Transactions after this will not yet be visible.</source> <translation>Las transacciones posteriores aún no están visibles.</translation> </message> <message> <source>Error</source> <translation>Error</translation> </message> <message> <source>Warning</source> <translation>Aviso</translation> </message> <message> <source>Information</source> <translation>Información</translation> </message> <message> <source>Up to date</source> <translation>Actualizado</translation> </message> <message> <source>&amp;Sending addresses</source> <translation>Direcciones de &amp;envío</translation> </message> <message> <source>&amp;Receiving addresses</source> <translation>Direcciones de &amp;recepción</translation> </message> <message> <source>Open Wallet</source> <translation>Abrir Monedero</translation> </message> <message> <source>Open a wallet</source> <translation>Abrir un monedero</translation> </message> <message> <source>Close Wallet...</source> <translation>Cerrar Monedero...</translation> </message> <message> <source>Close wallet</source> <translation>Cerrar monedero</translation> </message> <message> <source>Show the %1 help message to get a list with possible Nexalt command-line options</source> <translation>Mostrar el mensaje de ayuda %1 para obtener una lista de los posibles comandos de linea de comandos de Nexalt</translation> </message> <message> <source>default wallet</source> <translation>Monedero predeterminado</translation> </message> <message> <source>Opening Wallet &lt;b&gt;%1&lt;/b&gt;...</source> <translation>Abriendo monedero &lt;b&gt;%1&lt;/b&gt;...</translation> </message> <message> <source>Open Wallet Failed</source> <translation>Fallo al abrir monedero</translation> </message> <message> <source>&amp;Window</source> <translation>&amp;Ventana</translation> </message> <message> <source>Minimize</source> <translation>Minimizar</translation> </message> <message> <source>Zoom</source> <translation>Acercar</translation> </message> <message> <source>Restore</source> <translation>Restaurar</translation> </message> <message> <source>Main Window</source> <translation>Ventana principal</translation> </message> <message> <source>%1 client</source> <translation>%1 cliente</translation> </message> <message> <source>Connecting to peers...</source> <translation>Conectando a pares...</translation> </message> <message> <source>Catching up...</source> <translation>Actualizando...</translation> </message> <message> <source>Date: %1 </source> <translation>Fecha: %1 </translation> </message> <message> <source>Amount: %1 </source> <translation>Amount: %1 </translation> </message> <message> <source>Wallet: %1 </source> <translation>Monedero: %1</translation> </message> <message> <source>Type: %1 </source> <translation>Tipo: %1 </translation> </message> <message> <source>Label: %1 </source> <translation>Etiqueta: %1 </translation> </message> <message> <source>Address: %1 </source> <translation>Dirección: %1 </translation> </message> <message> <source>Sent transaction</source> <translation>Transacción enviada</translation> </message> <message> <source>Incoming transaction</source> <translation>Transacción entrante</translation> </message> <message> <source>HD key generation is &lt;b&gt;enabled&lt;/b&gt;</source> <translation>La generación de clave HD está &lt;b&gt;habilitada&lt;/b&gt;</translation> </message> <message> <source>HD key generation is &lt;b&gt;disabled&lt;/b&gt;</source> <translation>La generación de clave HD está &lt;b&gt;deshabilitada&lt;/b&gt;</translation> </message> <message> <source>Private key &lt;b&gt;disabled&lt;/b&gt;</source> <translation>Clave privada &lt;b&gt;deshabilitado&lt;/b&gt;</translation> </message> <message> <source>Wallet is &lt;b&gt;encrypted&lt;/b&gt; and currently &lt;b&gt;unlocked&lt;/b&gt;</source> <translation>El monedero está &lt;b&gt;cifrado&lt;/b&gt; y actualmente &lt;b&gt;desbloqueado&lt;/b&gt;</translation> </message> <message> <source>Wallet is &lt;b&gt;encrypted&lt;/b&gt; and currently &lt;b&gt;locked&lt;/b&gt;</source> <translation>El monedero está &lt;b&gt;cifrado&lt;/b&gt; y actualmente &lt;b&gt;bloqueado&lt;/b&gt;</translation> </message> <message> <source>A fatal error occurred. Nexalt can no longer continue safely and will quit.</source> <translation>Ha ocurrido un error fatal. Nexalt no puede seguir seguro y se cerrará.</translation> </message> </context> <context> <name>CoinControlDialog</name> <message> <source>Coin Selection</source> <translation>Selección de la moneda</translation> </message> <message> <source>Quantity:</source> <translation>Cantidad:</translation> </message> <message> <source>Bytes:</source> <translation>Bytes:</translation> </message> <message> <source>Amount:</source> <translation>Cuantía:</translation> </message> <message> <source>Fee:</source> <translation>Comisión:</translation> </message> <message> <source>Dust:</source> <translation>Polvo:</translation> </message> <message> <source>After Fee:</source> <translation>Después de aplicar la comisión:</translation> </message> <message> <source>Change:</source> <translation>Cambio:</translation> </message> <message> <source>(un)select all</source> <translation>(des)marcar todos</translation> </message> <message> <source>Tree mode</source> <translation>Modo árbol</translation> </message> <message> <source>List mode</source> <translation>Modo lista</translation> </message> <message> <source>Amount</source> <translation>Cantidad</translation> </message> <message> <source>Received with label</source> <translation>Recibido con etiqueta</translation> </message> <message> <source>Received with address</source> <translation>Recibido con dirección</translation> </message> <message> <source>Date</source> <translation>Fecha</translation> </message> <message> <source>Confirmations</source> <translation>Confirmaciones</translation> </message> <message> <source>Confirmed</source> <translation>Confirmado</translation> </message> <message> <source>Copy address</source> <translation>Copiar ubicación</translation> </message> <message> <source>Copy label</source> <translation>Copiar etiqueta</translation> </message> <message> <source>Copy amount</source> <translation>Copiar cantidad</translation> </message> <message> <source>Copy transaction ID</source> <translation>Copiar ID de transacción</translation> </message> <message> <source>Lock unspent</source> <translation>Bloquear lo no gastado</translation> </message> <message> <source>Unlock unspent</source> <translation>Desbloquear lo no gastado</translation> </message> <message> <source>Copy quantity</source> <translation>Copiar cantidad</translation> </message> <message> <source>Copy fee</source> <translation>Copiar comisión</translation> </message> <message> <source>Copy after fee</source> <translation>Copiar después de comisión</translation> </message> <message> <source>Copy bytes</source> <translation>Copiar bytes</translation> </message> <message> <source>Copy dust</source> <translation>Copiar polvo</translation> </message> <message> <source>Copy change</source> <translation>Copiar cambio</translation> </message> <message> <source>(%1 locked)</source> <translation>(%1 bloqueado)</translation> </message> <message> <source>yes</source> <translation>sí</translation> </message> <message> <source>no</source> <translation>no</translation> </message> <message> <source>This label turns red if any recipient receives an amount smaller than the current dust threshold.</source> <translation>Esta etiqueta se vuelve roja si algún destinatario recibe una cantidad inferior al actual umbral de polvo.</translation> </message> <message> <source>Can vary +/- %1 satoshi(s) per input.</source> <translation>Puede variar +/- %1 satoshi(s) por entrada.</translation> </message> <message> <source>(no label)</source> <translation>(sin etiqueta)</translation> </message> <message> <source>change from %1 (%2)</source> <translation>cambia desde %1 (%2)</translation> </message> <message> <source>(change)</source> <translation>(cambio)</translation> </message> </context> <context> <name>EditAddressDialog</name> <message> <source>Edit Address</source> <translation>Editar Dirección</translation> </message> <message> <source>&amp;Label</source> <translation>&amp;Etiqueta</translation> </message> <message> <source>The label associated with this address list entry</source> <translation>La etiqueta asociada con esta entrada de la lista de direcciones</translation> </message> <message> <source>The address associated with this address list entry. This can only be modified for sending addresses.</source> <translation>La dirección asociada con esta entrada de la lista de direcciones. Solo puede ser modificada para direcciones de envío.</translation> </message> <message> <source>&amp;Address</source> <translation>&amp;Dirección</translation> </message> <message> <source>New sending address</source> <translation>Nueva dirección de envío</translation> </message> <message> <source>Edit receiving address</source> <translation>Editar dirección de recepción</translation> </message> <message> <source>Edit sending address</source> <translation>Editar dirección de envío</translation> </message> <message> <source>The entered address "%1" is not a valid Nexalt address.</source> <translation>La dirección introducida "%1" no es una dirección Nexalt válida.</translation> </message> <message> <source>Address "%1" already exists as a receiving address with label "%2" and so cannot be added as a sending address.</source> <translation>La dirección "%1" ya existe como dirección de recepción con la etiqueta "%2" y, por lo tanto, no se puede agregar como dirección de envío.</translation> </message> <message> <source>The entered address "%1" is already in the address book with label "%2".</source> <translation>La dirección ingresada "%1" ya está en la libreta de direcciones con la etiqueta "%2".</translation> </message> <message> <source>Could not unlock wallet.</source> <translation>No se pudo desbloquear el monedero.</translation> </message> <message> <source>New key generation failed.</source> <translation>Falló la generación de la nueva clave.</translation> </message> </context> <context> <name>FreespaceChecker</name> <message> <source>A new data directory will be created.</source> <translation>Se creará un nuevo directorio de datos.</translation> </message> <message> <source>name</source> <translation>nombre</translation> </message> <message> <source>Directory already exists. Add %1 if you intend to create a new directory here.</source> <translation>El directorio ya existe. Añada %1 si pretende crear un directorio nuevo.</translation> </message> <message> <source>Path already exists, and is not a directory.</source> <translation>La ruta ya existe y no es un directorio.</translation> </message> <message> <source>Cannot create data directory here.</source> <translation>No se puede crear un directorio de datos aquí.</translation> </message> </context> <context> <name>HelpMessageDialog</name> <message> <source>version</source> <translation>versión</translation> </message> <message> <source>(%1-bit)</source> <translation>(%1-bit)</translation> </message> <message> <source>About %1</source> <translation>Acerca de %1</translation> </message> <message> <source>Command-line options</source> <translation>Opciones de la línea de comandos</translation> </message> </context> <context> <name>Intro</name> <message> <source>Welcome</source> <translation>Bienvenido</translation> </message> <message> <source>Welcome to %1.</source> <translation>Bienvenido a %1</translation> </message> <message> <source>As this is the first time the program is launched, you can choose where %1 will store its data.</source> <translation>Al ser la primera vez que se ejecuta el programa, puede elegir dónde %1 almacenará sus datos.</translation> </message> <message> <source>When you click OK, %1 will begin to download and process the full %4 block chain (%2GB) starting with the earliest transactions in %3 when %4 initially launched.</source> <translation>Cuando haga click en OK, %1 se empezará a descargar la %4 cadena de bloques completa (%2GB) empezando por la transacción más antigua en %3 cuando se publicó %4 originalmente.</translation> </message> <message> <source>This initial synchronisation is very demanding, and may expose hardware problems with your computer that had previously gone unnoticed. Each time you run %1, it will continue downloading where it left off.</source> <translation>La sincronización inicial demanda muchos recursos y podría revelar problemas de hardware que no se han notado previamente. Cada vez que ejecuta %1, continuará descargando a partir del punto anterior.</translation> </message> <message> <source>If you have chosen to limit block chain storage (pruning), the historical data must still be downloaded and processed, but will be deleted afterward to keep your disk usage low.</source> <translation>Si ha elegido limitar el almacenamiento de la cadena de bloques ("prunning"), se descargarán y procesarán los datos históricos igualmente, sin embargo, estos se eliminarán después para mantener un bajo uso del disco.</translation> </message> <message> <source>Use the default data directory</source> <translation>Utilizar el directorio de datos predeterminado</translation> </message> <message> <source>Use a custom data directory:</source> <translation>Utilizar un directorio de datos personalizado:</translation> </message> <message> <source>Nexalt</source> <translation>Nexalt</translation> </message> <message> <source>At least %1 GB of data will be stored in this directory, and it will grow over time.</source> <translation>Se almacenará cuanto menos %1 GB de datos en este directorio, y crecerá con el transcurso del tiempo.</translation> </message> <message> <source>Approximately %1 GB of data will be stored in this directory.</source> <translation>Se almacenará aproximadamente %1 GB de datos en este directorio.</translation> </message> <message> <source>%1 will download and store a copy of the Nexalt block chain.</source> <translation>%1 descargará y almacenará una copia de la cadena de bloques de Nexalt.</translation> </message> <message> <source>The wallet will also be stored in this directory.</source> <translation>El monedero se almacenará en este directorio.</translation> </message> <message> <source>Error: Specified data directory "%1" cannot be created.</source> <translation>Error: no ha podido crearse el directorio de datos especificado "%1".</translation> </message> <message> <source>Error</source> <translation>Error</translation> </message> <message numerus="yes"> <source>%n GB of free space available</source> <translation><numerusform>%n GB de espacio libre</numerusform><numerusform>%n GB de espacio disponible</numerusform></translation> </message> <message numerus="yes"> <source>(of %n GB needed)</source> <translation><numerusform>(de %n GB necesitados)</numerusform><numerusform>(de %n GB requeridos)</numerusform></translation> </message> </context> <context> <name>ModalOverlay</name> <message> <source>Form</source> <translation>Formulario</translation> </message> <message> <source>Recent transactions may not yet be visible, and therefore your wallet's balance might be incorrect. This information will be correct once your wallet has finished synchronizing with the nexalt network, as detailed below.</source> <translation>Las transacciones recientes aún no pueden ser visibles, y por lo tanto el saldo de su monedero podría ser incorrecto. Esta información será correcta cuando su monedero haya terminado de sincronizarse con la red de nexalt, como se detalla abajo.</translation> </message> <message> <source>Attempting to spend nexalts that are affected by not-yet-displayed transactions will not be accepted by the network.</source> <translation>La red no aceptará el intentar gastar nexalts que están afectados por transacciones aún no mostradas.</translation> </message> <message> <source>Number of blocks left</source> <translation>Número de bloques restantes</translation> </message> <message> <source>Unknown...</source> <translation>Desconocido...</translation> </message> <message> <source>Last block time</source> <translation>Hora del último bloque</translation> </message> <message> <source>Progress</source> <translation>Progreso</translation> </message> <message> <source>Progress increase per hour</source> <translation>Avance del progreso por hora</translation> </message> <message> <source>calculating...</source> <translation>calculando...</translation> </message> <message> <source>Estimated time left until synced</source> <translation>Tiempo estimado restante hasta la sincronización</translation> </message> <message> <source>Hide</source> <translation>Ocultar</translation> </message> <message> <source>Unknown. Syncing Headers (%1, %2%)...</source> <translation>Desconocido. Sincronizando Cabeceras (%1, %2%)...</translation> </message> </context> <context> <name>OpenURIDialog</name> <message> <source>Open URI</source> <translation>Abrir URI</translation> </message> <message> <source>Open payment request from URI or file</source> <translation>Abrir solicitud de pago a partir de un identificador URI o de un archivo</translation> </message> <message> <source>URI:</source> <translation>URI:</translation> </message> <message> <source>Select payment request file</source> <translation>Seleccionar archivo de solicitud de pago</translation> </message> <message> <source>Select payment request file to open</source> <translation>Seleccionar el archivo de solicitud de pago para abrir</translation> </message> </context> <context> <name>OptionsDialog</name> <message> <source>Options</source> <translation>Opciones</translation> </message> <message> <source>&amp;Main</source> <translation>&amp;Principal</translation> </message> <message> <source>Automatically start %1 after logging in to the system.</source> <translation>Iniciar automaticamente %1 al encender el sistema.</translation> </message> <message> <source>&amp;Start %1 on system login</source> <translation>&amp;Iniciar %1 al iniciar el sistema</translation> </message> <message> <source>Size of &amp;database cache</source> <translation>Tamaño del cache de la &amp;base de datos</translation> </message> <message> <source>Number of script &amp;verification threads</source> <translation>Número de hilos de &amp;verificación de scripts</translation> </message> <message> <source>IP address of the proxy (e.g. IPv4: 127.0.0.1 / IPv6: ::1)</source> <translation>Dirección IP del proxy (p. ej. IPv4: 127.0.0.1 / IPv6: ::1)</translation> </message> <message> <source>Shows if the supplied default SOCKS5 proxy is used to reach peers via this network type.</source> <translation>Muestra si el proxy SOCKS5 predeterminado se utiliza para conectarse a pares a través de este tipo de red.</translation> </message> <message> <source>Use separate SOCKS&amp;5 proxy to reach peers via Tor hidden services:</source> <translation>Usar proxy SOCKS&amp;5 para alcanzar nodos via servicios ocultos Tor:</translation> </message> <message> <source>Hide the icon from the system tray.</source> <translation>Ocultar ícono de la bandeja de sistema.</translation> </message> <message> <source>&amp;Hide tray icon</source> <translation>&amp;Ocultar ícono de la barra de tareas</translation> </message> <message> <source>Minimize instead of exit the application when the window is closed. When this option is enabled, the application will be closed only after selecting Exit in the menu.</source> <translation>Minimizar en lugar de salir de la aplicación cuando la ventana está cerrada. Cuando se activa esta opción, la aplicación sólo se cerrará después de seleccionar Salir en el menú.</translation> </message> <message> <source>Third party URLs (e.g. a block explorer) that appear in the transactions tab as context menu items. %s in the URL is replaced by transaction hash. Multiple URLs are separated by vertical bar |.</source> <translation>Identificadores URL de terceros (por ejemplo, un explorador de bloques) que aparecen en la pestaña de transacciones como elementos del menú contextual. El %s en la URL es reemplazado por el valor hash de la transacción. Se pueden separar URL múltiples por una barra vertical |.</translation> </message> <message> <source>Open the %1 configuration file from the working directory.</source> <translation>Abre el fichero de configuración %1 en el directorio de trabajo.</translation> </message> <message> <source>Open Configuration File</source> <translation>Abrir fichero de configuración</translation> </message> <message> <source>Reset all client options to default.</source> <translation>Restablecer todas las opciones predeterminadas del cliente.</translation> </message> <message> <source>&amp;Reset Options</source> <translation>&amp;Restablecer opciones</translation> </message> <message> <source>&amp;Network</source> <translation>&amp;Red</translation> </message> <message> <source>Disables some advanced features but all blocks will still be fully validated. Reverting this setting requires re-downloading the entire blockchain. Actual disk usage may be somewhat higher.</source> <translation>Desactiva algunas características avanzadas, pero todos los bloques se validarán por completo. Revertir esta configuración requiere volver a descargar todo el blockchain. El uso real del disco puede ser algo mayor.</translation> </message> <message> <source>Prune &amp;block storage to</source> <translation>Podar el almacenamiento de &amp;bloques para</translation> </message> <message> <source>GB</source> <translation>GB</translation> </message> <message> <source>Reverting this setting requires re-downloading the entire blockchain.</source> <translation>Revertir estas configuraciones requiere re-descargar el blockchain entero.</translation> </message> <message> <source>MiB</source> <translation>MiB</translation> </message> <message> <source>(0 = auto, &lt;0 = leave that many cores free)</source> <translation>(0 = automático, &lt;0 = dejar libres ese número de núcleos)</translation> </message> <message> <source>W&amp;allet</source> <translation>&amp;Monedero</translation> </message> <message> <source>Expert</source> <translation>Experto</translation> </message> <message> <source>Enable coin &amp;control features</source> <translation>Habilitar funcionalidad de &amp;Coin Control</translation> </message> <message> <source>If you disable the spending of unconfirmed change, the change from a transaction cannot be used until that transaction has at least one confirmation. This also affects how your balance is computed.</source> <translation>Si desactiva el gasto del cambio no confirmado, no se podrá usar el cambio de una transacción hasta que se alcance al menos una confirmación. Esto afecta también a cómo se calcula su saldo.</translation> </message> <message> <source>&amp;Spend unconfirmed change</source> <translation>&amp;Gastar cambio no confirmado</translation> </message> <message> <source>Automatically open the Nexalt client port on the router. This only works when your router supports UPnP and it is enabled.</source> <translation>Abrir automáticamente el puerto del cliente Nexalt en el router. Esta opción solo funciona si el router admite UPnP y está activado.</translation> </message> <message> <source>Map port using &amp;UPnP</source> <translation>Mapear el puerto mediante &amp;UPnP</translation> </message> <message> <source>Accept connections from outside.</source> <translation>Aceptar conexiones desde el exterior.</translation> </message> <message> <source>Allow incomin&amp;g connections</source> <translation>Permitir conexiones entrantes</translation> </message> <message> <source>Connect to the Nexalt network through a SOCKS5 proxy.</source> <translation>Conectarse a la red Nexalt a través de un proxy SOCKS5.</translation> </message> <message> <source>&amp;Connect through SOCKS5 proxy (default proxy):</source> <translation>&amp;Conectarse a través de proxy SOCKS5 (proxy predeterminado):</translation> </message> <message> <source>Proxy &amp;IP:</source> <translation>Dirección &amp;IP del proxy:</translation> </message> <message> <source>&amp;Port:</source> <translation>&amp;Puerto:</translation> </message> <message> <source>Port of the proxy (e.g. 9050)</source> <translation>Puerto del servidor proxy (ej. 9050)</translation> </message> <message> <source>Used for reaching peers via:</source> <translation>Usado para alcanzar pares via:</translation> </message> <message> <source>IPv4</source> <translation>IPv4</translation> </message> <message> <source>IPv6</source> <translation>IPv6</translation> </message> <message> <source>Tor</source> <translation>Tor</translation> </message> <message> <source>Connect to the Nexalt network through a separate SOCKS5 proxy for Tor hidden services.</source> <translation>Conectar a la red Nexalt mediante un proxy SOCKS5 por separado para los servicios ocultos de Tor.</translation> </message> <message> <source>&amp;Window</source> <translation>&amp;Ventana</translation> </message> <message> <source>Show only a tray icon after minimizing the window.</source> <translation>Minimizar la ventana a la bandeja de iconos del sistema.</translation> </message> <message> <source>&amp;Minimize to the tray instead of the taskbar</source> <translation>&amp;Minimizar a la bandeja en vez de a la barra de tareas</translation> </message> <message> <source>M&amp;inimize on close</source> <translation>M&amp;inimizar al cerrar</translation> </message> <message> <source>&amp;Display</source> <translation>&amp;Interfaz</translation> </message> <message> <source>User Interface &amp;language:</source> <translation>I&amp;dioma de la interfaz de usuario</translation> </message> <message> <source>The user interface language can be set here. This setting will take effect after restarting %1.</source> <translation>El idioma de la interfaz de usuario puede establecerse aquí. Esta configuración tendrá efecto tras reiniciar %1.</translation> </message> <message> <source>&amp;Unit to show amounts in:</source> <translation>&amp;Unidad en la cual mostrar las cantidades:</translation> </message> <message> <source>Choose the default subdivision unit to show in the interface and when sending coins.</source> <translation>Elegir la subdivisión predeterminada para mostrar cantidades en la interfaz y cuando se envían nexalts.</translation> </message> <message> <source>Whether to show coin control features or not.</source> <translation>Mostrar o no funcionalidad de Coin Control</translation> </message> <message> <source>&amp;Third party transaction URLs</source> <translation>URLs de transacciones de terceros</translation> </message> <message> <source>Options set in this dialog are overridden by the command line or in the configuration file:</source> <translation>Las opciones establecidas en este diálogo serán invalidadas por la línea de comando o en el fichero de configuración:</translation> </message> <message> <source>&amp;OK</source> <translation>&amp;Aceptar</translation> </message> <message> <source>&amp;Cancel</source> <translation>&amp;Cancelar</translation> </message> <message> <source>default</source> <translation>predeterminado</translation> </message> <message> <source>none</source> <translation>ninguna</translation> </message> <message> <source>Confirm options reset</source> <translation>Confirme el restablecimiento de las opciones</translation> </message> <message> <source>Client restart required to activate changes.</source> <translation>Se necesita reiniciar el cliente para activar los cambios.</translation> </message> <message> <source>Client will be shut down. Do you want to proceed?</source> <translation>El cliente se cerrará. ¿Desea continuar?</translation> </message> <message> <source>Configuration options</source> <translation>Opciones de configuración</translation> </message> <message> <source>The configuration file is used to specify advanced user options which override GUI settings. Additionally, any command-line options will override this configuration file.</source> <translation>El fichero de configuración se utiliza para especificar opciones de usuario avanzadas que reemplazar las configuraciones de la interfaz gráfica de usuario. Adicionalmente, cualquier opción introducida en la línea de comandos reemplazará a este fichero de configuración.</translation> </message> <message> <source>Error</source> <translation>Error</translation> </message> <message> <source>The configuration file could not be opened.</source> <translation>No se pudo abrir el fichero de configuración.</translation> </message> <message> <source>This change would require a client restart.</source> <translation>Este cambio exige el reinicio del cliente.</translation> </message> <message> <source>The supplied proxy address is invalid.</source> <translation>La dirección proxy indicada es inválida.</translation> </message> </context> <context> <name>OverviewPage</name> <message> <source>Form</source> <translation>Formulario</translation> </message> <message> <source>The displayed information may be out of date. Your wallet automatically synchronizes with the Nexalt network after a connection is established, but this process has not completed yet.</source> <translation>La información mostrada puede estar desactualizada. Su monedero se sincroniza automáticamente con la red Nexalt después de que se haya establecido una conexión, pero este proceso aún no se ha completado.</translation> </message> <message> <source>Watch-only:</source> <translation>Solo observación:</translation> </message> <message> <source>Available:</source> <translation>Disponible:</translation> </message> <message> <source>Your current spendable balance</source> <translation>Su saldo disponible actual</translation> </message> <message> <source>Pending:</source> <translation>Pendiente:</translation> </message> <message> <source>Total of transactions that have yet to be confirmed, and do not yet count toward the spendable balance</source> <translation>Total de transacciones pendientes de confirmar y que aún no contribuye al saldo disponible</translation> </message> <message> <source>Immature:</source> <translation>No madurado:</translation> </message> <message> <source>Mined balance that has not yet matured</source> <translation>Saldo recién minado que aún no ha madurado.</translation> </message> <message> <source>Balances</source> <translation>Saldos</translation> </message> <message> <source>Total:</source> <translation>Total:</translation> </message> <message> <source>Your current total balance</source> <translation>Su saldo actual total</translation> </message> <message> <source>Your current balance in watch-only addresses</source> <translation>Su saldo actual en direcciones watch-only (solo-observación)</translation> </message> <message> <source>Spendable:</source> <translation>Gastable:</translation> </message> <message> <source>Recent transactions</source> <translation>Transacciones recientes</translation> </message> <message> <source>Unconfirmed transactions to watch-only addresses</source> <translation>Transacciones sin confirmar en direcciones watch-only (solo-observación)</translation> </message> <message> <source>Mined balance in watch-only addresses that has not yet matured</source> <translation>Saldo minado en direcciones watch-only que aún no ha madurado</translation> </message> <message> <source>Current total balance in watch-only addresses</source> <translation>Saldo total en las direcciones watch-only (solo-observación)</translation> </message> </context> <context> <name>PaymentServer</name> <message> <source>Payment request error</source> <translation>Fallo en la solicitud de pago</translation> </message> <message> <source>Cannot start nexalt: click-to-pay handler</source> <translation>No se puede iniciar nexalt: encargado click-para-pagar</translation> </message> <message> <source>URI handling</source> <translation>Manejo de URI</translation> </message> <message> <source>'nexalt://' is not a valid URI. Use 'nexalt:' instead.</source> <translation>'nexalt: //' no es un URI válido. Use 'nexalt:' en su lugar.</translation> </message> <message> <source>You are using a BIP70 URL which will be unsupported in the future.</source> <translation>Está utilizando una URL BIP70 la cual dejará de tener soporte en el futuro.</translation> </message> <message> <source>Payment request fetch URL is invalid: %1</source> <translation>La búsqueda de solicitud de pago URL es válida: %1</translation> </message> <message> <source>Cannot process payment request because BIP70 support was not compiled in.</source> <translation>No se puede procesar la petición de pago debido a que no se ha incluido el soporte de BIP70.</translation> </message> <message> <source>Invalid payment address %1</source> <translation>Dirección de pago inválida %1</translation> </message> <message> <source>URI cannot be parsed! This can be caused by an invalid Nexalt address or malformed URI parameters.</source> <translation>URI no puede ser analizado! Esto puede ser causado por una dirección Nexalt inválida o parametros URI mal formados.</translation> </message> <message> <source>Payment request file handling</source> <translation>Manejo del archivo de solicitud de pago</translation> </message> <message> <source>Payment request file cannot be read! This can be caused by an invalid payment request file.</source> <translation>¡El archivo de solicitud de pago no puede ser leído! Esto puede ser causado por un archivo de solicitud de pago inválido.</translation> </message> <message> <source>Payment request rejected</source> <translation>Solicitud de pago rechazada</translation> </message> <message> <source>Payment request network doesn't match client network.</source> <translation>La red de solicitud de pago no coincide con la red cliente.</translation> </message> <message> <source>Payment request expired.</source> <translation>Solicitud de pago caducada.</translation> </message> <message> <source>Payment request is not initialized.</source> <translation>La solicitud de pago no se ha iniciado.</translation> </message> <message> <source>Unverified payment requests to custom payment scripts are unsupported.</source> <translation>Solicitudes de pago sin verificar a scripts de pago habitual no se soportan.</translation> </message> <message> <source>Invalid payment request.</source> <translation>Solicitud de pago inválida.</translation> </message> <message> <source>Requested payment amount of %1 is too small (considered dust).</source> <translation>Cantidad de pago solicitada de %1 es demasiado pequeña (considerado polvo).</translation> </message> <message> <source>Refund from %1</source> <translation>Reembolsar desde %1</translation> </message> <message> <source>Payment request %1 is too large (%2 bytes, allowed %3 bytes).</source> <translation>Solicitud de pago de %1 es demasiado grande (%2 bytes, permitidos %3 bytes).</translation> </message> <message> <source>Error communicating with %1: %2</source> <translation>Fallo al comunicar con %1: %2</translation> </message> <message> <source>Payment request cannot be parsed!</source> <translation>¡La solicitud de pago no puede ser analizada!</translation> </message> <message> <source>Bad response from server %1</source> <translation>Mala respuesta desde el servidor %1</translation> </message> <message> <source>Network request error</source> <translation>Fallo de solicitud de red</translation> </message> <message> <source>Payment acknowledged</source> <translation>Pago declarado</translation> </message> </context> <context> <name>PeerTableModel</name> <message> <source>User Agent</source> <translation>User Agent</translation> </message> <message> <source>Node/Service</source> <translation>Nodo/Servicio</translation> </message> <message> <source>NodeId</source> <translation>ID de nodo</translation> </message> <message> <source>Ping</source> <translation>Ping</translation> </message> <message> <source>Sent</source> <translation>Enviado</translation> </message> <message> <source>Received</source> <translation>Recibido</translation> </message> </context> <context> <name>QObject</name> <message> <source>Amount</source> <translation>Cantidad</translation> </message> <message> <source>Enter a Nexalt address (e.g. %1)</source> <translation>Introducir una dirección Nexalt (p. ej. %1)</translation> </message> <message> <source>%1 d</source> <translation>%1 d</translation> </message> <message> <source>%1 h</source> <translation>%1 h</translation> </message> <message> <source>%1 m</source> <translation>%1 m</translation> </message> <message> <source>%1 s</source> <translation>%1 s</translation> </message> <message> <source>None</source> <translation>Ninguno</translation> </message> <message> <source>N/A</source> <translation>N/D</translation> </message> <message> <source>%1 ms</source> <translation>%1 ms</translation> </message> <message numerus="yes"> <source>%n second(s)</source> <translation><numerusform>%n segundo</numerusform><numerusform>%n segundos</numerusform></translation> </message> <message numerus="yes"> <source>%n minute(s)</source> <translation><numerusform>%n minuto</numerusform><numerusform>%n minutos</numerusform></translation> </message> <message numerus="yes"> <source>%n hour(s)</source> <translation><numerusform>%n hora</numerusform><numerusform>%n horas</numerusform></translation> </message> <message numerus="yes"> <source>%n day(s)</source> <translation><numerusform>%n dia</numerusform><numerusform>%n dias</numerusform></translation> </message> <message numerus="yes"> <source>%n week(s)</source> <translation><numerusform>%n semana</numerusform><numerusform>%n semanas</numerusform></translation> </message> <message> <source>%1 and %2</source> <translation>%1 y %2</translation> </message> <message numerus="yes"> <source>%n year(s)</source> <translation><numerusform>%n año</numerusform><numerusform>%n años</numerusform></translation> </message> <message> <source>%1 B</source> <translation>%1 B</translation> </message> <message> <source>%1 KB</source> <translation>%1 KB</translation> </message> <message> <source>%1 MB</source> <translation>%1 MB</translation> </message> <message> <source>%1 GB</source> <translation>%1 GB</translation> </message> <message> <source>%1 didn't yet exit safely...</source> <translation>%1 no se ha cerrado de forma segura todavía...</translation> </message> <message> <source>unknown</source> <translation>desconocido</translation> </message> </context> <context> <name>QObject::QObject</name> <message> <source>Error parsing command line arguments: %1.</source> <translation>Error al parsear los argumentos de la línea de comando: %1.</translation> </message> <message> <source>Error: Specified data directory "%1" does not exist.</source> <translation>Error: El directorio de datos «%1» especificado no existe.</translation> </message> <message> <source>Error: Cannot parse configuration file: %1.</source> <translation>Error: No se puede analizar/parsear el archivo de configuración: %1.</translation> </message> <message> <source>Error: %1</source> <translation>Error: %1</translation> </message> </context> <context> <name>QRImageWidget</name> <message> <source>&amp;Save Image...</source> <translation>&amp;Guardar imagen...</translation> </message> <message> <source>&amp;Copy Image</source> <translation>&amp;Copiar imagen</translation> </message> <message> <source>Save QR Code</source> <translation>Guardar código QR</translation> </message> <message> <source>PNG Image (*.png)</source> <translation>Imagen PNG (*.png)</translation> </message> </context> <context> <name>RPCConsole</name> <message> <source>N/A</source> <translation>N/D</translation> </message> <message> <source>Client version</source> <translation>Versión del cliente</translation> </message> <message> <source>&amp;Information</source> <translation>&amp;Información</translation> </message> <message> <source>Debug window</source> <translation>Ventana de depuración</translation> </message> <message> <source>General</source> <translation>General</translation> </message> <message> <source>Using BerkeleyDB version</source> <translation>Utilizando la versión de BerkeleyDB</translation> </message> <message> <source>Datadir</source> <translation>Datadir</translation> </message> <message> <source>To specify a non-default location of the data directory use the '%1' option.</source> <translation>Para especificar una ubicación distinta a la ubicación por defecto del directorio de datos, use la opción '%1'.</translation> </message> <message> <source>Blocksdir</source> <translation>Blocksdir</translation> </message> <message> <source>To specify a non-default location of the blocks directory use the '%1' option.</source> <translation>Para especificar una ubicación distinta a la ubicación por defecto del directorio de bloques, use la opción '%1'.</translation> </message> <message> <source>Startup time</source> <translation>Hora de inicio</translation> </message> <message> <source>Network</source> <translation>Red</translation> </message> <message> <source>Name</source> <translation>Nombre</translation> </message> <message> <source>Number of connections</source> <translation>Número de conexiones</translation> </message> <message> <source>Block chain</source> <translation>Cadena de bloques</translation> </message> <message> <source>Current number of blocks</source> <translation>Número actual de bloques</translation> </message> <message> <source>Memory Pool</source> <translation>Piscina de Memoria</translation> </message> <message> <source>Current number of transactions</source> <translation>Número actual de transacciones</translation> </message> <message> <source>Memory usage</source> <translation>Uso de memoria</translation> </message> <message> <source>Wallet: </source> <translation>Monedero:</translation> </message> <message> <source>(none)</source> <translation>(ninguno)</translation> </message> <message> <source>&amp;Reset</source> <translation>&amp;Reiniciar</translation> </message> <message> <source>Received</source> <translation>Recibido</translation> </message> <message> <source>Sent</source> <translation>Enviado</translation> </message> <message> <source>&amp;Peers</source> <translation>&amp;Pares</translation> </message> <message> <source>Banned peers</source> <translation>Pares bloqueados</translation> </message> <message> <source>Select a peer to view detailed information.</source> <translation>Seleccionar un par para ver su información detallada.</translation> </message> <message> <source>Whitelisted</source> <translation>En la lista blanca</translation> </message> <message> <source>Direction</source> <translation>Dirección</translation> </message> <message> <source>Version</source> <translation>Versión</translation> </message> <message> <source>Starting Block</source> <translation>Importando bloques...</translation> </message> <message> <source>Synced Headers</source> <translation>Cabeceras Sincronizadas</translation> </message> <message> <source>Synced Blocks</source> <translation>Bloques Sincronizados</translation> </message> <message> <source>User Agent</source> <translation>User Agent</translation> </message> <message> <source>Open the %1 debug log file from the current data directory. This can take a few seconds for large log files.</source> <translation>Abrir el archivo de depuración %1 desde el directorio de datos actual. Puede tardar unos segundos para ficheros de gran tamaño.</translation> </message> <message> <source>Decrease font size</source> <translation>Disminuir tamaño de letra</translation> </message> <message> <source>Increase font size</source> <translation>Aumentar tamaño de letra</translation> </message> <message> <source>Services</source> <translation>Servicios</translation> </message> <message> <source>Ban Score</source> <translation>Puntuación de bloqueo</translation> </message> <message> <source>Connection Time</source> <translation>Duración de la conexión</translation> </message> <message> <source>Last Send</source> <translation>Último envío</translation> </message> <message> <source>Last Receive</source> <translation>Última recepción</translation> </message> <message> <source>Ping Time</source> <translation>Tiempo de Ping</translation> </message> <message> <source>The duration of a currently outstanding ping.</source> <translation>La duración de un ping actualmente en proceso.</translation> </message> <message> <source>Ping Wait</source> <translation>Espera de Ping</translation> </message> <message>
<source>Time Offset</source> <translation>Desplazamiento de tiempo</translation> </message> <message> <source>Last block time</source> <translation>Hora del último bloque</translation> </message> <message> <source>&amp;Open</source> <translation>&amp;Abrir</translation> </message> <message> <source>&amp;Console</source> <translation>&amp;Consola</translation> </message> <message> <source>&amp;Network Traffic</source> <translation>&amp;Tráfico de Red</translation> </message> <message> <source>Totals</source> <translation>Total:</translation> </message> <message> <source>In:</source> <translation>Entrante:</translation> </message> <message> <source>Out:</source> <translation>Saliente:</translation> </message> <message> <source>Debug log file</source> <translation>Archivo de registro de depuración</translation> </message> <message> <source>Clear console</source> <translation>Borrar consola</translation> </message> <message> <source>1 &amp;hour</source> <translation>1 &amp;hora</translation> </message> <message> <source>1 &amp;day</source> <translation>1 &amp;día</translation> </message> <message> <source>1 &amp;week</source> <translation>1 &amp;semana</translation> </message> <message> <source>1 &amp;year</source> <translation>1 &amp;año</translation> </message> <message> <source>&amp;Disconnect</source> <translation>&amp;Desconectar</translation> </message> <message> <source>Ban for</source> <translation>Prohibir para</translation> </message> <message> <source>&amp;Unban</source> <translation>&amp;Unban</translation> </message> <message> <source>Welcome to the %1 RPC console.</source> <translation>Bienvenido a la consola RPC %1.</translation> </message> <message> <source>Use up and down arrows to navigate history, and %1 to clear screen.</source> <translation>Utilice las teclas de navegación para revisar el historial, y %1 para limpiar la pantalla.</translation> </message> <message> <source>Type %1 for an overview of available commands.</source> <translation>Presione %1 para una vista previa de los comandos disponibles.</translation> </message> <message> <source>For more information on using this console type %1.</source> <translation>Para mas información sobre el uso de este tipo de consola %1</translation> </message> <message> <source>WARNING: Scammers have been active, telling users to type commands here, stealing their wallet contents. Do not use this console without fully understanding the ramifications of a command.</source> <translation>ADVERTENCIA: Los estafadores están solicitando a los usuarios introducir ordenes aquí, lo que ocasiona que estos roben los contenidos del monedero. No utilice esta consola sin comprender completamente las implicancias de cada orden.</translation> </message> <message> <source>Network activity disabled</source> <translation>Actividad de red deshabilitada</translation> </message> <message> <source>Executing command without any wallet</source> <translation>Ejecutar comando sin monedero</translation> </message> <message> <source>Executing command using "%1" wallet</source> <translation>Ejecutar comando usando "%1" monedero</translation> </message> <message> <source>(node id: %1)</source> <translation>(nodo: %1)</translation> </message> <message> <source>via %1</source> <translation>via %1</translation> </message> <message> <source>never</source> <translation>nunca</translation> </message> <message> <source>Inbound</source> <translation>Entrante</translation> </message> <message> <source>Outbound</source> <translation>Saliente</translation> </message> <message> <source>Yes</source> <translation>Sí</translation> </message> <message> <source>No</source> <translation>No</translation> </message> <message> <source>Unknown</source> <translation>Desconocido</translation> </message> </context> <context> <name>ReceiveCoinsDialog</name> <message> <source>&amp;Amount:</source> <translation>Cantidad</translation> </message> <message> <source>&amp;Label:</source> <translation>&amp;Etiqueta:</translation> </message> <message> <source>&amp;Message:</source> <translation>Mensaje:</translation> </message> <message> <source>An optional message to attach to the payment request, which will be displayed when the request is opened. Note: The message will not be sent with the payment over the Nexalt network.</source> <translation>Un mensaje opcional para adjuntar a la solicitud de pago, que se muestra cuando se abre la solicitud. Nota: El mensaje no se enviará con el pago por la red Nexalt.</translation> </message> <message> <source>An optional label to associate with the new receiving address.</source> <translation>Etiqueta opcional para asociar con la nueva dirección de recepción.</translation> </message> <message> <source>Use this form to request payments. All fields are &lt;b&gt;optional&lt;/b&gt;.</source> <translation>Utilice este formulario para solicitar pagos. Todos los campos son &lt;b&gt;opcionales&lt;/b&gt;.</translation> </message> <message> <source>An optional amount to request. Leave this empty or zero to not request a specific amount.</source> <translation>Para solicitar una cantidad opcional. Deje este vacío o cero para no solicitar una cantidad específica.</translation> </message> <message> <source>Clear all fields of the form.</source> <translation>Vaciar todos los campos del formulario.</translation> </message> <message> <source>Clear</source> <translation>Vaciar</translation> </message> <message> <source>Native segwit addresses (aka Bech32 or BIP-173) reduce your transaction fees later on and offer better protection against typos, but old wallets don't support them. When unchecked, an address compatible with older wallets will be created instead.</source> <translation>Las direcciones segwit nativas (también conocidas como Bech32 o BIP-173) reducen las comisiones de transacción más adelante y ofrecen una mejor protección contra errores tipográficos, pero las billeteras antiguas no las admiten. Cuando no está marcada, se creará una dirección compatible con billeteras más antiguas.</translation> </message> <message> <source>Generate native segwit (Bech32) address</source> <translation>Generar dirección segwit nativa (Bech32)</translation> </message> <message> <source>Requested payments history</source> <translation>Historial de pagos solicitados</translation> </message> <message> <source>&amp;Request payment</source> <translation>&amp;Solicitar pago</translation> </message> <message> <source>Show the selected request (does the same as double clicking an entry)</source> <translation>Muestra la petición seleccionada (También doble clic)</translation> </message> <message> <source>Show</source> <translation>Mostrar</translation> </message> <message> <source>Remove the selected entries from the list</source> <translation>Borrar las entradas seleccionadas de la lista</translation> </message> <message> <source>Remove</source> <translation>Eliminar</translation> </message> <message> <source>Copy URI</source> <translation>Copiar URI</translation> </message> <message> <source>Copy label</source> <translation>Copiar etiqueta</translation> </message> <message> <source>Copy message</source> <translation>Copiar imagen</translation> </message> <message> <source>Copy amount</source> <translation>Copiar cantidad</translation> </message> </context> <context> <name>ReceiveRequestDialog</name> <message> <source>QR Code</source> <translation>Código QR</translation> </message> <message> <source>Copy &amp;URI</source> <translation>Copiar &amp;URI</translation> </message> <message> <source>Copy &amp;Address</source> <translation>Copiar &amp;Dirección</translation> </message> <message> <source>&amp;Save Image...</source> <translation>Guardar Imagen...</translation> </message> <message> <source>Request payment to %1</source> <translation>Solicitar pago a %1</translation> </message> <message> <source>Payment information</source> <translation>Información de pago</translation> </message> <message> <source>URI</source> <translation>URI</translation> </message> <message> <source>Address</source> <translation>Dirección</translation> </message> <message> <source>Amount</source> <translation>Cantidad</translation> </message> <message> <source>Label</source> <translation>Etiqueta</translation> </message> <message> <source>Message</source> <translation>Mensaje</translation> </message> <message> <source>Wallet</source> <translation>Monedero</translation> </message> <message> <source>Resulting URI too long, try to reduce the text for label / message.</source> <translation>URI resultante demasiado grande, trate de reducir el texto de etiqueta / mensaje.</translation> </message> <message> <source>Error encoding URI into QR Code.</source> <translation>Fallo al codificar URI en código QR.</translation> </message> </context> <context> <name>RecentRequestsTableModel</name> <message> <source>Date</source> <translation>Fecha</translation> </message> <message> <source>Label</source> <translation>Etiqueta</translation> </message> <message> <source>Message</source> <translation>Mensaje</translation> </message> <message> <source>(no label)</source> <translation>(sin etiqueta)</translation> </message> <message> <source>(no message)</source> <translation>(no hay mensaje)</translation> </message> <message> <source>(no amount requested)</source> <translation>(no hay solicitud de cantidad)</translation> </message> <message> <source>Requested</source> <translation>Solicitado</translation> </message> </context> <context> <name>SendCoinsDialog</name> <message> <source>Send Coins</source> <translation>Enviar nexalts</translation> </message> <message> <source>Coin Control Features</source> <translation>Características de Coin Control</translation> </message> <message> <source>Inputs...</source> <translation>Entradas...</translation> </message> <message> <source>automatically selected</source> <translation>seleccionado automáticamente</translation> </message> <message> <source>Insufficient funds!</source> <translation>Fondos insuficientes!</translation> </message> <message> <source>Quantity:</source> <translation>Cantidad:</translation> </message> <message> <source>Bytes:</source> <translation>Bytes:</translation> </message> <message> <source>Amount:</source> <translation>Cuantía:</translation> </message> <message> <source>Fee:</source> <translation>Comisión:</translation> </message> <message> <source>After Fee:</source> <translation>Después de comisión:</translation> </message> <message> <source>Change:</source> <translation>Cambio:</translation> </message> <message> <source>If this is activated, but the change address is empty or invalid, change will be sent to a newly generated address.</source> <translation>Si se marca esta opción pero la dirección de cambio está vacía o es inválida, el cambio se enviará a una nueva dirección recién generada.</translation> </message> <message> <source>Custom change address</source> <translation>Dirección propia</translation> </message> <message> <source>Transaction Fee:</source> <translation>Comisión de Transacción:</translation> </message> <message> <source>Choose...</source> <translation>Elija...</translation> </message> <message> <source>Using the fallbackfee can result in sending a transaction that will take several hours or days (or never) to confirm. Consider choosing your fee manually or wait until you have validated the complete chain.</source> <translation>Si utilizas la comisión por defecto, la transacción puede tardar varias horas o incluso días (o nunca) en confirmarse. Considera elegir la comisión de forma manual o espera hasta que se haya validado completamente la cadena.</translation> </message> <message> <source>Warning: Fee estimation is currently not possible.</source> <translation>Advertencia: En este momento no se puede estimar la comisión.</translation> </message> <message> <source>collapse fee-settings</source> <translation>Colapsar ajustes de comisión.</translation> </message> <message> <source>Specify a custom fee per kB (1,000 bytes) of the transaction's virtual size. Note: Since the fee is calculated on a per-byte basis, a fee of "100 satoshis per kB" for a transaction size of 500 bytes (half of 1 kB) would ultimately yield a fee of only 50 satoshis.</source> <translation>Especifique una comisión personalizada por kB (1,000 bytes) del tamaño virtual de la transacción. Nota: Dado que la comisión se calcula por byte, una comisión de "100 satoshis por kB" para un tamaño de transacción de 500 bytes (la mitad de 1 kB) finalmente generará una comisión de solo 50 satoshis.</translation> </message> <message> <source>per kilobyte</source> <translation>por kilobyte</translation> </message> <message> <source>Hide</source> <translation>Ocultar</translation> </message> <message> <source>Recommended:</source> <translation>Recomendada:</translation> </message> <message> <source>Custom:</source> <translation>Personalizada:</translation> </message> <message> <source>(Smart fee not initialized yet. This usually takes a few blocks...)</source> <translation>(Aún no se ha inicializado la Comisión Inteligente. Esto generalmente tarda pocos bloques...)</translation> </message> <message> <source>Send to multiple recipients at once</source> <translation>Enviar a múltiples destinatarios de una vez</translation> </message> <message> <source>Add &amp;Recipient</source> <translation>Añadir &amp;destinatario</translation> </message> <message> <source>Clear all fields of the form.</source> <translation>Vaciar todos los campos del formulario</translation> </message> <message> <source>Dust:</source> <translation>Polvo:</translation> </message> <message> <source>When there is less transaction volume than space in the blocks, miners as well as relaying nodes may enforce a minimum fee. Paying only this minimum fee is just fine, but be aware that this can result in a never confirming transaction once there is more demand for nexalt transactions than the network can process.</source> <translation>Cuando hay menos volumen de transacciónes que espacio en los bloques, los mineros y los nodos de retransmisión pueden imponer una comisión mínima. Pagar solo esta comisión mínima está bien, pero tenga en cuenta que esto puede resultar en una transacción nunca confirmada una vez que haya más demanda de transacciones de Nexalt de la que la red puede procesar.</translation> </message> <message> <source>A too low fee might result in a never confirming transaction (read the tooltip)</source> <translation>Una comisión muy pequeña puede derivar en una transacción que nunca será confirmada</translation> </message> <message> <source>Confirmation time target:</source> <translation>Objetivo de tiempo de confirmación</translation> </message> <message> <source>Enable Replace-By-Fee</source> <translation>Habilitar Replace-By-Fee</translation> </message> <message> <source>With Replace-By-Fee (BIP-125) you can increase a transaction's fee after it is sent. Without this, a higher fee may be recommended to compensate for increased transaction delay risk.</source> <translation>Con Replace-By-Fee (BIP-125) puede incrementar la comisión después de haber enviado la transacción. Si no utiliza esto, se recomienda que añada una comisión mayor para compensar el riesgo adicional de que la transacción se retrase.</translation> </message> <message> <source>Clear &amp;All</source> <translation>Vaciar &amp;todo</translation> </message> <message> <source>Balance:</source> <translation>Saldo:</translation> </message> <message> <source>Confirm the send action</source> <translation>Confirmar el envío</translation> </message> <message> <source>S&amp;end</source> <translation>&amp;Enviar</translation> </message> <message> <source>Copy quantity</source> <translation>Copiar cantidad</translation> </message> <message> <source>Copy amount</source> <translation>Copiar cantidad</translation> </message> <message> <source>Copy fee</source> <translation>Copiar comisión</translation> </message> <message> <source>Copy after fee</source> <translation>Copiar después de comisión</translation> </message> <message> <source>Copy bytes</source> <translation>Copiar bytes</translation> </message> <message> <source>Copy dust</source> <translation>Copiar polvo</translation> </message> <message> <source>Copy change</source> <translation>Copiar cambio</translation> </message> <message> <source>%1 (%2 blocks)</source> <translation>%1 (%2 bloques)</translation> </message> <message> <source>%1 to %2</source> <translation>%1 a %2</translation> </message> <message> <source>Are you sure you want to send?</source> <translation>¿Seguro que quiere enviar?</translation> </message> <message> <source>or</source> <translation>o</translation> </message> <message> <source>You can increase the fee later (signals Replace-By-Fee, BIP-125).</source> <translation>Puede incrementar la comisión más tarde (usa Replace-By-Fee, BIP-125).</translation> </message> <message> <source>from wallet %1</source> <translation>de monedero %1</translation> </message> <message> <source>Please, review your transaction.</source> <translation>Por favor, revisa tu transacción</translation> </message> <message> <source>Transaction fee</source> <translation>Comisión de transacción</translation> </message> <message> <source>Not signalling Replace-By-Fee, BIP-125.</source> <translation>No usa Replace-By-Fee, BIP-125.</translation> </message> <message> <source>Total Amount</source> <translation>Monto total</translation> </message> <message> <source>Confirm send coins</source> <translation>Confirmar enviar monedas</translation> </message> <message> <source>The recipient address is not valid. Please recheck.</source> <translation>La dirección de destinatario no es válida. Por favor revísela.</translation> </message> <message> <source>The amount to pay must be larger than 0.</source> <translation>La cantidad a pagar debe de ser mayor que 0.</translation> </message> <message> <source>The amount exceeds your balance.</source> <translation>La cantidad excede su saldo.</translation> </message> <message> <source>The total exceeds your balance when the %1 transaction fee is included.</source> <translation>El total excede su saldo cuando la comisión de transacción de %1 es incluida.</translation> </message> <message> <source>Duplicate address found: addresses should only be used once each.</source> <translation>Dirección duplicada encontrada: la dirección sólo debería ser utilizada una vez por cada uso.</translation> </message> <message> <source>Transaction creation failed!</source> <translation>¡Falló la creación de transacción!</translation> </message> <message> <source>The transaction was rejected with the following reason: %1</source> <translation>Se ha rechazado la transacción por la siguiente razón: %1</translation> </message> <message> <source>A fee higher than %1 is considered an absurdly high fee.</source> <translation>Una comisión mayor que %1 se considera una comisión irracionalmente alta.</translation> </message> <message> <source>Payment request expired.</source> <translation>Solicitud de pago caducada.</translation> </message> <message numerus="yes"> <source>Estimated to begin confirmation within %n block(s).</source> <translation><numerusform>Estimado para empezar la confirmación dentro de %n bloque.</numerusform><numerusform>Estimado para empezar la confirmación dentro de %n bloques.</numerusform></translation> </message> <message> <source>Warning: Invalid Nexalt address</source> <translation>Alerta: dirección Nexalt inválida</translation> </message> <message> <source>Warning: Unknown change address</source> <translation>Alerta: dirección de cambio desconocida</translation> </message> <message> <source>Confirm custom change address</source> <translation>Confirmar dirección de cambio personalizada</translation> </message> <message> <source>The address you selected for change is not part of this wallet. Any or all funds in your wallet may be sent to this address. Are you sure?</source> <translation>La dirección que ha seleccionado para cambiar no es parte de este monedero. ninguno o todos los fondos de su monedero pueden ser enviados a esta dirección. ¿Está seguro?</translation> </message> <message> <source>(no label)</source> <translation>(sin etiqueta)</translation> </message> </context> <context> <name>SendCoinsEntry</name> <message> <source>A&amp;mount:</source> <translation>Ca&amp;ntidad:</translation> </message> <message> <source>Pay &amp;To:</source> <translation>&amp;Pagar a:</translation> </message> <message> <source>&amp;Label:</source> <translation>&amp;Etiqueta:</translation> </message> <message> <source>Choose previously used address</source> <translation>Escoger direcciones previamente usadas</translation> </message> <message> <source>This is a normal payment.</source> <translation>Esto es un pago ordinario.</translation> </message> <message> <source>The Nexalt address to send the payment to</source> <translation>Dirección Nexalt a la que enviar el pago</translation> </message> <message> <source>Alt+A</source> <translation>Alt+A</translation> </message> <message> <source>Paste address from clipboard</source> <translation>Pegar dirección desde portapapeles</translation> </message> <message> <source>Alt+P</source> <translation>Alt+P</translation> </message> <message> <source>Remove this entry</source> <translation>Eliminar esta transacción</translation> </message> <message> <source>The fee will be deducted from the amount being sent. The recipient will receive less nexalts than you enter in the amount field. If multiple recipients are selected, the fee is split equally.</source> <translation>La comisión será deducida de la cantidad que sea mandada. El destinatario recibirá menos nexalts de la cantidad introducida en el campo Cantidad. Si hay varios destinatarios, la comisión será distribuida a partes iguales.</translation> </message> <message> <source>S&amp;ubtract fee from amount</source> <translation>Restar comisiones de la cantidad.</translation> </message> <message> <source>Use available balance</source> <translation>Usar balance disponible</translation> </message> <message> <source>Message:</source> <translation>Mensaje:</translation> </message> <message> <source>This is an unauthenticated payment request.</source> <translation>Esta es una petición de pago no autentificada.</translation> </message> <message> <source>This is an authenticated payment request.</source> <translation>Esta es una petición de pago autentificada.</translation> </message> <message> <source>Enter a label for this address to add it to the list of used addresses</source> <translation>Introduce una etiqueta para esta dirección para añadirla a la lista de direcciones utilizadas</translation> </message> <message> <source>A message that was attached to the nexalt: URI which will be stored with the transaction for your reference. Note: This message will not be sent over the Nexalt network.</source> <translation>Un mensaje que se adjuntó a la nexalt: URL que será almacenada con la transacción para su referencia. Nota: Este mensaje no se envía a través de la red Nexalt.</translation> </message> <message> <source>Pay To:</source> <translation>Paga a:</translation> </message> <message> <source>Memo:</source> <translation>Memo:</translation> </message> <message> <source>Enter a label for this address to add it to your address book</source> <translation>Introduzca una etiqueta para esta dirección para añadirla a su lista de direcciones.</translation> </message> </context> <context> <name>SendConfirmationDialog</name> <message> <source>Yes</source> <translation>Sí</translation> </message> </context> <context> <name>ShutdownWindow</name> <message> <source>%1 is shutting down...</source> <translation>%1 se esta cerrando...</translation> </message> <message> <source>Do not shut down the computer until this window disappears.</source> <translation>No apague el equipo hasta que desaparezca esta ventana.</translation> </message> </context> <context> <name>SignVerifyMessageDialog</name> <message> <source>Signatures - Sign / Verify a Message</source> <translation>Firmas - Firmar / verificar un mensaje</translation> </message> <message> <source>&amp;Sign Message</source> <translation>&amp;Firmar mensaje</translation> </message> <message> <source>You can sign messages/agreements with your addresses to prove you can receive nexalts sent to them. Be careful not to sign anything vague or random, as phishing attacks may try to trick you into signing your identity over to them. Only sign fully-detailed statements you agree to.</source> <translation>Puede firmar los mensajes con sus direcciones para demostrar que las posee. Tenga cuidado de no firmar cualquier cosa de manera vaga o aleatoria, pues los ataques de phishing pueden tratar de engañarle firmando su identidad a través de ellos. Sólo firme declaraciones totalmente detalladas con las que usted esté de acuerdo.</translation> </message> <message> <source>The Nexalt address to sign the message with</source> <translation>Dirección Nexalt con la que firmar el mensaje</translation> </message> <message> <source>Choose previously used address</source> <translation>Escoger dirección previamente usada</translation> </message> <message> <source>Alt+A</source> <translation>Alt+A</translation> </message> <message> <source>Paste address from clipboard</source> <translation>Pegar dirección desde portapapeles</translation> </message> <message> <source>Alt+P</source> <translation>Alt+P</translation> </message> <message> <source>Enter the message you want to sign here</source> <translation>Introduzca el mensaje que desea firmar aquí</translation> </message> <message> <source>Signature</source> <translation>Firma</translation> </message> <message> <source>Copy the current signature to the system clipboard</source> <translation>Copiar la firma actual al portapapeles del sistema</translation> </message> <message> <source>Sign the message to prove you own this Nexalt address</source> <translation>Firmar el mensaje para demostrar que se posee esta dirección Nexalt</translation> </message> <message> <source>Sign &amp;Message</source> <translation>Firmar &amp;mensaje</translation> </message> <message> <source>Reset all sign message fields</source> <translation>Vaciar todos los campos de la firma de mensaje</translation> </message> <message> <source>Clear &amp;All</source> <translation>Vaciar &amp;todo</translation> </message> <message> <source>&amp;Verify Message</source> <translation>&amp;Verificar mensaje</translation> </message> <message> <source>Enter the receiver's address, message (ensure you copy line breaks, spaces, tabs, etc. exactly) and signature below to verify the message. Be careful not to read more into the signature than what is in the signed message itself, to avoid being tricked by a man-in-the-middle attack. Note that this only proves the signing party receives with the address, it cannot prove sendership of any transaction!</source> <translation>Introduzca la dirección para la firma, el mensaje (asegurándose de copiar tal cual los saltos de línea, espacios, tabulaciones, etc.) y la firma a continuación para verificar el mensaje. Tenga cuidado de no asumir más información de lo que dice el propio mensaje firmado para evitar fraudes basados en ataques de tipo man-in-the-middle. </translation> </message> <message> <source>The Nexalt address the message was signed with</source> <translation>La dirección Nexalt con la que se firmó el mensaje</translation> </message> <message> <source>Verify the message to ensure it was signed with the specified Nexalt address</source> <translation>Verificar el mensaje para comprobar que fue firmado con la dirección Nexalt indicada</translation> </message> <message> <source>Verify &amp;Message</source> <translation>Verificar &amp;mensaje</translation> </message> <message> <source>Reset all verify message fields</source> <translation>Vaciar todos los campos de la verificación de mensaje</translation> </message> <message> <source>Click "Sign Message" to generate signature</source> <translation>Click en "Fírmar mensaje" para generar una firma</translation> </message> <message> <source>The entered address is invalid.</source> <translation>La dirección introducida no es válida.</translation> </message> <message> <source>Please check the address and try again.</source> <translation>Por favor revise la dirección e inténtelo de nuevo.</translation> </message> <message> <source>The entered address does not refer to a key.</source> <translation>La dirección introducida no remite a una clave.</translation> </message> <message> <source>Wallet unlock was cancelled.</source> <translation>El desbloqueo del monedero fue cancelado.</translation> </message> <message> <source>Private key for the entered address is not available.</source> <translation>La clave privada de la dirección introducida no está disponible.</translation> </message> <message> <source>Message signing failed.</source> <translation>Falló la firma del mensaje.</translation> </message> <message> <source>Message signed.</source> <translation>Mensaje firmado.</translation> </message> <message> <source>The signature could not be decoded.</source> <translation>La firma no pudo descodificarse.</translation> </message> <message> <source>Please check the signature and try again.</source> <translation>Por favor compruebe la firma y pruebe de nuevo.</translation> </message> <message> <source>The signature did not match the message digest.</source> <translation>La firma no se combinó con el mensaje.</translation> </message> <message> <source>Message verification failed.</source> <translation>Falló la verificación del mensaje.</translation> </message> <message> <source>Message verified.</source> <translation>Mensaje verificado.</translation> </message> </context> <context> <name>SplashScreen</name> <message> <source>[testnet]</source> <translation>[testnet]</translation> </message> </context> <context> <name>TrafficGraphWidget</name> <message> <source>KB/s</source> <translation>KB/s</translation> </message> </context> <context> <name>TransactionDesc</name> <message numerus="yes"> <source>Open for %n more block(s)</source> <translation><numerusform>Abrir para %n bloque más</numerusform><numerusform>Abrir para %n bloques más</numerusform></translation> </message> <message> <source>Open until %1</source> <translation>Abierto hasta %1</translation> </message> <message> <source>conflicted with a transaction with %1 confirmations</source> <translation>Hay un conflicto con una transacción con %1 confirmaciones</translation> </message> <message> <source>0/unconfirmed, %1</source> <translation>0/no confirmado, %1</translation> </message> <message> <source>in memory pool</source> <translation>en el pool de memoria</translation> </message> <message> <source>not in memory pool</source> <translation>no en el pool de memoria</translation> </message> <message> <source>abandoned</source> <translation>abandonado</translation> </message> <message> <source>%1/unconfirmed</source> <translation>%1/no confirmado</translation> </message> <message> <source>%1 confirmations</source> <translation>confirmaciones %1</translation> </message> <message> <source>Status</source> <translation>Estado</translation> </message> <message> <source>Date</source> <translation>Fecha</translation> </message> <message> <source>Source</source> <translation>Fuente</translation> </message> <message> <source>Generated</source> <translation>Generado</translation> </message> <message> <source>From</source> <translation>Desde</translation> </message> <message> <source>unknown</source> <translation>desconocido</translation> </message> <message> <source>To</source> <translation>Para</translation> </message> <message> <source>own address</source> <translation>dirección propia</translation> </message> <message> <source>watch-only</source> <translation>de observación</translation> </message> <message> <source>label</source> <translation>etiqueta</translation> </message> <message> <source>Credit</source> <translation>Credito</translation> </message> <message numerus="yes"> <source>matures in %n more block(s)</source> <translation><numerusform>disponible en %n bloque más</numerusform><numerusform>disponible en %n bloques más</numerusform></translation> </message> <message> <source>not accepted</source> <translation>no aceptada</translation> </message> <message> <source>Debit</source> <translation>Enviado</translation> </message> <message> <source>Total debit</source> <translation>Total enviado</translation> </message> <message> <source>Total credit</source> <translation>Total recibido</translation> </message> <message> <source>Transaction fee</source> <translation>Comisión de transacción</translation> </message> <message> <source>Net amount</source> <translation>Cantidad neta</translation> </message> <message> <source>Message</source> <translation>Mensaje</translation> </message> <message> <source>Comment</source> <translation>Comentario</translation> </message> <message> <source>Transaction ID</source> <translation>Identificador de transacción (ID)</translation> </message> <message> <source>Transaction total size</source> <translation>Tamaño total de transacción</translation> </message> <message> <source>Transaction virtual size</source> <translation>Tamaño virtual de transacción</translation> </message> <message> <source>Output index</source> <translation>Indice de salida</translation> </message> <message> <source>Merchant</source> <translation>Vendedor</translation> </message> <message> <source>Generated coins must mature %1 blocks before they can be spent. When you generated this block, it was broadcast to the network to be added to the block chain. If it fails to get into the chain, its state will change to "not accepted" and it won't be spendable. This may occasionally happen if another node generates a block within a few seconds of yours.</source> <translation>Los nexalts generados deben madurar %1 bloques antes de que puedan gastarse. Cuando generó este bloque, se transmitió a la red para que se añadiera a la cadena de bloques. Si no consigue entrar en la cadena, su estado cambiará a "no aceptado" y ya no se podrá gastar. Esto puede ocurrir ocasionalmente si otro nodo genera un bloque a pocos segundos del suyo.</translation> </message> <message> <source>Debug information</source> <translation>Información de depuración</translation> </message> <message> <source>Transaction</source> <translation>Transacción</translation> </message> <message> <source>Inputs</source> <translation>Entradas</translation> </message> <message> <source>Amount</source> <translation>Cantidad</translation> </message> <message> <source>true</source> <translation>verdadero</translation> </message> <message> <source>false</source> <translation>falso</translation> </message> </context> <context> <name>TransactionDescDialog</name> <message> <source>This pane shows a detailed description of the transaction</source> <translation>Esta ventana muestra información detallada sobre la transacción</translation> </message> <message> <source>Details for %1</source> <translation>Detalles para %1</translation> </message> </context> <context> <name>TransactionTableModel</name> <message> <source>Date</source> <translation>Fecha</translation> </message> <message> <source>Type</source> <translation>Tipo</translation> </message> <message> <source>Label</source> <translation>Etiqueta</translation> </message> <message numerus="yes"> <source>Open for %n more block(s)</source> <translation><numerusform>Abrir para %n bloque más</numerusform><numerusform>Abrir para %n bloques más</numerusform></translation> </message> <message> <source>Open until %1</source> <translation>Abierto hasta %1</translation> </message> <message> <source>Unconfirmed</source> <translation>Sin confirmar</translation> </message> <message> <source>Abandoned</source> <translation>Abandonado</translation> </message> <message> <source>Confirming (%1 of %2 recommended confirmations)</source> <translation>Confirmando (%1 de %2 confirmaciones recomendadas)</translation> </message> <message> <source>Confirmed (%1 confirmations)</source> <translation>Confirmado (%1 confirmaciones)</translation> </message> <message> <source>Conflicted</source> <translation>En conflicto</translation> </message> <message> <source>Immature (%1 confirmations, will be available after %2)</source> <translation>No disponible (%1 confirmaciones. Estarán disponibles al cabo de %2)</translation> </message> <message> <source>Generated but not accepted</source> <translation>Generado pero no aceptado</translation> </message> <message> <source>Received with</source> <translation>Recibido con</translation> </message> <message> <source>Received from</source> <translation>Recibidos de</translation> </message> <message> <source>Sent to</source> <translation>Enviado a</translation> </message> <message> <source>Payment to yourself</source> <translation>Pago proprio</translation> </message> <message> <source>Mined</source> <translation>Minado</translation> </message> <message> <source>watch-only</source> <translation>de observación</translation> </message> <message> <source>(n/a)</source> <translation>(nd)</translation> </message> <message> <source>(no label)</source> <translation>(sin etiqueta)</translation> </message> <message> <source>Transaction status. Hover over this field to show number of confirmations.</source> <translation>Estado de transacción. Pasa el ratón sobre este campo para ver el número de confirmaciones.</translation> </message> <message> <source>Date and time that the transaction was received.</source> <translation>Fecha y hora en que se recibió la transacción.</translation> </message> <message> <source>Type of transaction.</source> <translation>Tipo de transacción.</translation> </message> <message> <source>Whether or not a watch-only address is involved in this transaction.</source> <translation>Si una dirección watch-only está involucrada en esta transacción o no.</translation> </message> <message> <source>User-defined intent/purpose of the transaction.</source> <translation>Descripción de la transacción definido por el usuario.</translation> </message> <message> <source>Amount removed from or added to balance.</source> <translation>Cantidad retirada o añadida al saldo.</translation> </message> </context> <context> <name>TransactionView</name> <message> <source>All</source> <translation>Todo</translation> </message> <message> <source>Today</source> <translation>Hoy</translation> </message> <message> <source>This week</source> <translation>Esta semana</translation> </message> <message> <source>This month</source> <translation>Este mes</translation> </message> <message> <source>Last month</source> <translation>Mes pasado</translation> </message> <message> <source>This year</source> <translation>Este año</translation> </message> <message> <source>Range...</source> <translation>Rango...</translation> </message> <message> <source>Received with</source> <translation>Recibido con</translation> </message> <message> <source>Sent to</source> <translation>Enviado a</translation> </message> <message> <source>To yourself</source> <translation>A usted mismo</translation> </message> <message> <source>Mined</source> <translation>Minado</translation> </message> <message> <source>Other</source> <translation>Otra</translation> </message> <message> <source>Enter address, transaction id, or label to search</source> <translation>Introduzca dirección, id de transacción o etiqueta a buscar</translation> </message> <message> <source>Min amount</source> <translation>Cantidad mínima</translation> </message> <message> <source>Abandon transaction</source> <translation>Transacción abandonada</translation> </message> <message> <source>Increase transaction fee</source> <translation>Incrementar cuota de transacción</translation> </message> <message> <source>Copy address</source> <translation>Copiar ubicación</translation> </message> <message> <source>Copy label</source> <translation>Copiar etiqueta</translation> </message> <message> <source>Copy amount</source> <translation>Copiar cantidad</translation> </message> <message> <source>Copy transaction ID</source> <translation>Copiar ID de transacción</translation> </message> <message> <source>Copy raw transaction</source> <translation>Copiar transacción raw</translation> </message> <message> <source>Copy full transaction details</source> <translation>Copiar todos los detalles de la transacción</translation> </message> <message> <source>Edit label</source> <translation>Editar etiqueta</translation> </message> <message> <source>Show transaction details</source> <translation>Mostrar detalles de la transacción</translation> </message> <message> <source>Export Transaction History</source> <translation>Exportar historial de transacciones</translation> </message> <message> <source>Comma separated file (*.csv)</source> <translation>Archivo separado de coma (*.csv)</translation> </message> <message> <source>Confirmed</source> <translation>Confirmado</translation> </message> <message> <source>Watch-only</source> <translation>De observación</translation> </message> <message> <source>Date</source> <translation>Fecha</translation> </message> <message> <source>Type</source> <translation>Tipo</translation> </message> <message> <source>Label</source> <translation>Etiqueta</translation> </message> <message> <source>Address</source> <translation>Dirección</translation> </message> <message> <source>ID</source> <translation>ID</translation> </message> <message> <source>Exporting Failed</source> <translation>Falló la exportación</translation> </message> <message> <source>There was an error trying to save the transaction history to %1.</source> <translation>Ha habido un error al intentar guardar la transacción con %1.</translation> </message> <message> <source>Exporting Successful</source> <translation>Exportación finalizada</translation> </message> <message> <source>The transaction history was successfully saved to %1.</source> <translation>La transacción ha sido guardada en %1.</translation> </message> <message> <source>Range:</source> <translation>Rango:</translation> </message> <message> <source>to</source> <translation>para</translation> </message> </context> <context> <name>UnitDisplayStatusBarControl</name> <message> <source>Unit to show amounts in. Click to select another unit.</source> <translation>Unidad en la que se muestran las cantidades. Haga clic para seleccionar otra unidad.</translation> </message> </context> <context> <name>WalletController</name> <message> <source>Close wallet</source> <translation>Cerrar monedero</translation> </message> <message> <source>Are you sure you wish to close wallet &lt;i&gt;%1&lt;/i&gt;?</source> <translation>¿Está seguro que desea cerra el monedero &lt;i&gt;%1&lt;/i&gt;?</translation> </message> <message> <source>Closing the wallet for too long can result in having to resync the entire chain if pruning is enabled.</source> <translation>Cerrar la monedero durante demasiado tiempo puede causar resincronizado de toda la cadena si la poda es habilitado.</translation> </message> </context> <context> <name>WalletFrame</name> <message> <source>No wallet has been loaded.</source> <translation>No se ha cargado ningún monedero</translation> </message> </context> <context> <name>WalletModel</name> <message> <source>Send Coins</source> <translation>Enviar</translation> </message> <message> <source>Fee bump error</source> <translation>Error de incremento de comisión</translation> </message> <message> <source>Increasing transaction fee failed</source> <translation>Ha fallado el incremento de la comisión de transacción.</translation> </message> <message> <source>Do you want to increase the fee?</source> <translation>¿Desea incrementar la comisión?</translation> </message> <message> <source>Current fee:</source> <translation>Comisión actual:</translation> </message> <message> <source>Increase:</source> <translation>Incremento:</translation> </message> <message> <source>New fee:</source> <translation>Nueva comisión:</translation> </message> <message> <source>Confirm fee bump</source> <translation>Confirmar incremento de comisión.</translation> </message> <message> <source>Can't sign transaction.</source> <translation>No se ha podido firmar la transacción.</translation> </message> <message> <source>Could not commit transaction</source> <translation>No se pudo confirmar la transacción</translation> </message> <message> <source>default wallet</source> <translation>Monedero predeterminado</translation> </message> </context> <context> <name>WalletView</name> <message> <source>&amp;Export</source> <translation>&amp;Exportar</translation> </message> <message> <source>Export the data in the current tab to a file</source> <translation>Exportar a un archivo los datos de esta pestaña</translation> </message> <message> <source>Backup Wallet</source> <translation>Copia de seguridad del monedero</translation> </message> <message> <source>Wallet Data (*.dat)</source> <translation>Datos de monedero (*.dat)</translation> </message> <message> <source>Backup Failed</source> <translation>La copia de seguridad ha fallado</translation> </message> <message> <source>There was an error trying to save the wallet data to %1.</source> <translation>Ha habido un error al intentar guardar los datos del monedero en %1.</translation> </message> <message> <source>Backup Successful</source> <translation>Se ha completado con éxito la copia de respaldo</translation> </message> <message> <source>The wallet data was successfully saved to %1.</source> <translation>Los datos del monedero se han guardado con éxito en %1.</translation> </message> <message> <source>Cancel</source> <translation>Cancelar</translation> </message> </context> <context> <name>bitcoin-core</name> <message> <source>Distributed under the MIT software license, see the accompanying file %s or %s</source> <translation>Distribuido bajo la licencia de software MIT, vea el archivo adjunto %s o %s</translation> </message> <message> <source>Prune configured below the minimum of %d MiB. Please use a higher number.</source> <translation>La Poda se ha configurado por debajo del minimo de %d MiB. Por favor utiliza un valor más alto.</translation> </message> <message> <source>Prune: last wallet synchronisation goes beyond pruned data. You need to -reindex (download the whole blockchain again in case of pruned node)</source> <translation>Poda: la ultima sincronizacion del monedero sobrepasa los datos podados. Necesitas reindexar con -reindex (o descargar la cadena de bloques de nuevo en el caso de un nodo podado)</translation> </message> <message> <source>Rescans are not possible in pruned mode. You will need to use -reindex which will download the whole blockchain again.</source> <translation>Nos es posible re-escanear en modo podado.Necesitas utilizar -reindex el cual descargara la cadena de bloques al completo de nuevo.</translation> </message> <message> <source>Error: A fatal internal error occurred, see debug.log for details</source> <translation>Un error interno fatal ocurrió, ver debug.log para detalles</translation> </message> <message> <source>Pruning blockstore...</source> <translation>Poda blockstore ...</translation> </message> <message> <source>Unable to start HTTP server. See debug log for details.</source> <translation>No se ha podido comenzar el servidor HTTP. Ver debug log para detalles.</translation> </message> <message> <source>Nexalt Core</source> <translation>Nexalt Core</translation> </message> <message> <source>The %s developers</source> <translation>Los desarrolladores de %s</translation> </message> <message> <source>Can't generate a change-address key. No keys in the internal keypool and can't generate any keys.</source> <translation>No se puede generar una clave de cambio-de-dirección. No hay claves en el cojunto de claves internas y no se pueden generar claves.</translation> </message> <message> <source>Cannot obtain a lock on data directory %s. %s is probably already running.</source> <translation>No se puede bloquear el directorio %s. %s ya se está ejecutando.</translation> </message> <message> <source>Cannot provide specific connections and have addrman find outgoing connections at the same.</source> <translation>No es posible mostrar las conexiones indicadas y tener addrman buscando conexiones al mismo tiempo.</translation> </message> <message> <source>Error reading %s! All keys read correctly, but transaction data or address book entries might be missing or incorrect.</source> <translation>Error leyendo %s!. Todas las claves se han leido correctamente, pero los datos de transacciones o la libreta de direcciones pueden faltar o ser incorrectos.</translation> </message> <message> <source>Please check that your computer's date and time are correct! If your clock is wrong, %s will not work properly.</source> <translation>Por favor, compruebe si la fecha y hora en su computadora son correctas! Si su reloj esta mal, %s no trabajara correctamente. </translation> </message> <message> <source>Please contribute if you find %s useful. Visit %s for further information about the software.</source> <translation>Contribuya si encuentra %s de utilidad. Visite %s para mas información acerca del programa.</translation> </message> <message> <source>The block database contains a block which appears to be from the future. This may be due to your computer's date and time being set incorrectly. Only rebuild the block database if you are sure that your computer's date and time are correct</source> <translation>La base de datos de bloques contiene un bloque que parece ser del futuro. Esto puede ser porque la fecha y hora de tu ordenador están mal ajustados. Reconstruye la base de datos de bloques solo si estas seguro de que la fecha y hora de tu ordenador estan ajustados correctamente.</translation> </message> <message> <source>This is a pre-release test build - use at your own risk - do not use for mining or merchant applications</source> <translation>Esta es una versión de prueba prelanzada - utilícelo a su propio riesgo - no lo utilice para aplicaciones de minería o comerciales</translation> </message> <message> <source>This is the transaction fee you may discard if change is smaller than dust at this level</source> <translation>Esta es la comisión de transacción que puedes descartar si el cambio es menor que el polvo a este nivel</translation> </message> <message> <source>Unable to replay blocks. You will need to rebuild the database using -reindex-chainstate.</source> <translation>No se ha podido reproducir los bloques. Deberá reconstruir la base de datos utilizando -reindex-chainstate.</translation> </message> <message> <source>Unable to rewind the database to a pre-fork state. You will need to redownload the blockchain</source> <translation>No es posible reconstruir la base de datos a un estado anterior. Debe descargar de nuevo la cadena de bloques.</translation> </message> <message> <source>Warning: The network does not appear to fully agree! Some miners appear to be experiencing issues.</source> <translation>Advertencia: ¡La red no parece coincidir del todo! Algunos mineros parecen estar experimentando problemas.</translation> </message> <message> <source>Warning: We do not appear to fully agree with our peers! You may need to upgrade, or other nodes may need to upgrade.</source> <translation>Advertencia: ¡No parecemos estar del todo con nuestros pares! Puede que necesite actualizarse, o puede que otros nodos necesiten actualizarse.</translation> </message> <message> <source>%d of last 100 blocks have unexpected version</source> <translation>%d de los últimos 100 bloques tienen versión no esperada</translation> </message> <message> <source>%s corrupt, salvage failed</source> <translation>%s corrupto. Fracasó la recuperacion</translation> </message> <message> <source>-maxmempool must be at least %d MB</source> <translation>-maxmempool debe ser por lo menos de %d MB</translation> </message> <message> <source>Cannot resolve -%s address: '%s'</source> <translation>No se puede resolver -%s direccion: '%s'</translation> </message> <message> <source>Change index out of range</source> <translation>Cambio de indice fuera de rango</translation> </message> <message> <source>Config setting for %s only applied on %s network when in [%s] section.</source> <translation>La configuración para %s solo se aplica en la red %s cuando son en la sección [%s].</translation> </message> <message> <source>Copyright (C) %i-%i</source> <translation>Copyright (C) %i-%i</translation> </message> <message> <source>Corrupted block database detected</source> <translation>Corrupción de base de datos de bloques detectada.</translation> </message> <message> <source>Do you want to rebuild the block database now?</source> <translation>¿Quieres reconstruir la base de datos de bloques ahora?</translation> </message> <message> <source>Error initializing block database</source> <translation>Error al inicializar la base de datos de bloques</translation> </message> <message> <source>Error initializing wallet database environment %s!</source> <translation>Error al inicializar el entorno de la base de datos del monedero %s</translation> </message> <message> <source>Error loading %s</source> <translation>Error cargando %s</translation> </message> <message> <source>Error loading %s: Private keys can only be disabled during creation</source> <translation>Error cargando %s: las claves privadas solo pueden ser deshabilitado durante la creación</translation> </message> <message> <source>Error loading %s: Wallet corrupted</source> <translation>Error cargando %s: Monedero dañado</translation> </message> <message> <source>Error loading %s: Wallet requires newer version of %s</source> <translation>Error cargando %s: Monedero requiere un versión mas reciente de %s</translation> </message> <message> <source>Error loading block database</source> <translation>Error cargando base de datos de bloques</translation> </message> <message> <source>Error opening block database</source> <translation>Error al abrir base de datos de bloques.</translation> </message> <message> <source>Error: Disk space is low!</source> <translation>Error: ¡Espacio en disco bajo!</translation> </message> <message> <source>Failed to listen on any port. Use -listen=0 if you want this.</source> <translation>Ha fallado la escucha en todos los puertos. Use -listen=0 si desea esto.</translation> </message> <message> <source>Failed to rescan the wallet during initialization</source> <translation>Fallo al escanear el monedero durante la inicialización</translation> </message> <message> <source>Importing...</source> <translation>Importando...</translation> </message> <message> <source>Incorrect or no genesis block found. Wrong datadir for network?</source> <translation>Incorrecto o bloque de génesis no encontrado. Datadir equivocada para la red?</translation> </message> <message> <source>Initialization sanity check failed. %s is shutting down.</source> <translation>La inicialización de la verificación de validez falló. Se está apagando %s.</translation> </message> <message> <source>Invalid amount for -%s=&lt;amount&gt;: '%s'</source> <translation>Cantidad no valida para -%s=&lt;amount&gt;: '%s'</translation> </message> <message> <source>Invalid amount for -discardfee=&lt;amount&gt;: '%s'</source> <translation>Cantidad inválida para -discardfee=&lt;amount&gt;: '%s'</translation> </message> <message> <source>Invalid amount for -fallbackfee=&lt;amount&gt;: '%s'</source> <translation>Cantidad inválida para -fallbackfee=&lt;amount&gt;: '%s'</translation> </message> <message> <source>Specified blocks directory "%s" does not exist.</source> <translation>El directorio de bloques «%s» especificado no existe.</translation> </message> <message> <source>Unable to create the PID file '%s': %s</source> <translation>No es posible crear el fichero PID '%s': %s</translation> </message> <message> <source>Upgrading txindex database</source> <translation>Actualización de la base de datos txindex</translation> </message> <message> <source>Loading P2P addresses...</source> <translation>Cargando direcciones P2P ...</translation> </message> <message> <source>Loading banlist...</source> <translation>Cargando banlist...</translation> </message> <message> <source>Not enough file descriptors available.</source> <translation>No hay suficientes descriptores de archivo disponibles. </translation> </message> <message> <source>Prune cannot be configured with a negative value.</source> <translation>Pode no se puede configurar con un valor negativo.</translation> </message> <message> <source>Prune mode is incompatible with -txindex.</source> <translation>El modo recorte es incompatible con -txindex.</translation> </message> <message> <source>Replaying blocks...</source> <translation>Reproduciendo bloques ...</translation> </message> <message> <source>Rewinding blocks...</source> <translation>Verificando bloques...</translation> </message> <message> <source>The source code is available from %s.</source> <translation>El código fuente esta disponible desde %s.</translation> </message> <message> <source>Transaction fee and change calculation failed</source> <translation>El cálculo de la comisión de transacción y del cambio han fallado</translation> </message> <message> <source>Unable to bind to %s on this computer. %s is probably already running.</source> <translation>No se ha podido conectar con %s en este equipo. %s es posible que este todavia en ejecución.</translation> </message> <message> <source>Unable to generate keys</source> <translation>Incapaz de generar claves</translation> </message> <message> <source>Unsupported logging category %s=%s.</source> <translation>Categoría de registro no soportada %s=%s.</translation> </message> <message> <source>Upgrading UTXO database</source> <translation>Actualizando la base de datos UTXO</translation> </message> <message> <source>User Agent comment (%s) contains unsafe characters.</source> <translation>El comentario del Agente de Usuario (%s) contiene caracteres inseguros.</translation> </message> <message> <source>Verifying blocks...</source> <translation>Verificando bloques...</translation> </message> <message> <source>Wallet needed to be rewritten: restart %s to complete</source> <translation>Es necesario reescribir el monedero: reiniciar %s para completar</translation> </message> <message> <source>Error: Listening for incoming connections failed (listen returned error %s)</source> <translation>Error: la escucha para conexiones entrantes falló (la escucha regresó el error %s)</translation> </message> <message> <source>Invalid amount for -maxtxfee=&lt;amount&gt;: '%s' (must be at least the minrelay fee of %s to prevent stuck transactions)</source> <translation>Cantidad no válida para -maxtxfee=&lt;amount&gt;: '%s' (debe ser por lo menos la comisión mínima de %s para prevenir transacciones atascadas)</translation> </message> <message> <source>The transaction amount is too small to send after the fee has been deducted</source> <translation>Monto de transacción muy pequeña luego de la deducción por comisión</translation> </message> <message> <source>You need to rebuild the database using -reindex to go back to unpruned mode. This will redownload the entire blockchain</source> <translation>Necesitas reconstruir la base de datos utilizando -reindex para volver al modo sin recorte. Esto volverá a descargar toda la cadena de bloques</translation> </message> <message> <source>Error reading from database, shutting down.</source> <translation>Error al leer la base de datos, cerrando.</translation> </message> <message> <source>Error upgrading chainstate database</source> <translation>Error actualizando la base de datos chainstate</translation> </message> <message> <source>Information</source> <translation>Información</translation> </message> <message> <source>Invalid -onion address or hostname: '%s'</source> <translation>Dirección -onion o nombre de host inválido: '%s'</translation> </message> <message> <source>Invalid -proxy address or hostname: '%s'</source> <translation>Dirección -proxy o nombre de host inválido: '%s'</translation> </message> <message> <source>Invalid amount for -paytxfee=&lt;amount&gt;: '%s' (must be at least %s)</source> <translation>Cantidad inválida para -paytxfee=&lt;amount&gt;: '%s' (debe ser por lo menos %s)</translation> </message> <message> <source>Invalid netmask specified in -whitelist: '%s'</source> <translation>Máscara de red inválida especificada en -whitelist: '%s'</translation> </message> <message> <source>Need to specify a port with -whitebind: '%s'</source> <translation>Necesita especificar un puerto con -whitebind: '%s'</translation> </message> <message> <source>Reducing -maxconnections from %d to %d, because of system limitations.</source> <translation>Reduciendo -maxconnections de %d a %d, debido a limitaciones del sistema.</translation> </message> <message> <source>Section [%s] is not recognized.</source> <translation>La sección [%s] no se ha reconocido.</translation> </message> <message> <source>Signing transaction failed</source> <translation>Transacción falló</translation> </message> <message> <source>Specified -walletdir "%s" does not exist</source> <translation>El -walletdir indicado "%s" no existe</translation> </message> <message> <source>Specified -walletdir "%s" is a relative path</source> <translation>Indique -walletdir "%s" como una ruta relativa</translation> </message> <message> <source>Specified -walletdir "%s" is not a directory</source> <translation>El -walletdir "%s" indicado no es un directorio</translation> </message> <message> <source>The specified config file %s does not exist </source> <translation>El fichero de configuración %s especificado no existe </translation> </message> <message> <source>The transaction amount is too small to pay the fee</source> <translation>Cantidad de la transacción demasiado pequeña para pagar la comisión</translation> </message> <message> <source>This is experimental software.</source> <translation>Este software es experimental.</translation> </message> <message> <source>Transaction amount too small</source> <translation>Cantidad de la transacción demasiado pequeña</translation> </message> <message> <source>Transaction too large for fee policy</source> <translation>Transacción demasiado grande para la política de comisiones</translation> </message> <message> <source>Transaction too large</source> <translation>Transacción demasiado grande, intenta dividirla en varias.</translation> </message> <message> <source>Unable to bind to %s on this computer (bind returned error %s)</source> <translation>No es posible conectar con %s en este sistema (bind ha dado el error %s)</translation> </message> <message> <source>Unable to generate initial keys</source> <translation>No es posible generar llaves iniciales</translation> </message> <message> <source>Verifying wallet(s)...</source> <translation>Verificando monedero(s)...</translation> </message> <message> <source>Wallet %s resides outside wallet directory %s</source> <translation>Monedero %s situado fuera del directorio de monedero %s</translation> </message> <message> <source>Warning</source> <translation>Aviso</translation> </message> <message> <source>Warning: unknown new rules activated (versionbit %i)</source> <translation>Advertencia: nuevas reglas desconocidas activadas (versionbit %i)</translation> </message> <message> <source>Zapping all transactions from wallet...</source> <translation>Eliminando todas las transacciones del monedero...</translation> </message> <message> <source>-maxtxfee is set very high! Fees this large could be paid on a single transaction.</source> <translation>-maxtxfee tiene un ajuste muy elevado! Comisiones muy grandes podrían ser pagadas en una única transaccion.</translation> </message> <message> <source>This is the transaction fee you may pay when fee estimates are not available.</source> <translation>Esta es la comisión de transacción que debe pagar cuando las estimaciones de comisión no estén disponibles.</translation> </message> <message> <source>This product includes software developed by the OpenSSL Project for use in the OpenSSL Toolkit %s and cryptographic software written by Eric Young and UPnP software written by Thomas Bernard.</source> <translation>Este producto incluye software desarrollado por el Proyecto OpenSSL para utilizarlo en el juego de herramientas OpenSSL %s y software criptográfico escrito por Eric Young y software UPnP escrito por Thomas Bernard.</translation> </message> <message> <source>Total length of network version string (%i) exceeds maximum length (%i). Reduce the number or size of uacomments.</source> <translation>La longitud total de la cadena de versión de red ( %i ) supera la longitud máxima ( %i ) . Reducir el número o tamaño de uacomments .</translation> </message> <message> <source>Warning: Wallet file corrupt, data salvaged! Original %s saved as %s in %s; if your balance or transactions are incorrect you should restore from a backup.</source> <translation>Aviso: fichero de monedero corrupto, datos recuperados! Original %s guardado como %s en %s; si su balance de transacciones es incorrecto, debe restaurar desde una copia de seguridad.</translation> </message> <message> <source>%s is set very high!</source> <translation>¡%s se establece muy alto!</translation> </message> <message> <source>Error loading wallet %s. Duplicate -wallet filename specified.</source> <translation>Error cargando el monedero %s. Se ha especificado un nombre de fichero -wallet duplicado.</translation> </message> <message> <source>Keypool ran out, please call keypoolrefill first</source> <translation>Keypool se ha agotado, llame a keypoolrefill primero</translation> </message> <message> <source>Starting network threads...</source> <translation>Iniciando funciones de red...</translation> </message> <message> <source>The wallet will avoid paying less than the minimum relay fee.</source> <translation>El monedero evitará pagar menos que la cuota de retransmisión mínima.</translation> </message> <message> <source>This is the minimum transaction fee you pay on every transaction.</source> <translation>Esta es la comisión mínima de transacción que usted paga en cada transacción.</translation> </message> <message> <source>This is the transaction fee you will pay if you send a transaction.</source> <translation>Esta es la comisión de transacción que pagará si envía una transacción.</translation> </message> <message> <source>Transaction amounts must not be negative</source> <translation>Las cantidades de transacción no deben ser negativa</translation> </message> <message> <source>Transaction has too long of a mempool chain</source> <translation>La transacción tiene demasiado tiempo de una cadena de mempool</translation> </message> <message> <source>Transaction must have at least one recipient</source> <translation>La transacción debe de tener al menos un receptor</translation> </message> <message> <source>Unknown network specified in -onlynet: '%s'</source> <translation>La red especificada en -onlynet '%s' es desconocida</translation> </message> <message> <source>Insufficient funds</source> <translation>Fondos insuficientes</translation> </message> <message> <source>Cannot upgrade a non HD split wallet without upgrading to support pre split keypool. Please use -upgradewallet=169900 or -upgradewallet with no version specified.</source> <translation>No se puede actualizar un monedero dividido sin HD sin actualizar para admitir el keypool pre dividido. Utilice -upgradewallet = 169900 o -upgradewallet sin una versión especificada.</translation> </message> <message> <source>Fee estimation failed. Fallbackfee is disabled. Wait a few blocks or enable -fallbackfee.</source> <translation>Estimación de la comisión fallida. Fallbackfee está deshabilitado. Espere unos pocos bloques o habilite -fallbackfee.</translation> </message> <message> <source>Warning: Private keys detected in wallet {%s} with disabled private keys</source> <translation>Advertencia: claves privadas detectadas en el monedero {%s} con claves privadas deshabilitadas</translation> </message> <message> <source>Cannot write to data directory '%s'; check permissions.</source> <translation>No se puede escribir en el directorio de datos '%s'; verificar permisos.</translation> </message> <message> <source>Loading block index...</source> <translation>Cargando el índice de bloques...</translation> </message> <message> <source>Loading wallet...</source> <translation>Cargando monedero...</translation> </message> <message> <source>Cannot downgrade wallet</source> <translation>No se puede cambiar a una versión mas antigua el monedero</translation> </message> <message> <source>Rescanning...</source> <translation>Reexplorando...</translation> </message> <message> <source>Done loading</source> <translation>Se terminó de cargar</translation> </message> <message> <source>Error</source> <translation>Error</translation> </message> </context> </TS>
<source>Min Ping</source> <translation>Min Ping</translation> </message> <message>
error.rs
// Copyright (c) The Libra Core Contributors // SPDX-License-Identifier: Apache-2.0 use serde::{de, ser}; use std::{error, fmt}; pub type Result<T> = std::result::Result<T, Error>; #[derive(Clone, Debug, PartialEq)] pub enum Error { Eof, ExceededMaxLen(usize), ExpectedBoolean, ExpectedMapKey, ExpectedMapValue, ExpectedOption, Custom(String), MissingLen, NotSupported(&'static str), RemainingInput, Utf8, } impl ser::Error for Error { fn custom<T: fmt::Display>(msg: T) -> Self { Error::Custom(msg.to_string()) } } impl de::Error for Error { fn
<T: fmt::Display>(msg: T) -> Self { Error::Custom(msg.to_string()) } } impl fmt::Display for Error { fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { formatter.write_str(std::error::Error::description(self)) } } impl error::Error for Error { fn description(&self) -> &str { use Error::*; match self { Eof => "unexpected end of input", ExceededMaxLen(_) => "exceeded max sequence length", ExpectedBoolean => "expected boolean", ExpectedMapKey => "expected map key", ExpectedMapValue => "expected map value", ExpectedOption => "expected option type", Custom(msg) => msg, MissingLen => "sequence missing length", NotSupported(_) => "not supported", RemainingInput => "remaining input", Utf8 => "malformed utf8", } } }
custom
amiga.rs
use super::byteorder::{BigEndian, ByteOrder}; use super::amiga_hunk_parser::{HunkParser, Hunk, HunkType}; use super::musashi::Musashi; use std::io; // Memory layout of the 'Amiga' // 0 - 512K is reserved for the "rom" // 512 - 4MB - Executable has the range of 16MB // 4MB - 16MB - 16MB -> Heap, bss, etc static mut AMIGA_MEMORY: [u8; 16 * 1024 * 1024] = [0; 16 * 1024 * 1024]; const EXE_START: usize = 512 * 1024; pub struct Amiga { pub dummy: u32, } impl Amiga { pub fn new() -> Amiga { Amiga { dummy: 0, } } // TODO: We should store within the amiga what data is allowed to be accesed fn get_amiga_memory_long(offset: u32) -> u32 { unsafe { let v0 = AMIGA_MEMORY[offset as usize + 0] as u32; let v1 = AMIGA_MEMORY[offset as usize + 1] as u32; let v2 = AMIGA_MEMORY[offset as usize + 2] as u32; let v3 = AMIGA_MEMORY[offset as usize + 3] as u32; (v0 << 24) | (v1 << 16) | (v2 << 8) | v3 } } // TODO: We should store within the amiga what data is allowed to be accesed fn set_amiga_memory_long(offset: u32, value: u32) { unsafe { AMIGA_MEMORY[offset as usize + 0] = ((value >> 24) & 0xff) as u8; AMIGA_MEMORY[offset as usize + 1] = ((value >> 16) & 0xff) as u8; AMIGA_MEMORY[offset as usize + 2] = ((value >> 8) & 0xff) as u8; AMIGA_MEMORY[offset as usize + 3] = ((value >> 0) & 0xff) as u8; } } pub fn parse_executable(filename: &str) -> Result<Vec<Hunk>, io::Error> { HunkParser::parse_file(filename) } fn copy_data<'a>(src: &'a [u8], dest: &'a mut [u8], size: usize) { for i in 0..size { dest[i] = src[i]; } } fn clear_memory<'a>(dest: &'a mut [u8], size: usize) { for i in 0..size { dest[i] = 0; } } pub fn load_code_data(hunks: &mut Vec<Hunk>, hunk_type: HunkType, offset: usize) -> usize { let mut curr_offset = offset; for hunk in hunks.iter_mut() { if hunk.hunk_type == hunk_type { hunk.memory_offset = curr_offset; hunk.code_data.as_ref().map(|data| { unsafe { Self::copy_data(&data, &mut AMIGA_MEMORY[curr_offset..], hunk.data_size); } curr_offset += hunk.data_size; }); } } curr_offset } fn init_bss_sections(hunks: &mut Vec<Hunk>, offset: usize) -> usize { let mut curr_offset = offset; for hunk in hunks.iter_mut() { if hunk.hunk_type == HunkType::Bss { hunk.memory_offset = curr_offset; hunk.code_data.as_ref().map(|_| { unsafe { // Needs to be unsafe because Musashi callbacks doesn't provide userdata // thus the Amiga memory needs to be global Self::clear_memory(&mut AMIGA_MEMORY[curr_offset..], hunk.data_size); } curr_offset += hunk.data_size; }); } } curr_offset } fn reloc_hunk(hunk: &Hunk, hunks: &Vec<Hunk>) { if let Some(reloc_data) = hunk.reloc_32.as_ref() { let hunk_offset = hunk.memory_offset as u32; for reloc in reloc_data { let target_hunk_offset = hunks[reloc.target].memory_offset as u32; for offset in &reloc.data { let write_target = hunk_offset + offset; let value = Self::get_amiga_memory_long(write_target); Self::set_amiga_memory_long(write_target, target_hunk_offset + value); } } } } /// /// Relocates the code within our memory region /// fn reloc_code_data(hunks: &Vec<Hunk>) { for hunk in hunks { if hunk.hunk_type == HunkType::Code || hunk.hunk_type == HunkType::Data { Self::reloc_hunk(hunk, hunks); } } } fn load_to_memory(hunks: &mut Vec<Hunk>) { let code_end = Self::load_code_data(hunks, HunkType::Code, EXE_START); let data_end = Self::load_code_data(hunks, HunkType::Data, code_end); let bss_end = Self::init_bss_sections(hunks, data_end); Self::reloc_code_data(hunks); println!("code end: {} data end: {} bss end: {}", code_end, data_end, bss_end); let mut pc = EXE_START as u32; while pc < code_end as u32 { pc += Musashi::disassemble(pc); } } pub fn load_executable_to_memory(&self, filename: &str) -> io::Result<()>
} // // This is kinda ugly but this is the way Musashi works. When we have // our own 68k emulator this should be cleaned up and not be global // #[no_mangle] pub extern "C" fn m68k_read_memory_32(address: u32) -> u32 { unsafe { BigEndian::read_u32(&AMIGA_MEMORY[address as usize..]) } } #[no_mangle] pub extern "C" fn m68k_read_memory_16(address: u32) -> u16 { unsafe { BigEndian::read_u16(&AMIGA_MEMORY[address as usize..]) as u16 } } #[no_mangle] pub extern "C" fn m68k_read_memory_8(address: u32) -> u32 { unsafe { AMIGA_MEMORY[address as usize] as u32 } } #[no_mangle] pub extern "C" fn m68k_write_memory_8(address: u32, value: u32) { unsafe { AMIGA_MEMORY[address as usize] = value as u8 } } #[no_mangle] pub extern "C" fn m68k_write_memory_16(address: u32, value: u32) { unsafe { BigEndian::write_u16(&mut AMIGA_MEMORY[address as usize..], value as u16) } } #[no_mangle] pub extern "C" fn m68k_write_memory_32(address: u32, value: u32) { unsafe { BigEndian::write_u32(&mut AMIGA_MEMORY[address as usize..], value) } } #[no_mangle] pub extern "C" fn m68k_read_disassembler_32(address: u32) -> u32 { m68k_read_memory_32(address) } #[no_mangle] pub extern "C" fn m68k_read_disassembler_16(address: u32) -> u32 { m68k_read_memory_16(address) as u32 } #[no_mangle] pub extern "C" fn m68k_read_disassembler_8(address: u32) -> u32 { m68k_read_memory_8(address) }
{ let mut hunks = Self::parse_executable(filename)?; /* for hunk in &hunks { println!("type {:?} - size {} - alloc_size {}", hunk.hunk_type, hunk.data_size, hunk.alloc_size); } */ Self::load_to_memory(&mut hunks); for hunk in &hunks { println!("type {:?} - {:?}", hunk.hunk_type, hunk); } Ok(()) }
set_zone_config.go
// Copyright 2017 The Cockroach Authors. // // Use of this software is governed by the Business Source License // included in the file licenses/BSL.txt. // // As of the Change Date specified in that file, in accordance with // the Business Source License, use of this software will be governed // by the Apache License, Version 2.0, included in the file // licenses/APL.txt. package sql import ( "context" "fmt" "sort" "strings" "github.com/cockroachdb/cockroach/pkg/config" "github.com/cockroachdb/cockroach/pkg/config/zonepb" "github.com/cockroachdb/cockroach/pkg/internal/client" "github.com/cockroachdb/cockroach/pkg/keys" "github.com/cockroachdb/cockroach/pkg/roachpb" "github.com/cockroachdb/cockroach/pkg/server/serverpb" "github.com/cockroachdb/cockroach/pkg/server/telemetry" "github.com/cockroachdb/cockroach/pkg/sql/pgwire/pgcode" "github.com/cockroachdb/cockroach/pkg/sql/pgwire/pgerror" "github.com/cockroachdb/cockroach/pkg/sql/privilege" "github.com/cockroachdb/cockroach/pkg/sql/sem/tree" "github.com/cockroachdb/cockroach/pkg/sql/sqlbase" "github.com/cockroachdb/cockroach/pkg/sql/sqltelemetry" "github.com/cockroachdb/cockroach/pkg/sql/types" "github.com/cockroachdb/cockroach/pkg/util/protoutil" "github.com/cockroachdb/errors" "github.com/gogo/protobuf/proto" "gopkg.in/yaml.v2" ) type optionValue struct { inheritValue bool explicitValue tree.TypedExpr } type setZoneConfigNode struct { zoneSpecifier tree.ZoneSpecifier allIndexes bool yamlConfig tree.TypedExpr options map[tree.Name]optionValue setDefault bool run setZoneConfigRun } // supportedZoneConfigOptions indicates how to translate SQL variable // assignments in ALTER CONFIGURE ZONE to assignments to the member // fields of zonepb.ZoneConfig. var supportedZoneConfigOptions = map[tree.Name]struct { requiredType *types.T setter func(*zonepb.ZoneConfig, tree.Datum) }{ "range_min_bytes": {types.Int, func(c *zonepb.ZoneConfig, d tree.Datum) { c.RangeMinBytes = proto.Int64(int64(tree.MustBeDInt(d))) }}, "range_max_bytes": {types.Int, func(c *zonepb.ZoneConfig, d tree.Datum) { c.RangeMaxBytes = proto.Int64(int64(tree.MustBeDInt(d))) }}, "num_replicas": {types.Int, func(c *zonepb.ZoneConfig, d tree.Datum) { c.NumReplicas = proto.Int32(int32(tree.MustBeDInt(d))) }}, "gc.ttlseconds": {types.Int, func(c *zonepb.ZoneConfig, d tree.Datum) { c.GC = &zonepb.GCPolicy{TTLSeconds: int32(tree.MustBeDInt(d))} }}, "constraints": {types.String, func(c *zonepb.ZoneConfig, d tree.Datum) { constraintsList := zonepb.ConstraintsList{ Constraints: c.Constraints, Inherited: c.InheritedConstraints, } loadYAML(&constraintsList, string(tree.MustBeDString(d))) c.Constraints = constraintsList.Constraints c.InheritedConstraints = false }}, "lease_preferences": {types.String, func(c *zonepb.ZoneConfig, d tree.Datum) { loadYAML(&c.LeasePreferences, string(tree.MustBeDString(d))) c.InheritedLeasePreferences = false }}, } // zoneOptionKeys contains the keys from suportedZoneConfigOptions in // deterministic order. Needed to make the event log output // deterministic. var zoneOptionKeys = func() []string { l := make([]string, 0, len(supportedZoneConfigOptions)) for k := range supportedZoneConfigOptions { l = append(l, string(k)) } sort.Strings(l) return l }() func loadYAML(dst interface{}, yamlString string) { if err := yaml.UnmarshalStrict([]byte(yamlString), dst); err != nil { panic(err) } } func (p *planner) SetZoneConfig(ctx context.Context, n *tree.SetZoneConfig) (planNode, error) { if err := checkPrivilegeForSetZoneConfig(ctx, p, n.ZoneSpecifier); err != nil { return nil, err } var yamlConfig tree.TypedExpr if n.YAMLConfig != nil { // We have a CONFIGURE ZONE = <expr> assignment. // This can be either a literal NULL (deletion), or a string containing YAML. // We also support byte arrays for backward compatibility with // previous versions of CockroachDB. var err error yamlConfig, err = p.analyzeExpr( ctx, n.YAMLConfig, nil, tree.IndexedVarHelper{}, types.String, false /*requireType*/, "configure zone") if err != nil { return nil, err } switch typ := yamlConfig.ResolvedType(); typ.Family() { case types.UnknownFamily: // Unknown occurs if the user entered a literal NULL. That's OK and will mean deletion. case types.StringFamily: case types.BytesFamily: default: return nil, pgerror.Newf(pgcode.InvalidParameterValue, "zone config must be of type string or bytes, not %s", typ) } } var options map[tree.Name]optionValue if n.Options != nil { // We have a CONFIGURE ZONE USING ... assignment. // Here we are constrained by the supported ZoneConfig fields, // as described by supportedZoneConfigOptions above. options = make(map[tree.Name]optionValue) for _, opt := range n.Options { if _, alreadyExists := options[opt.Key]; alreadyExists { return nil, pgerror.Newf(pgcode.InvalidParameterValue, "duplicate zone config parameter: %q", tree.ErrString(&opt.Key)) } req, ok := supportedZoneConfigOptions[opt.Key] if !ok { return nil, pgerror.Newf(pgcode.InvalidParameterValue, "unsupported zone config parameter: %q", tree.ErrString(&opt.Key)) } telemetry.Inc( sqltelemetry.SchemaSetZoneConfig( n.ZoneSpecifier.TelemetryName(), string(opt.Key), ), ) if opt.Value == nil { options[opt.Key] = optionValue{inheritValue: true, explicitValue: nil} continue } valExpr, err := p.analyzeExpr( ctx, opt.Value, nil, tree.IndexedVarHelper{}, req.requiredType, true /*requireType*/, string(opt.Key)) if err != nil { return nil, err } options[opt.Key] = optionValue{inheritValue: false, explicitValue: valExpr} } } return &setZoneConfigNode{ zoneSpecifier: n.ZoneSpecifier, allIndexes: n.AllIndexes, yamlConfig: yamlConfig, options: options, setDefault: n.SetDefault, }, nil } func checkPrivilegeForSetZoneConfig(ctx context.Context, p *planner, zs tree.ZoneSpecifier) error { // For system ranges, the system database, or system tables, the user must be // an admin. Otherwise we require CREATE privileges on the database or table // in question. if zs.NamedZone != "" { return p.RequireAdminRole(ctx, "alter system ranges") } if zs.Database != "" { if zs.Database == "system" { return p.RequireAdminRole(ctx, "alter the system database") } dbDesc, err := p.ResolveUncachedDatabaseByName(ctx, string(zs.Database), true) if err != nil { return err } dbCreatePrivilegeErr := p.CheckPrivilege(ctx, dbDesc, privilege.CREATE) dbZoneConfigPrivilegeErr := p.CheckPrivilege(ctx, dbDesc, privilege.ZONECONFIG) // Can set ZoneConfig if user has either CREATE privilege or ZONECONFIG privilege at the Database level if dbZoneConfigPrivilegeErr == nil || dbCreatePrivilegeErr == nil { return nil } return pgerror.Newf(pgcode.InsufficientPrivilege, "user %s does not have %s or %s privilege on %s %s", p.SessionData().User, privilege.ZONECONFIG, privilege.CREATE, dbDesc.TypeName(), dbDesc.GetName()) } tableDesc, err := p.resolveTableForZone(ctx, &zs) if err != nil { if zs.TargetsIndex() && zs.TableOrIndex.Table.TableName == "" { err = errors.WithHint(err, "try specifying the index as <tablename>@<indexname>") } return err
// Can set ZoneConfig if user has either CREATE privilege or ZONECONFIG privilege at the Table level tableCreatePrivilegeErr := p.CheckPrivilege(ctx, tableDesc, privilege.CREATE) tableZoneConfigPrivilegeErr := p.CheckPrivilege(ctx, tableDesc, privilege.ZONECONFIG) if tableCreatePrivilegeErr == nil || tableZoneConfigPrivilegeErr == nil { return nil } return pgerror.Newf(pgcode.InsufficientPrivilege, "user %s does not have %s or %s privilege on %s %s", p.SessionData().User, privilege.ZONECONFIG, privilege.CREATE, tableDesc.TypeName(), tableDesc.GetName()) } // setZoneConfigRun contains the run-time state of setZoneConfigNode during local execution. type setZoneConfigRun struct { numAffected int } // ReadingOwnWrites implements the planNodeReadingOwnWrites interface. // This is because CONFIGURE ZONE performs multiple KV operations on descriptors // and expects to see its own writes. func (n *setZoneConfigNode) ReadingOwnWrites() {} func (n *setZoneConfigNode) startExec(params runParams) error { var yamlConfig string var setters []func(c *zonepb.ZoneConfig) deleteZone := false // Evaluate the configuration input. if n.yamlConfig != nil { // From a YAML string. datum, err := n.yamlConfig.Eval(params.EvalContext()) if err != nil { return err } switch val := datum.(type) { case *tree.DString: yamlConfig = string(*val) case *tree.DBytes: yamlConfig = string(*val) default: deleteZone = true } // Trim spaces, to detect empty zonfigurations. // We'll add back the missing newline below. yamlConfig = strings.TrimSpace(yamlConfig) } var optionStr strings.Builder var copyFromParentList []tree.Name if n.options != nil { // Set from var = value attributes. // // We iterate over zoneOptionKeys instead of iterating over // n.options directly so that the optionStr string constructed for // the event log remains deterministic. for i := range zoneOptionKeys { name := (*tree.Name)(&zoneOptionKeys[i]) val, ok := n.options[*name] if !ok { continue } // We don't add the setters for the fields that will copy values // from the parents. These fields will be set by taking what // value would apply to the zone and setting that value explicitly. // Instead we add the fields to a list that we use at a later time // to copy values over. inheritVal, expr := val.inheritValue, val.explicitValue if inheritVal { copyFromParentList = append(copyFromParentList, *name) if optionStr.Len() > 0 { optionStr.WriteString(", ") } fmt.Fprintf(&optionStr, "%s = COPY FROM PARENT", name) continue } datum, err := expr.Eval(params.EvalContext()) if err != nil { return err } if datum == tree.DNull { return pgerror.Newf(pgcode.InvalidParameterValue, "unsupported NULL value for %q", tree.ErrString(name)) } setter := supportedZoneConfigOptions[*name].setter setters = append(setters, func(c *zonepb.ZoneConfig) { setter(c, datum) }) if optionStr.Len() > 0 { optionStr.WriteString(", ") } fmt.Fprintf(&optionStr, "%s = %s", name, datum) } } telemetry.Inc( sqltelemetry.SchemaChangeAlterWithExtra(n.zoneSpecifier.TelemetryName(), "configure_zone"), ) // If the specifier is for a table, partition or index, this will // resolve the table descriptor. If the specifier is for a database // or range, this is a no-op and a nil pointer is returned as // descriptor. table, err := params.p.resolveTableForZone(params.ctx, &n.zoneSpecifier) if err != nil { return err } if n.zoneSpecifier.TargetsPartition() && len(n.zoneSpecifier.TableOrIndex.Index) == 0 && !n.allIndexes { // Backward compatibility for ALTER PARTITION ... OF TABLE. Determine which // index has the specified partition. partitionName := string(n.zoneSpecifier.Partition) indexes := table.FindIndexesWithPartition(partitionName) switch len(indexes) { case 0: return fmt.Errorf("partition %q does not exist on table %q", partitionName, table.Name) case 1: n.zoneSpecifier.TableOrIndex.Index = tree.UnrestrictedName(indexes[0].Name) default: err := fmt.Errorf( "partition %q exists on multiple indexes of table %q", partitionName, table.Name) err = pgerror.WithCandidateCode(err, pgcode.InvalidParameterValue) err = errors.WithHint(err, "try ALTER PARTITION ... OF INDEX ...") return err } } // If this is an ALTER ALL PARTITIONS statement, we need to find all indexes // with the specified partition name and apply the zone configuration to all // of them. var specifiers []tree.ZoneSpecifier if n.zoneSpecifier.TargetsPartition() && n.allIndexes { sqltelemetry.IncrementPartitioningCounter(sqltelemetry.AlterAllPartitions) for _, idx := range table.AllNonDropIndexes() { if p := idx.FindPartitionByName(string(n.zoneSpecifier.Partition)); p != nil { zs := n.zoneSpecifier zs.TableOrIndex.Index = tree.UnrestrictedName(idx.Name) specifiers = append(specifiers, zs) } } } else { specifiers = append(specifiers, n.zoneSpecifier) } applyZoneConfig := func(zs tree.ZoneSpecifier) error { subzonePlaceholder := false // resolveZone determines the ID of the target object of the zone // specifier. This ought to succeed regardless of whether there is // already a zone config for the target object. targetID, err := resolveZone(params.ctx, params.p.txn, &zs) if err != nil { return err } // NamespaceTableID is not in the system gossip range, but users should not // be allowed to set zone configs on it. if targetID != keys.SystemDatabaseID && sqlbase.IsSystemConfigID(targetID) || targetID == keys.NamespaceTableID { return pgerror.Newf(pgcode.CheckViolation, `cannot set zone configs for system config tables; `+ `try setting your config on the entire "system" database instead`) } else if targetID == keys.RootNamespaceID && deleteZone { return pgerror.Newf(pgcode.CheckViolation, "cannot remove default zone") } // resolveSubzone determines the sub-parts of the zone // specifier. This ought to succeed regardless of whether there is // already a zone config. index, partition, err := resolveSubzone(&zs, table) if err != nil { return err } // Retrieve the partial zone configuration partialZone, err := getZoneConfigRaw(params.ctx, params.p.txn, targetID) if err != nil { return err } // No zone was found. Possibly a SubzonePlaceholder depending on the index. if partialZone == nil { partialZone = zonepb.NewZoneConfig() if index != nil { subzonePlaceholder = true } } var partialSubzone *zonepb.Subzone if index != nil { partialSubzone = partialZone.GetSubzoneExact(uint32(index.ID), partition) if partialSubzone == nil { partialSubzone = &zonepb.Subzone{Config: *zonepb.NewZoneConfig()} } } // Retrieve the zone configuration. // // If the statement was USING DEFAULT, we want to ignore the zone // config that exists on targetID and instead skip to the inherited // default (whichever applies -- a database if targetID is a table, // default if targetID is a database, etc.). For this, we use the last // parameter getInheritedDefault to GetZoneConfigInTxn(). // These zones are only used for validations. The merged zone is will // not be written. _, completeZone, completeSubzone, err := GetZoneConfigInTxn(params.ctx, params.p.txn, uint32(targetID), index, partition, n.setDefault) if err == errNoZoneConfigApplies { // No zone config yet. // // GetZoneConfigInTxn will fail with errNoZoneConfigApplies when // the target ID is not a database object, i.e. one of the system // ranges (liveness, meta, etc.), and did not have a zone config // already. completeZone = protoutil.Clone( params.extendedEvalCtx.ExecCfg.DefaultZoneConfig).(*zonepb.ZoneConfig) } else if err != nil { return err } // We need to inherit zone configuration information from the correct zone, // not completeZone. { // Function for getting the zone config within the current transaction. getKey := func(key roachpb.Key) (*roachpb.Value, error) { kv, err := params.p.txn.Get(params.ctx, key) if err != nil { return nil, err } return kv.Value, nil } if index == nil { // If we are operating on a zone, get all fields that the zone would // inherit from its parent. We do this by using an empty zoneConfig // and completing at the level of the current zone. zoneInheritedFields := zonepb.ZoneConfig{} if err := completeZoneConfig(&zoneInheritedFields, uint32(targetID), getKey); err != nil { return err } partialZone.CopyFromZone(zoneInheritedFields, copyFromParentList) } else { // If we are operating on a subZone, we need to inherit all remaining // unset fields in its parent zone, which is partialZone. zoneInheritedFields := *partialZone if err := completeZoneConfig(&zoneInheritedFields, uint32(targetID), getKey); err != nil { return err } // In the case we have just an index, we should copy from the inherited // zone's fields (whether that was the table or database). if partition == "" { partialSubzone.Config.CopyFromZone(zoneInheritedFields, copyFromParentList) } else { // In the case of updating a partition, we need try inheriting fields // from the subzone's index, and inherit the remainder from the zone. subzoneInheritedFields := zonepb.ZoneConfig{} if indexSubzone := completeZone.GetSubzone(uint32(index.ID), ""); indexSubzone != nil { subzoneInheritedFields.InheritFromParent(&indexSubzone.Config) } subzoneInheritedFields.InheritFromParent(&zoneInheritedFields) // After inheriting fields, copy the requested ones into the // partialSubzone.Config. partialSubzone.Config.CopyFromZone(subzoneInheritedFields, copyFromParentList) } } } if deleteZone { if index != nil { didDelete := completeZone.DeleteSubzone(uint32(index.ID), partition) _ = partialZone.DeleteSubzone(uint32(index.ID), partition) if !didDelete { // If we didn't do any work, return early. We'd otherwise perform an // update that would make it look like one row was affected. return nil } } else { completeZone.DeleteTableConfig() partialZone.DeleteTableConfig() } } else { // Validate the user input. if len(yamlConfig) == 0 || yamlConfig[len(yamlConfig)-1] != '\n' { // YAML values must always end with a newline character. If there is none, // for UX convenience add one. yamlConfig += "\n" } // Determine where to load the configuration. newZone := *completeZone if completeSubzone != nil { newZone = completeSubzone.Config } // Determine where to load the partial configuration. // finalZone is where the new changes are unmarshalled onto. // It must be a fresh ZoneConfig if a new subzone is being created. // If an existing subzone is being modified, finalZone is overridden. finalZone := *partialZone if partialSubzone != nil { finalZone = partialSubzone.Config } // ALTER RANGE default USING DEFAULT sets the default to the in // memory default value. if n.setDefault && keys.RootNamespaceID == uint32(targetID) { finalZone = *protoutil.Clone( params.extendedEvalCtx.ExecCfg.DefaultZoneConfig).(*zonepb.ZoneConfig) } else if n.setDefault { finalZone = *zonepb.NewZoneConfig() } // Load settings from YAML. If there was no YAML (e.g. because the // query specified CONFIGURE ZONE USING), the YAML string will be // empty, in which case the unmarshaling will be a no-op. This is // innocuous. if err := yaml.UnmarshalStrict([]byte(yamlConfig), &newZone); err != nil { return pgerror.Newf(pgcode.CheckViolation, "could not parse zone config: %v", err) } // Load settings from YAML into the partial zone as well. if err := yaml.UnmarshalStrict([]byte(yamlConfig), &finalZone); err != nil { return pgerror.Newf(pgcode.CheckViolation, "could not parse zone config: %v", err) } // Load settings from var = val assignments. If there were no such // settings, (e.g. because the query specified CONFIGURE ZONE = or // USING DEFAULT), the setter slice will be empty and this will be // a no-op. This is innocuous. for _, setter := range setters { // A setter may fail with an error-via-panic. Catch those. if err := func() (err error) { defer func() { if p := recover(); p != nil { if errP, ok := p.(error); ok { // Catch and return the error. err = errP } else { // Nothing we know about, let it continue as a panic. panic(p) } } }() setter(&newZone) setter(&finalZone) return nil }(); err != nil { return err } } // Validate that there are no conflicts in the zone setup. if err := validateNoRepeatKeysInZone(&newZone); err != nil { return err } // Validate that the result makes sense. if err := validateZoneAttrsAndLocalities( params.ctx, params.extendedEvalCtx.StatusServer.Nodes, &newZone, ); err != nil { return err } // Are we operating on an index? if index == nil { // No: the final zone config is the one we just processed. completeZone = &newZone partialZone = &finalZone // Since we are writing to a zone that is not a subzone, we need to // make sure that the zone config is not considered a placeholder // anymore. If the settings applied to this zone don't touch the // NumReplicas field, set it to nil so that the zone isn't considered a // placeholder anymore. if partialZone.IsSubzonePlaceholder() { partialZone.NumReplicas = nil } } else { // If the zone config for targetID was a subzone placeholder, it'll have // been skipped over by GetZoneConfigInTxn. We need to load it regardless // to avoid blowing away other subzones. // TODO(ridwanmsharif): How is this supposed to change? getZoneConfigRaw // gives no guarantees about completeness. Some work might need to happen // here to complete the missing fields. The reason is because we don't know // here if a zone is a placeholder or not. Can we do a GetConfigInTxn here? // And if it is a placeholder, we use getZoneConfigRaw to create one. completeZone, err = getZoneConfigRaw(params.ctx, params.p.txn, targetID) if err != nil { return err } else if completeZone == nil { completeZone = zonepb.NewZoneConfig() } completeZone.SetSubzone(zonepb.Subzone{ IndexID: uint32(index.ID), PartitionName: partition, Config: newZone, }) // The partial zone might just be empty. If so, // replace it with a SubzonePlaceholder. if subzonePlaceholder { partialZone.DeleteTableConfig() } partialZone.SetSubzone(zonepb.Subzone{ IndexID: uint32(index.ID), PartitionName: partition, Config: finalZone, }) } // Finally revalidate everything. Validate only the completeZone config. if err := completeZone.Validate(); err != nil { return pgerror.Newf(pgcode.CheckViolation, "could not validate zone config: %v", err) } // Finally check for the extra protection partial zone configs would // require from changes made to parent zones. The extra protections are: // // RangeMinBytes and RangeMaxBytes must be set together // LeasePreferences cannot be set unless Constraints are explicitly set // Per-replica constraints cannot be set unless num_replicas is explicitly set if err := finalZone.ValidateTandemFields(); err != nil { err = errors.Wrap(err, "could not validate zone config") err = pgerror.WithCandidateCode(err, pgcode.InvalidParameterValue) err = errors.WithHint(err, "try ALTER ... CONFIGURE ZONE USING <field_name> = COPY FROM PARENT [, ...] to populate the field") return err } } // Write the partial zone configuration. hasNewSubzones := !deleteZone && index != nil execConfig := params.extendedEvalCtx.ExecCfg zoneToWrite := partialZone n.run.numAffected, err = writeZoneConfig(params.ctx, params.p.txn, targetID, table, zoneToWrite, execConfig, hasNewSubzones) if err != nil { return err } // Record that the change has occurred for auditing. var eventLogType EventLogType info := struct { Target string Config string `json:",omitempty"` Options string `json:",omitempty"` User string }{ Target: tree.AsStringWithFQNames(&zs, params.Ann()), Config: strings.TrimSpace(yamlConfig), Options: optionStr.String(), User: params.SessionData().User, } if deleteZone { eventLogType = EventLogRemoveZoneConfig } else { eventLogType = EventLogSetZoneConfig } return MakeEventLogger(params.extendedEvalCtx.ExecCfg).InsertEventRecord( params.ctx, params.p.txn, eventLogType, int32(targetID), int32(params.extendedEvalCtx.NodeID), info, ) } for _, zs := range specifiers { // Note(solon): Currently the zone configurations are applied serially for // each specifier. This could certainly be made more efficient. For // instance, we should only need to write to the system.zones table once // rather than once for every specifier. However, the number of specifiers // is expected to be low--it's bounded by the number of indexes on the // table--so I'm holding off on adding that complexity unless we find it's // necessary. if err := applyZoneConfig(zs); err != nil { return err } } return nil } func (n *setZoneConfigNode) Next(runParams) (bool, error) { return false, nil } func (n *setZoneConfigNode) Values() tree.Datums { return nil } func (*setZoneConfigNode) Close(context.Context) {} func (n *setZoneConfigNode) FastPathResults() (int, bool) { return n.run.numAffected, true } type nodeGetter func(context.Context, *serverpb.NodesRequest) (*serverpb.NodesResponse, error) // Check that there are not duplicated values for a particular // constraint. For example, constraints [+region=us-east1,+region=us-east2] // will be rejected. Additionally, invalid constraints such as // [+region=us-east1, -region=us-east1] will also be rejected. func validateNoRepeatKeysInZone(zone *zonepb.ZoneConfig) error { for _, constraints := range zone.Constraints { // Because we expect to have a small number of constraints, a nested // loop is probably better than allocating a map. for i, curr := range constraints.Constraints { for _, other := range constraints.Constraints[i+1:] { // We don't want to enter the other validation logic if both of the constraints // are attributes, due to the keys being the same for attributes. if curr.Key == "" && other.Key == "" { if curr.Value == other.Value { return pgerror.Newf(pgcode.CheckViolation, "incompatible zone constraints: %q and %q", curr, other) } } else { if curr.Type == zonepb.Constraint_REQUIRED { if other.Type == zonepb.Constraint_REQUIRED && other.Key == curr.Key || other.Type == zonepb.Constraint_PROHIBITED && other.Key == curr.Key && other.Value == curr.Value { return pgerror.Newf(pgcode.CheckViolation, "incompatible zone constraints: %q and %q", curr, other) } } else if curr.Type == zonepb.Constraint_PROHIBITED { // If we have a -k=v pair, verify that there are not any // +k=v pairs in the constraints. if other.Type == zonepb.Constraint_REQUIRED && other.Key == curr.Key && other.Value == curr.Value { return pgerror.Newf(pgcode.CheckViolation, "incompatible zone constraints: %q and %q", curr, other) } } } } } } return nil } // validateZoneAttrsAndLocalities ensures that all constraints/lease preferences // specified in the new zone config snippet are actually valid, meaning that // they match at least one node. This protects against user typos causing // zone configs that silently don't work as intended. // // Note that this really only catches typos in required constraints -- we don't // want to reject prohibited constraints whose attributes/localities don't // match any of the current nodes because it's a reasonable use case to add // prohibited constraints for a new set of nodes before adding the new nodes to // the cluster. If you had to first add one of the nodes before creating the // constraints, data could be replicated there that shouldn't be. func validateZoneAttrsAndLocalities( ctx context.Context, getNodes nodeGetter, zone *zonepb.ZoneConfig, ) error { if len(zone.Constraints) == 0 && len(zone.LeasePreferences) == 0 { return nil } // Given that we have something to validate, do the work to retrieve the // set of attributes and localities present on at least one node. nodes, err := getNodes(ctx, &serverpb.NodesRequest{}) if err != nil { return err } // Accumulate a unique list of constraints to validate. toValidate := make([]zonepb.Constraint, 0) addToValidate := func(c zonepb.Constraint) { var alreadyInList bool for _, val := range toValidate { if c == val { alreadyInList = true break } } if !alreadyInList { toValidate = append(toValidate, c) } } for _, constraints := range zone.Constraints { for _, constraint := range constraints.Constraints { addToValidate(constraint) } } for _, leasePreferences := range zone.LeasePreferences { for _, constraint := range leasePreferences.Constraints { addToValidate(constraint) } } // Check that each constraint matches some store somewhere in the cluster. for _, constraint := range toValidate { // We skip validation for negative constraints. See the function-level comment. if constraint.Type == zonepb.Constraint_PROHIBITED { continue } var found bool node: for _, node := range nodes.Nodes { for _, store := range node.StoreStatuses { // We could alternatively use zonepb.StoreMatchesConstraint here to // catch typos in prohibited constraints as well, but as noted in the // function-level comment that could break very reasonable use cases for // prohibited constraints. if zonepb.StoreSatisfiesConstraint(store.Desc, constraint) { found = true break node } } } if !found { return pgerror.Newf(pgcode.CheckViolation, "constraint %q matches no existing nodes within the cluster - did you enter it correctly?", constraint) } } return nil } func writeZoneConfig( ctx context.Context, txn *client.Txn, targetID sqlbase.ID, table *sqlbase.TableDescriptor, zone *zonepb.ZoneConfig, execCfg *ExecutorConfig, hasNewSubzones bool, ) (numAffected int, err error) { if len(zone.Subzones) > 0 { st := execCfg.Settings zone.SubzoneSpans, err = GenerateSubzoneSpans( st, execCfg.ClusterID(), table, zone.Subzones, hasNewSubzones) if err != nil { return 0, err } } else { // To keep the Subzone and SubzoneSpan arrays consistent zone.SubzoneSpans = nil } if zone.IsSubzonePlaceholder() && len(zone.Subzones) == 0 { return execCfg.InternalExecutor.Exec(ctx, "delete-zone", txn, "DELETE FROM system.zones WHERE id = $1", targetID) } buf, err := protoutil.Marshal(zone) if err != nil { return 0, pgerror.Newf(pgcode.CheckViolation, "could not marshal zone config: %v", err) } return execCfg.InternalExecutor.Exec(ctx, "update-zone", txn, "UPSERT INTO system.zones (id, config) VALUES ($1, $2)", targetID, buf) } // getZoneConfigRaw looks up the zone config with the given ID. Unlike // getZoneConfig, it does not attempt to ascend the zone config hierarchy. If no // zone config exists for the given ID, it returns nil. func getZoneConfigRaw( ctx context.Context, txn *client.Txn, id sqlbase.ID, ) (*zonepb.ZoneConfig, error) { kv, err := txn.Get(ctx, config.MakeZoneKey(uint32(id))) if err != nil { return nil, err } if kv.Value == nil { return nil, nil } var zone zonepb.ZoneConfig if err := kv.ValueProto(&zone); err != nil { return nil, err } return &zone, nil } // removeIndexZoneConfigs removes the zone configurations for some // indexs being dropped. It is a no-op if there is no zone // configuration. // // It operates entirely on the current goroutine and is thus able to // reuse an existing client.Txn safely. func removeIndexZoneConfigs( ctx context.Context, txn *client.Txn, execCfg *ExecutorConfig, tableID sqlbase.ID, indexDescs []sqlbase.IndexDescriptor, ) error { tableDesc, err := sqlbase.GetTableDescFromID(ctx, txn, tableID) if err != nil { return err } zone, err := getZoneConfigRaw(ctx, txn, tableID) if err != nil { return err } else if zone == nil { zone = zonepb.NewZoneConfig() } for _, indexDesc := range indexDescs { zone.DeleteIndexSubzones(uint32(indexDesc.ID)) } // Ignore CCL required error to allow schema change to progress. _, err = writeZoneConfig(ctx, txn, tableID, tableDesc, zone, execCfg, false /* hasNewSubzones */) if err != nil && !sqlbase.IsCCLRequiredError(err) { return err } return nil }
} if tableDesc.ParentID == keys.SystemDatabaseID { return p.RequireAdminRole(ctx, "alter system tables") }
upgrade.go
/* Copyright 2019 The Skaffold Authors Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package v2beta2 import ( next "github.com/GoogleContainerTools/skaffold/pkg/skaffold/schema/latest" "github.com/GoogleContainerTools/skaffold/pkg/skaffold/schema/util" pkgutil "github.com/GoogleContainerTools/skaffold/pkg/skaffold/util" ) // Upgrade upgrades a configuration to the next version. // Config changes from v2beta2 to v2beta3 // 1. Additions: // 2. Removals: // 3. Updates: func (c *SkaffoldConfig) Upgrade() (util.VersionedConfig, error) { var newConfig next.SkaffoldConfig pkgutil.CloneThroughJSON(c, &newConfig) newConfig.APIVersion = next.Version err := util.UpgradePipelines(c, &newConfig, upgradeOnePipeline) return &newConfig, err } func
(_, _ interface{}) error { return nil }
upgradeOnePipeline
PipelineGraph.tsx
import {Colors} from '@blueprintjs/core'; import gql from 'graphql-tag'; import * as React from 'react'; import styled from 'styled-components/macro'; import {ParentSolidNode, SVGLabeledParentRect} from 'src/graph/ParentSolidNode'; import {SVGViewport, DETAIL_ZOOM, SVGViewportInteractor} from 'src/graph/SVGViewport'; import {SolidLinks} from 'src/graph/SolidLinks'; import {SolidNode} from 'src/graph/SolidNode'; import {IFullPipelineLayout, IFullSolidLayout, ILayout} from 'src/graph/getFullSolidLayout'; import {Edge, isHighlighted, isSolidHighlighted} from 'src/graph/highlighting'; import {PipelineGraphSolidFragment} from 'src/graph/types/PipelineGraphSolidFragment'; import {SolidNameOrPath} from 'src/solids/SolidNameOrPath'; const NoOp = () => {}; interface IPipelineGraphProps { pipelineName: string; backgroundColor: string; layout: IFullPipelineLayout; solids: PipelineGraphSolidFragment[]; focusSolids: PipelineGraphSolidFragment[]; parentHandleID?: string; parentSolid?: PipelineGraphSolidFragment; selectedHandleID?: string; selectedSolid?: PipelineGraphSolidFragment; highlightedSolids: Array<PipelineGraphSolidFragment>; interactor?: SVGViewportInteractor; onClickSolid?: (arg: SolidNameOrPath) => void; onDoubleClickSolid?: (arg: SolidNameOrPath) => void; onEnterCompositeSolid?: (arg: SolidNameOrPath) => void; onLeaveCompositeSolid?: () => void; onClickBackground?: () => void; } interface IPipelineContentsProps extends IPipelineGraphProps { minified: boolean; layout: IFullPipelineLayout; } interface IPipelineContentsState { highlighted: Edge[]; } /** * Identifies groups of solids that share a similar `prefix.` and returns * an array of bounding boxes and common prefixes. Used to render lightweight * outlines around flattened composites. */ function
(layout: IFullPipelineLayout) { const groups: {[base: string]: ILayout[]} = {}; let maxDepth = 0; for (const key of Object.keys(layout.solids)) { const parts = key.split('.'); if (parts.length === 1) { continue; } for (let ii = 1; ii < parts.length; ii++) { const base = parts.slice(0, ii).join('.'); groups[base] = groups[base] || []; groups[base].push(layout.solids[key].boundingBox); maxDepth = Math.max(maxDepth, ii); } } const boxes: (ILayout & {name: string})[] = []; for (const base of Object.keys(groups)) { const group = groups[base]; const depth = base.split('.').length; const margin = 5 + (maxDepth - depth) * 5; if (group.length === 1) { continue; } const x1 = Math.min(...group.map((l) => l.x)) - margin; const x2 = Math.max(...group.map((l) => l.x + l.width)) + margin; const y1 = Math.min(...group.map((l) => l.y)) - margin; const y2 = Math.max(...group.map((l) => l.y + l.height)) + margin; boxes.push({name: base, x: x1, y: y1, width: x2 - x1, height: y2 - y1}); } return boxes; } export class PipelineGraphContents extends React.PureComponent< IPipelineContentsProps, IPipelineContentsState > { state: IPipelineContentsState = { highlighted: [], }; onHighlightEdges = (highlighted: Edge[]) => { this.setState({highlighted}); }; render() { const { layout, minified, solids, focusSolids, parentSolid, parentHandleID, onClickSolid = NoOp, onDoubleClickSolid = NoOp, onEnterCompositeSolid = NoOp, highlightedSolids, selectedSolid, selectedHandleID, } = this.props; return ( <> {parentSolid && layout.parent && layout.parent.invocationBoundingBox.width > 0 && ( <SVGLabeledParentRect {...layout.parent.invocationBoundingBox} key={`composite-rect-${parentHandleID}`} label={parentSolid.name} fill={Colors.LIGHT_GRAY5} minified={minified} /> )} {selectedSolid && layout.solids[selectedSolid.name] && ( // this rect is hidden beneath the user's selection with a React key so that // when they expand the composite solid React sees this component becoming // the one above and re-uses the DOM node. This allows us to animate the rect's // bounds from the parent layout to the inner layout with no React state. <SVGLabeledParentRect {...layout.solids[selectedSolid.name].solid} key={`composite-rect-${selectedHandleID}`} label={''} fill={Colors.LIGHT_GRAY5} minified={true} /> )} {parentSolid && ( <ParentSolidNode onClickSolid={onClickSolid} onDoubleClick={(name) => onDoubleClickSolid({name})} onHighlightEdges={this.onHighlightEdges} highlightedEdges={this.state.highlighted} key={`composite-rect-${parentHandleID}-definition`} minified={minified} solid={parentSolid} layout={layout} /> )} <SolidLinks layout={layout} opacity={0.2} connections={layout.connections} onHighlight={this.onHighlightEdges} /> <SolidLinks layout={layout} opacity={0.55} onHighlight={this.onHighlightEdges} connections={layout.connections.filter(({from, to}) => isHighlighted(this.state.highlighted, { a: from.solidName, b: to.solidName, }), )} /> {computeSolidPrefixBoundingBoxes(layout).map((box, idx) => ( <rect key={idx} {...box} stroke="rgb(230, 219, 238)" fill="rgba(230, 219, 238, 0.2)" strokeWidth={2} /> ))} {solids.map((solid) => ( <SolidNode key={solid.name} invocation={solid} definition={solid.definition} minified={minified} onClick={() => onClickSolid({name: solid.name})} onDoubleClick={() => onDoubleClickSolid({name: solid.name})} onEnterComposite={() => onEnterCompositeSolid({name: solid.name})} onHighlightEdges={this.onHighlightEdges} layout={layout.solids[solid.name]} selected={selectedSolid === solid} focused={focusSolids.includes(solid)} highlightedEdges={ isSolidHighlighted(this.state.highlighted, solid.name) ? this.state.highlighted : EmptyHighlightedArray } dim={highlightedSolids.length > 0 && highlightedSolids.indexOf(solid) === -1} /> ))} </> ); } } // This is a specific empty array we pass to represent the common / empty case // so that SolidNode can use shallow equality comparisons in shouldComponentUpdate. const EmptyHighlightedArray: never[] = []; export class PipelineGraph extends React.Component<IPipelineGraphProps> { static fragments = { PipelineGraphSolidFragment: gql` fragment PipelineGraphSolidFragment on Solid { name ...SolidNodeInvocationFragment definition { name ...SolidNodeDefinitionFragment } } ${SolidNode.fragments.SolidNodeInvocationFragment} ${SolidNode.fragments.SolidNodeDefinitionFragment} `, }; viewportEl: React.RefObject<SVGViewport> = React.createRef(); resolveSolidPosition = ( arg: SolidNameOrPath, cb: (cx: number, cy: number, layout: IFullSolidLayout) => void, ) => { const lastName = 'name' in arg ? arg.name : arg.path[arg.path.length - 1]; const solidLayout = this.props.layout.solids[lastName]; if (!solidLayout) { return; } const cx = solidLayout.boundingBox.x + solidLayout.boundingBox.width / 2; const cy = solidLayout.boundingBox.y + solidLayout.boundingBox.height / 2; cb(cx, cy, solidLayout); }; centerSolid = (arg: SolidNameOrPath) => { this.resolveSolidPosition(arg, (cx, cy) => { const viewportEl = this.viewportEl.current!; viewportEl.smoothZoomToSVGCoords(cx, cy, viewportEl.state.scale); }); }; focusOnSolid = (arg: SolidNameOrPath) => { this.resolveSolidPosition(arg, (cx, cy) => { this.viewportEl.current!.smoothZoomToSVGCoords(cx, cy, DETAIL_ZOOM); }); }; closestSolidInDirection = (dir: string): string | undefined => { const {layout, selectedSolid} = this.props; if (!selectedSolid) { return; } const current = layout.solids[selectedSolid.name]; const center = (solid: IFullSolidLayout): {x: number; y: number} => ({ x: solid.boundingBox.x + solid.boundingBox.width / 2, y: solid.boundingBox.y + solid.boundingBox.height / 2, }); /* Sort all the solids in the graph based on their attractiveness as a jump target. We want the nearest node in the exact same row for left/right, and the visually "closest" node above/below for up/down. */ const score = (solid: IFullSolidLayout): number => { const dx = center(solid).x - center(current).x; const dy = center(solid).y - center(current).y; if (dir === 'left' && dy === 0 && dx < 0) { return -dx; } if (dir === 'right' && dy === 0 && dx > 0) { return dx; } if (dir === 'up' && dy < 0) { return -dy + Math.abs(dx) / 5; } if (dir === 'down' && dy > 0) { return dy + Math.abs(dx) / 5; } return Number.NaN; }; const closest = Object.keys(layout.solids) .map((name) => ({name, score: score(layout.solids[name])})) .filter((e) => e.name !== selectedSolid.name && !Number.isNaN(e.score)) .sort((a, b) => b.score - a.score) .pop(); return closest ? closest.name : undefined; }; onKeyDown = (e: React.KeyboardEvent<HTMLDivElement>) => { if (e.target && (e.target as HTMLElement).nodeName === 'INPUT') { return; } const dir = {37: 'left', 38: 'up', 39: 'right', 40: 'down'}[e.keyCode]; if (!dir) { return; } const nextSolid = this.closestSolidInDirection(dir); if (nextSolid && this.props.onClickSolid) { e.preventDefault(); e.stopPropagation(); this.props.onClickSolid({name: nextSolid}); } }; unfocus = (e: React.MouseEvent<any>) => { this.viewportEl.current!.autocenter(true); e.stopPropagation(); }; unfocusOutsideContainer = (e: React.MouseEvent<any>) => { if (this.props.parentSolid && this.props.onLeaveCompositeSolid) { this.props.onLeaveCompositeSolid(); } else { this.unfocus(e); } }; componentDidUpdate(prevProps: IPipelineGraphProps) { if (prevProps.parentSolid !== this.props.parentSolid) { this.viewportEl.current!.cancelAnimations(); this.viewportEl.current!.autocenter(); } if (prevProps.layout !== this.props.layout) { this.viewportEl.current!.autocenter(); } if (prevProps.selectedSolid !== this.props.selectedSolid && this.props.selectedSolid) { this.centerSolid(this.props.selectedSolid); } } render() { const { layout, interactor, pipelineName, backgroundColor, onClickBackground, onDoubleClickSolid, } = this.props; return ( <SVGViewport ref={this.viewportEl} key={pipelineName} interactor={interactor || SVGViewport.Interactors.PanAndZoom} backgroundColor={backgroundColor} graphWidth={layout.width} graphHeight={layout.height} onKeyDown={this.onKeyDown} onDoubleClick={this.unfocusOutsideContainer} > {({scale}: any) => ( <> <SVGContainer width={layout.width} height={layout.height + 200} onClick={onClickBackground} onDoubleClick={this.unfocus} > <PipelineGraphContents layout={layout} minified={scale < DETAIL_ZOOM - 0.01} onDoubleClickSolid={onDoubleClickSolid || this.focusOnSolid} {...this.props} /> </SVGContainer> </> )} </SVGViewport> ); } } const SVGContainer = styled.svg` overflow: visible; border-radius: 0; `;
computeSolidPrefixBoundingBoxes
cell.py
""" Defines the Cell class """ #*************************************************************************************************** # Copyright 2015, 2019 National Technology & Engineering Solutions of Sandia, LLC (NTESS). # Under the terms of Contract DE-NA0003525 with NTESS, the U.S. Government retains certain rights # in this software. # Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except # in compliance with the License. You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 or in the LICENSE file in the root pyGSTi directory. #*************************************************************************************************** from pygsti.report.convert import convert_dict as _convert_dict from pygsti.report.formatters import format_dict as _format_dict class Cell(object): """ Representation of a table cell, containing formatting and labeling info Parameters ---------- data : ReportableQty data to be reported formatter_name : string, optional name of the formatter to be used (ie 'Effect') label : string, optional label of the cell """ def __init__(self, data=None, formatter_name=None, label=None):
def __getstate__(self): state_dict = self.__dict__.copy() return state_dict def __setstate__(self, d): self.__dict__.update(d) def _render_data(self, fmt, spec): ''' Render self.data as a string Parameters ---------- fmt : string name of format to be used spec: dict dictionary of formatting options Returns ------- string ''' if self.formatterName is not None: formatter = _format_dict[self.formatterName] formatted_item = formatter[fmt](self.data, spec) assert formatted_item is not None, ("Formatter " + str(type(formatter[fmt])) + " returned None for item = " + str(self.data)) return formatted_item else: if self.data.value is not None: return str(self.data) else: raise ValueError("Unformatted None in Cell") def render(self, fmt, spec): """ Render full cell as a string Parameters ---------- fmt : string name of format to be used spec : dict dictionary of formatting options Returns ------- string """ format_cell = _convert_dict[fmt]['cell'] # Function for rendering a cell in the format "fmt" formattedData = self._render_data(fmt, spec) return format_cell(formattedData, self.label, spec)
''' Creates Cell object Parameters ---------- data : ReportableQty data to be reported formatter_name : string name of the formatter to be used (ie 'Effect') label : string label of the cell ''' self.data = data self.formatterName = formatter_name self.label = label
Edmonds-Karp.ts
import { Graph, GraphMutation, Node, Edge, GraphEdgeFlowMutation, GraphNodeHighlightMutation, GraphEdgeHighlightMutation } from "../CytoscapeGraph"; import { Algorithm } from "../algorithm"; /** The Edmonds-Karp algorithm */ const EdmondsKarp: Algorithm = { name: "Edmonds-Karp", linearDataStructure: "queue", pseudocode: ({ sourceName, sinkName }) => String.raw` \begin{algorithm} \begin{algorithmic} \PROCEDURE{Edmonds-Karp}{$G=(V,\ E),\ ${sourceName} \in V,\ ${sinkName} \in V$} \STATE $f = 0$ \REPEAT \STATE $p = \left[\ \right]$ \STATE $q = \left[\ ${sourceName}\ \right]$ \COMMENT{create queue} \WHILE{$q_\mathrm{length}$ > 0} \STATE $c =$ \CALL{dequeue}{$q$} \FOR{edge $e$ originating from $c$} \IF{$e_\mathrm{target} \notin p$ \AND $e_\mathrm{target} \neq ${sourceName}$ \AND $e_\mathrm{capacity} > e_\mathrm{flow}$} \STATE $p[e_\mathrm{target}] = e$ \STATE \CALL{enqueue}{$q$, $e_\mathrm{target}$} \ENDIF \ENDFOR \ENDWHILE \IF{$p[${sinkName}] \neq \varnothing$} \STATE $\Delta f = \infty$ \FOR{$e \in p$} \STATE $\Delta f = $ \CALL{min}{$\Delta f$, $e_\mathrm{capacity} - e_\mathrm{flow}$} \ENDFOR \FOR{$e \in p$} \STATE $r = e_\mathrm{reverse}$ \STATE $e_\mathrm{flow} = e_\mathrm{flow} + \Delta f$ \STATE $r_\mathrm{flow} = r_\mathrm{flow} - \Delta f$ \ENDFOR \STATE $f = f + \Delta f$ \ENDIF \UNTIL{$p[${sinkName}] = \varnothing$} \RETURN $f$ \ENDPROCEDURE \end{algorithmic} \end{algorithm} `, references: [ { label: `Edmonds-Karp Algorithm at Brilliant.org`, url: "https://brilliant.org/wiki/edmonds-karp-algorithm/" }, { label: `Jack Edmonds, Richard M. Karp: Theoretical improvements in algorithmic efficiency for network flow problems (1972)`, url: "https://web.eecs.umich.edu/~pettie/matching/Edmonds-Karp-network-flow.pdf" } ], labeledBlocks: [ { lines: [4, 14], color: "#ffdcdc", label: "Breadth-first search" }, { lines: [15, 26], color: "#e3ffff", label: "Increase flow along found path" } ], implementation: function*( graph: Graph ): IterableIterator<{ highlightedLines?: number[]; linearNodes: Node[]; graphMutations?: GraphMutation[]; done?: true; }> { const sourceNode = graph.getSourceNode(); const sinkNode = graph.getSinkNode(); let flow = 0; let pred: { [key: string]: Edge }; do { const q = [sourceNode]; pred = {}; const mutationsToUndoAfterSearch = []; yield { highlightedLines: [4, 5], linearNodes: q }; while (q.length > 0 && !pred[sinkNode.getId()]) { const cur = q.shift()!; mutationsToUndoAfterSearch.push( new GraphNodeHighlightMutation(cur).inverse() ); yield { highlightedLines: [7], linearNodes: q, graphMutations: [new GraphNodeHighlightMutation(cur)] }; for (let edge of cur.getOutgoingEdges()) { if ( pred[edge.getTargetNode().getId()] === undefined && !edge.getTargetNode().isEqualTo(sourceNode) && edge.getCapacity() > edge.getFlow() ) { pred[edge.getTargetNode().getId()] = edge; q.push(edge.getTargetNode()); } mutationsToUndoAfterSearch.push( new GraphEdgeHighlightMutation(edge).inverse() ); yield { highlightedLines: [10, 11], linearNodes: q, graphMutations: [new GraphEdgeHighlightMutation(edge)] }; if (edge.getTargetNode().isEqualTo(sinkNode)) break; } } if (pred[sinkNode.getId()] !== undefined) { let currentHighlightEdge = pred[sinkNode.getId()]; const foundPathHighlightMutations: GraphMutation[] = []; while (currentHighlightEdge) { foundPathHighlightMutations.push( new GraphEdgeHighlightMutation(currentHighlightEdge), new GraphNodeHighlightMutation( currentHighlightEdge.getSourceNode() ), new GraphNodeHighlightMutation(currentHighlightEdge.getTargetNode()) ); currentHighlightEdge = pred[currentHighlightEdge.getSourceNode().getId()]; } const mutationsToUndoAfterUpdate = foundPathHighlightMutations .slice() .reverse() .map(mutation => mutation.inverse()); yield { highlightedLines: [16], linearNodes: q, graphMutations: [ ...mutationsToUndoAfterSearch, ...foundPathHighlightMutations ] }; let df = Infinity; let currentEdge = pred[sinkNode.getId()]; while (currentEdge !== undefined) { df = Math.min(df, currentEdge.getCapacity() - currentEdge.getFlow()); currentEdge = pred[currentEdge.getSourceNode().getId()]; } currentEdge = pred[sinkNode.getId()]; while (currentEdge !== undefined) { const reverseCurrentEdge = currentEdge.getReverseEdge();
new GraphEdgeFlowMutation(currentEdge, df), new GraphEdgeFlowMutation(reverseCurrentEdge, -df) ] }; currentEdge = pred[currentEdge.getSourceNode().getId()]; } flow = flow + df; yield { highlightedLines: [25], linearNodes: q, graphMutations: mutationsToUndoAfterUpdate }; } } while (pred[sinkNode.getId()] !== undefined); yield { highlightedLines: [28], linearNodes: [], done: true }; return flow; } }; export default EdmondsKarp;
yield { highlightedLines: [22, 23], linearNodes: q, graphMutations: [
0001__initial.py
# Generated by Django 2.0.2 on 2018-02-23 08:56 from django.db import migrations, models import django.utils.timezone class
(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Playlists', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('code', models.CharField(default=None, max_length=100, unique=True)), ('title', models.CharField(default=None, max_length=200)), ('slug', models.SlugField(default=None, max_length=200, unique=True)), ('description', models.TextField(blank=True)), ('created', models.DateTimeField(default=django.utils.timezone.now, verbose_name='date created')), ('updated', models.DateTimeField(default=django.utils.timezone.now, verbose_name='date updated')), ], options={ 'verbose_name': 'Playlists', 'verbose_name_plural': 'Playlists', 'ordering': ['-created'], 'get_latest_by': ['-created'], }, ), ]
Migration
logger.py
# -*- coding: utf-8 -*- """ ------------------------------------------------- File Name: logger Description : Author : Liangs date: 2019/7/28 ------------------------------------------------- Change Activity: 2019/7/28: ------------------------------------------------- """ import logging def init_logger(logger_name, log_file=None, is_debug=False, only_console=False): if not only_console: assert log_file logger = logging.getLogger(logger_name) if is_debug: logger.setLevel(logging.DEBUG) else: logger.setLevel(logging.INFO) # handlers: c_handler = logging.StreamHandler() c_handler.setLevel(logging.INFO) c_format = logging.Formatter("%(asctime)s-%(levelname)s-%(message)s") c_handler.setFormatter(c_format) logger.addHandler(c_handler) if not only_console: f_handler = logging.FileHandler(log_file) f_handler.setLevel(logging.INFO) f_format = logging.Formatter("%(asctime)s-%(levelname)s-%(message)s") f_handler.setFormatter(f_format) logger.addHandler(f_handler)
logger.info(f'===================== NEW LOGGER:{logger_name} =========================') return logger def get_logger(logger_name): return logging.getLogger(logger_name) if __name__ == '__main__': my_logger = init_logger('test', 'test.log') my_logger.info('this is a info')
benchmarking.rs
// This file is part of Substrate. // Copyright (C) 2020-2021 Parity Technologies (UK) Ltd. // SPDX-License-Identifier: Apache-2.0 // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. //! Kitties pallet benchmarking. #![cfg(feature = "runtime-benchmarks")] use super::*; use frame_benchmarking::{benchmarks, whitelisted_caller, account}; use frame_system::RawOrigin; use crate::pallet::BalanceOf; use frame_support::sp_runtime::traits::Hash; const SEED: u32 = 0; fn assert_last_event<T: Config>(generic_event: <T as Config>::Event)
benchmarks! { create_kitty { // set up an account that is of signed origin let caller: T::AccountId = whitelisted_caller(); }: _(RawOrigin::Signed(caller.clone())) verify { // verify that there is an hash(kitty_id) of a kitty already in storage let hash = <Kitties<T>>::iter_keys().next().unwrap(); // assert that the last event that is being called when you run the extrinsic function assert_last_event::<T>(Event::Created(caller, hash).into()); } // another benchmark of another extrinsic // set_price set_price { // set up an account let caller: T::AccountId = whitelisted_caller(); let price: BalanceOf<T> = 100u32.into(); // because we need the kitty id let kitty_id = crate::Pallet::<T>::mint(&caller,None,None).unwrap(); }: set_price(RawOrigin::Signed(caller.clone()), kitty_id, Some(price)) verify { assert_last_event::<T>(Event::PriceSet(caller, kitty_id, Some(price)).into()); } transfer { // set up an account let caller: T::AccountId = whitelisted_caller(); let to: T::AccountId = account("recipient", 0, SEED); // because we need the kitty id let kitty_id = crate::Pallet::<T>::mint(&caller,None,None).unwrap(); }: _(RawOrigin::Signed(caller.clone()), to.clone(), kitty_id) verify { assert_last_event::<T>(Event::Transferred(caller, to, kitty_id).into()); } } // ./target/release/node-kitties benchmark --chain=dev --steps=50 --repeat=20 --pallet=pallet_kitties --extrinsic=transfer --execution=wasm --wasm-execution=compiled --heap-pages=4096 --output=.
{ frame_system::Pallet::<T>::assert_last_event(generic_event.into()); }
loginTokenQueries.ts
import db from '../../db/dbConnect'; import { LoginToken } from '../../types/LoginToken'; export async function
(id: number): Promise<LoginToken> { try { const query = `SELECT id, token, user_id from login_tokens WHERE id = :id`; const [[loginToken]]: [[LoginToken]] = (await db.query(query, { id, })) as [[LoginToken]]; return loginToken; } catch (e) { throw new Error(`Could not get token by ID. Reason: ${e as string}`); } } export async function getLoginTokenByUserId(id: number, authToken: string): Promise<LoginToken> { try { const columns = ['id', 'token', 'user_id']; const query = `SELECT ${columns.toString()} from login_tokens WHERE user_id =:id`; const [[loginToken]]: [[LoginToken]] = (await db.query(authToken, query, { id }, columns)) as [[LoginToken]]; return loginToken; } catch (e) { throw new Error(`Could not get token by User ID. Reason: ${e as string}`); } } export async function getLoginTokenByToken(token: string): Promise<LoginToken> { try { const query = `SELECT id, token, user_id from login_tokens WHERE token =:token`; const [[loginToken]]: [[LoginToken]] = (await db.query(query, { token, })) as [[LoginToken]]; return loginToken; } catch (e) { throw new Error(`Did not find token. Reason: ${e as string}`); } }
getLoginTokenById
find.go
// Copyright (C) 2020-2021 azumakuniyuki and sisimai development team, All rights reserved. // This software is distributed under The BSD 2-Clause License. package address import "fmt" import "strings" import sisimoji "sisimai/string" // Find() is an email address parser func Find(argv0 string) []string { // @param [string] argv0 String including email address // @return [[]string] Email address list if len(argv0) == 0 { return []string {} } table, aargh := Seek(argv0); if aargh != nil { return []string {} } addrs := []string {} for _, e := range table { // Pick an email address only from the results of Seek() addrs = append(addrs, e[0]) } return addrs } // Seek() is an email address parser with a name and a comment func Seek(argv0 string) ([][3]string, error) { // @param [string] argv0 String including email address // @return [[][]string] Email address list with a name and a comment if len(argv0) == 0 { return [][3]string {}, fmt.Errorf("String is empty") } delimiters := `<>(),"` indicators := map[string]uint8 { "email-address": (1 << 0), // <[email protected]> "quoted-string": (1 << 1), // "Neko, Nyaan" "comment-block": (1 << 2), // (nekochan) } emailtable := [3]string { "", "", "" } // Address, Name, Comment addrtables := [][3]string {} readbuffer := [][3]string { emailtable } var readcursor uint8 = 0 // Points the current cursor position var p int8 = -1 // Current position: 0 = address, 1 = name, or 2 = comment var v *[3]string = &readbuffer[0] argv0 = strings.ReplaceAll(argv0, "\r", "") // Remove CR argv0 = strings.ReplaceAll(argv0, "\n", "") // Remove NL for _, e := range(strings.Split(argv0, "")) { // Check each character if strings.Index(e, delimiters) > -1 { // The character is a delimiter if e == "," { // The "," is a email address separator or a character in a "name" if strings.HasPrefix((*v)[0], "<") && strings.Contains((*v)[0], "@") && strings.HasSuffix((*v)[0], ">") { // An email address has already been picked if readcursor & indicators["comment-block"] > 0 { // The cursor is in the comment block (Neko, Nyaan) (*v)[2] += e } else if readcursor & indicators["quoted-string"] > 0 { // "Neko, Nyaan" (*v)[1] += e } else { // The cursor is not in neither the quoted-string nor the comment block readcursor = 0 // Reset the cursor position readbuffer = append(readbuffer, emailtable) v = &readbuffer[len(readbuffer) - 1] } } else { // "Neko, Nyaan" <[email protected]> OR <"neko,nyaan"@example.org> if p > -1 { (*v)[p] += e } else { (*v)[1] += e } } continue } // END OF if "," if e == "<" { // "<": The beginning of an email address or not if len((*v)[0]) > 0 { if p > -1 { (*v)[p] += e } else { (*v)[1] += e } } else { // <[email protected]> readcursor |= indicators["email-address"] (*v)[0] += e p = 0 } continue } // END OF if "<" if e == ">" { // ">": The end of an email address or not if readcursor & indicators["email-address"] > 0 { // <[email protected]> readcursor &= ^indicators["email-address"] (*v)[0] += e p = -1 } else { // a comment block or a display name if p > -1 { (*v)[2] += e } else { (*v)[1] += e } } continue } // END OF if ">" if e == "(" {
// The beginning of a comment block or not if readcursor & indicators["email-address"] > 0 { // <"neko(nyaan)"@example.org> or <neko(nyaan)@example.org> if strings.Contains((*v)[0], `"`) { // Quoted local part: <"neko(nyaan)"@example.org> (*v)[0] += e } else { // Comment: <neko(nyaan)@example.org> readcursor |= indicators["comment-block"] if strings.HasSuffix((*v)[2], ")") { (*v)[2] += " " } (*v)[2] += e p = 2 } } else if readcursor & indicators["comment-block"] > 0 { // Comment at the outside of an email address (...(...) if strings.HasSuffix((*v)[2], ")") { (*v)[2] += " " } (*v)[2] += e } else if readcursor & indicators["quoted-string"] > 0 { // "Neko, Nyaan(cat)", Deal as a display name (*v)[1] += e } else { // The beginning of a comment block readcursor |= indicators["comment-block"] if strings.HasSuffix((*v)[2], ")") { (*v)[2] += " " } (*v)[2] += e p = 2 } continue } // END OF if "(" if e == ")" { // The end of a comment block or not if readcursor & indicators["email-address"] > 0 { // <"neko(nyaan)"@example.org> OR <neko(nyaan)@example.org> if strings.Contains((*v)[0], `"`) { // Quoted string in the local part: <"neko(nyaan)"@example.org> (*v)[0] += e } else { // Comment: <neko(nyaan)@example.org> readcursor &= ^indicators["comment-block"] (*v)[2] += e p = 0 } } else if readcursor & indicators["comment-block"] > 0 { // Comment at the outside of an email address (...(...) readcursor &= ^indicators["comment-block"] (*v)[2] += e p = -1 } else { // Deal as a display name readcursor &= ^indicators["comment-block"] (*v)[1] += e p = -1 } continue } // END OF if ")" if e == `"` { // The beginning or the end of a quoted-string if p > -1 { // email-address or comment-block (*v)[p] += e } else { // Display name like "Neko, Nyaan" (*v)[1] += e if readcursor & indicators["quoted-string"] == 0 { continue } if strings.HasSuffix((*v)[1], `\"`) { continue } // "Neko, Nyaan \"... readcursor &= ^indicators["quoted-string"] p = -1 } continue } // END of if `"` } else { // The character is not a delimiter if p > -1 { (*v)[p] += e } else { (*v)[1] += e } continue } } for _, e := range(readbuffer) { // Check the value of each email address if len(e[0]) == 0 { // The email address part is empty if IsEmailAddress(e[1]) { // Try to use the value of name as an email address token := strings.Split(e[1], "@") token[0] = strings.Trim(token[0], " ") token[1] = strings.Trim(token[1], " ") e[0] = token[0] + "@" + token[1] } else if IsMailerDaemon(e[1]) { // Allow Mailer-Daemon e[0] = e[1] } else { // There is no valid email address stirng in the argument continue } } // Remove the comment from the email address if strings.Count(e[0], "(") == 1 && strings.Count(e[0], ")") == 1 { // (nyaan)[email protected], nekochan(nyaan)[email protected] or nekochan(nyaan)@example.org p1 := strings.Index(e[0], "(") p2 := strings.Index(e[0], ")") p3 := strings.Index(e[0], "@") e[0] = e[0][0:p1] + e[0][p2 + 1:p3] + "@" + e[0][p3 + 1:len(e[0])] e[2] = e[0][p1 + 1:p2] } else { // TODO: neko(nyaan)kijitora(nyaan)[email protected] continue } // The email address should be a valid email address if IsMailerDaemon(e[0]) && IsEmailAddress(e[0]) == false { continue } // Remove angle brackets, other brackets, and quotations: ()[]<>{}'`;. and `"` e[0] = strings.Trim(e[0], "<>{}()[]`';.") if IsQuotedAddress(e[0]) == false { e[0] = strings.Trim(e[0], `"`) } // Remove trailing spaces at the value of 1.name and 2.comment e[1] = strings.TrimSpace(e[1]) e[2] = strings.TrimSpace(e[2]) // Remove the value of 2.comment when the value do not include "(" and ")" if !strings.HasPrefix(e[2], "(") && !strings.HasSuffix(e[2], ")") { e[2] = "" } // Remove redundant spaces when tha value of 1.name do not include `"` if !strings.HasPrefix(e[1], `"`) && !strings.HasSuffix(e[1], `"`) { e[1] = sisimoji.Squeeze(e[1], " ") } if IsQuotedAddress(e[1]) == false { e[1] = strings.Trim(e[1], `"`) } addrtables = append(addrtables, e) } // END OF for(readbuffer) if len(addrtables) == 0 { return addrtables, fmt.Errorf("No valid email address exist") } return addrtables, nil }
duration.rs
use super::*; use crate::prelude::*; pub type DurationChunked = Logical<DurationType, Int64Type>; impl Int64Chunked { pub fn into_duration(self, timeunit: TimeUnit) -> DurationChunked { let mut dt = DurationChunked::new_logical(self); dt.2 = Some(DataType::Duration(timeunit)); dt } } impl LogicalType for DurationChunked { fn dtype(&self) -> &DataType
fn get_any_value(&self, i: usize) -> AnyValue<'_> { self.0.get_any_value(i).into_duration(self.time_unit()) } fn cast(&self, dtype: &DataType) -> Result<Series> { use DataType::*; match (self.dtype(), dtype) { (Duration(TimeUnit::Milliseconds), Duration(TimeUnit::Nanoseconds)) => { Ok((self.0.as_ref() * 1_000_000i64) .into_duration(TimeUnit::Nanoseconds) .into_series()) } (Duration(TimeUnit::Milliseconds), Duration(TimeUnit::Microseconds)) => { Ok((self.0.as_ref() * 1_000i64) .into_duration(TimeUnit::Microseconds) .into_series()) } (Duration(TimeUnit::Nanoseconds), Duration(TimeUnit::Milliseconds)) => { Ok((self.0.as_ref() / 1_000_000i64) .into_duration(TimeUnit::Milliseconds) .into_series()) } (Duration(TimeUnit::Nanoseconds), Duration(TimeUnit::Microseconds)) => { Ok((self.0.as_ref() / 1_000i64) .into_duration(TimeUnit::Microseconds) .into_series()) } _ => self.0.cast(dtype), } } }
{ self.2.as_ref().unwrap() }
logging.py
# Copyright © 2019 National Institute of Advanced Industrial Science and Technology (AIST). All rights reserved. # !/usr/bin/env python3.6 # coding=utf-8 import inspect import logging from functools import wraps from pathlib import Path from datetime import datetime from pytz import timezone # グローバル変数 ログ保存フォルダパス g_log_dir = Path('./logs') def set_log_dir(dir: str) -> None: """ ログの出力ディレクトリを指定します。 Specifies the output directory of the log. Args: dir (str) : ログの出力ディレクトリ output directory of the log """ global g_log_dir g_log_dir = Path(dir) def get_log_path() -> str: """ ログの出力ファイルを取得します。 Get the output file of the log.
jst_datetime_str = jst_datetime.strftime('%Y%m%d') return str(g_log_dir / f'qunomon_{jst_datetime_str}.log') def get_logger() -> logging.Logger: """ logging.Loggerを作成します。 Create a logging.Logger. Returns: logger (logging.Logger): logging.Loggerのインスタンス logging.Logger instance """ # basicConfigのformat引数でログのフォーマットを指定する log_format = '[%(asctime)s] [%(thread)d] %(levelname)s\t%(filename)s' \ ' - %(funcName)s:%(lineno)s -> %(message)s' log_path = get_log_path() Path(log_path).parent.mkdir(parents=True, exist_ok=True) handler = logging.FileHandler(filename=log_path, mode='a', encoding='utf-8') logging.basicConfig(format=log_format, level=logging.DEBUG, handlers=[handler]) logger = logging.getLogger(__name__) return logger def log(logger, log_func_args: bool = True): """ デコレーターでloggerを引数にとるためのラッパー関数 A wrapper function for taking a logger as an argument in the decorator Args: logger (logging.Logger) log_func_args (bool) Returns: _decoratorの返り値 return of _decorator """ def _decorator(func): """ デコレーターを使用する関数を引数とする A function that takes a function with a decorator as an argument Args: func (function) Returns: wrapperの返り値 return of wrapper """ # funcのメタデータを引き継ぐ @wraps(func) def wrapper(*args, **kwargs): """ 実際の処理を書くための関数 Functions for writing the actual process Args: *args, **kwargs: funcの引数 args of func Returns: funcの返り値 return of func """ func_name = func.__name__ file_name = inspect.getfile(func) line_no = inspect.currentframe().f_back.f_lineno real_func_info = f'{file_name}[{line_no}]:{func_name}' if log_func_args and (args is not None) and (len(args) != 0): args_str = ','.join([str(a) for a in args]) message = f'[START] {real_func_info}({args_str})' else: message = f'[START] {real_func_info}()' logger.debug(message) try: # funcの実行 ret = func(*args, **kwargs) if log_func_args and ret is not None: logger.debug(f'[END] {real_func_info}() = {ret}') else: logger.debug(f'[END] {real_func_info}()') return ret except Exception as err: # funcのエラーハンドリング logger.error(err, exc_info=True) logger.error(f'[KILLED] {real_func_info}()') raise return wrapper return _decorator
Returns: output file path(str): """ jst_datetime = datetime.now().astimezone(timezone('Asia/Tokyo'))
test_pyfunc_multiprocess.py
# Copyright 2022 Huawei Technologies Co., Ltd # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """ Test Python Multiprocessing with Python functions/ops """ import numpy as np import pytest import mindspore.dataset as ds import mindspore.dataset.transforms.py_transforms as py_transforms import mindspore.dataset.vision.py_transforms as py_vision from util import visualize_list MNIST_DATA_DIR = "../data/dataset/testMnistData" TF_DATA_DIR = ["../data/dataset/test_tf_file_3_images/train-0000-of-0001.data"] TF_SCHEMA_DIR = "../data/dataset/test_tf_file_3_images/datasetSchema.json" PYFUNCMAP_DATA_DIR = ["../data/dataset/testPyfuncMap/data.data"] PYFUNCMAP_SCHEMA_DIR = "../data/dataset/testPyfuncMap/schema.json" def skip_test_pyfunc_multiproc_shrmem(): """ Feature: PyFunc in Map op Description: Test python_multiprocessing=True with shared memory enabled Expectation: Data results are correct """ def pyfunc(x): return x # Confirm shared memory optimization is enabled by default mem_original = ds.config.get_enable_shared_mem() assert mem_original # Reduce memory needed by reducing queue size prefetch_original = ds.config.get_prefetch_size() ds.config.set_prefetch_size(1) max_elements = 2000 np_data = list(range(0, max_elements)) data1 = ds.NumpySlicesDataset(np_data, shuffle=False) data1 = data1.map(pyfunc, num_parallel_workers=8, python_multiprocessing=True, max_rowsize=1) for i, data in enumerate(data1): np.testing.assert_equal(data[0].asnumpy(), np_data[i]) assert data1.get_dataset_size() == max_elements ds.config.set_prefetch_size(prefetch_original) def create_dataset_pyop_multiproc(num_parallel_workers=None, max_rowsize=16, batch_size=32, repeat_size=1, num_samples=None): """ Create dataset with Python ops list and python_multiprocessing=True for Map op """ # Define dataset data1 = ds.MnistDataset(MNIST_DATA_DIR, num_samples=num_samples) data1 = data1.map(operations=[py_vision.ToType(np.int32)], input_columns="label", num_parallel_workers=num_parallel_workers, python_multiprocessing=True, max_rowsize=max_rowsize) # Setup transforms list which include Python ops transforms_list = [ lambda x: x, py_vision.HWC2CHW(), py_vision.RandomErasing(0.9, value='random'), py_vision.Cutout(4, 2), lambda y: y ] compose_op = py_transforms.Compose(transforms_list) data1 = data1.map(operations=compose_op, input_columns="image", num_parallel_workers=num_parallel_workers, python_multiprocessing=True, max_rowsize=max_rowsize) # Apply Dataset Ops buffer_size = 10000 data1 = data1.shuffle(buffer_size=buffer_size) data1 = data1.batch(batch_size, drop_remainder=True) data1 = data1.repeat(repeat_size) return data1 def test_pyfunc_multiproc_noshrmem(): """ Feature: Python Multiprocessing Description: Test Map op with python_multiprocessing=True Expectation: Number of return data rows is correct """ # Reduce memory required by disabling the shared memory optimization mem_original = ds.config.get_enable_shared_mem() ds.config.set_enable_shared_mem(False) mydata1 = create_dataset_pyop_multiproc(num_parallel_workers=12, repeat_size=2) mycount1 = 0 for _ in mydata1.create_dict_iterator(num_epochs=1): mycount1 += 1 assert mycount1 == 624 ds.config.set_enable_shared_mem(mem_original) def test_pyfunc_multiproc_max_rowsize_small(): """ Feature: Python Multiprocessing Description: Test Map op with python_multiprocessing=True and max_rowsize=1 (less than default of 16) Expectation: Number of return data rows is correct """ # Reduce memory needed by reducing queue size # and disabling the shared memory optimization prefetch_original = ds.config.get_prefetch_size() ds.config.set_prefetch_size(1) mem_original = ds.config.get_enable_shared_mem() ds.config.set_enable_shared_mem(False) mydata1 = create_dataset_pyop_multiproc(num_parallel_workers=2, max_rowsize=1, num_samples=500) mycount1 = 0 for _ in mydata1.create_dict_iterator(num_epochs=1): mycount1 += 1 assert mycount1 == 15 ds.config.set_prefetch_size(prefetch_original) ds.config.set_enable_shared_mem(mem_original) def test_pyfunc_multiproc_max_rowsize_large(): """ Feature: Python Multiprocessing Description: Test Map op with python_multiprocessing=True and max_rowsize=20 (more than default of 16) Expectation: Number of return data rows is correct """ # Reduce memory required by disabling the shared memory optimization mem_original = ds.config.get_enable_shared_mem() ds.config.set_enable_shared_mem(False) mydata1 = create_dataset_pyop_multiproc(num_parallel_workers=4, max_rowsize=20, num_samples=500) mycount1 = 0 for _ in mydata1.create_dict_iterator(num_epochs=1): mycount1 += 1 assert mycount1 == 15 ds.config.set_enable_shared_mem(mem_original) def test_pyfunc_multiproc_basic_pipeline(plot=False): """ Feature: Python Multiprocessing Description: Test Map op with python_multiprocessing=True in a basic pipeline with Py ops Expectation: Images in plots from the 2 pipelines are visually fine """ # Reduce memory required by disabling the shared memory optimization mem_original = ds.config.get_enable_shared_mem() ds.config.set_enable_shared_mem(False) # Define map operations transforms_list = [py_vision.CenterCrop(64), py_vision.RandomRotation(30)] transforms1 = [ py_vision.Decode(), py_transforms.RandomChoice(transforms_list), py_vision.ToTensor() ] transform1 = py_transforms.Compose(transforms1) transforms2 = [ py_vision.Decode(), py_vision.ToTensor() ] transform2 = py_transforms.Compose(transforms2) # First dataset data1 = ds.TFRecordDataset(TF_DATA_DIR, TF_SCHEMA_DIR, columns_list=["image"], shuffle=False) data1 = data1.map(operations=transform1, input_columns=["image"], num_parallel_workers=2, python_multiprocessing=True, max_rowsize=1) # Second dataset data2 = ds.TFRecordDataset(TF_DATA_DIR, TF_SCHEMA_DIR, columns_list=["image"], shuffle=False) data2 = data2.map(operations=transform2, input_columns=["image"]) image_choice = [] image_original = [] for item1, item2 in zip(data1.create_dict_iterator(num_epochs=1, output_numpy=True), data2.create_dict_iterator(num_epochs=1, output_numpy=True)): image1 = (item1["image"].transpose(1, 2, 0) * 255).astype(np.uint8) image2 = (item2["image"].transpose(1, 2, 0) * 255).astype(np.uint8) image_choice.append(image1) image_original.append(image2) if plot: visualize_list(image_original, image_choice) ds.config.set_enable_shared_mem(mem_original) def
(): """ Feature: Python Multiprocessing Description: Test Map op with python_multiprocessing=True with Python op encountering exception Expectation: Exception is correctly processed """ # Reduce memory required by disabling the shared memory optimization mem_original = ds.config.get_enable_shared_mem() ds.config.set_enable_shared_mem(False) # Define map operations # Note: crop size[5000, 5000] > image size[4032, 2268] transforms_list = [py_vision.RandomCrop(5000)] transforms = [ py_vision.Decode(), py_transforms.RandomChoice(transforms_list), py_vision.ToTensor() ] transform = py_transforms.Compose(transforms) # Generate dataset data = ds.TFRecordDataset(TF_DATA_DIR, TF_SCHEMA_DIR, columns_list=["image"], shuffle=False) data = data.map(operations=transform, input_columns=["image"], python_multiprocessing=True) # Note: Expect error raised with RandomCrop input: crop size greater than image size with pytest.raises(RuntimeError) as info: data.create_dict_iterator(num_epochs=1).__next__() assert "Crop size" in str(info.value) ds.config.set_enable_shared_mem(mem_original) def test_pyfunc_multiproc_mainproc_exception(): """ Feature: PyFunc in Map op Description: Test python_multiprocessing=True with exception in main process Expectation: Exception is received and test ends gracefully """ # Reduce memory required by disabling the shared memory optimization mem_original = ds.config.get_enable_shared_mem() ds.config.set_enable_shared_mem(False) # Apply dataset operations data1 = ds.TFRecordDataset(PYFUNCMAP_DATA_DIR, PYFUNCMAP_SCHEMA_DIR, shuffle=False) data1 = data1.map(operations=(lambda x: x + x), input_columns="col0", output_columns="out", python_multiprocessing=True) with pytest.raises(ZeroDivisionError) as info: i = 0 for _ in data1.create_dict_iterator(num_epochs=1, output_numpy=True): i = i + 4 if i > 8: # Cause division by zero error _ = i / 0 assert "division by zero" in str(info.value) ds.config.set_enable_shared_mem(mem_original) if __name__ == '__main__': skip_test_pyfunc_multiproc_shrmem() test_pyfunc_multiproc_noshrmem() test_pyfunc_multiproc_max_rowsize_small() test_pyfunc_multiproc_max_rowsize_large() test_pyfunc_multiproc_basic_pipeline(plot=True) test_pyfunc_multiproc_child_exception() test_pyfunc_multiproc_mainproc_exception()
test_pyfunc_multiproc_child_exception
adapters.rs
// Copyright 2018 The Grin Developers // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. //! Adapters connecting new block, new transaction, and accepted transaction //! events to consumers of those events. use crate::util::RwLock; use std::fs::File; use std::net::SocketAddr; use std::sync::{Arc, Weak}; use std::thread; use std::time::Instant; use crate::chain::{self, BlockStatus, ChainAdapter, Options}; use crate::common::types::{self, ChainValidationMode, ServerConfig, SyncState, SyncStatus}; use crate::core::core::hash::{Hash, Hashed}; use crate::core::core::transaction::Transaction; use crate::core::core::verifier_cache::VerifierCache; use crate::core::core::{BlockHeader, BlockSums, CompactBlock}; use crate::core::pow::Difficulty; use crate::core::{core, global}; use crate::p2p; use crate::pool; use crate::util::OneTime; use chrono::prelude::*; use chrono::Duration; use rand::prelude::*; /// Implementation of the NetAdapter for the . Gets notified when new /// blocks and transactions are received and forwards to the chain and pool /// implementations. pub struct NetToChainAdapter { sync_state: Arc<SyncState>, chain: Weak<chain::Chain>, tx_pool: Arc<RwLock<pool::TransactionPool>>, verifier_cache: Arc<RwLock<dyn VerifierCache>>, peers: OneTime<Weak<p2p::Peers>>, config: ServerConfig, } impl p2p::ChainAdapter for NetToChainAdapter { fn total_difficulty(&self) -> Difficulty { self.chain().head().unwrap().total_difficulty } fn total_height(&self) -> u64 { self.chain().head().unwrap().height } fn get_transaction(&self, kernel_hash: Hash) -> Option<core::Transaction> { self.tx_pool.read().retrieve_tx_by_kernel_hash(kernel_hash) } fn tx_kernel_received(&self, kernel_hash: Hash, addr: SocketAddr) { // nothing much we can do with a new transaction while syncing if self.sync_state.is_syncing() { return; } let tx = self.tx_pool.read().retrieve_tx_by_kernel_hash(kernel_hash); if tx.is_none() { self.request_transaction(kernel_hash, &addr); } } fn transaction_received(&self, tx: core::Transaction, stem: bool) { // nothing much we can do with a new transaction while syncing if self.sync_state.is_syncing() { return; } let source = pool::TxSource { debug_name: "p2p".to_string(), identifier: "?.?.?.?".to_string(), }; let tx_hash = tx.hash(); let header = self.chain().head_header().unwrap(); debug!( "Received tx {}, [in/out/kern: {}/{}/{}] going to process.", tx_hash, tx.inputs().len(), tx.outputs().len(), tx.kernels().len(), ); let res = { let mut tx_pool = self.tx_pool.write(); tx_pool.add_to_pool(source, tx, stem, &header) }; if let Err(e) = res { debug!("Transaction {} rejected: {:?}", tx_hash, e); } } fn block_received(&self, b: core::Block, addr: SocketAddr, was_requested: bool) -> bool { debug!( "Received block {} at {} from {} [in/out/kern: {}/{}/{}] going to process.", b.hash(), b.header.height, addr, b.inputs().len(), b.outputs().len(), b.kernels().len(), ); self.process_block(b, addr, was_requested) } fn compact_block_received(&self, cb: core::CompactBlock, addr: SocketAddr) -> bool { let bhash = cb.hash(); debug!( "Received compact_block {} at {} from {} [out/kern/kern_ids: {}/{}/{}] going to process.", bhash, cb.header.height, addr, cb.out_full().len(), cb.kern_full().len(), cb.kern_ids().len(), ); let cb_hash = cb.hash(); if cb.kern_ids().is_empty() { // push the freshly hydrated block through the chain pipeline match core::Block::hydrate_from(cb, vec![]) { Ok(block) => self.process_block(block, addr, false), Err(e) => { debug!("Invalid hydrated block {}: {:?}", cb_hash, e); return false; } } } else { // check at least the header is valid before hydrating if let Err(e) = self .chain() .process_block_header(&cb.header, self.chain_opts(false)) { debug!("Invalid compact block header {}: {:?}", cb_hash, e.kind()); return !e.is_bad_data(); } let (txs, missing_short_ids) = { self.tx_pool .read() .retrieve_transactions(cb.hash(), cb.nonce, cb.kern_ids()) }; debug!( "adapter: txs from tx pool - {}, (unknown kern_ids: {})", txs.len(), missing_short_ids.len(), ); // TODO - 3 scenarios here - // 1) we hydrate a valid block (good to go) // 2) we hydrate an invalid block (txs legit missing from our pool) // 3) we hydrate an invalid block (peer sent us a "bad" compact block) - [TBD] let block = match core::Block::hydrate_from(cb.clone(), txs) { Ok(block) => block, Err(e) => { debug!("Invalid hydrated block {}: {:?}", cb.hash(), e); return false; } }; if let Ok(prev) = self.chain().get_previous_header(&cb.header) { if block .validate(&prev.total_kernel_offset, self.verifier_cache.clone()) .is_ok() { debug!("successfully hydrated block from tx pool!"); self.process_block(block, addr, false) } else { if self.sync_state.status() == SyncStatus::NoSync { debug!("adapter: block invalid after hydration, requesting full block"); self.request_block(&cb.header, &addr); true } else { debug!("block invalid after hydration, ignoring it, cause still syncing"); true } } } else { debug!("failed to retrieve previous block header (still syncing?)"); true } } } fn header_received(&self, bh: core::BlockHeader, addr: SocketAddr) -> bool { let bhash = bh.hash(); debug!( "Received block header {} at {} from {}, going to process.", bhash, bh.height, addr, ); // pushing the new block header through the header chain pipeline // we will go ask for the block if this is a new header let res = self .chain() .process_block_header(&bh, self.chain_opts(false)); if let &Err(ref e) = &res { debug!("Block header {} refused by chain: {:?}", bhash, e.kind()); if e.is_bad_data() { return false; } else { // we got an error when trying to process the block header // but nothing serious enough to need to ban the peer upstream return true; } } // we have successfully processed a block header // so we can go request the block itself self.request_compact_block(&bh, &addr); // done receiving the header true } fn headers_received(&self, bhs: &[core::BlockHeader], addr: SocketAddr) -> bool { info!("Received {} block headers from {}", bhs.len(), addr,); if bhs.len() == 0 { return false; } // try to add headers to our header chain let res = self.chain().sync_block_headers(bhs, self.chain_opts(true)); if let &Err(ref e) = &res { debug!("Block headers refused by chain: {:?}", e); if e.is_bad_data() { return false; } } true } fn locate_headers(&self, locator: &[Hash]) -> Vec<core::BlockHeader> { debug!("locator: {:?}", locator); let header = match self.find_common_header(locator) { Some(header) => header, None => return vec![], }; let max_height = self.chain().header_head().unwrap().height; let txhashset = self.chain().txhashset(); let txhashset = txhashset.read(); // looks like we know one, getting as many following headers as allowed let hh = header.height; let mut headers = vec![]; for h in (hh + 1)..=(hh + (p2p::MAX_BLOCK_HEADERS as u64)) { if h > max_height { break; } if let Ok(header) = txhashset.get_header_by_height(h) { headers.push(header); } else { error!("Failed to locate headers successfully."); break; } } debug!("returning headers: {}", headers.len()); headers } /// Gets a full block by its hash. fn get_block(&self, h: Hash) -> Option<core::Block> { let b = self.chain().get_block(&h); match b { Ok(b) => Some(b), _ => None, } } /// Provides a reading view into the current txhashset state as well as /// the required indexes for a consumer to rewind to a consistent state /// at the provided block hash. fn txhashset_read(&self, h: Hash) -> Option<p2p::TxHashSetRead> { match self.chain().txhashset_read(h.clone()) { Ok((out_index, kernel_index, read)) => Some(p2p::TxHashSetRead { output_index: out_index, kernel_index: kernel_index, reader: read, }), Err(e) => { warn!("Couldn't produce txhashset data for block {}: {:?}", h, e); None } } } fn txhashset_receive_ready(&self) -> bool { match self.sync_state.status() { SyncStatus::TxHashsetDownload { .. } => true, _ => false, } } fn txhashset_download_update( &self, start_time: DateTime<Utc>, downloaded_size: u64, total_size: u64, ) -> bool { match self.sync_state.status() { SyncStatus::TxHashsetDownload { .. } => { self.sync_state .update_txhashset_download(SyncStatus::TxHashsetDownload { start_time, downloaded_size, total_size, }) } _ => false, } } /// Writes a reading view on a txhashset state that's been provided to us. /// If we're willing to accept that new state, the data stream will be /// read as a zip file, unzipped and the resulting state files should be /// rewound to the provided indexes. fn txhashset_write(&self, h: Hash, txhashset_data: File, _peer_addr: SocketAddr) -> bool { // check status again after download, in case 2 txhashsets made it somehow if let SyncStatus::TxHashsetDownload { .. } = self.sync_state.status() { } else { return true; } if let Err(e) = self .chain() .txhashset_write(h, txhashset_data, self.sync_state.as_ref()) { error!("Failed to save txhashset archive: {}", e); let is_good_data = !e.is_bad_data(); self.sync_state.set_sync_error(types::Error::Chain(e)); is_good_data } else { info!("Received valid txhashset data for {}.", h); true } } } impl NetToChainAdapter { /// Construct a new NetToChainAdapter instance pub fn new( sync_state: Arc<SyncState>, chain: Arc<chain::Chain>, tx_pool: Arc<RwLock<pool::TransactionPool>>, verifier_cache: Arc<RwLock<dyn VerifierCache>>, config: ServerConfig, ) -> NetToChainAdapter { NetToChainAdapter { sync_state, chain: Arc::downgrade(&chain), tx_pool, verifier_cache, peers: OneTime::new(), config, } } /// Initialize a NetToChainAdaptor with reference to a Peers object. /// Should only be called once. pub fn init(&self, peers: Arc<p2p::Peers>) { self.peers.init(Arc::downgrade(&peers)); } fn peers(&self) -> Arc<p2p::Peers> { self.peers .borrow() .upgrade() .expect("Failed to upgrade weak ref to our peers.") } fn chain(&self) -> Arc<chain::Chain> { self.chain .upgrade() .expect("Failed to upgrade weak ref to our chain.") } // Find the first locator hash that refers to a known header on our main chain. fn find_common_header(&self, locator: &[Hash]) -> Option<BlockHeader>
// pushing the new block through the chain pipeline // remembering to reset the head if we have a bad block fn process_block(&self, b: core::Block, addr: SocketAddr, was_requested: bool) -> bool { // We cannot process blocks earlier than the horizon so check for this here. { let head = self.chain().head().unwrap(); let horizon = head .height .saturating_sub(global::cut_through_horizon() as u64); if b.header.height < horizon { return true; } } let bhash = b.hash(); let previous = self.chain().get_previous_header(&b.header); match self .chain() .process_block(b, self.chain_opts(was_requested)) { Ok(_) => { self.validate_chain(bhash); self.check_compact(); true } Err(ref e) if e.is_bad_data() => { self.validate_chain(bhash); false } Err(e) => { match e.kind() { chain::ErrorKind::Orphan => { if let Ok(previous) = previous { // make sure we did not miss the parent block if !self.chain().is_orphan(&previous.hash()) && !self.sync_state.is_syncing() { debug!("process_block: received an orphan block, checking the parent: {:}", previous.hash()); self.request_block_by_hash(previous.hash(), &addr) } } true } _ => { debug!( "process_block: block {} refused by chain: {}", bhash, e.kind() ); true } } } } } fn validate_chain(&self, bhash: Hash) { // If we are running in "validate the full chain every block" then // panic here if validation fails for any reason. // We are out of consensus at this point and want to track the problem // down as soon as possible. // Skip this if we are currently syncing (too slow). if self.config.chain_validation_mode == ChainValidationMode::EveryBlock && self.chain().head().unwrap().height > 0 && !self.sync_state.is_syncing() { let now = Instant::now(); debug!( "process_block: ***** validating full chain state at {}", bhash, ); self.chain() .validate(true) .expect("chain validation failed, hard stop"); debug!( "process_block: ***** done validating full chain state, took {}s", now.elapsed().as_secs(), ); } } fn check_compact(&self) { // Skip compaction if we are syncing. if self.sync_state.is_syncing() { return; } // Roll the dice to trigger compaction at 1/COMPACTION_CHECK chance per block, // uses a different thread to avoid blocking the caller thread (likely a peer) let mut rng = thread_rng(); if 0 == rng.gen_range(0, global::COMPACTION_CHECK) { let chain = self.chain().clone(); let _ = thread::Builder::new() .name("compactor".to_string()) .spawn(move || { if let Err(e) = chain.compact() { error!("Could not compact chain: {:?}", e); } }); } } fn request_transaction(&self, h: Hash, addr: &SocketAddr) { self.send_tx_request_to_peer(h, addr, |peer, h| peer.send_tx_request(h)) } // After receiving a compact block if we cannot successfully hydrate // it into a full block then fallback to requesting the full block // from the same peer that gave us the compact block // consider additional peers for redundancy? fn request_block(&self, bh: &BlockHeader, addr: &SocketAddr) { self.request_block_by_hash(bh.hash(), addr) } fn request_block_by_hash(&self, h: Hash, addr: &SocketAddr) { self.send_block_request_to_peer(h, addr, |peer, h| peer.send_block_request(h)) } // After we have received a block header in "header first" propagation // we need to go request the block (compact representation) from the // same peer that gave us the header (unless we have already accepted the block) fn request_compact_block(&self, bh: &BlockHeader, addr: &SocketAddr) { self.send_block_request_to_peer(bh.hash(), addr, |peer, h| { peer.send_compact_block_request(h) }) } fn send_tx_request_to_peer<F>(&self, h: Hash, addr: &SocketAddr, f: F) where F: Fn(&p2p::Peer, Hash) -> Result<(), p2p::Error>, { match self.peers().get_connected_peer(addr) { None => debug!( "send_tx_request_to_peer: can't send request to peer {:?}, not connected", addr ), Some(peer) => { if let Err(e) = f(&peer, h) { error!("send_tx_request_to_peer: failed: {:?}", e) } } } } fn send_block_request_to_peer<F>(&self, h: Hash, addr: &SocketAddr, f: F) where F: Fn(&p2p::Peer, Hash) -> Result<(), p2p::Error>, { match self.chain().block_exists(h) { Ok(false) => match self.peers().get_connected_peer(addr) { None => debug!( "send_block_request_to_peer: can't send request to peer {:?}, not connected", addr ), Some(peer) => { if let Err(e) = f(&peer, h) { error!("send_block_request_to_peer: failed: {:?}", e) } } }, Ok(true) => debug!("send_block_request_to_peer: block {} already known", h), Err(e) => error!( "send_block_request_to_peer: failed to check block exists: {:?}", e ), } } /// Prepare options for the chain pipeline fn chain_opts(&self, was_requested: bool) -> chain::Options { let opts = if was_requested { chain::Options::SYNC } else { chain::Options::NONE }; opts } } /// Implementation of the ChainAdapter for the network. Gets notified when the /// accepted a new block, asking the pool to update its state and /// the network to broadcast the block pub struct ChainToPoolAndNetAdapter { sync_state: Arc<SyncState>, tx_pool: Arc<RwLock<pool::TransactionPool>>, peers: OneTime<Weak<p2p::Peers>>, } impl ChainAdapter for ChainToPoolAndNetAdapter { fn block_accepted(&self, b: &core::Block, status: BlockStatus, opts: Options) { match status { BlockStatus::Reorg => { warn!( "block_accepted (REORG!): {:?} at {} (diff: {})", b.hash(), b.header.height, b.header.total_difficulty(), ); } BlockStatus::Fork => { debug!( "block_accepted (fork?): {:?} at {} (diff: {})", b.hash(), b.header.height, b.header.total_difficulty(), ); } BlockStatus::Next => { debug!( "block_accepted (head+): {:?} at {} (diff: {})", b.hash(), b.header.height, b.header.total_difficulty(), ); } } // not broadcasting blocks received through sync if !opts.contains(chain::Options::SYNC) { // If we mined the block then we want to broadcast the compact block. // If we received the block from another node then broadcast "header first" // to minimize network traffic. if opts.contains(Options::MINE) { // propagate compact block out if we mined the block let cb: CompactBlock = b.clone().into(); self.peers().broadcast_compact_block(&cb); } else { // "header first" propagation if we are not the originator of this block self.peers().broadcast_header(&b.header); } } // Reconcile the txpool against the new block *after* we have broadcast it too our peers. // This may be slow and we do not want to delay block propagation. // We only want to reconcile the txpool against the new block *if* total work has increased. if status == BlockStatus::Next || status == BlockStatus::Reorg { let mut tx_pool = self.tx_pool.write(); let _ = tx_pool.reconcile_block(b); // First "age out" any old txs in the reorg_cache. let cutoff = Utc::now() - Duration::minutes(30); tx_pool.truncate_reorg_cache(cutoff); } if status == BlockStatus::Reorg { let _ = self.tx_pool.write().reconcile_reorg_cache(&b.header); } } } impl ChainToPoolAndNetAdapter { /// Construct a ChainToPoolAndNetAdapter instance. pub fn new( sync_state: Arc<SyncState>, tx_pool: Arc<RwLock<pool::TransactionPool>>, ) -> ChainToPoolAndNetAdapter { ChainToPoolAndNetAdapter { sync_state, tx_pool, peers: OneTime::new(), } } /// Initialize a ChainToPoolAndNetAdapter instance with handle to a Peers /// object. Should only be called once. pub fn init(&self, peers: Arc<p2p::Peers>) { self.peers.init(Arc::downgrade(&peers)); } fn peers(&self) -> Arc<p2p::Peers> { self.peers .borrow() .upgrade() .expect("Failed to upgrade weak ref to our peers.") } } /// Adapter between the transaction pool and the network, to relay /// transactions that have been accepted. pub struct PoolToNetAdapter { peers: OneTime<Weak<p2p::Peers>>, } impl pool::PoolAdapter for PoolToNetAdapter { fn stem_tx_accepted(&self, tx: &core::Transaction) -> Result<(), pool::PoolError> { self.peers() .relay_stem_transaction(tx) .map_err(|_| pool::PoolError::DandelionError)?; Ok(()) } fn tx_accepted(&self, tx: &core::Transaction) { self.peers().broadcast_transaction(tx); } } impl PoolToNetAdapter { /// Create a new pool to net adapter pub fn new() -> PoolToNetAdapter { PoolToNetAdapter { peers: OneTime::new(), } } /// Setup the p2p server on the adapter pub fn init(&self, peers: Arc<p2p::Peers>) { self.peers.init(Arc::downgrade(&peers)); } fn peers(&self) -> Arc<p2p::Peers> { self.peers .borrow() .upgrade() .expect("Failed to upgrade weak ref to our peers.") } } /// Implements the view of the required by the TransactionPool to /// operate. Mostly needed to break any direct lifecycle or implementation /// dependency between the pool and the chain. #[derive(Clone)] pub struct PoolToChainAdapter { chain: OneTime<Weak<chain::Chain>>, } impl PoolToChainAdapter { /// Create a new pool adapter pub fn new() -> PoolToChainAdapter { PoolToChainAdapter { chain: OneTime::new(), } } /// Set the pool adapter's chain. Should only be called once. pub fn set_chain(&self, chain_ref: Arc<chain::Chain>) { self.chain.init(Arc::downgrade(&chain_ref)); } fn chain(&self) -> Arc<chain::Chain> { self.chain .borrow() .upgrade() .expect("Failed to upgrade the weak ref to our chain.") } } impl pool::BlockChain for PoolToChainAdapter { fn chain_head(&self) -> Result<BlockHeader, pool::PoolError> { self.chain() .head_header() .map_err(|_| pool::PoolError::Other(format!("failed to get head_header"))) } fn get_block_header(&self, hash: &Hash) -> Result<BlockHeader, pool::PoolError> { self.chain() .get_block_header(hash) .map_err(|_| pool::PoolError::Other(format!("failed to get block_header"))) } fn get_block_sums(&self, hash: &Hash) -> Result<BlockSums, pool::PoolError> { self.chain() .get_block_sums(hash) .map_err(|_| pool::PoolError::Other(format!("failed to get block_sums"))) } fn validate_tx(&self, tx: &Transaction) -> Result<(), pool::PoolError> { self.chain() .validate_tx(tx) .map_err(|_| pool::PoolError::Other(format!("failed to validate tx"))) } fn verify_coinbase_maturity(&self, tx: &Transaction) -> Result<(), pool::PoolError> { self.chain() .verify_coinbase_maturity(tx) .map_err(|_| pool::PoolError::ImmatureCoinbase) } fn verify_tx_lock_height(&self, tx: &Transaction) -> Result<(), pool::PoolError> { self.chain() .verify_tx_lock_height(tx) .map_err(|_| pool::PoolError::ImmatureTransaction) } }
{ let txhashset = self.chain().txhashset(); let txhashset = txhashset.read(); for hash in locator { if let Ok(header) = self.chain().get_block_header(&hash) { if let Ok(header_at_height) = txhashset.get_header_by_height(header.height) { if header.hash() == header_at_height.hash() { return Some(header); } } } } None }
index.ts
export { parse, SyntaxError, ParseError } from './parse/index' export { uriEncode, uriDecode, toSvg } from './codegen' export { DataStore } from './DataStore' export { Exporter, formats } from './exporter'
export { toDot } from './dot-writer'
analyzer.py
import os import re from .syllables import count as count_syllables from nltk.tokenize import sent_tokenize, TweetTokenizer from nltk.stem.porter import PorterStemmer class
: def __init__(self, stats): self.stats = stats @property def num_poly_syllable_words(self): return self.stats['num_poly_syllable_words'] @property def num_syllables(self): return self.stats['num_syllables'] @property def num_letters(self): return self.stats['num_letters'] @property def num_words(self): return self.stats['num_words'] @property def num_sentences(self): return self.stats['num_sentences'] @property def num_gunning_complex(self): return self.stats['num_gunning_complex'] @property def num_dale_chall_complex(self): return self.stats['num_dale_chall_complex'] @property def num_spache_complex(self): return self.stats['num_spache_complex'] @property def avg_words_per_sentence(self): return self.num_words / self.num_sentences @property def avg_syllables_per_word(self): return self.num_syllables / self.num_words def __str__(self): return str(self.stats) + \ ", avg_words_per_sentence " + str(self.avg_words_per_sentence) + \ ", avg_syllables_per_word " + str(self.avg_syllables_per_word) class Analyzer: def __init__(self): pass def analyze(self, text): self._dale_chall_set = self._load_dale_chall() self._spache_set = self._load_spache() stats = self._statistics(text) self.sentences = stats['sentences'] # hack for smog return AnalyzerStatistics(stats) def _statistics(self, text): tokens = self._tokenize(text) syllable_count = 0 poly_syllable_count = 0 word_count = 0 letters_count = 0 gunning_complex_count = 0 dale_chall_complex_count = 0 spache_complex_count = 0 porter_stemmer = PorterStemmer() def is_gunning_complex(t, syllable_count): return syllable_count >= 3 and \ not (self._is_proper_noun(t) or self._is_compound_word(t)) def is_dale_chall_complex(t): stem = porter_stemmer.stem(t.lower()) return stem not in self._dale_chall_set def is_spache_complex(t): stem = porter_stemmer.stem(t.lower()) return stem not in self._spache_set for t in tokens: if not self._is_punctuation(t): word_count += 1 word_syllable_count = count_syllables(t) syllable_count += word_syllable_count letters_count += len(t) poly_syllable_count += 1 if word_syllable_count >= 3 else 0 gunning_complex_count += \ 1 if is_gunning_complex(t, word_syllable_count) \ else 0 dale_chall_complex_count += \ 1 if is_dale_chall_complex(t) else 0 spache_complex_count += \ 1 if is_spache_complex(t) else 0 sentences = self._tokenize_sentences(text) sentence_count = len(sentences) return { 'num_syllables': syllable_count, 'num_poly_syllable_words': poly_syllable_count, 'num_words': word_count, 'num_sentences': sentence_count, 'num_letters': letters_count, 'num_gunning_complex': gunning_complex_count, 'num_dale_chall_complex': dale_chall_complex_count, 'num_spache_complex': spache_complex_count, 'sentences': sentences, } def _tokenize_sentences(self, text): return sent_tokenize(text) def _tokenize(self, text): tokenizer = TweetTokenizer() return tokenizer.tokenize(text) def _is_punctuation(self, token): match = re.match('^[.,\/#!$%\'\^&\*\’;:{}=\-_`~()]$', token) return match is not None def _is_proper_noun(self, token): # pos = pos_tag(token)[0][1] # return pos == 'NNP' return token[0].isupper() def _is_compound_word(self, token): return re.match('.*[-].*', token) is not None def _load_dale_chall(self): file = 'dale_chall_porterstem.txt' cur_path = os.path.dirname(os.path.realpath(__file__)) dale_chall_path = os.path.join(cur_path, '..', 'data', file) with open(dale_chall_path) as f: return set(line.strip() for line in f) def _load_spache(self): file = 'spache_easy_porterstem.txt' cur_path = os.path.dirname(os.path.realpath(__file__)) spache_path = os.path.join(cur_path, '..', 'data', file) with open(spache_path) as f: return set(line.strip() for line in f)
AnalyzerStatistics
www_authenticate.rs
use crate::auth::AuthenticationScheme; use crate::bail_status as bail; use crate::headers::{HeaderName, HeaderValue, Headers, WWW_AUTHENTICATE}; /// Define the authentication method that should be used to gain access to a /// resource. /// /// # Specifications /// /// - [RFC 7235, section 4.1: WWW-Authenticate](https://tools.ietf.org/html/rfc7235#section-4.1) /// /// # Implementation Notes /// /// This implementation only encodes and parses a single authentication method, /// further authorization methods are ignored. It also always passes the utf-8 encoding flag. /// /// # Examples /// /// ``` /// # fn main() -> http_types::Result<()> { /// # /// use http_types::Response; /// use http_types::auth::{AuthenticationScheme, WwwAuthenticate}; /// /// let scheme = AuthenticationScheme::Basic; /// let realm = "Access to the staging site"; /// let authz = WwwAuthenticate::new(scheme, realm.into()); /// /// let mut res = Response::new(200); /// authz.apply(&mut res); /// /// let authz = WwwAuthenticate::from_headers(res)?.unwrap(); /// /// assert_eq!(authz.scheme(), AuthenticationScheme::Basic); /// assert_eq!(authz.realm(), realm); /// # /// # Ok(()) } /// ``` #[derive(Debug)] pub struct WwwAuthenticate { scheme: AuthenticationScheme, realm: String, } impl WwwAuthenticate { /// Create a new instance of `WwwAuthenticate`. pub fn new(scheme: AuthenticationScheme, realm: String) -> Self { Self { scheme, realm } } /// Create a new instance from headers. pub fn from_headers(headers: impl AsRef<Headers>) -> crate::Result<Option<Self>> { let headers = match headers.as_ref().get(WWW_AUTHENTICATE) { Some(headers) => headers, None => return Ok(None), }; // If we successfully parsed the header then there's always at least one // entry. We want the last entry. let value = headers.iter().last().unwrap(); let mut iter = value.as_str().splitn(2, ' '); let scheme = iter.next(); let credential = iter.next(); let (scheme, realm) = match (scheme, credential) { (None, _) => bail!(400, "Could not find scheme"), (Some(_), None) => bail!(400, "Could not find realm"), (Some(scheme), Some(realm)) => (scheme.parse()?, realm.to_owned()), }; let realm = realm.trim_start(); let realm = match realm.strip_prefix(r#"realm=""#) { Some(realm) => realm, None => bail!(400, "realm not found"), }; let mut chars = realm.chars(); let mut closing_quote = false; let realm = (&mut chars) .take_while(|c| { if c == &'"' { closing_quote = true; false } else { true } }) .collect(); if !closing_quote { bail!(400, r"Expected a closing quote"); } Ok(Some(Self { scheme, realm })) } /// Sets the header. pub fn apply(&self, mut headers: impl AsMut<Headers>) { headers.as_mut().insert(self.name(), self.value()); } /// Get the `HeaderName`. pub fn name(&self) -> HeaderName { WWW_AUTHENTICATE } /// Get the `HeaderValue`. pub fn value(&self) -> HeaderValue { let output = format!(r#"{} realm="{}", charset="UTF-8""#, self.scheme, self.realm); // SAFETY: the internal string is validated to be ASCII. unsafe { HeaderValue::from_bytes_unchecked(output.into()) } } /// Get the authorization scheme. pub fn scheme(&self) -> AuthenticationScheme { self.scheme } /// Set the authorization scheme. pub fn set_scheme(&mut self, scheme: AuthenticationScheme)
/// Get the authorization realm. pub fn realm(&self) -> &str { self.realm.as_str() } /// Set the authorization realm. pub fn set_realm(&mut self, realm: String) { self.realm = realm; } } #[cfg(test)] mod test { use super::*; use crate::headers::Headers; #[test] fn smoke() -> crate::Result<()> { let scheme = AuthenticationScheme::Basic; let realm = "Access to the staging site"; let authz = WwwAuthenticate::new(scheme, realm.into()); let mut headers = Headers::new(); authz.apply(&mut headers); assert_eq!( headers["WWW-Authenticate"], r#"Basic realm="Access to the staging site", charset="UTF-8""# ); let authz = WwwAuthenticate::from_headers(headers)?.unwrap(); assert_eq!(authz.scheme(), AuthenticationScheme::Basic); assert_eq!(authz.realm(), realm); Ok(()) } #[test] fn bad_request_on_parse_error() -> crate::Result<()> { let mut headers = Headers::new(); headers.insert(WWW_AUTHENTICATE, "<nori ate the tag. yum.>"); let err = WwwAuthenticate::from_headers(headers).unwrap_err(); assert_eq!(err.status(), 400); Ok(()) } }
{ self.scheme = scheme; }
completion.go
/* Copyright 2019 The Skaffold Authors Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ /* NOTICE: The zsh wrapper code below is derived from the completion code in kubectl (k8s.io/kubernetes/pkg/kubectl/cmd/completion/completion.go), with the following license: Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package cmd import ( "bytes" "fmt" "io" "os" "github.com/spf13/cobra" ) const ( longDescription = ` Outputs shell completion for the given shell (bash or zsh) This depends on the bash-completion binary. Example installation instructions: OS X: $ brew install bash-completion $ source $(brew --prefix)/etc/bash_completion $ skaffold completion bash > ~/.skaffold-completion # for bash users $ skaffold completion zsh > ~/.skaffold-completion # for zsh users $ source ~/.skaffold-completion Ubuntu: $ apt-get install bash-completion $ source /etc/bash-completion $ source <(skaffold completion bash) # for bash users $ source <(skaffold completion zsh) # for zsh users Additionally, you may want to output the completion to a file and source in your .bashrc ` zshInitialization = `#compdef skaffold __skaffold_bash_source() { alias shopt=':' alias _expand=_bash_expand alias _complete=_bash_comp emulate -L sh setopt kshglob noshglob braceexpand source "$@" } __skaffold_type() { # -t is not supported by zsh if [ "$1" == "-t" ]; then shift # fake Bash 4 to disable "complete -o nospace". Instead # "compopt +-o nospace" is used in the code to toggle trailing # spaces. We don't support that, but leave trailing spaces on # all the time if [ "$1" = "__skaffold_compopt" ]; then echo builtin return 0 fi fi type "$@" } __skaffold_compgen() { local completions w completions=( $(compgen "$@") ) || return $? # filter by given word as prefix while [[ "$1" = -* && "$1" != -- ]]; do shift shift done if [[ "$1" == -- ]]; then shift fi for w in "${completions[@]}"; do if [[ "${w}" = "$1"* ]]; then echo "${w}" fi done } __skaffold_compopt() { true # don't do anything. Not supported by bashcompinit in zsh } __skaffold_ltrim_colon_completions() { if [[ "$1" == *:* && "$COMP_WORDBREAKS" == *:* ]]; then # Remove colon-word prefix from COMPREPLY items local colon_word=${1%${1##*:}} local i=${#COMPREPLY[*]} while [[ $((--i)) -ge 0 ]]; do COMPREPLY[$i]=${COMPREPLY[$i]#"$colon_word"} done fi } __skaffold_get_comp_words_by_ref() { cur="${COMP_WORDS[COMP_CWORD]}" prev="${COMP_WORDS[${COMP_CWORD}-1]}" words=("${COMP_WORDS[@]}") cword=("${COMP_CWORD[@]}") } __skaffold_filedir() { local RET OLD_IFS w qw __skaffold_debug "_filedir $@ cur=$cur" if [[ "$1" = \~* ]]; then # somehow does not work. Maybe, zsh does not call this at all eval echo "$1" return 0 fi OLD_IFS="$IFS" IFS=$'\n' if [ "$1" = "-d" ]; then shift RET=( $(compgen -d) ) else RET=( $(compgen -f) ) fi IFS="$OLD_IFS" IFS="," __skaffold_debug "RET=${RET[@]} len=${#RET[@]}" for w in ${RET[@]}; do if [[ ! "${w}" = "${cur}"* ]]; then continue fi if eval "[[ \"\${w}\" = *.$1 || -d \"\${w}\" ]]"; then qw="$(__skaffold_quote "${w}")" if [ -d "${w}" ]; then COMPREPLY+=("${qw}/") else COMPREPLY+=("${qw}")
} __skaffold_quote() { if [[ $1 == \'* || $1 == \"* ]]; then # Leave out first character printf %q "${1:1}" else printf %q "$1" fi } autoload -U +X bashcompinit && bashcompinit # use word boundary patterns for BSD or GNU sed LWORD='[[:<:]]' RWORD='[[:>:]]' if sed --help 2>&1 | grep -q GNU; then LWORD='\<' RWORD='\>' fi __skaffold_convert_bash_to_zsh() { sed \ -e 's/declare -F/whence -w/' \ -e 's/_get_comp_words_by_ref "\$@"/_get_comp_words_by_ref "\$*"/' \ -e 's/local \([a-zA-Z0-9_]*\)=/local \1; \1=/' \ -e 's/flags+=("\(--.*\)=")/flags+=("\1"); two_word_flags+=("\1")/' \ -e 's/must_have_one_flag+=("\(--.*\)=")/must_have_one_flag+=("\1")/' \ -e "s/${LWORD}_filedir${RWORD}/__skaffold_filedir/g" \ -e "s/${LWORD}_get_comp_words_by_ref${RWORD}/__skaffold_get_comp_words_by_ref/g" \ -e "s/${LWORD}__ltrim_colon_completions${RWORD}/__skaffold_ltrim_colon_completions/g" \ -e "s/${LWORD}compgen${RWORD}/__skaffold_compgen/g" \ -e "s/${LWORD}compopt${RWORD}/__skaffold_compopt/g" \ -e "s/${LWORD}declare${RWORD}/builtin declare/g" \ -e "s/\\\$(type${RWORD}/\$(__skaffold_type/g" \ <<'BASH_COMPLETION_EOF' ` zshTail = ` BASH_COMPLETION_EOF } __skaffold_bash_source <(__skaffold_convert_bash_to_zsh) _complete skaffold 2>/dev/null ` ) func completion(cmd *cobra.Command, args []string) { switch args[0] { case "bash": rootCmd(cmd).GenBashCompletion(os.Stdout) case "zsh": runCompletionZsh(cmd, os.Stdout) } } // NewCmdCompletion returns the cobra command that outputs shell completion code func NewCmdCompletion(out io.Writer) *cobra.Command { return &cobra.Command{ Use: "completion SHELL", Args: func(cmd *cobra.Command, args []string) error { if len(args) != 1 { return fmt.Errorf("requires 1 arg, found %d", len(args)) } return cobra.OnlyValidArgs(cmd, args) }, ValidArgs: []string{"bash", "zsh"}, Short: "Output shell completion for the given shell (bash or zsh)", Long: longDescription, Run: completion, } } func runCompletionZsh(cmd *cobra.Command, out io.Writer) { io.WriteString(out, zshInitialization) buf := new(bytes.Buffer) rootCmd(cmd).GenBashCompletion(buf) out.Write(buf.Bytes()) io.WriteString(out, zshTail) } func rootCmd(cmd *cobra.Command) *cobra.Command { parent := cmd for parent.HasParent() { parent = parent.Parent() } return parent }
fi fi done
feature_gate.rs
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. //! Feature gating //! //! This modules implements the gating necessary for preventing certain compiler //! features from being used by default. This module will crawl a pre-expanded //! AST to ensure that there are no features which are used that are not //! enabled. //! //! Features are enabled in programs via the crate-level attributes of //! `#![feature(...)]` with a comma-separated list of features. use self::Status::*; use abi::RustIntrinsic; use ast::NodeId; use ast; use attr; use attr::AttrMetaMethods; use codemap::{CodeMap, Span}; use diagnostic::SpanHandler; use visit; use visit::Visitor; use parse::token; use std::slice; use std::ascii::AsciiExt; // if you change this list without updating src/doc/reference.md, @cmr will be sad static KNOWN_FEATURES: &'static [(&'static str, Status)] = &[ ("globs", Active), ("macro_rules", Active), ("struct_variant", Accepted), ("asm", Active), ("managed_boxes", Removed), ("non_ascii_idents", Active), ("thread_local", Active), ("link_args", Active), ("phase", Active), ("plugin_registrar", Active), ("log_syntax", Active), ("trace_macros", Active), ("concat_idents", Active), ("unsafe_destructor", Active), ("intrinsics", Active), ("lang_items", Active), ("simd", Active), ("default_type_params", Active), ("quote", Active), ("link_llvm_intrinsics", Active), ("linkage", Active), ("struct_inherit", Removed), ("quad_precision_float", Removed), ("rustc_diagnostic_macros", Active), ("unboxed_closures", Active), ("import_shadowing", Active), ("advanced_slice_patterns", Active), ("tuple_indexing", Accepted), ("associated_types", Active), ("visible_private_types", Active), ("slicing_syntax", Active), ("if_let", Accepted), ("while_let", Accepted), // A temporary feature gate used to enable parser extensions needed // to bootstrap fix for #5723. ("issue_5723_bootstrap", Accepted), // A way to temporarily opt out of opt in copy. This will *never* be accepted. ("opt_out_copy", Deprecated), // A way to temporarily opt out of the new orphan rules. This will *never* be accepted. ("old_orphan_check", Deprecated), // These are used to test this portion of the compiler, they don't actually // mean anything ("test_accepted_feature", Accepted), ("test_removed_feature", Removed), ]; enum Status { /// Represents an active feature that is currently being implemented or /// currently being considered for addition/removal. Active, /// Represents a feature gate that is temporarily enabling deprecated behavior. /// This gate will never be accepted. Deprecated, /// Represents a feature which has since been removed (it was once Active) Removed, /// This language feature has since been Accepted (it was once Active) Accepted, } /// A set of features to be used by later passes. #[derive(Copy)] pub struct Features { pub default_type_params: bool, pub unboxed_closures: bool, pub rustc_diagnostic_macros: bool, pub import_shadowing: bool, pub visible_private_types: bool, pub quote: bool, pub opt_out_copy: bool, pub old_orphan_check: bool, } impl Features { pub fn new() -> Features { Features { default_type_params: false, unboxed_closures: false, rustc_diagnostic_macros: false, import_shadowing: false, visible_private_types: false, quote: false, opt_out_copy: false, old_orphan_check: false, } } } struct Context<'a> { features: Vec<&'static str>, span_handler: &'a SpanHandler, cm: &'a CodeMap, } impl<'a> Context<'a> { fn gate_feature(&self, feature: &str, span: Span, explain: &str) { if !self.has_feature(feature) { self.span_handler.span_err(span, explain); self.span_handler.span_help(span, format!("add #![feature({})] to the \ crate attributes to enable", feature)[]); } } fn has_feature(&self, feature: &str) -> bool { self.features.iter().any(|&n| n == feature) } } struct MacroVisitor<'a> { context: &'a Context<'a> } impl<'a, 'v> Visitor<'v> for MacroVisitor<'a> { fn visit_view_item(&mut self, i: &ast::ViewItem) { match i.node { ast::ViewItemExternCrate(..) => { for attr in i.attrs.iter() { if attr.name().get() == "phase"{ self.context.gate_feature("phase", attr.span, "compile time crate loading is \ experimental and possibly buggy"); } } }, _ => { } } visit::walk_view_item(self, i) } fn visit_mac(&mut self, macro: &ast::Mac) { let ast::MacInvocTT(ref path, _, _) = macro.node; let id = path.segments.last().unwrap().identifier; if id == token::str_to_ident("macro_rules") { self.context.gate_feature("macro_rules", path.span, "macro definitions are \ not stable enough for use and are subject to change"); } else if id == token::str_to_ident("asm") { self.context.gate_feature("asm", path.span, "inline assembly is not \ stable enough for use and is subject to change"); } else if id == token::str_to_ident("log_syntax") { self.context.gate_feature("log_syntax", path.span, "`log_syntax!` is not \ stable enough for use and is subject to change"); } else if id == token::str_to_ident("trace_macros") { self.context.gate_feature("trace_macros", path.span, "`trace_macros` is not \ stable enough for use and is subject to change"); } else if id == token::str_to_ident("concat_idents") { self.context.gate_feature("concat_idents", path.span, "`concat_idents` is not \ stable enough for use and is subject to change"); } } } struct PostExpansionVisitor<'a> { context: &'a Context<'a> } impl<'a> PostExpansionVisitor<'a> { fn gate_feature(&self, feature: &str, span: Span, explain: &str) { if !self.context.cm.span_is_internal(span) { self.context.gate_feature(feature, span, explain) } } } impl<'a, 'v> Visitor<'v> for PostExpansionVisitor<'a> { fn visit_name(&mut self, sp: Span, name: ast::Name) { if !token::get_name(name).get().is_ascii() { self.gate_feature("non_ascii_idents", sp, "non-ascii idents are not fully supported."); } } fn visit_view_item(&mut self, i: &ast::ViewItem) { match i.node { ast::ViewItemUse(ref path) => { if let ast::ViewPathGlob(..) = path.node { self.gate_feature("globs", path.span, "glob import statements are \ experimental and possibly buggy"); } } ast::ViewItemExternCrate(..) => { for attr in i.attrs.iter() { if attr.name().get() == "phase"{ self.gate_feature("phase", attr.span, "compile time crate loading is \ experimental and possibly buggy"); } } } } visit::walk_view_item(self, i) } fn visit_item(&mut self, i: &ast::Item) { for attr in i.attrs.iter() { if attr.name() == "thread_local" { self.gate_feature("thread_local", i.span, "`#[thread_local]` is an experimental feature, and does not \ currently handle destructors. There is no corresponding \ `#[task_local]` mapping to the task model"); } else if attr.name() == "linkage" { self.gate_feature("linkage", i.span, "the `linkage` attribute is experimental \ and not portable across platforms") } } match i.node { ast::ItemForeignMod(ref foreign_module) => { if attr::contains_name(i.attrs[], "link_args") { self.gate_feature("link_args", i.span, "the `link_args` attribute is not portable \ across platforms, it is recommended to \ use `#[link(name = \"foo\")]` instead") } if foreign_module.abi == RustIntrinsic { self.gate_feature("intrinsics", i.span, "intrinsics are subject to change") } } ast::ItemFn(..) => { if attr::contains_name(i.attrs[], "plugin_registrar") { self.gate_feature("plugin_registrar", i.span, "compiler plugins are experimental and possibly buggy"); } } ast::ItemStruct(..) => { if attr::contains_name(i.attrs[], "simd") { self.gate_feature("simd", i.span, "SIMD types are experimental and possibly buggy"); } } ast::ItemImpl(_, _, _, _, ref items) => { if attr::contains_name(i.attrs[], "unsafe_destructor") { self.gate_feature("unsafe_destructor", i.span, "`#[unsafe_destructor]` allows too \ many unsafe patterns and may be \ removed in the future"); } for item in items.iter() { match *item { ast::MethodImplItem(_) => {} ast::TypeImplItem(ref typedef) => { self.gate_feature("associated_types", typedef.span, "associated types are \ experimental") } } } } _ => {} } visit::walk_item(self, i); } fn visit_trait_item(&mut self, trait_item: &ast::TraitItem) { match *trait_item { ast::RequiredMethod(_) | ast::ProvidedMethod(_) => {} ast::TypeTraitItem(ref ti) =>
} } fn visit_foreign_item(&mut self, i: &ast::ForeignItem) { if attr::contains_name(i.attrs[], "linkage") { self.gate_feature("linkage", i.span, "the `linkage` attribute is experimental \ and not portable across platforms") } let links_to_llvm = match attr::first_attr_value_str_by_name(i.attrs[], "link_name") { Some(val) => val.get().starts_with("llvm."), _ => false }; if links_to_llvm { self.gate_feature("link_llvm_intrinsics", i.span, "linking to LLVM intrinsics is experimental"); } visit::walk_foreign_item(self, i) } fn visit_ty(&mut self, t: &ast::Ty) { if let ast::TyClosure(ref closure) = t.node { // this used to be blocked by a feature gate, but it should just // be plain impossible right now assert!(closure.onceness != ast::Once); } visit::walk_ty(self, t); } fn visit_expr(&mut self, e: &ast::Expr) { match e.node { ast::ExprRange(..) => { self.gate_feature("slicing_syntax", e.span, "range syntax is experimental"); } _ => {} } visit::walk_expr(self, e); } fn visit_generics(&mut self, generics: &ast::Generics) { for type_parameter in generics.ty_params.iter() { match type_parameter.default { Some(ref ty) => { self.gate_feature("default_type_params", ty.span, "default type parameters are \ experimental and possibly buggy"); } None => {} } } visit::walk_generics(self, generics); } fn visit_attribute(&mut self, attr: &ast::Attribute) { if attr::contains_name(slice::ref_slice(attr), "lang") { self.gate_feature("lang_items", attr.span, "language items are subject to change"); } } fn visit_pat(&mut self, pattern: &ast::Pat) { match pattern.node { ast::PatVec(_, Some(_), ref last) if !last.is_empty() => { self.gate_feature("advanced_slice_patterns", pattern.span, "multiple-element slice matches anywhere \ but at the end of a slice (e.g. \ `[0, ..xs, 0]` are experimental") } _ => {} } visit::walk_pat(self, pattern) } fn visit_fn(&mut self, fn_kind: visit::FnKind<'v>, fn_decl: &'v ast::FnDecl, block: &'v ast::Block, span: Span, _node_id: NodeId) { match fn_kind { visit::FkItemFn(_, _, _, abi) if abi == RustIntrinsic => { self.gate_feature("intrinsics", span, "intrinsics are subject to change") } _ => {} } visit::walk_fn(self, fn_kind, fn_decl, block, span); } } fn check_crate_inner<F>(cm: &CodeMap, span_handler: &SpanHandler, krate: &ast::Crate, check: F) -> (Features, Vec<Span>) where F: FnOnce(&mut Context, &ast::Crate) { let mut cx = Context { features: Vec::new(), span_handler: span_handler, cm: cm, }; let mut unknown_features = Vec::new(); for attr in krate.attrs.iter() { if !attr.check_name("feature") { continue } match attr.meta_item_list() { None => { span_handler.span_err(attr.span, "malformed feature attribute, \ expected #![feature(...)]"); } Some(list) => { for mi in list.iter() { let name = match mi.node { ast::MetaWord(ref word) => (*word).clone(), _ => { span_handler.span_err(mi.span, "malformed feature, expected just \ one word"); continue } }; match KNOWN_FEATURES.iter() .find(|& &(n, _)| name == n) { Some(&(name, Active)) => { cx.features.push(name); } Some(&(name, Deprecated)) => { cx.features.push(name); span_handler.span_warn( mi.span, "feature is deprecated and will only be available \ for a limited time, please rewrite code that relies on it"); } Some(&(_, Removed)) => { span_handler.span_err(mi.span, "feature has been removed"); } Some(&(_, Accepted)) => { span_handler.span_warn(mi.span, "feature has been added to Rust, \ directive not necessary"); } None => { unknown_features.push(mi.span); } } } } } } check(&mut cx, krate); (Features { default_type_params: cx.has_feature("default_type_params"), unboxed_closures: cx.has_feature("unboxed_closures"), rustc_diagnostic_macros: cx.has_feature("rustc_diagnostic_macros"), import_shadowing: cx.has_feature("import_shadowing"), visible_private_types: cx.has_feature("visible_private_types"), quote: cx.has_feature("quote"), opt_out_copy: cx.has_feature("opt_out_copy"), old_orphan_check: cx.has_feature("old_orphan_check"), }, unknown_features) } pub fn check_crate_macros(cm: &CodeMap, span_handler: &SpanHandler, krate: &ast::Crate) -> (Features, Vec<Span>) { check_crate_inner(cm, span_handler, krate, |ctx, krate| visit::walk_crate(&mut MacroVisitor { context: ctx }, krate)) } pub fn check_crate(cm: &CodeMap, span_handler: &SpanHandler, krate: &ast::Crate) -> (Features, Vec<Span>) { check_crate_inner(cm, span_handler, krate, |ctx, krate| visit::walk_crate(&mut PostExpansionVisitor { context: ctx }, krate)) }
{ self.gate_feature("associated_types", ti.ty_param.span, "associated types are experimental") }
fake_uaaclient.go
// Code generated by counterfeiter. DO NOT EDIT. package v2actionfakes import ( "sync" "code.cloudfoundry.org/cli/actor/v2action" "code.cloudfoundry.org/cli/api/uaa" "code.cloudfoundry.org/cli/api/uaa/constant" ) type FakeUAAClient struct { AuthenticateStub func(ID string, secret string, grantType constant.GrantType) (string, string, error) authenticateMutex sync.RWMutex authenticateArgsForCall []struct { ID string secret string grantType constant.GrantType } authenticateReturns struct { result1 string result2 string result3 error } authenticateReturnsOnCall map[int]struct { result1 string result2 string result3 error } CreateUserStub func(username string, password string, origin string) (uaa.User, error) createUserMutex sync.RWMutex createUserArgsForCall []struct { username string password string origin string } createUserReturns struct { result1 uaa.User result2 error } createUserReturnsOnCall map[int]struct { result1 uaa.User result2 error } GetSSHPasscodeStub func(accessToken string, sshOAuthClient string) (string, error) getSSHPasscodeMutex sync.RWMutex getSSHPasscodeArgsForCall []struct { accessToken string sshOAuthClient string } getSSHPasscodeReturns struct { result1 string result2 error } getSSHPasscodeReturnsOnCall map[int]struct { result1 string result2 error } RefreshAccessTokenStub func(refreshToken string) (uaa.RefreshedTokens, error) refreshAccessTokenMutex sync.RWMutex refreshAccessTokenArgsForCall []struct { refreshToken string } refreshAccessTokenReturns struct { result1 uaa.RefreshedTokens result2 error } refreshAccessTokenReturnsOnCall map[int]struct { result1 uaa.RefreshedTokens result2 error } invocations map[string][][]interface{} invocationsMutex sync.RWMutex } func (fake *FakeUAAClient) Authenticate(ID string, secret string, grantType constant.GrantType) (string, string, error) { fake.authenticateMutex.Lock() ret, specificReturn := fake.authenticateReturnsOnCall[len(fake.authenticateArgsForCall)] fake.authenticateArgsForCall = append(fake.authenticateArgsForCall, struct { ID string secret string grantType constant.GrantType }{ID, secret, grantType}) fake.recordInvocation("Authenticate", []interface{}{ID, secret, grantType}) fake.authenticateMutex.Unlock() if fake.AuthenticateStub != nil { return fake.AuthenticateStub(ID, secret, grantType) } if specificReturn { return ret.result1, ret.result2, ret.result3 } return fake.authenticateReturns.result1, fake.authenticateReturns.result2, fake.authenticateReturns.result3 } func (fake *FakeUAAClient) AuthenticateCallCount() int { fake.authenticateMutex.RLock() defer fake.authenticateMutex.RUnlock() return len(fake.authenticateArgsForCall) } func (fake *FakeUAAClient) AuthenticateArgsForCall(i int) (string, string, constant.GrantType) { fake.authenticateMutex.RLock() defer fake.authenticateMutex.RUnlock() return fake.authenticateArgsForCall[i].ID, fake.authenticateArgsForCall[i].secret, fake.authenticateArgsForCall[i].grantType } func (fake *FakeUAAClient) AuthenticateReturns(result1 string, result2 string, result3 error) { fake.AuthenticateStub = nil fake.authenticateReturns = struct { result1 string result2 string result3 error }{result1, result2, result3} } func (fake *FakeUAAClient) AuthenticateReturnsOnCall(i int, result1 string, result2 string, result3 error) { fake.AuthenticateStub = nil if fake.authenticateReturnsOnCall == nil { fake.authenticateReturnsOnCall = make(map[int]struct { result1 string result2 string result3 error }) } fake.authenticateReturnsOnCall[i] = struct {
} func (fake *FakeUAAClient) CreateUser(username string, password string, origin string) (uaa.User, error) { fake.createUserMutex.Lock() ret, specificReturn := fake.createUserReturnsOnCall[len(fake.createUserArgsForCall)] fake.createUserArgsForCall = append(fake.createUserArgsForCall, struct { username string password string origin string }{username, password, origin}) fake.recordInvocation("CreateUser", []interface{}{username, password, origin}) fake.createUserMutex.Unlock() if fake.CreateUserStub != nil { return fake.CreateUserStub(username, password, origin) } if specificReturn { return ret.result1, ret.result2 } return fake.createUserReturns.result1, fake.createUserReturns.result2 } func (fake *FakeUAAClient) CreateUserCallCount() int { fake.createUserMutex.RLock() defer fake.createUserMutex.RUnlock() return len(fake.createUserArgsForCall) } func (fake *FakeUAAClient) CreateUserArgsForCall(i int) (string, string, string) { fake.createUserMutex.RLock() defer fake.createUserMutex.RUnlock() return fake.createUserArgsForCall[i].username, fake.createUserArgsForCall[i].password, fake.createUserArgsForCall[i].origin } func (fake *FakeUAAClient) CreateUserReturns(result1 uaa.User, result2 error) { fake.CreateUserStub = nil fake.createUserReturns = struct { result1 uaa.User result2 error }{result1, result2} } func (fake *FakeUAAClient) CreateUserReturnsOnCall(i int, result1 uaa.User, result2 error) { fake.CreateUserStub = nil if fake.createUserReturnsOnCall == nil { fake.createUserReturnsOnCall = make(map[int]struct { result1 uaa.User result2 error }) } fake.createUserReturnsOnCall[i] = struct { result1 uaa.User result2 error }{result1, result2} } func (fake *FakeUAAClient) GetSSHPasscode(accessToken string, sshOAuthClient string) (string, error) { fake.getSSHPasscodeMutex.Lock() ret, specificReturn := fake.getSSHPasscodeReturnsOnCall[len(fake.getSSHPasscodeArgsForCall)] fake.getSSHPasscodeArgsForCall = append(fake.getSSHPasscodeArgsForCall, struct { accessToken string sshOAuthClient string }{accessToken, sshOAuthClient}) fake.recordInvocation("GetSSHPasscode", []interface{}{accessToken, sshOAuthClient}) fake.getSSHPasscodeMutex.Unlock() if fake.GetSSHPasscodeStub != nil { return fake.GetSSHPasscodeStub(accessToken, sshOAuthClient) } if specificReturn { return ret.result1, ret.result2 } return fake.getSSHPasscodeReturns.result1, fake.getSSHPasscodeReturns.result2 } func (fake *FakeUAAClient) GetSSHPasscodeCallCount() int { fake.getSSHPasscodeMutex.RLock() defer fake.getSSHPasscodeMutex.RUnlock() return len(fake.getSSHPasscodeArgsForCall) } func (fake *FakeUAAClient) GetSSHPasscodeArgsForCall(i int) (string, string) { fake.getSSHPasscodeMutex.RLock() defer fake.getSSHPasscodeMutex.RUnlock() return fake.getSSHPasscodeArgsForCall[i].accessToken, fake.getSSHPasscodeArgsForCall[i].sshOAuthClient } func (fake *FakeUAAClient) GetSSHPasscodeReturns(result1 string, result2 error) { fake.GetSSHPasscodeStub = nil fake.getSSHPasscodeReturns = struct { result1 string result2 error }{result1, result2} } func (fake *FakeUAAClient) GetSSHPasscodeReturnsOnCall(i int, result1 string, result2 error) { fake.GetSSHPasscodeStub = nil if fake.getSSHPasscodeReturnsOnCall == nil { fake.getSSHPasscodeReturnsOnCall = make(map[int]struct { result1 string result2 error }) } fake.getSSHPasscodeReturnsOnCall[i] = struct { result1 string result2 error }{result1, result2} } func (fake *FakeUAAClient) RefreshAccessToken(refreshToken string) (uaa.RefreshedTokens, error) { fake.refreshAccessTokenMutex.Lock() ret, specificReturn := fake.refreshAccessTokenReturnsOnCall[len(fake.refreshAccessTokenArgsForCall)] fake.refreshAccessTokenArgsForCall = append(fake.refreshAccessTokenArgsForCall, struct { refreshToken string }{refreshToken}) fake.recordInvocation("RefreshAccessToken", []interface{}{refreshToken}) fake.refreshAccessTokenMutex.Unlock() if fake.RefreshAccessTokenStub != nil { return fake.RefreshAccessTokenStub(refreshToken) } if specificReturn { return ret.result1, ret.result2 } return fake.refreshAccessTokenReturns.result1, fake.refreshAccessTokenReturns.result2 } func (fake *FakeUAAClient) RefreshAccessTokenCallCount() int { fake.refreshAccessTokenMutex.RLock() defer fake.refreshAccessTokenMutex.RUnlock() return len(fake.refreshAccessTokenArgsForCall) } func (fake *FakeUAAClient) RefreshAccessTokenArgsForCall(i int) string { fake.refreshAccessTokenMutex.RLock() defer fake.refreshAccessTokenMutex.RUnlock() return fake.refreshAccessTokenArgsForCall[i].refreshToken } func (fake *FakeUAAClient) RefreshAccessTokenReturns(result1 uaa.RefreshedTokens, result2 error) { fake.RefreshAccessTokenStub = nil fake.refreshAccessTokenReturns = struct { result1 uaa.RefreshedTokens result2 error }{result1, result2} } func (fake *FakeUAAClient) RefreshAccessTokenReturnsOnCall(i int, result1 uaa.RefreshedTokens, result2 error) { fake.RefreshAccessTokenStub = nil if fake.refreshAccessTokenReturnsOnCall == nil { fake.refreshAccessTokenReturnsOnCall = make(map[int]struct { result1 uaa.RefreshedTokens result2 error }) } fake.refreshAccessTokenReturnsOnCall[i] = struct { result1 uaa.RefreshedTokens result2 error }{result1, result2} } func (fake *FakeUAAClient) Invocations() map[string][][]interface{} { fake.invocationsMutex.RLock() defer fake.invocationsMutex.RUnlock() fake.authenticateMutex.RLock() defer fake.authenticateMutex.RUnlock() fake.createUserMutex.RLock() defer fake.createUserMutex.RUnlock() fake.getSSHPasscodeMutex.RLock() defer fake.getSSHPasscodeMutex.RUnlock() fake.refreshAccessTokenMutex.RLock() defer fake.refreshAccessTokenMutex.RUnlock() copiedInvocations := map[string][][]interface{}{} for key, value := range fake.invocations { copiedInvocations[key] = value } return copiedInvocations } func (fake *FakeUAAClient) recordInvocation(key string, args []interface{}) { fake.invocationsMutex.Lock() defer fake.invocationsMutex.Unlock() if fake.invocations == nil { fake.invocations = map[string][][]interface{}{} } if fake.invocations[key] == nil { fake.invocations[key] = [][]interface{}{} } fake.invocations[key] = append(fake.invocations[key], args) } var _ v2action.UAAClient = new(FakeUAAClient)
result1 string result2 string result3 error }{result1, result2, result3}
fisher_von_mises.py
# -*- coding: utf-8 -*- import numpy as np import torch """ The complete formulas and explanations are available in our doc: https://dwi-ml.readthedocs.io/en/latest/formulas.html """ def
(mus, kappa, targets): log_c = np.log(kappa) - np.log(2 * np.pi) - np.log(np.exp(kappa) - np.exp(-kappa)) log_prob = log_c + (kappa * (mus * targets).sum(axis=-1)) return log_prob def fisher_von_mises_log_prob(mus, kappa, targets, eps=1e-6): log_2pi = np.log(2 * np.pi).astype(np.float32) # Add an epsilon in case kappa is too small (i.e. a uniform # distribution) log_diff_exp_kappa = torch.log(torch.exp(kappa) - torch.exp(-kappa) + eps) log_c = torch.log(kappa) - log_2pi - log_diff_exp_kappa batch_dot_product = torch.sum(mus * targets, dim=1) log_prob = log_c + (kappa * batch_dot_product) return log_prob
fisher_von_mises_log_prob_vector
main.rs
use pwhash::{bcrypt, bsdi_crypt, md5_crypt, sha1_crypt, sha256_crypt, unix_crypt}; use std::env; fn main()
{ let mut password = "password"; let args: Vec<String> = env::args().collect(); if args.len() > 1 { password = args[1].as_str(); } println!("Password:\t{:}", password); let mut h_new = bcrypt::hash(password).unwrap(); println!("\nBcrypt:\t\t{:}", h_new); h_new = bsdi_crypt::hash(password).unwrap(); println!("BSDI Crypt:\t{:}", h_new); h_new = md5_crypt::hash(password).unwrap(); println!("MD5 Crypt:\t{:}", h_new); h_new = sha1_crypt::hash(password).unwrap(); println!("SHA1 Crypt:\t{:}", h_new); h_new = sha256_crypt::hash(password).unwrap(); println!("SHA-256 Crypt:\t{:}", h_new); h_new = unix_crypt::hash(password).unwrap(); println!("Unix crypt:\t{:}", h_new); // let rtn=bcrypt::verify(password, h); // println!("{:?}",rtn); }
main.go
// Package main is a client for the chat service to demonstrate how it would work for a client. To // run the client, first launch the chat service by running `micro run ./chat` from the top level of // this repo. Then run `micro run ./chat/client` and `micro logs -f client` to follow the logs of // the client. package main import ( "context" "fmt" "time" "github.com/google/uuid" "github.com/micro/micro/v3/service" "github.com/micro/micro/v3/service/context/metadata" "github.com/micro/micro/v3/service/logger" chat "github.com/micro/services/test/chat/proto" "google.golang.org/protobuf/types/known/timestamppb" ) var ( userOneID = "user-one-" + uuid.New().String() userTwoID = "user-two-" + uuid.New().String() ) func
() { // create a chat service client srv := service.New() cli := chat.NewChatService("chat", srv.Client()) // create a chat for our users userIDs := []string{userOneID, userTwoID} nRsp, err := cli.New(context.TODO(), &chat.NewRequest{UserIds: userIDs}) if err != nil { logger.Fatalf("Error creating the chat: %v", err) } chatID := nRsp.GetChatId() logger.Infof("Chat Created. ID: %v", chatID) // list the number messages in the chat history hRsp, err := cli.History(context.TODO(), &chat.HistoryRequest{ChatId: chatID}) if err != nil { logger.Fatalf("Error getting the chat history: %v", err) } logger.Infof("Chat has %v message(s)", len(hRsp.Messages)) // create a channel to handle errors errChan := make(chan error) // run user one go func() { ctx := metadata.NewContext(context.TODO(), metadata.Metadata{ "user-id": userOneID, "chat-id": chatID, }) stream, err := cli.Connect(ctx) if err != nil { errChan <- err return } for i := 1; true; i++ { // send a message to the chat err = stream.Send(&chat.Message{ ClientId: uuid.New().String(), SentAt: timestamppb.New(time.Now()), Subject: "Message from user one", Text: fmt.Sprintf("Message #%v", i), }) if err != nil { errChan <- err return } logger.Infof("User one sent message") // wait for user two to respond msg, err := stream.Recv() if err != nil { errChan <- err return } logger.Infof("User one recieved message %v from %v", msg.Text, msg.UserId) time.Sleep(time.Second) } }() // run user two go func() { ctx := metadata.NewContext(context.TODO(), metadata.Metadata{ "user-id": userTwoID, "chat-id": chatID, }) stream, err := cli.Connect(ctx) if err != nil { errChan <- err return } for i := 1; true; i++ { // send a response to the chat err = stream.Send(&chat.Message{ ClientId: uuid.New().String(), SentAt: timestamppb.New(time.Now()), Subject: "Response from user two", Text: fmt.Sprintf("Response #%v", i), }) if err != nil { errChan <- err return } logger.Infof("User two sent message") // wait for a message from user one msg, err := stream.Recv() if err != nil { errChan <- err return } logger.Infof("User two recieved message %v from %v", msg.Text, msg.UserId) time.Sleep(time.Second) } }() logger.Fatal(<-errChan) }
main
hello.go
package main import "fltk" func
() { w := fltk.NewWindow(300, 180) w.Begin() b := fltk.NewWidget(20, 40, 260, 100, "Hello there!") b.Box(fltk.UP_BOX) b.LabelFont(fltk.HELVETICA_BOLD_ITALIC) b.LabelSize(36) b.LabelType(fltk.SHADOW_LABEL) w.End() w.Show([]string{}) fltk.Run(func() bool {return true}) }
main
secret_manager.go
package deploy import ( "os" "path/filepath" "github.com/werf/logboek" "github.com/werf/werf/pkg/deploy/secret" "github.com/werf/werf/pkg/deploy/werf_chart" ) func GetSafeSecretManager(projectDir, helmChartDir string, secretValues []string, ignoreSecretKey bool) (secret.Manager, error) { isSecretsExists := false if _, err := os.Stat(filepath.Join(helmChartDir, werf_chart.SecretDirName)); !os.IsNotExist(err) { isSecretsExists = true } if _, err := os.Stat(filepath.Join(helmChartDir, werf_chart.DefaultSecretValuesFileName)); !os.IsNotExist(err) { isSecretsExists = true } if len(secretValues) > 0 { isSecretsExists = true } if isSecretsExists { if ignoreSecretKey { logboek.Default.LogLnDetails("Secrets decryption disabled") return secret.NewSafeManager() } key, err := secret.GetSecretKey(projectDir) if err != nil
return secret.NewManager(key) } else { return secret.NewSafeManager() } }
{ return nil, err }
api_op_DeleteEndpoint.go
// Code generated by smithy-go-codegen DO NOT EDIT. package databasemigrationservice
awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" "github.com/aws/aws-sdk-go-v2/aws/signer/v4" "github.com/aws/aws-sdk-go-v2/service/databasemigrationservice/types" "github.com/aws/smithy-go/middleware" smithyhttp "github.com/aws/smithy-go/transport/http" ) // Deletes the specified endpoint. All tasks associated with the endpoint must be // deleted before you can delete the endpoint. func (c *Client) DeleteEndpoint(ctx context.Context, params *DeleteEndpointInput, optFns ...func(*Options)) (*DeleteEndpointOutput, error) { if params == nil { params = &DeleteEndpointInput{} } result, metadata, err := c.invokeOperation(ctx, "DeleteEndpoint", params, optFns, addOperationDeleteEndpointMiddlewares) if err != nil { return nil, err } out := result.(*DeleteEndpointOutput) out.ResultMetadata = metadata return out, nil } // type DeleteEndpointInput struct { // The Amazon Resource Name (ARN) string that uniquely identifies the endpoint. // // This member is required. EndpointArn *string } // type DeleteEndpointOutput struct { // The endpoint that was deleted. Endpoint *types.Endpoint // Metadata pertaining to the operation's result. ResultMetadata middleware.Metadata } func addOperationDeleteEndpointMiddlewares(stack *middleware.Stack, options Options) (err error) { err = stack.Serialize.Add(&awsAwsjson11_serializeOpDeleteEndpoint{}, middleware.After) if err != nil { return err } err = stack.Deserialize.Add(&awsAwsjson11_deserializeOpDeleteEndpoint{}, middleware.After) if err != nil { return err } if err = addSetLoggerMiddleware(stack, options); err != nil { return err } if err = awsmiddleware.AddClientRequestIDMiddleware(stack); err != nil { return err } if err = smithyhttp.AddComputeContentLengthMiddleware(stack); err != nil { return err } if err = addResolveEndpointMiddleware(stack, options); err != nil { return err } if err = v4.AddComputePayloadSHA256Middleware(stack); err != nil { return err } if err = addRetryMiddlewares(stack, options); err != nil { return err } if err = addHTTPSignerV4Middleware(stack, options); err != nil { return err } if err = awsmiddleware.AddRawResponseToMetadata(stack); err != nil { return err } if err = awsmiddleware.AddRecordResponseTiming(stack); err != nil { return err } if err = addClientUserAgent(stack); err != nil { return err } if err = smithyhttp.AddErrorCloseResponseBodyMiddleware(stack); err != nil { return err } if err = smithyhttp.AddCloseResponseBodyMiddleware(stack); err != nil { return err } if err = addOpDeleteEndpointValidationMiddleware(stack); err != nil { return err } if err = stack.Initialize.Add(newServiceMetadataMiddleware_opDeleteEndpoint(options.Region), middleware.Before); err != nil { return err } if err = addRequestIDRetrieverMiddleware(stack); err != nil { return err } if err = addResponseErrorMiddleware(stack); err != nil { return err } if err = addRequestResponseLogging(stack, options); err != nil { return err } return nil } func newServiceMetadataMiddleware_opDeleteEndpoint(region string) *awsmiddleware.RegisterServiceMetadata { return &awsmiddleware.RegisterServiceMetadata{ Region: region, ServiceID: ServiceID, SigningName: "dms", OperationName: "DeleteEndpoint", } }
import ( "context"
macro_rules.rs
use crate::base::{DummyResult, ExtCtxt, MacResult, TTMacroExpander}; use crate::base::{SyntaxExtension, SyntaxExtensionKind}; use crate::expand::{ensure_complete_parse, parse_ast_fragment, AstFragment, AstFragmentKind}; use crate::mbe; use crate::mbe::macro_check; use crate::mbe::macro_parser::parse_tt; use crate::mbe::macro_parser::{Error, ErrorReported, Failure, Success}; use crate::mbe::macro_parser::{MatchedNonterminal, MatchedSeq}; use crate::mbe::transcribe::transcribe; use rustc_ast as ast; use rustc_ast::token::{self, NonterminalKind, NtTT, Token, TokenKind::*}; use rustc_ast::tokenstream::{DelimSpan, TokenStream}; use rustc_ast_pretty::pprust; use rustc_attr::{self as attr, TransparencyError}; use rustc_data_structures::fx::FxHashMap; use rustc_data_structures::sync::Lrc; use rustc_errors::{Applicability, DiagnosticBuilder}; use rustc_feature::Features; use rustc_parse::parser::Parser; use rustc_session::parse::ParseSess; use rustc_session::Session; use rustc_span::edition::Edition; use rustc_span::hygiene::Transparency; use rustc_span::symbol::{kw, sym, Ident, MacroRulesNormalizedIdent}; use rustc_span::Span; use std::borrow::Cow; use std::collections::hash_map::Entry; use std::{mem, slice}; use tracing::debug; crate struct ParserAnyMacro<'a> { parser: Parser<'a>, /// Span of the expansion site of the macro this parser is for site_span: Span, /// The ident of the macro we're parsing macro_ident: Ident, arm_span: Span, } crate fn annotate_err_with_kind( err: &mut DiagnosticBuilder<'_>, kind: AstFragmentKind, span: Span, ) { match kind { AstFragmentKind::Ty => { err.span_label(span, "this macro call doesn't expand to a type"); } AstFragmentKind::Pat => { err.span_label(span, "this macro call doesn't expand to a pattern"); } _ => {} }; } /// Instead of e.g. `vec![a, b, c]` in a pattern context, suggest `[a, b, c]`. fn suggest_slice_pat(e: &mut DiagnosticBuilder<'_>, site_span: Span, parser: &Parser<'_>) { let mut suggestion = None; if let Ok(code) = parser.sess.source_map().span_to_snippet(site_span) { if let Some(bang) = code.find('!') { suggestion = Some(code[bang + 1..].to_string()); } } if let Some(suggestion) = suggestion { e.span_suggestion( site_span, "use a slice pattern here instead", suggestion, Applicability::MachineApplicable, ); } else { e.span_label(site_span, "use a slice pattern here instead"); } e.help( "for more information, see https://doc.rust-lang.org/edition-guide/\ rust-2018/slice-patterns.html", ); } fn emit_frag_parse_err( mut e: DiagnosticBuilder<'_>, parser: &Parser<'_>, orig_parser: &mut Parser<'_>, site_span: Span, macro_ident: Ident, arm_span: Span, kind: AstFragmentKind, ) { if parser.token == token::Eof && e.message().ends_with(", found `<eof>`") { if !e.span.is_dummy() { // early end of macro arm (#52866) e.replace_span_with(parser.sess.source_map().next_point(parser.token.span)); } let msg = &e.message[0]; e.message[0] = ( format!( "macro expansion ends with an incomplete expression: {}", msg.0.replace(", found `<eof>`", ""), ), msg.1, ); } if e.span.is_dummy() { // Get around lack of span in error (#30128) e.replace_span_with(site_span); if !parser.sess.source_map().is_imported(arm_span) { e.span_label(arm_span, "in this macro arm"); } } else if parser.sess.source_map().is_imported(parser.token.span) { e.span_label(site_span, "in this macro invocation"); } match kind { AstFragmentKind::Pat if macro_ident.name == sym::vec => { suggest_slice_pat(&mut e, site_span, parser); } // Try a statement if an expression is wanted but failed and suggest adding `;` to call. AstFragmentKind::Expr => match parse_ast_fragment(orig_parser, AstFragmentKind::Stmts) { Err(mut err) => err.cancel(), Ok(_) => { e.note( "the macro call doesn't expand to an expression, but it can expand to a statement", ); e.span_suggestion_verbose( site_span.shrink_to_hi(), "add `;` to interpret the expansion as a statement", ";".to_string(), Applicability::MaybeIncorrect, ); } }, _ => annotate_err_with_kind(&mut e, kind, site_span), }; e.emit(); } impl<'a> ParserAnyMacro<'a> { crate fn make(mut self: Box<ParserAnyMacro<'a>>, kind: AstFragmentKind) -> AstFragment { let ParserAnyMacro { site_span, macro_ident, ref mut parser, arm_span } = *self; let snapshot = &mut parser.clone(); let fragment = match parse_ast_fragment(parser, kind) { Ok(f) => f, Err(err) => { emit_frag_parse_err(err, parser, snapshot, site_span, macro_ident, arm_span, kind); return kind.dummy(site_span); } }; // We allow semicolons at the end of expressions -- e.g., the semicolon in // `macro_rules! m { () => { panic!(); } }` isn't parsed by `.parse_expr()`, // but `m!()` is allowed in expression positions (cf. issue #34706). if kind == AstFragmentKind::Expr && parser.token == token::Semi { parser.bump(); } // Make sure we don't have any tokens left to parse so we don't silently drop anything. let path = ast::Path::from_ident(macro_ident.with_span_pos(site_span)); ensure_complete_parse(parser, &path, kind.name(), site_span); fragment } } struct MacroRulesMacroExpander { name: Ident, span: Span, transparency: Transparency, lhses: Vec<mbe::TokenTree>, rhses: Vec<mbe::TokenTree>, valid: bool, } impl TTMacroExpander for MacroRulesMacroExpander { fn expand<'cx>( &self, cx: &'cx mut ExtCtxt<'_>, sp: Span, input: TokenStream, ) -> Box<dyn MacResult + 'cx> { if !self.valid { return DummyResult::any(sp); } generic_extension( cx, sp, self.span, self.name, self.transparency, input, &self.lhses, &self.rhses, ) } } fn macro_rules_dummy_expander<'cx>( _: &'cx mut ExtCtxt<'_>, span: Span, _: TokenStream, ) -> Box<dyn MacResult + 'cx> { DummyResult::any(span) } fn trace_macros_note(cx_expansions: &mut FxHashMap<Span, Vec<String>>, sp: Span, message: String) { let sp = sp.macro_backtrace().last().map(|trace| trace.call_site).unwrap_or(sp); cx_expansions.entry(sp).or_default().push(message); } /// Given `lhses` and `rhses`, this is the new macro we create fn generic_extension<'cx>( cx: &'cx mut ExtCtxt<'_>, sp: Span, def_span: Span, name: Ident, transparency: Transparency, arg: TokenStream, lhses: &[mbe::TokenTree], rhses: &[mbe::TokenTree], ) -> Box<dyn MacResult + 'cx> { let sess = &cx.sess.parse_sess; if cx.trace_macros() { let msg = format!("expanding `{}! {{ {} }}`", name, pprust::tts_to_string(&arg)); trace_macros_note(&mut cx.expansions, sp, msg); } // Which arm's failure should we report? (the one furthest along) let mut best_failure: Option<(Token, &str)> = None; // We create a base parser that can be used for the "black box" parts. // Every iteration needs a fresh copy of that parser. However, the parser // is not mutated on many of the iterations, particularly when dealing with // macros like this: // // macro_rules! foo { // ("a") => (A); // ("b") => (B); // ("c") => (C); // // ... etc. (maybe hundreds more) // } // // as seen in the `html5ever` benchmark. We use a `Cow` so that the base // parser is only cloned when necessary (upon mutation). Furthermore, we // reinitialize the `Cow` with the base parser at the start of every // iteration, so that any mutated parsers are not reused. This is all quite // hacky, but speeds up the `html5ever` benchmark significantly. (Issue // 68836 suggests a more comprehensive but more complex change to deal with // this situation.) let parser = parser_from_cx(sess, arg.clone()); for (i, lhs) in lhses.iter().enumerate() { // try each arm's matchers let lhs_tt = match *lhs { mbe::TokenTree::Delimited(_, ref delim) => &delim.tts[..], _ => cx.span_bug(sp, "malformed macro lhs"), }; // Take a snapshot of the state of pre-expansion gating at this point. // This is used so that if a matcher is not `Success(..)`ful, // then the spans which became gated when parsing the unsuccessful matcher // are not recorded. On the first `Success(..)`ful matcher, the spans are merged. let mut gated_spans_snapshot = mem::take(&mut *sess.gated_spans.spans.borrow_mut()); match parse_tt(&mut Cow::Borrowed(&parser), lhs_tt) { Success(named_matches) => { // The matcher was `Success(..)`ful. // Merge the gated spans from parsing the matcher with the pre-existing ones. sess.gated_spans.merge(gated_spans_snapshot); let rhs = match rhses[i] { // ignore delimiters mbe::TokenTree::Delimited(_, ref delimed) => delimed.tts.clone(), _ => cx.span_bug(sp, "malformed macro rhs"), }; let arm_span = rhses[i].span(); let rhs_spans = rhs.iter().map(|t| t.span()).collect::<Vec<_>>(); // rhs has holes ( `$id` and `$(...)` that need filled) let mut tts = match transcribe(cx, &named_matches, rhs, transparency) { Ok(tts) => tts, Err(mut err) => { err.emit(); return DummyResult::any(arm_span); } }; // Replace all the tokens for the corresponding positions in the macro, to maintain // proper positions in error reporting, while maintaining the macro_backtrace. if rhs_spans.len() == tts.len() { tts = tts.map_enumerated(|i, tt| { let mut tt = tt.clone(); let mut sp = rhs_spans[i]; sp = sp.with_ctxt(tt.span().ctxt()); tt.set_span(sp); tt }); } if cx.trace_macros() { let msg = format!("to `{}`", pprust::tts_to_string(&tts)); trace_macros_note(&mut cx.expansions, sp, msg); } let mut p = Parser::new(sess, tts, false, None); p.last_type_ascription = cx.current_expansion.prior_type_ascription; // Let the context choose how to interpret the result. // Weird, but useful for X-macros. return Box::new(ParserAnyMacro { parser: p, // Pass along the original expansion site and the name of the macro // so we can print a useful error message if the parse of the expanded // macro leaves unparsed tokens. site_span: sp, macro_ident: name, arm_span, }); } Failure(token, msg) => match best_failure { Some((ref best_token, _)) if best_token.span.lo() >= token.span.lo() => {} _ => best_failure = Some((token, msg)), }, Error(err_sp, ref msg) => { let span = err_sp.substitute_dummy(sp); cx.struct_span_err(span, &msg).emit(); return DummyResult::any(span); } ErrorReported => return DummyResult::any(sp), } // The matcher was not `Success(..)`ful. // Restore to the state before snapshotting and maybe try again. mem::swap(&mut gated_spans_snapshot, &mut sess.gated_spans.spans.borrow_mut()); } drop(parser); let (token, label) = best_failure.expect("ran no matchers"); let span = token.span.substitute_dummy(sp); let mut err = cx.struct_span_err(span, &parse_failure_msg(&token)); err.span_label(span, label); if !def_span.is_dummy() && !cx.source_map().is_imported(def_span) { err.span_label(cx.source_map().guess_head_span(def_span), "when calling this macro"); } // Check whether there's a missing comma in this macro call, like `println!("{}" a);` if let Some((arg, comma_span)) = arg.add_comma() { for lhs in lhses { // try each arm's matchers let lhs_tt = match *lhs { mbe::TokenTree::Delimited(_, ref delim) => &delim.tts[..], _ => continue, }; if let Success(_) = parse_tt(&mut Cow::Borrowed(&parser_from_cx(sess, arg.clone())), lhs_tt) { if comma_span.is_dummy() { err.note("you might be missing a comma"); } else { err.span_suggestion_short( comma_span, "missing comma here", ", ".to_string(), Applicability::MachineApplicable, ); } } } } err.emit(); cx.trace_macros_diag(); DummyResult::any(sp) } // Note that macro-by-example's input is also matched against a token tree: // $( $lhs:tt => $rhs:tt );+ // // Holy self-referential! /// Converts a macro item into a syntax extension. pub fn compile_declarative_macro( sess: &Session, features: &Features, def: &ast::Item, edition: Edition, ) -> SyntaxExtension { debug!("compile_declarative_macro: {:?}", def); let mk_syn_ext = |expander| { SyntaxExtension::new( sess, SyntaxExtensionKind::LegacyBang(expander), def.span, Vec::new(), edition, def.ident.name, &def.attrs, ) }; let diag = &sess.parse_sess.span_diagnostic; let lhs_nm = Ident::new(sym::lhs, def.span); let rhs_nm = Ident::new(sym::rhs, def.span); let tt_spec = NonterminalKind::TT; // Parse the macro_rules! invocation let (macro_rules, body) = match &def.kind { ast::ItemKind::MacroDef(def) => (def.macro_rules, def.body.inner_tokens()), _ => unreachable!(), }; // The pattern that macro_rules matches. // The grammar for macro_rules! is: // $( $lhs:tt => $rhs:tt );+ // ...quasiquoting this would be nice. // These spans won't matter, anyways let argument_gram = vec![ mbe::TokenTree::Sequence( DelimSpan::dummy(), Lrc::new(mbe::SequenceRepetition { tts: vec![ mbe::TokenTree::MetaVarDecl(def.span, lhs_nm, tt_spec), mbe::TokenTree::token(token::FatArrow, def.span), mbe::TokenTree::MetaVarDecl(def.span, rhs_nm, tt_spec), ], separator: Some(Token::new( if macro_rules { token::Semi } else { token::Comma }, def.span, )), kleene: mbe::KleeneToken::new(mbe::KleeneOp::OneOrMore, def.span), num_captures: 2, }), ), // to phase into semicolon-termination instead of semicolon-separation mbe::TokenTree::Sequence( DelimSpan::dummy(), Lrc::new(mbe::SequenceRepetition { tts: vec![mbe::TokenTree::token(
)], separator: None, kleene: mbe::KleeneToken::new(mbe::KleeneOp::ZeroOrMore, def.span), num_captures: 0, }), ), ]; let parser = Parser::new(&sess.parse_sess, body, true, rustc_parse::MACRO_ARGUMENTS); let argument_map = match parse_tt(&mut Cow::Borrowed(&parser), &argument_gram) { Success(m) => m, Failure(token, msg) => { let s = parse_failure_msg(&token); let sp = token.span.substitute_dummy(def.span); sess.parse_sess.span_diagnostic.struct_span_err(sp, &s).span_label(sp, msg).emit(); return mk_syn_ext(Box::new(macro_rules_dummy_expander)); } Error(sp, msg) => { sess.parse_sess .span_diagnostic .struct_span_err(sp.substitute_dummy(def.span), &msg) .emit(); return mk_syn_ext(Box::new(macro_rules_dummy_expander)); } ErrorReported => { return mk_syn_ext(Box::new(macro_rules_dummy_expander)); } }; let mut valid = true; // Extract the arguments: let lhses = match argument_map[&MacroRulesNormalizedIdent::new(lhs_nm)] { MatchedSeq(ref s) => s .iter() .map(|m| { if let MatchedNonterminal(ref nt) = *m { if let NtTT(ref tt) = **nt { let tt = mbe::quoted::parse(tt.clone().into(), true, &sess.parse_sess, def.id) .pop() .unwrap(); valid &= check_lhs_nt_follows(&sess.parse_sess, features, &def.attrs, &tt); return tt; } } sess.parse_sess.span_diagnostic.span_bug(def.span, "wrong-structured lhs") }) .collect::<Vec<mbe::TokenTree>>(), _ => sess.parse_sess.span_diagnostic.span_bug(def.span, "wrong-structured lhs"), }; let rhses = match argument_map[&MacroRulesNormalizedIdent::new(rhs_nm)] { MatchedSeq(ref s) => s .iter() .map(|m| { if let MatchedNonterminal(ref nt) = *m { if let NtTT(ref tt) = **nt { return mbe::quoted::parse( tt.clone().into(), false, &sess.parse_sess, def.id, ) .pop() .unwrap(); } } sess.parse_sess.span_diagnostic.span_bug(def.span, "wrong-structured lhs") }) .collect::<Vec<mbe::TokenTree>>(), _ => sess.parse_sess.span_diagnostic.span_bug(def.span, "wrong-structured rhs"), }; for rhs in &rhses { valid &= check_rhs(&sess.parse_sess, rhs); } // don't abort iteration early, so that errors for multiple lhses can be reported for lhs in &lhses { valid &= check_lhs_no_empty_seq(&sess.parse_sess, slice::from_ref(lhs)); } valid &= macro_check::check_meta_variables(&sess.parse_sess, def.id, def.span, &lhses, &rhses); let (transparency, transparency_error) = attr::find_transparency(sess, &def.attrs, macro_rules); match transparency_error { Some(TransparencyError::UnknownTransparency(value, span)) => { diag.span_err(span, &format!("unknown macro transparency: `{}`", value)) } Some(TransparencyError::MultipleTransparencyAttrs(old_span, new_span)) => { diag.span_err(vec![old_span, new_span], "multiple macro transparency attributes") } None => {} } mk_syn_ext(Box::new(MacroRulesMacroExpander { name: def.ident, span: def.span, transparency, lhses, rhses, valid, })) } fn check_lhs_nt_follows( sess: &ParseSess, features: &Features, attrs: &[ast::Attribute], lhs: &mbe::TokenTree, ) -> bool { // lhs is going to be like TokenTree::Delimited(...), where the // entire lhs is those tts. Or, it can be a "bare sequence", not wrapped in parens. if let mbe::TokenTree::Delimited(_, ref tts) = *lhs { check_matcher(sess, features, attrs, &tts.tts) } else { let msg = "invalid macro matcher; matchers must be contained in balanced delimiters"; sess.span_diagnostic.span_err(lhs.span(), msg); false } // we don't abort on errors on rejection, the driver will do that for us // after parsing/expansion. we can report every error in every macro this way. } /// Checks that the lhs contains no repetition which could match an empty token /// tree, because then the matcher would hang indefinitely. fn check_lhs_no_empty_seq(sess: &ParseSess, tts: &[mbe::TokenTree]) -> bool { use mbe::TokenTree; for tt in tts { match *tt { TokenTree::Token(..) | TokenTree::MetaVar(..) | TokenTree::MetaVarDecl(..) => (), TokenTree::Delimited(_, ref del) => { if !check_lhs_no_empty_seq(sess, &del.tts) { return false; } } TokenTree::Sequence(span, ref seq) => { if seq.separator.is_none() && seq.tts.iter().all(|seq_tt| match *seq_tt { TokenTree::MetaVarDecl(_, _, NonterminalKind::Vis) => true, TokenTree::Sequence(_, ref sub_seq) => { sub_seq.kleene.op == mbe::KleeneOp::ZeroOrMore || sub_seq.kleene.op == mbe::KleeneOp::ZeroOrOne } _ => false, }) { let sp = span.entire(); sess.span_diagnostic.span_err(sp, "repetition matches empty token tree"); return false; } if !check_lhs_no_empty_seq(sess, &seq.tts) { return false; } } } } true } fn check_rhs(sess: &ParseSess, rhs: &mbe::TokenTree) -> bool { match *rhs { mbe::TokenTree::Delimited(..) => return true, _ => sess.span_diagnostic.span_err(rhs.span(), "macro rhs must be delimited"), } false } fn check_matcher( sess: &ParseSess, features: &Features, attrs: &[ast::Attribute], matcher: &[mbe::TokenTree], ) -> bool { let first_sets = FirstSets::new(matcher); let empty_suffix = TokenSet::empty(); let err = sess.span_diagnostic.err_count(); check_matcher_core(sess, features, attrs, &first_sets, matcher, &empty_suffix); err == sess.span_diagnostic.err_count() } // `The FirstSets` for a matcher is a mapping from subsequences in the // matcher to the FIRST set for that subsequence. // // This mapping is partially precomputed via a backwards scan over the // token trees of the matcher, which provides a mapping from each // repetition sequence to its *first* set. // // (Hypothetically, sequences should be uniquely identifiable via their // spans, though perhaps that is false, e.g., for macro-generated macros // that do not try to inject artificial span information. My plan is // to try to catch such cases ahead of time and not include them in // the precomputed mapping.) struct FirstSets { // this maps each TokenTree::Sequence `$(tt ...) SEP OP` that is uniquely identified by its // span in the original matcher to the First set for the inner sequence `tt ...`. // // If two sequences have the same span in a matcher, then map that // span to None (invalidating the mapping here and forcing the code to // use a slow path). first: FxHashMap<Span, Option<TokenSet>>, } impl FirstSets { fn new(tts: &[mbe::TokenTree]) -> FirstSets { use mbe::TokenTree; let mut sets = FirstSets { first: FxHashMap::default() }; build_recur(&mut sets, tts); return sets; // walks backward over `tts`, returning the FIRST for `tts` // and updating `sets` at the same time for all sequence // substructure we find within `tts`. fn build_recur(sets: &mut FirstSets, tts: &[TokenTree]) -> TokenSet { let mut first = TokenSet::empty(); for tt in tts.iter().rev() { match *tt { TokenTree::Token(..) | TokenTree::MetaVar(..) | TokenTree::MetaVarDecl(..) => { first.replace_with(tt.clone()); } TokenTree::Delimited(span, ref delimited) => { build_recur(sets, &delimited.tts[..]); first.replace_with(delimited.open_tt(span)); } TokenTree::Sequence(sp, ref seq_rep) => { let subfirst = build_recur(sets, &seq_rep.tts[..]); match sets.first.entry(sp.entire()) { Entry::Vacant(vac) => { vac.insert(Some(subfirst.clone())); } Entry::Occupied(mut occ) => { // if there is already an entry, then a span must have collided. // This should not happen with typical macro_rules macros, // but syntax extensions need not maintain distinct spans, // so distinct syntax trees can be assigned the same span. // In such a case, the map cannot be trusted; so mark this // entry as unusable. occ.insert(None); } } // If the sequence contents can be empty, then the first // token could be the separator token itself. if let (Some(sep), true) = (&seq_rep.separator, subfirst.maybe_empty) { first.add_one_maybe(TokenTree::Token(sep.clone())); } // Reverse scan: Sequence comes before `first`. if subfirst.maybe_empty || seq_rep.kleene.op == mbe::KleeneOp::ZeroOrMore || seq_rep.kleene.op == mbe::KleeneOp::ZeroOrOne { // If sequence is potentially empty, then // union them (preserving first emptiness). first.add_all(&TokenSet { maybe_empty: true, ..subfirst }); } else { // Otherwise, sequence guaranteed // non-empty; replace first. first = subfirst; } } } } first } } // walks forward over `tts` until all potential FIRST tokens are // identified. fn first(&self, tts: &[mbe::TokenTree]) -> TokenSet { use mbe::TokenTree; let mut first = TokenSet::empty(); for tt in tts.iter() { assert!(first.maybe_empty); match *tt { TokenTree::Token(..) | TokenTree::MetaVar(..) | TokenTree::MetaVarDecl(..) => { first.add_one(tt.clone()); return first; } TokenTree::Delimited(span, ref delimited) => { first.add_one(delimited.open_tt(span)); return first; } TokenTree::Sequence(sp, ref seq_rep) => { let subfirst_owned; let subfirst = match self.first.get(&sp.entire()) { Some(&Some(ref subfirst)) => subfirst, Some(&None) => { subfirst_owned = self.first(&seq_rep.tts[..]); &subfirst_owned } None => { panic!("We missed a sequence during FirstSets construction"); } }; // If the sequence contents can be empty, then the first // token could be the separator token itself. if let (Some(sep), true) = (&seq_rep.separator, subfirst.maybe_empty) { first.add_one_maybe(TokenTree::Token(sep.clone())); } assert!(first.maybe_empty); first.add_all(subfirst); if subfirst.maybe_empty || seq_rep.kleene.op == mbe::KleeneOp::ZeroOrMore || seq_rep.kleene.op == mbe::KleeneOp::ZeroOrOne { // Continue scanning for more first // tokens, but also make sure we // restore empty-tracking state. first.maybe_empty = true; continue; } else { return first; } } } } // we only exit the loop if `tts` was empty or if every // element of `tts` matches the empty sequence. assert!(first.maybe_empty); first } } // A set of `mbe::TokenTree`s, which may include `TokenTree::Match`s // (for macro-by-example syntactic variables). It also carries the // `maybe_empty` flag; that is true if and only if the matcher can // match an empty token sequence. // // The First set is computed on submatchers like `$($a:expr b),* $(c)* d`, // which has corresponding FIRST = {$a:expr, c, d}. // Likewise, `$($a:expr b),* $(c)+ d` has FIRST = {$a:expr, c}. // // (Notably, we must allow for *-op to occur zero times.) #[derive(Clone, Debug)] struct TokenSet { tokens: Vec<mbe::TokenTree>, maybe_empty: bool, } impl TokenSet { // Returns a set for the empty sequence. fn empty() -> Self { TokenSet { tokens: Vec::new(), maybe_empty: true } } // Returns the set `{ tok }` for the single-token (and thus // non-empty) sequence [tok]. fn singleton(tok: mbe::TokenTree) -> Self { TokenSet { tokens: vec![tok], maybe_empty: false } } // Changes self to be the set `{ tok }`. // Since `tok` is always present, marks self as non-empty. fn replace_with(&mut self, tok: mbe::TokenTree) { self.tokens.clear(); self.tokens.push(tok); self.maybe_empty = false; } // Changes self to be the empty set `{}`; meant for use when // the particular token does not matter, but we want to // record that it occurs. fn replace_with_irrelevant(&mut self) { self.tokens.clear(); self.maybe_empty = false; } // Adds `tok` to the set for `self`, marking sequence as non-empy. fn add_one(&mut self, tok: mbe::TokenTree) { if !self.tokens.contains(&tok) { self.tokens.push(tok); } self.maybe_empty = false; } // Adds `tok` to the set for `self`. (Leaves `maybe_empty` flag alone.) fn add_one_maybe(&mut self, tok: mbe::TokenTree) { if !self.tokens.contains(&tok) { self.tokens.push(tok); } } // Adds all elements of `other` to this. // // (Since this is a set, we filter out duplicates.) // // If `other` is potentially empty, then preserves the previous // setting of the empty flag of `self`. If `other` is guaranteed // non-empty, then `self` is marked non-empty. fn add_all(&mut self, other: &Self) { for tok in &other.tokens { if !self.tokens.contains(tok) { self.tokens.push(tok.clone()); } } if !other.maybe_empty { self.maybe_empty = false; } } } // Checks that `matcher` is internally consistent and that it // can legally be followed by a token `N`, for all `N` in `follow`. // (If `follow` is empty, then it imposes no constraint on // the `matcher`.) // // Returns the set of NT tokens that could possibly come last in // `matcher`. (If `matcher` matches the empty sequence, then // `maybe_empty` will be set to true.) // // Requires that `first_sets` is pre-computed for `matcher`; // see `FirstSets::new`. fn check_matcher_core( sess: &ParseSess, features: &Features, attrs: &[ast::Attribute], first_sets: &FirstSets, matcher: &[mbe::TokenTree], follow: &TokenSet, ) -> TokenSet { use mbe::TokenTree; let mut last = TokenSet::empty(); // 2. For each token and suffix [T, SUFFIX] in M: // ensure that T can be followed by SUFFIX, and if SUFFIX may be empty, // then ensure T can also be followed by any element of FOLLOW. 'each_token: for i in 0..matcher.len() { let token = &matcher[i]; let suffix = &matcher[i + 1..]; let build_suffix_first = || { let mut s = first_sets.first(suffix); if s.maybe_empty { s.add_all(follow); } s }; // (we build `suffix_first` on demand below; you can tell // which cases are supposed to fall through by looking for the // initialization of this variable.) let suffix_first; // First, update `last` so that it corresponds to the set // of NT tokens that might end the sequence `... token`. match *token { TokenTree::Token(..) | TokenTree::MetaVar(..) | TokenTree::MetaVarDecl(..) => { if token_can_be_followed_by_any(token) { // don't need to track tokens that work with any, last.replace_with_irrelevant(); // ... and don't need to check tokens that can be // followed by anything against SUFFIX. continue 'each_token; } else { last.replace_with(token.clone()); suffix_first = build_suffix_first(); } } TokenTree::Delimited(span, ref d) => { let my_suffix = TokenSet::singleton(d.close_tt(span)); check_matcher_core(sess, features, attrs, first_sets, &d.tts, &my_suffix); // don't track non NT tokens last.replace_with_irrelevant(); // also, we don't need to check delimited sequences // against SUFFIX continue 'each_token; } TokenTree::Sequence(_, ref seq_rep) => { suffix_first = build_suffix_first(); // The trick here: when we check the interior, we want // to include the separator (if any) as a potential // (but not guaranteed) element of FOLLOW. So in that // case, we make a temp copy of suffix and stuff // delimiter in there. // // FIXME: Should I first scan suffix_first to see if // delimiter is already in it before I go through the // work of cloning it? But then again, this way I may // get a "tighter" span? let mut new; let my_suffix = if let Some(sep) = &seq_rep.separator { new = suffix_first.clone(); new.add_one_maybe(TokenTree::Token(sep.clone())); &new } else { &suffix_first }; // At this point, `suffix_first` is built, and // `my_suffix` is some TokenSet that we can use // for checking the interior of `seq_rep`. let next = check_matcher_core(sess, features, attrs, first_sets, &seq_rep.tts, my_suffix); if next.maybe_empty { last.add_all(&next); } else { last = next; } // the recursive call to check_matcher_core already ran the 'each_last // check below, so we can just keep going forward here. continue 'each_token; } } // (`suffix_first` guaranteed initialized once reaching here.) // Now `last` holds the complete set of NT tokens that could // end the sequence before SUFFIX. Check that every one works with `suffix`. for token in &last.tokens { if let TokenTree::MetaVarDecl(_, name, kind) = *token { for next_token in &suffix_first.tokens { match is_in_follow(next_token, kind) { IsInFollow::Yes => {} IsInFollow::No(possible) => { let may_be = if last.tokens.len() == 1 && suffix_first.tokens.len() == 1 { "is" } else { "may be" }; let sp = next_token.span(); let mut err = sess.span_diagnostic.struct_span_err( sp, &format!( "`${name}:{frag}` {may_be} followed by `{next}`, which \ is not allowed for `{frag}` fragments", name = name, frag = kind, next = quoted_tt_to_string(next_token), may_be = may_be ), ); err.span_label(sp, format!("not allowed after `{}` fragments", kind)); let msg = "allowed there are: "; match possible { &[] => {} &[t] => { err.note(&format!( "only {} is allowed after `{}` fragments", t, kind, )); } ts => { err.note(&format!( "{}{} or {}", msg, ts[..ts.len() - 1] .iter() .copied() .collect::<Vec<_>>() .join(", "), ts[ts.len() - 1], )); } } err.emit(); } } } } } } last } fn token_can_be_followed_by_any(tok: &mbe::TokenTree) -> bool { if let mbe::TokenTree::MetaVarDecl(_, _, kind) = *tok { frag_can_be_followed_by_any(kind) } else { // (Non NT's can always be followed by anything in matchers.) true } } /// Returns `true` if a fragment of type `frag` can be followed by any sort of /// token. We use this (among other things) as a useful approximation /// for when `frag` can be followed by a repetition like `$(...)*` or /// `$(...)+`. In general, these can be a bit tricky to reason about, /// so we adopt a conservative position that says that any fragment /// specifier which consumes at most one token tree can be followed by /// a fragment specifier (indeed, these fragments can be followed by /// ANYTHING without fear of future compatibility hazards). fn frag_can_be_followed_by_any(kind: NonterminalKind) -> bool { match kind { NonterminalKind::Item // always terminated by `}` or `;` | NonterminalKind::Block // exactly one token tree | NonterminalKind::Ident // exactly one token tree | NonterminalKind::Literal // exactly one token tree | NonterminalKind::Meta // exactly one token tree | NonterminalKind::Lifetime // exactly one token tree | NonterminalKind::TT => true, // exactly one token tree _ => false, } } enum IsInFollow { Yes, No(&'static [&'static str]), } /// Returns `true` if `frag` can legally be followed by the token `tok`. For /// fragments that can consume an unbounded number of tokens, `tok` /// must be within a well-defined follow set. This is intended to /// guarantee future compatibility: for example, without this rule, if /// we expanded `expr` to include a new binary operator, we might /// break macros that were relying on that binary operator as a /// separator. // when changing this do not forget to update doc/book/macros.md! fn is_in_follow(tok: &mbe::TokenTree, kind: NonterminalKind) -> IsInFollow { use mbe::TokenTree; if let TokenTree::Token(Token { kind: token::CloseDelim(_), .. }) = *tok { // closing a token tree can never be matched by any fragment; // iow, we always require that `(` and `)` match, etc. IsInFollow::Yes } else { match kind { NonterminalKind::Item => { // since items *must* be followed by either a `;` or a `}`, we can // accept anything after them IsInFollow::Yes } NonterminalKind::Block => { // anything can follow block, the braces provide an easy boundary to // maintain IsInFollow::Yes } NonterminalKind::Stmt | NonterminalKind::Expr => { const TOKENS: &[&str] = &["`=>`", "`,`", "`;`"]; match tok { TokenTree::Token(token) => match token.kind { FatArrow | Comma | Semi => IsInFollow::Yes, _ => IsInFollow::No(TOKENS), }, _ => IsInFollow::No(TOKENS), } } NonterminalKind::Pat => { const TOKENS: &[&str] = &["`=>`", "`,`", "`=`", "`|`", "`if`", "`in`"]; match tok { TokenTree::Token(token) => match token.kind { FatArrow | Comma | Eq | BinOp(token::Or) => IsInFollow::Yes, Ident(name, false) if name == kw::If || name == kw::In => IsInFollow::Yes, _ => IsInFollow::No(TOKENS), }, _ => IsInFollow::No(TOKENS), } } NonterminalKind::Path | NonterminalKind::Ty => { const TOKENS: &[&str] = &[ "`{`", "`[`", "`=>`", "`,`", "`>`", "`=`", "`:`", "`;`", "`|`", "`as`", "`where`", ]; match tok { TokenTree::Token(token) => match token.kind { OpenDelim(token::DelimToken::Brace) | OpenDelim(token::DelimToken::Bracket) | Comma | FatArrow | Colon | Eq | Gt | BinOp(token::Shr) | Semi | BinOp(token::Or) => IsInFollow::Yes, Ident(name, false) if name == kw::As || name == kw::Where => { IsInFollow::Yes } _ => IsInFollow::No(TOKENS), }, TokenTree::MetaVarDecl(_, _, NonterminalKind::Block) => IsInFollow::Yes, _ => IsInFollow::No(TOKENS), } } NonterminalKind::Ident | NonterminalKind::Lifetime => { // being a single token, idents and lifetimes are harmless IsInFollow::Yes } NonterminalKind::Literal => { // literals may be of a single token, or two tokens (negative numbers) IsInFollow::Yes } NonterminalKind::Meta | NonterminalKind::TT => { // being either a single token or a delimited sequence, tt is // harmless IsInFollow::Yes } NonterminalKind::Vis => { // Explicitly disallow `priv`, on the off chance it comes back. const TOKENS: &[&str] = &["`,`", "an ident", "a type"]; match tok { TokenTree::Token(token) => match token.kind { Comma => IsInFollow::Yes, Ident(name, is_raw) if is_raw || name != kw::Priv => IsInFollow::Yes, _ => { if token.can_begin_type() { IsInFollow::Yes } else { IsInFollow::No(TOKENS) } } }, TokenTree::MetaVarDecl( _, _, NonterminalKind::Ident | NonterminalKind::Ty | NonterminalKind::Path, ) => IsInFollow::Yes, _ => IsInFollow::No(TOKENS), } } } } } fn quoted_tt_to_string(tt: &mbe::TokenTree) -> String { match *tt { mbe::TokenTree::Token(ref token) => pprust::token_to_string(&token), mbe::TokenTree::MetaVar(_, name) => format!("${}", name), mbe::TokenTree::MetaVarDecl(_, name, kind) => format!("${}:{}", name, kind), _ => panic!( "unexpected mbe::TokenTree::{{Sequence or Delimited}} \ in follow set checker" ), } } fn parser_from_cx(sess: &ParseSess, tts: TokenStream) -> Parser<'_> { Parser::new(sess, tts, true, rustc_parse::MACRO_ARGUMENTS) } /// Generates an appropriate parsing failure message. For EOF, this is "unexpected end...". For /// other tokens, this is "unexpected token...". fn parse_failure_msg(tok: &Token) -> String { match tok.kind { token::Eof => "unexpected end of macro invocation".to_string(), _ => format!("no rules expected the token `{}`", pprust::token_to_string(tok),), } }
if macro_rules { token::Semi } else { token::Comma }, def.span,
api_op_GetSigningCertificate.go
// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. package cognitoidentityprovider import ( "context" "github.com/aws/aws-sdk-go-v2/aws" "github.com/aws/aws-sdk-go-v2/internal/awsutil" ) // Request to get a signing certificate from Cognito. // Please also see https://docs.aws.amazon.com/goto/WebAPI/cognito-idp-2016-04-18/GetSigningCertificateRequest type GetSigningCertificateInput struct { _ struct{} `type:"structure"` // The user pool ID. // // UserPoolId is a required field UserPoolId *string `min:"1" type:"string" required:"true"` } // String returns the string representation func (s GetSigningCertificateInput) String() string { return awsutil.Prettify(s) } // Validate inspects the fields of the type to determine if they are valid. func (s *GetSigningCertificateInput) Validate() error { invalidParams := aws.ErrInvalidParams{Context: "GetSigningCertificateInput"} if s.UserPoolId == nil { invalidParams.Add(aws.NewErrParamRequired("UserPoolId")) } if s.UserPoolId != nil && len(*s.UserPoolId) < 1 { invalidParams.Add(aws.NewErrParamMinLen("UserPoolId", 1)) } if invalidParams.Len() > 0 { return invalidParams } return nil } // Response from Cognito for a signing certificate request. // Please also see https://docs.aws.amazon.com/goto/WebAPI/cognito-idp-2016-04-18/GetSigningCertificateResponse type GetSigningCertificateOutput struct { _ struct{} `type:"structure"` // The signing certificate. Certificate *string `type:"string"` } // String returns the string representation func (s GetSigningCertificateOutput) String() string { return awsutil.Prettify(s) } const opGetSigningCertificate = "GetSigningCertificate" // GetSigningCertificateRequest returns a request value for making API operation for // Amazon Cognito Identity Provider. // // This method takes a user pool ID, and returns the signing certificate. // // // Example sending a request using GetSigningCertificateRequest. // req := client.GetSigningCertificateRequest(params) // resp, err := req.Send(context.TODO()) // if err == nil { // fmt.Println(resp) // } //
op := &aws.Operation{ Name: opGetSigningCertificate, HTTPMethod: "POST", HTTPPath: "/", } if input == nil { input = &GetSigningCertificateInput{} } req := c.newRequest(op, input, &GetSigningCertificateOutput{}) return GetSigningCertificateRequest{Request: req, Input: input, Copy: c.GetSigningCertificateRequest} } // GetSigningCertificateRequest is the request type for the // GetSigningCertificate API operation. type GetSigningCertificateRequest struct { *aws.Request Input *GetSigningCertificateInput Copy func(*GetSigningCertificateInput) GetSigningCertificateRequest } // Send marshals and sends the GetSigningCertificate API request. func (r GetSigningCertificateRequest) Send(ctx context.Context) (*GetSigningCertificateResponse, error) { r.Request.SetContext(ctx) err := r.Request.Send() if err != nil { return nil, err } resp := &GetSigningCertificateResponse{ GetSigningCertificateOutput: r.Request.Data.(*GetSigningCertificateOutput), response: &aws.Response{Request: r.Request}, } return resp, nil } // GetSigningCertificateResponse is the response type for the // GetSigningCertificate API operation. type GetSigningCertificateResponse struct { *GetSigningCertificateOutput response *aws.Response } // SDKResponseMetdata returns the response metadata for the // GetSigningCertificate request. func (r *GetSigningCertificateResponse) SDKResponseMetdata() *aws.Response { return r.response }
// Please also see https://docs.aws.amazon.com/goto/WebAPI/cognito-idp-2016-04-18/GetSigningCertificate func (c *Client) GetSigningCertificateRequest(input *GetSigningCertificateInput) GetSigningCertificateRequest {
mulps.rs
use ::{BroadcastMode, Instruction, MaskReg, MergeMode, Mnemonic, OperandSize, Reg, RoundingMode}; use ::RegType::*; use ::instruction_def::*; use ::Operand::*; use ::Reg::*; use ::RegScale::*; fn mulps_1() { run_test(&Instruction { mnemonic: Mnemonic::MULPS, operand1: Some(Direct(XMM2)), operand2: Some(Direct(XMM1)), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[15, 89, 209], OperandSize::Dword) } fn mulps_2() {
run_test(&Instruction { mnemonic: Mnemonic::MULPS, operand1: Some(Direct(XMM4)), operand2: Some(Direct(XMM3)), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[15, 89, 227], OperandSize::Qword) } fn mulps_4() { run_test(&Instruction { mnemonic: Mnemonic::MULPS, operand1: Some(Direct(XMM7)), operand2: Some(IndirectScaledDisplaced(RSI, Eight, 2144972213, Some(OperandSize::Xmmword), None)), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[15, 89, 60, 245, 181, 173, 217, 127], OperandSize::Qword) }
run_test(&Instruction { mnemonic: Mnemonic::MULPS, operand1: Some(Direct(XMM0)), operand2: Some(IndirectScaledDisplaced(EDI, Eight, 991414085, Some(OperandSize::Xmmword), None)), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[15, 89, 4, 253, 69, 199, 23, 59], OperandSize::Dword) } fn mulps_3() {
create_em_managed_external_exadata_insight_details.go
// Copyright (c) 2016, 2018, 2022, Oracle and/or its affiliates. All rights reserved. // This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE-2.0. You may choose either license. // Code generated. DO NOT EDIT. // Operations Insights API // // Use the Operations Insights API to perform data extraction operations to obtain database // resource utilization, performance statistics, and reference information. For more information, // see About Oracle Cloud Infrastructure Operations Insights (https://docs.cloud.oracle.com/en-us/iaas/operations-insights/doc/operations-insights.html). // package opsi import ( "encoding/json" "fmt" "github.com/oracle/oci-go-sdk/v58/common" "strings" ) // CreateEmManagedExternalExadataInsightDetails The information about the Exadata system to be analyzed. If memberEntityDetails is not specified, the the Enterprise Manager entity (e.g. databases and hosts) associated with an Exadata system will be placed in the same compartment as the Exadata system. type CreateEmManagedExternalExadataInsightDetails struct { // Compartment Identifier of Exadata insight CompartmentId *string `mandatory:"true" json:"compartmentId"` // Enterprise Manager Unique Identifier EnterpriseManagerIdentifier *string `mandatory:"true" json:"enterpriseManagerIdentifier"` // OPSI Enterprise Manager Bridge OCID EnterpriseManagerBridgeId *string `mandatory:"true" json:"enterpriseManagerBridgeId"` // Enterprise Manager Entity Unique Identifier EnterpriseManagerEntityIdentifier *string `mandatory:"true" json:"enterpriseManagerEntityIdentifier"` // Simple key-value pair that is applied without any predefined name, type or scope. Exists for cross-compatibility only. // Example: `{"bar-key": "value"}` FreeformTags map[string]string `mandatory:"false" json:"freeformTags"` // Defined tags for this resource. Each key is predefined and scoped to a namespace. // Example: `{"foo-namespace": {"bar-key": "value"}}` DefinedTags map[string]map[string]interface{} `mandatory:"false" json:"definedTags"` MemberEntityDetails []CreateEmManagedExternalExadataMemberEntityDetails `mandatory:"false" json:"memberEntityDetails"` // Set to true to enable automatic enablement and disablement of related targets from Enterprise Manager. New resources (e.g. Database Insights) will be placed in the same compartment as the related Exadata Insight. IsAutoSyncEnabled *bool `mandatory:"false" json:"isAutoSyncEnabled"` } //GetCompartmentId returns CompartmentId func (m CreateEmManagedExternalExadataInsightDetails) GetCompartmentId() *string { return m.CompartmentId } //GetFreeformTags returns FreeformTags func (m CreateEmManagedExternalExadataInsightDetails) GetFreeformTags() map[string]string { return m.FreeformTags } //GetDefinedTags returns DefinedTags func (m CreateEmManagedExternalExadataInsightDetails) GetDefinedTags() map[string]map[string]interface{} { return m.DefinedTags } func (m CreateEmManagedExternalExadataInsightDetails) String() string { return common.PointerString(m) } // ValidateEnumValue returns an error when providing an unsupported enum value // This function is being called during constructing API request process // Not recommended for calling this function directly func (m CreateEmManagedExternalExadataInsightDetails) ValidateEnumValue() (bool, error) { errMessage := []string{} if len(errMessage) > 0
return false, nil } // MarshalJSON marshals to json representation func (m CreateEmManagedExternalExadataInsightDetails) MarshalJSON() (buff []byte, e error) { type MarshalTypeCreateEmManagedExternalExadataInsightDetails CreateEmManagedExternalExadataInsightDetails s := struct { DiscriminatorParam string `json:"entitySource"` MarshalTypeCreateEmManagedExternalExadataInsightDetails }{ "EM_MANAGED_EXTERNAL_EXADATA", (MarshalTypeCreateEmManagedExternalExadataInsightDetails)(m), } return json.Marshal(&s) }
{ return true, fmt.Errorf(strings.Join(errMessage, "\n")) }
scid_utils.rs
// This file is Copyright its original authors, visible in version control // history. // // This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE // or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option. // You may not use this file except in accordance with one or both of these // licenses. /// Maximum block height that can be used in a `short_channel_id`. This /// value is based on the 3-bytes available for block height. pub const MAX_SCID_BLOCK: u64 = 0x00ffffff; /// Maximum transaction index that can be used in a `short_channel_id`. /// This value is based on the 3-bytes available for tx index. pub const MAX_SCID_TX_INDEX: u64 = 0x00ffffff; /// Maximum vout index that can be used in a `short_channel_id`. This /// value is based on the 2-bytes available for the vout index. pub const MAX_SCID_VOUT_INDEX: u64 = 0xffff; /// A `short_channel_id` construction error #[derive(Debug, PartialEq)] pub enum ShortChannelIdError { BlockOverflow, TxIndexOverflow, VoutIndexOverflow, } /// Extracts the block height (most significant 3-bytes) from the `short_channel_id` pub fn block_from_scid(short_channel_id: &u64) -> u32 { return (short_channel_id >> 40) as u32; } /// Constructs a `short_channel_id` using the components pieces. Results in an error /// if the block height, tx index, or vout index overflow the maximum sizes. pub fn scid_from_parts(block: u64, tx_index: u64, vout_index: u64) -> Result<u64, ShortChannelIdError> { if block > MAX_SCID_BLOCK { return Err(ShortChannelIdError::BlockOverflow); } if tx_index > MAX_SCID_TX_INDEX
if vout_index > MAX_SCID_VOUT_INDEX { return Err(ShortChannelIdError::VoutIndexOverflow); } Ok((block << 40) | (tx_index << 16) | vout_index) } #[cfg(test)] mod tests { use super::*; #[test] fn test_block_from_scid() { assert_eq!(block_from_scid(&0x000000_000000_0000), 0); assert_eq!(block_from_scid(&0x000001_000000_0000), 1); assert_eq!(block_from_scid(&0x000001_ffffff_ffff), 1); assert_eq!(block_from_scid(&0x800000_ffffff_ffff), 0x800000); assert_eq!(block_from_scid(&0xffffff_ffffff_ffff), 0xffffff); } #[test] fn test_scid_from_parts() { assert_eq!(scid_from_parts(0x00000000, 0x00000000, 0x0000).unwrap(), 0x000000_000000_0000); assert_eq!(scid_from_parts(0x00000001, 0x00000002, 0x0003).unwrap(), 0x000001_000002_0003); assert_eq!(scid_from_parts(0x00111111, 0x00222222, 0x3333).unwrap(), 0x111111_222222_3333); assert_eq!(scid_from_parts(0x00ffffff, 0x00ffffff, 0xffff).unwrap(), 0xffffff_ffffff_ffff); assert_eq!(scid_from_parts(0x01ffffff, 0x00000000, 0x0000).err().unwrap(), ShortChannelIdError::BlockOverflow); assert_eq!(scid_from_parts(0x00000000, 0x01ffffff, 0x0000).err().unwrap(), ShortChannelIdError::TxIndexOverflow); assert_eq!(scid_from_parts(0x00000000, 0x00000000, 0x010000).err().unwrap(), ShortChannelIdError::VoutIndexOverflow); } }
{ return Err(ShortChannelIdError::TxIndexOverflow); }
clients.go
package gateway import ( "fmt" grpc_prometheus "github.com/grpc-ecosystem/go-grpc-prometheus" "github.com/pkg/errors" log "github.com/sirupsen/logrus" "google.golang.org/grpc" "github.com/chef/automate/api/external/applications" "github.com/chef/automate/api/external/secrets" "github.com/chef/automate/api/interservice/authn" authz "github.com/chef/automate/api/interservice/authz" iam_v2beta "github.com/chef/automate/api/interservice/authz/v2" cfgmgmt "github.com/chef/automate/api/interservice/cfgmgmt/service" deployment "github.com/chef/automate/api/interservice/deployment" chef_ingest "github.com/chef/automate/api/interservice/ingest" license_control "github.com/chef/automate/api/interservice/license_control" "github.com/chef/automate/api/interservice/local_user" teams_v1 "github.com/chef/automate/api/interservice/teams/v1" teams_v2 "github.com/chef/automate/api/interservice/teams/v2" automate_feed "github.com/chef/automate/components/compliance-service/api/automate-feed" jobs "github.com/chef/automate/components/compliance-service/api/jobs" profiles "github.com/chef/automate/components/compliance-service/api/profiles" cc_reporting "github.com/chef/automate/components/compliance-service/api/reporting" cc_stats "github.com/chef/automate/components/compliance-service/api/stats" cc_version "github.com/chef/automate/components/compliance-service/api/version" cc_ingest "github.com/chef/automate/components/compliance-service/ingest/ingest" manager "github.com/chef/automate/components/nodemanager-service/api/manager" nodes "github.com/chef/automate/components/nodemanager-service/api/nodes" notifications "github.com/chef/automate/components/notifications-client/api" "github.com/chef/automate/components/notifications-client/notifier" "github.com/chef/automate/lib/grpc/secureconn" "github.com/chef/automate/lib/tracing" ) var defaultEndpoints = map[string]string{ "authn-service": "0.0.0.0:9091", "authz-service": "0.0.0.0:10130", "config-mgmt-service": "0.0.0.0:10119", "compliance-service": "0.0.0.0:10121", "data-feed-service": "0.0.0.0:14001", "deployment-service": "0.0.0.0:10161", "ingest-service": "0.0.0.0:10122", "license-control-service": "0.0.0.0:10124", "local-user-service": "0.0.0.0:9092", "notifications-service": "0.0.0.0:4001", "teams-service": "0.0.0.0:9093", "secrets-service": "0.0.0.0:10131", "applications-service": "0.0.0.0:10133", "nodemanager-service": "0.0.0.0:10120", } // clientMetrics holds the clients (identified by service) for which we'll // enable gathering metrics through the grpc-middleware for prometheus. This // comes at a cost, so we don't just enable all the clients. // This list should include those clients that are not only serving a specific // server endpoint, but are interesting to inspect for their own sake. var clientMetrics = map[string]bool{ "authn-service": true, // this only exists as a client "authz-service": true, // auth middleware calls are done using this client "ingest-service": true, // the handcrafted legacy ingestion handlers use this to bypass the server } // ClientConfig describes the endpoints we wish to connect to type ClientConfig struct { Endpoints map[string]ConnectionOptions `mapstructure:"endpoints" toml:"endpoints"` Notifier NotifierOptions `mapstructure:"notifier" toml:"notifier"` } // ConnectionOptions describes how we wish to connect to a certain // endpoint. type ConnectionOptions struct { // Target to connect to Target string `mapstructure:"target" toml:"target"` Secure bool `mapstructure:"secure" toml:"secure"` } // ClientsFactory is the interface for grpc client connections type ClientsFactory interface { CfgMgmtClient() (cfgmgmt.CfgMgmtClient, error) IngestStatusClient() (chef_ingest.IngestStatusClient, error) ChefIngesterClient() (chef_ingest.ChefIngesterClient, error) ChefIngesterJobSchedulerClient() (chef_ingest.JobSchedulerClient, error) ComplianceIngesterClient() (cc_ingest.ComplianceIngesterClient, error) NotificationsClient() (notifications.NotificationsClient, error) AuthenticationClient() (authn.AuthenticationClient, error) AuthorizationClient() (authz.AuthorizationClient, error) AuthorizationV2Client() (iam_v2beta.AuthorizationClient, error) PoliciesClient() (iam_v2beta.PoliciesClient, error) ProjectsClient() (iam_v2beta.ProjectsClient, error) TeamsV1Client() (teams_v1.TeamsV1Client, error) TeamsV2Client() (teams_v2.TeamsV2Client, error) TokensMgmtClient() (authn.TokensMgmtClient, error) UsersMgmtClient() (local_user.UsersMgmtClient, error) Notifier() (notifier.Notifier, error) ApplicationsClient() (applications.ApplicationsServiceClient, error) SecretClient() (secrets.SecretsServiceClient, error) NodesClient() (nodes.NodesServiceClient, error) FeedClient() (automate_feed.FeedServiceClient, error) ComplianceReportingServiceClient() (cc_reporting.ReportingServiceClient, error) ComplianceProfilesServiceClient() (profiles.ProfilesServiceClient, error) ComplianceJobsServiceClient() (jobs.JobsServiceClient, error) ComplianceStatsServiceClient() (cc_stats.StatsServiceClient, error) ComplianceVersionServiceClient() (cc_version.VersionServiceClient, error) NodeManagerClient() (manager.NodeManagerServiceClient, error) LicenseControlClient() (license_control.LicenseControlClient, error) DeploymentServiceClient() (deployment.DeploymentClient, error) } // clientsFactory caches grpc client connections and returns clients type clientsFactory struct { config ClientConfig connections map[string]*grpc.ClientConn // Notifications has a very heavy cost for us, therefore we // are going to have a unique client that we will initialize // when this object is created notifierClient notifier.Notifier } // NotifierOptions contains options used to configure Notifier type NotifierOptions struct { } // NewClientsFactory creates a client factory that keeps one ClientConn per endpoint. // Each factory method that returns a client will reuse the ClientConn endpoint. // What this means is that you are allowed to cache each client. The target can // never change. The underlying ClientConn will be responsible for maintaining // the connection, where maintaining includes dealing with disconnects, service // processes entering and leaving the pool, ip addresses changing, etc. func NewClientsFactory(config ClientConfig, connFactory *secureconn.Factory) ClientsFactory { clients := clientsFactory{ connections: map[string]*grpc.ClientConn{}, config: config, } // Note: this only affects selected clients, which receive the metrics // interceptor options -- see below. grpc_prometheus.EnableClientHandlingTimeHistogram() for service, endpoint := range config.Endpoints { if endpoint.Target != "" { metricsEnabled := clientMetrics[service] log.WithFields(log.Fields{ "service": service, "endpoint": endpoint.Target, "metrics_enabled": metricsEnabled, }).Info("Dialing") var conn *grpc.ClientConn var err error opts := []grpc.DialOption{} if metricsEnabled { opts = append(opts, grpc.WithUnaryInterceptor(grpc_prometheus.UnaryClientInterceptor), grpc.WithStreamInterceptor(grpc_prometheus.StreamClientInterceptor)) } if endpoint.Secure { conn, err = connFactory.Dial(service, endpoint.Target, opts...) } else { // Q: do we (still) have non-tls endpoints? conn, err = grpc.Dial( endpoint.Target, append(opts, grpc.WithInsecure(), tracing.GlobalClientInterceptor())..., ) } if err != nil { // This case should never happen (unless you tell Dial to block) log.WithFields(log.Fields{ "service": service, "error": err, }).Fatal("Could not create connection") } clients.connections[service] = conn } else { log.WithFields(log.Fields{ "service": service, }).Warn("Missing target") } } // Initialize the notifications client if exists n, exists := clients.connections["notifications-service"] if exists { clients.notifierClient = notifier.New(n) } return &clients } // CfgMgmtClient returns a client for the CfgMgmt service. // It requires the `cfgmgmt` endpoint to be configured func (c *clientsFactory) CfgMgmtClient() (cfgmgmt.CfgMgmtClient, error) { conn, err := c.connectionByName("config-mgmt-service") if err != nil { return nil, err } return cfgmgmt.NewCfgMgmtClient(conn), nil } // IngestStatusClient returns a client for the IngestStatus service. // It requires the `ingest` endpoint to be configured func (c *clientsFactory) IngestStatusClient() (chef_ingest.IngestStatusClient, error) { conn, err := c.connectionByName("ingest-service") if err != nil { return nil, err } return chef_ingest.NewIngestStatusClient(conn), nil } // ChefIngesterClient returns a client for the ChefIngester service. // It requires the `ingest` endpoint to be configured func (c *clientsFactory) ChefIngesterClient() (chef_ingest.ChefIngesterClient, error) { conn, err := c.connectionByName("ingest-service") if err != nil { return nil, err } return chef_ingest.NewChefIngesterClient(conn), nil } // ChefIngesterJobSchedulerClient returns a client for the ChefIngesterJobScheduler service. // It requires the `ingest` endpoint to be configured func (c *clientsFactory) ChefIngesterJobSchedulerClient() (chef_ingest.JobSchedulerClient, error) { conn, err := c.connectionByName("ingest-service") if err != nil { return nil, err } return chef_ingest.NewJobSchedulerClient(conn), nil } // ComplianceIngesterClient returns a client for the InspecIngester service. // It requires the `ingest` endpoint to be configured func (c *clientsFactory) ComplianceIngesterClient() (cc_ingest.ComplianceIngesterClient, error) { conn, err := c.connectionByName("compliance-service") if err != nil { return nil, err } return cc_ingest.NewComplianceIngesterClient(conn), nil } // NotificationsClient returns a client for the Notifications service. // It requires the `notifications` endpoint to be configured func (c *clientsFactory) NotificationsClient() (notifications.NotificationsClient, error) { conn, err := c.connectionByName("notifications-service") if err != nil { return nil, err } return notifications.NewNotificationsClient(conn), nil } // AuthenticationClient returns a client for the Authentication service. // It requires the `auth` endpoint to be configured func (c *clientsFactory) AuthenticationClient() (authn.AuthenticationClient, error) { conn, err := c.connectionByName("authn-service") if err != nil { return nil, err } return authn.NewAuthenticationClient(conn), nil } // AuthorizationClient returns a client for the Authorization service. // It requires the `authz` endpoint to be configured func (c *clientsFactory) AuthorizationClient() (authz.AuthorizationClient, error) { conn, err := c.connectionByName("authz-service") if err != nil { return nil, err } return authz.NewAuthorizationClient(conn), nil } // AuthorizationV2Client returns a client for the Authorization (IAMv2) service. // It requires the `authz` endpoint to be configured func (c *clientsFactory) AuthorizationV2Client() (iam_v2beta.AuthorizationClient, error) { conn, err := c.connectionByName("authz-service") if err != nil { return nil, err } return iam_v2beta.NewAuthorizationClient(conn), nil } // PoliciesClient returns a client for the Policies service. // It requires the `authz` endpoint to be configured func (c *clientsFactory) PoliciesClient() (iam_v2beta.PoliciesClient, error) { conn, err := c.connectionByName("authz-service") if err != nil { return nil, err } return iam_v2beta.NewPoliciesClient(conn), nil } // ProjectsClient returns a client for the Projects service. // It requires the `authz` endpoint to be configured func (c *clientsFactory) ProjectsClient() (iam_v2beta.ProjectsClient, error) { conn, err := c.connectionByName("authz-service") if err != nil { return nil, err } return iam_v2beta.NewProjectsClient(conn), nil } // TeamsV1Client returns a V1 client for the Teams service. // It requires the `teams` endpoint to be configured func (c *clientsFactory) TeamsV1Client() (teams_v1.TeamsV1Client, error) { conn, err := c.connectionByName("teams-service") if err != nil { return nil, err } return teams_v1.NewTeamsV1Client(conn), nil } // TeamsV2Client returns a V2 client for the Teams service. // It requires the `teams` endpoint to be configured func (c *clientsFactory) TeamsV2Client() (teams_v2.TeamsV2Client, error) { conn, err := c.connectionByName("teams-service") if err != nil { return nil, err } return teams_v2.NewTeamsV2Client(conn), nil } // TokensMgmtClient returns a client for the Tokens Mgmt service. // It requires the `auth` endpoint to be configured func (c *clientsFactory) TokensMgmtClient() (authn.TokensMgmtClient, error) { conn, err := c.connectionByName("authn-service") if err != nil { return nil, err } return authn.NewTokensMgmtClient(conn), nil } // UsersMgmtClient returns a client for the Users Mgmt service. // It requires the `local-user-service` endpoint to be configured func (c *clientsFactory) UsersMgmtClient() (local_user.UsersMgmtClient, error) { conn, err := c.connectionByName("local-user-service") if err != nil { return nil, err } return local_user.NewUsersMgmtClient(conn), nil } // Notifier returns the unique client for the Notifications service. // We are reusing the same notifier since it's quite heavy func (c *clientsFactory) Notifier() (notifier.Notifier, error) { var err error if c.notifierClient == nil { err = errors.New("Expected connection for notifications-service, but none was found. Check to make sure it is correctly configured") } return c.notifierClient, err } func (c *clientsFactory) ApplicationsClient() (applications.ApplicationsServiceClient, error) { conn, err := c.connectionByName("applications-service") if err != nil { return nil, err } return applications.NewApplicationsServiceClient(conn), nil } func (c *clientsFactory) SecretClient() (secrets.SecretsServiceClient, error) { conn, err := c.connectionByName("secrets-service") if err != nil { return nil, err } return secrets.NewSecretsServiceClient(conn), nil } func (c *clientsFactory) NodesClient() (nodes.NodesServiceClient, error) { conn, err := c.connectionByName("nodemanager-service") if err != nil { return nil, err } return nodes.NewNodesServiceClient(conn), nil } func (c *clientsFactory) FeedClient() (automate_feed.FeedServiceClient, error) { conn, err := c.connectionByName("compliance-service") if err != nil { return nil, err } return automate_feed.NewFeedServiceClient(conn), nil } func (c *clientsFactory) ComplianceReportingServiceClient() (cc_reporting.ReportingServiceClient, error) { conn, err := c.connectionByName("compliance-service") if err != nil { return nil, err } return cc_reporting.NewReportingServiceClient(conn), nil } func (c *clientsFactory) ComplianceProfilesServiceClient() (profiles.ProfilesServiceClient, error) { conn, err := c.connectionByName("compliance-service") if err != nil { return nil, err } return profiles.NewProfilesServiceClient(conn), nil } func (c *clientsFactory) ComplianceJobsServiceClient() (jobs.JobsServiceClient, error) { conn, err := c.connectionByName("compliance-service") if err != nil { return nil, err } return jobs.NewJobsServiceClient(conn), nil } func (c *clientsFactory) ComplianceStatsServiceClient() (cc_stats.StatsServiceClient, error) { conn, err := c.connectionByName("compliance-service") if err != nil { return nil, err } return cc_stats.NewStatsServiceClient(conn), nil } func (c *clientsFactory) ComplianceVersionServiceClient() (cc_version.VersionServiceClient, error) { conn, err := c.connectionByName("compliance-service") if err != nil { return nil, err } return cc_version.NewVersionServiceClient(conn), nil } func (c *clientsFactory) NodeManagerClient() (manager.NodeManagerServiceClient, error) { conn, err := c.connectionByName("nodemanager-service") if err != nil { return nil, err } return manager.NewNodeManagerServiceClient(conn), nil } func (c *clientsFactory) LicenseControlClient() (license_control.LicenseControlClient, error) { conn, err := c.connectionByName("license-control-service") if err != nil { return nil, err } return license_control.NewLicenseControlClient(conn), nil } func (c *clientsFactory) DeploymentServiceClient() (deployment.DeploymentClient, error) { conn, err := c.connectionByName("deployment-service") if err != nil
return deployment.NewDeploymentClient(conn), nil } func (c *clientsFactory) connectionByName(name string) (*grpc.ClientConn, error) { conn, exists := c.connections[name] if !exists { err := fmt.Errorf("Expected connection for %s, but none was found. Check to make sure it is correctly configured", name) return nil, err } return conn, nil } // Populate our endpoints with default targets func (c *ClientConfig) configureDefaultEndpoints() { if c.Endpoints == nil { c.Endpoints = map[string]ConnectionOptions{} } for service, target := range defaultEndpoints { // If the endpoint already exists don't overwrite it with a default if _, ok := c.Endpoints[service]; ok { continue } c.Endpoints[service] = ConnectionOptions{ Target: target, Secure: true, } } }
{ return nil, err }
security-plugins.js
// @flow import { getSecurity } from '../common'; export function generateSecurityPlugins( op: OA3Operation | null, api: OpenApi3Spec, tags: Array<string>, ): Array<DCPlugin> { const plugins = []; const components = api.components || {}; const securitySchemes = components.securitySchemes || {}; const security = op ? getSecurity(op) : getSecurity(api); for (const securityItem of security || []) { for (const name of Object.keys(securityItem)) { const scheme: OA3SecurityScheme = securitySchemes[name] || {}; const args = securityItem[name]; const p = generateSecurityPlugin(scheme, args, tags); if (p) { plugins.push(p); } } } return plugins; } export function generateApiKeySecurityPlugin(scheme: OA3SecuritySchemeApiKey): DCPlugin { if (!['query', 'header', 'cookie'].includes(scheme.in)) { throw new Error(`a ${scheme.type} object expects valid "in" property. Got ${scheme.in}`); } if (!scheme.name) { throw new Error(`a ${scheme.type} object expects valid "name" property. Got ${scheme.name}`); } return { name: 'key-auth', config: { key_names: [scheme.name] }, }; } export function
(scheme: OA3SecuritySchemeHttp): DCPlugin { if ((scheme.scheme || '').toLowerCase() !== 'basic') { throw new Error(`Only "basic" http scheme supported. got ${scheme.scheme}`); } return { name: 'basic-auth' }; } export function generateOpenIdConnectSecurityPlugin( scheme: OA3SecuritySchemeOpenIdConnect, args: Array<any>, ): DCPlugin { if (!scheme.openIdConnectUrl) { throw new Error(`invalid "openIdConnectUrl" property. Got ${scheme.openIdConnectUrl}`); } return { name: 'openid-connect', config: { issuer: scheme.openIdConnectUrl, scopes_required: args || [], }, }; } export function generateOAuth2SecurityPlugin( scheme: OA3SecuritySchemeOAuth2, args: ?Array<any>, ): DCPlugin { return { config: { auth_methods: ['client_credentials'], }, name: 'openid-connect', }; } export function generateSecurityPlugin( scheme: OA3SecurityScheme, args: Array<any>, tags: Array<string>, ): DCPlugin | null { let plugin: DCPlugin | null = null; // Flow doesn't like this (hence the "any" casting) but we're // comparing the scheme type in a more flexible way to favor // usability const type = (scheme.type || '').toLowerCase(); // Generate base plugin if (type === 'apikey') { plugin = generateApiKeySecurityPlugin((scheme: any)); } else if (type === 'http') { plugin = generateHttpSecurityPlugin((scheme: any)); } else if (type === 'openidconnect') { plugin = generateOpenIdConnectSecurityPlugin((scheme: any), args); } else if (type === 'oauth2') { plugin = generateOAuth2SecurityPlugin((scheme: any)); } else { return null; } // Add additional plugin configuration from x-kong-security-* property // Only search for the matching key // i.e. OAuth2 security with x-kong-security-basic-auth should not match const kongSecurity = (scheme: Object)[`x-kong-security-${plugin.name}`] ?? {}; if (kongSecurity.config) { plugin.config = kongSecurity.config; } // Add global tags plugin.tags = [...tags, ...(kongSecurity.tags ?? [])]; return plugin; }
generateHttpSecurityPlugin
utils.py
import asyncio from datetime import datetime from typing import Any, Callable, List, Optional, Union, TYPE_CHECKING from aat import AATException from aat.config import ExitRoutine, InstrumentType, TradingType from aat.core import Instrument, ExchangeType, Event, Order, Trade, OrderBook from aat.exchange import Exchange from .periodic import Periodic if TYPE_CHECKING: from aat.engine import TradingEngine from aat.strategy import Strategy class StrategyManagerUtilsMixin(object): _engine: "TradingEngine" _exchanges: List[Exchange] _periodics: List[Periodic] _data_subscriptions = {} # type: ignore ################# # Other Methods # ################# def tradingType(self) -> TradingType: return self._engine.trading_type def loop(self) -> asyncio.AbstractEventLoop: return self._engine.event_loop def now(self) -> datetime: """Return the current datetime. Useful to avoid code changes between live trading and backtesting. Defaults to `datetime.now`""" return self._engine.now() def instruments( self, type: InstrumentType = None, exchange: Optional[ExchangeType] = None ) -> List[Instrument]: """Return list of all available instruments""" return Instrument._instrumentdb.instruments(type=type, exchange=exchange) def exchanges(self, type: InstrumentType = None) -> List[ExchangeType]: """Return list of all available exchanges""" if type: raise NotImplementedError() return [exc.exchange() for exc in self._exchanges] async def subscribe(self, instrument: Instrument, strategy: "Strategy") -> None: """Subscribe to market data for the given instrument""" if strategy not in self._data_subscriptions: self._data_subscriptions[strategy] = [] self._data_subscriptions[strategy].append(instrument) if instrument.exchange not in self.exchanges(): raise AATException( "Exchange not installed: {} (Installed are [{}]".format( instrument.exchange, self.exchanges() ) ) for exc in self._exchanges: if instrument and instrument.exchange == exc.exchange(): await exc.subscribe(instrument) def dataSubscriptions(self, handler: Callable, event: Event) -> bool: """does handler subscribe to the data for event""" if handler not in self._data_subscriptions: # subscribe all by default return True target: Union[Order, Trade] = event.target # type: ignore return target.instrument in self._data_subscriptions[handler] async def lookup( self, instrument: Optional[Instrument], exchange: ExchangeType = None ) -> List[Instrument]: """Return list of all available instruments that match the instrument given""" if exchange: for exchange_inst in self._exchanges: if exchange == exchange_inst.exchange(): if instrument: return await exchange_inst.lookup(instrument) return [] elif exchange is None: ret = [] for exchange_inst in self._exchanges: if instrument: ret.extend(await exchange_inst.lookup(instrument)) return ret # None implement raise NotImplementedError() async def book(self, instrument: Instrument) -> Optional[OrderBook]: """Return list of all available instruments that match the instrument given""" if instrument.exchange not in self.exchanges(): raise AATException("") for exchange_inst in self._exchanges: if instrument.exchange == exchange_inst.exchange(): return await exchange_inst.book(instrument) return None def _make_async(self, function: Callable) -> Callable: async def _wrapper() -> Any: return await self.loop().run_in_executor( self._engine, self._engine.executor, function ) return _wrapper def periodic( self, function: Callable, second: Union[int, str] = 0, minute: Union[int, str] = "*", hour: Union[int, str] = "*", ) -> Periodic: """periodically run a given async function. NOTE: precise timing is NOT guaranteed due to event loop scheduling.""" if not self.loop().is_running(): raise Exception("Install periodics after engine start (e.g. in `onStart`)") # Validation if not asyncio.iscoroutinefunction(function): function = self._make_async(function) if not isinstance(second, (int, str)): raise Exception("`second` arg must be int or str") if not isinstance(minute, (int, str)): raise Exception("`minute` arg must be int or str") if not isinstance(hour, (int, str)): raise Exception("`hour` arg must be int or str") if isinstance(second, str) and second != "*": raise Exception('Only "*" or int allowed for argument `second`') elif isinstance(second, str): second = None # type: ignore elif second < 0 or second > 60: raise Exception("`second` must be between 0 and 60") if isinstance(minute, str) and minute != "*": raise Exception('Only "*" or int allowed for argument `minute`') elif isinstance(minute, str): minute = None # type: ignore elif minute < 0 or minute > 60: raise Exception("`minute` must be between 0 and 60") if isinstance(hour, str) and hour != "*": raise Exception('Only "*" or int allowed for argument `hour`') elif isinstance(hour, str): hour = None # type: ignore elif hour < 0 or hour > 24: raise Exception("`hour` must be between 0 and 24") # End Validation periodic = Periodic( self.loop(), self._engine._latest, function, second, minute, hour # type: ignore ) self._periodics.append(periodic) return periodic def restrictTradingHours( self, strategy: "Strategy", start_second: Optional[int] = None, start_minute: Optional[int] = None, start_hour: Optional[int] = None, end_second: Optional[int] = None, end_minute: Optional[int] = None, end_hour: Optional[int] = None, on_end_of_day: ExitRoutine = ExitRoutine.NONE,
) -> None: pass
A Star Pathfinding.py
import pygame, random, math, queue, pdb pygame.init() clock = pygame.time.Clock() SCREEN_WIDTH = 800 COLUMNS = 100 ROWS = 100 CELL_WIDTH = 8 CELL_COLOURS = { "empty" : (128, 128, 128), "wall" : (0, 0, 0), "start" : (0, 255, 0), "goal" : (255, 0, 0), "path" : (255, 255, 255), "explored" : (0, 0, 255), } DIRECTIONS = { "R" : pygame.math.Vector2(1, 0), "L" : pygame.math.Vector2(-1, 0), "D" : pygame.math.Vector2(0, 1), "U" : pygame.math.Vector2(0, -1) } from dataclasses import dataclass, field from typing import Any @dataclass(order=True) class
: priority: int item: Any=field(compare=False) size = (SCREEN_WIDTH, SCREEN_WIDTH) screen = pygame.display.set_mode(size) grid = [] for column in range(COLUMNS): grid.append([]) for row in range(ROWS): grid[column].append("empty") for i in range(2500): x = random.randint(2, ROWS - 3) y = random.randint(2, COLUMNS - 3) if grid[y][x] == "empty": grid[y][x] = "wall" class Node: global nodes, grid, CELL_COLOURS def __init__(self, nodeType, position): nodes.append(self) self.position = position self.nodeType = nodeType self.colour = CELL_COLOURS[nodeType] grid[int(position.y)][int(position.x)] = nodeType def getNeighbours(position): global DIRECTIONS neighbours = [] for key, direction in DIRECTIONS.items(): neighbourPosition = position + direction neighbours.append(neighbourPosition) return neighbours def getKey(position): key = str(int(position.x)) + "_" + str(int(position.y)) return key def pathfind(startPosition, goalPosition): global grid frontier = queue.PriorityQueue() frontier.put(PrioritizedItem(0, startPosition)) cameFrom = dict() costSoFar = dict() startPositionKey = getKey(startPosition) cameFrom[startPositionKey] = None costSoFar[startPositionKey] = 0 while not frontier.empty(): current = frontier.get().item currentKey = getKey(current) for neighbour in getNeighbours(current): cell = grid[int(neighbour.y)][int(neighbour.x)] neighbourKey = getKey(neighbour) if cell == "goal": return currentKey, cameFrom if cell == "wall" or cell == "start": continue newCost = costSoFar[currentKey] + 0.01 if neighbourKey not in costSoFar or newCost < costSoFar[neighbourKey]: costSoFar[neighbourKey] = newCost distance = neighbour.distance_to(goalPosition) priority = costSoFar[neighbourKey] + distance frontier.put(PrioritizedItem(priority, neighbour)) cameFrom[neighbourKey] = current grid[int(neighbour.y)][int(neighbour.x)] = "explored" def drawCell(colour, position): global CELL_WIDTH pygame.draw.rect(screen, colour, (int(position.x * CELL_WIDTH), int(position.y * CELL_WIDTH), CELL_WIDTH, CELL_WIDTH)) def drawGrid(): global grid, COLUMNS, ROWS, CELL_COLOURS for column in range(COLUMNS): for row in range(ROWS): cell = grid[column][row] colour = CELL_COLOURS[cell] position = pygame.math.Vector2(row, column) drawCell(colour, position) def createWalls(): global grid, COLUMNS, ROWS for column in range(COLUMNS): grid[column][0] = "wall" grid[column][ROWS - 1] = "wall" for row in range(ROWS): grid[0][row] = "wall" grid[COLUMNS - 1][row] = "wall" createWalls() nodes = [] start = Node("start", pygame.math.Vector2(1, 1)) goal = Node("goal", pygame.math.Vector2(98, 98)) currentKey, cameFrom = pathfind(start.position, goal.position) while cameFrom[currentKey]: position = cameFrom[currentKey] grid[int(position.y)][int(position.x)] = "path" currentKey = getKey(position) drawGrid() run = True while run: clock.tick(60) for event in pygame.event.get(): if event.type == pygame.QUIT: run = False #screen.fill((0, 0, 0)) pygame.display.update() pygame.quit()
PrioritizedItem
vose_alias.py
import os import numpy as np from paddlehub.common.logger import logger from lda_webpage.util import rand, rand_k class VoseAlias(object): """Vose's Alias Method. """ def __init__(self):
def initialize(self, distribution): """Initialize the alias table according to the input distribution Arg: distribution: Numpy array. """ size = distribution.shape[0] self.__alias = np.zeros(size, dtype=np.int64) self.__prob = np.zeros(size) sum_ = np.sum(distribution) p = distribution / sum_ * size # Scale up probability. large, small = [], [] for i, p_ in enumerate(p): if p_ < 1.0: small.append(i) else: large.append(i) while large and small: l = small[0] g = large[0] small.pop(0) large.pop(0) self.__prob[l] = p[l] self.__alias[l] = g p[g] = p[g] + p[l] - 1 # A more numerically stable option. if p[g] < 1.0: small.append(g) else: large.append(g) while large: g = large[0] large.pop(0) self.__prob[g] = 1.0 while small: l = small[0] small.pop(0) self.__prob[l] = 1.0 def generate(self): """Generate samples from given distribution. """ dart1 = rand_k(self.size()) dart2 = int(rand()) return dart1 if dart2 > self.__prob[dart1] else self.__alias[dart1] def size(self): return self.__prob.shape[0]
self.__alias = None self.__prob = None # np.array
worker.rs
use chrono::{Duration, Utc}; use clokwerk::{ScheduleHandle, Scheduler, TimeUnits}; use diesel::prelude::*; use std::collections::HashMap; use std::fs; use std::ops::Sub; use crate::util::Error::UnsupportedSource; use crate::util::Result; use super::db; use super::models::SourceType; use super::schema; mod image; mod stream; mod youtube; pub struct Worker { scheduler: Scheduler, pool: db::ConnectionPool, } impl Worker { pub fn
(database_url: &str) -> Worker { Worker { scheduler: Scheduler::new(), pool: db::ConnectionPool::new(database_url), } } pub fn start(mut self, interval: Duration) -> Result<ScheduleHandle> { let pool = self.pool.clone(); self.scheduler.every(15.minutes()).run(move || { if let Err(e) = update_sources(&pool.get()) { eprintln!("Unable to update sources: {}", e); } }); let pool = self.pool.clone(); self.scheduler.every(1.minutes()).run(move || { if let Err(e) = download_images(&pool.get()) { eprintln!("Unable to download images: {}", e); } }); let pool = self.pool.clone(); self.scheduler.every(1.hours()).run(move || { if let Err(e) = remove_images(&pool.get()) { eprintln!("Unable to remove old images: {}", e); } }); // Initial update. let count = update_sources(&self.pool.get())?; println!("Updated {} sources.", count); let interval = interval.to_std()?; Ok(self.scheduler.watch_thread(interval)) } } /// Updates source playlist URLs if they don't exist or haven't been updated in 5 minutes. fn update_sources(conn: &SqliteConnection) -> Result<usize> { use schema::sources::dsl; let threshold = Utc::now().sub(Duration::minutes(5)).timestamp(); let mut count = 0; let sources = dsl::sources .filter(dsl::playlist.is_null()) .or_filter(dsl::updated_at.le(threshold)) .load::<db::Source>(conn)?; for source in &sources { if !source.enabled { continue; } let result = match SourceType::from(source.typ) { SourceType::YouTube => youtube::update(source, conn), _ => continue, }; if let Err(e) = result { eprintln!("Unable to update source '{}': {}", source.name, e); continue; } count += 1; } Ok(count) } /// Downloads the images of all sources. fn download_images(conn: &SqliteConnection) -> Result<usize> { use schema::sources::dsl; let sources = dsl::sources.load::<db::Source>(conn)?; let mut count = 0; for source in &sources { use schema::images::{dsl, table}; if !source.enabled { continue; } // Create the target directory, if necessary. let directory = format!("images/{}", source.name); fs::create_dir_all(&directory)?; let timestamp = Utc::now().timestamp(); let filename = format!("{}/{}.jpg", directory, timestamp); let result = match SourceType::from(source.typ) { SourceType::Url => image::download(source, &filename), SourceType::YouTube | SourceType::Stream => stream::download(source, &filename), typ => Err(UnsupportedSource(typ).into()), }; if let Err(e) = result { eprintln!( "Unable to download image for source '{}': {}", source.name, e ); continue; } diesel::insert_into(table) .values((dsl::source_id.eq(source.id), dsl::timestamp.eq(timestamp))) .execute(conn)?; count += 1; } Ok(count) } /// Removes images older than 7 days. fn remove_images(conn: &SqliteConnection) -> Result<usize> { use schema::images::{dsl, table}; let sources = schema::sources::dsl::sources .load::<db::Source>(conn)? .into_iter() .map(|source| (source.id, source.name)) .collect::<HashMap<i64, String>>(); let threshold = Utc::now().sub(Duration::days(7)).timestamp(); let predicate = dsl::timestamp.le(threshold); let images = dsl::images.filter(&predicate).load::<db::Image>(conn)?; diesel::delete(table).filter(&predicate).execute(conn)?; for image in &images { if let Some(source) = sources.get(&image.source_id) { let filename = format!("images/{}/{}.jpg", source, image.timestamp); fs::remove_file(filename).ok(); } } Ok(images.len()) }
new
smb_client.js
"use strict"; var SmbClient = {}; if ("undefined" === typeof module) { window.SmbClient = SmbClient; } else { module.exports = SmbClient; } })();
(function() {
typeGuardsInIfStatement.ts
// In the true branch statement of an 'if' statement, // the type of a variable or parameter is narrowed by any type guard in the 'if' condition when true, // provided the true branch statement contains no assignments to the variable or parameter. // In the false branch statement of an 'if' statement, // the type of a variable or parameter is narrowed by any type guard in the 'if' condition when false, // provided the false branch statement contains no assignments to the variable or parameter function foo(x: number | string) { if (typeof x === "string") { return x.length; // string } else { return x++; // number } } function foo2(x: number | string) { // x is assigned in the if true branch, the type is not narrowed if (typeof x === "string") { x = 10; return x; // string | number } else { return x; // string | number } } function foo3(x: number | string) { // x is assigned in the if true branch, the type is not narrowed if (typeof x === "string") { x = "Hello"; // even though assigned using same type as narrowed expression return x; // string | number } else { return x; // string | number } } function foo4(x: number | string) { // false branch updates the variable - so here it is not number if (typeof x === "string") { return x; // string | number } else { x = 10; // even though assigned number - this should result in x to be string | number return x; // string | number } } function foo5(x: number | string) { // false branch updates the variable - so here it is not number if (typeof x === "string") { return x; // string | number } else { x = "hello"; return x; // string | number } } function
(x: number | string) { // Modify in both branches if (typeof x === "string") { x = 10; return x; // string | number } else { x = "hello"; return x; // string | number } } function foo7(x: number | string | boolean) { if (typeof x === "string") { return x === "hello"; // string } else if (typeof x === "boolean") { return x; // boolean } else { return x == 10; // number } } function foo8(x: number | string | boolean) { if (typeof x === "string") { return x === "hello"; // string } else { var b: number | boolean = x; // number | boolean if (typeof x === "boolean") { return x; // boolean } else { return x == 10; // number } } } function foo9(x: number | string) { var y = 10; if (typeof x === "string") { // usage of x or assignment to separate variable shouldn't cause narrowing of type to stop y = x.length; return x === "hello"; // string } else { return x == 10; // number } } function foo10(x: number | string | boolean) { // Mixing typeguard narrowing in if statement with conditional expression typeguard if (typeof x === "string") { return x === "hello"; // string } else { var y: boolean | string; var b = x; // number | boolean return typeof x === "number" ? x === 10 // number : x; // x should be boolean } } function foo11(x: number | string | boolean) { // Mixing typeguard narrowing in if statement with conditional expression typeguard // Assigning value to x deep inside another guard stops narrowing of type too if (typeof x === "string") { return x; // string | number | boolean - x changed in else branch } else { var y: number| boolean | string; var b = x; // number | boolean | string - because below we are changing value of x in if statement return typeof x === "number" ? ( // change value of x x = 10 && x.toString() // number | boolean | string ) : ( // do not change value y = x && x.toString() // number | boolean | string ); } } function foo12(x: number | string | boolean) { // Mixing typeguard narrowing in if statement with conditional expression typeguard // Assigning value to x in outer guard shouldn't stop narrowing in the inner expression if (typeof x === "string") { return x.toString(); // string | number | boolean - x changed in else branch } else { x = 10; var b = x; // number | boolean | string return typeof x === "number" ? x.toString() // number : x.toString(); // boolean | string } }
foo6