Best JavaScript code snippet using ava
IntelHex.js
Source:IntelHex.js
1'use strict';2/*3* Parse and verify Intel Hex4* Derek K5* etx313@gmail.com6*/7var IntelHex = (function() {8 /*9 * @constructor10 */11 function IntelHex(hexString){12 13 this.buffer = {};14 this.intelHexEnd = ':00000001FF';15 this.startAddress = 0;16 17 18 if(hexString) this.parse(hexString);19 20 }21 22 23 24 /*25 * Parse loaded Hex into ArrayBuffer26 * @param {String} hex27 */28 IntelHex.prototype.parse = function(hex){29 30 var checksumError = -1,31 index = 0,32 bufferSize;33 34 // Fix any line ending weirdness35 hex = hex.replace(/\r?\n/g, "\r\n");36 37 // Determine buffer size38 var hexLines = hex.split('\r\n');39 40 // Start at the end and find the last memory address41 for(index=hexLines.length-1; index > -1; index--){42 var line = hexLines[index];43 if( line.length > 4 && line.slice(0,11) != this.intelHexEnd ){44 bufferSize = parseInt(line.slice(3,7), 16) + parseInt( line.slice(1,3), 16 );45 break;46 }47 }48 49 50 this.startAddress = parseInt( hexLines[0].slice(3,7), 16 );51 52 53 // Init a new buffer to hold the data54 this.buffer = new ArrayBuffer(bufferSize);55 var view = new Uint8Array(this.buffer);56 57 58 // Fill with FF59 for( index=0; index<bufferSize; index++ )60 view[index] = 0xFF;61 62 // Copy String data from hex file into the buffer63 hexLines.forEach((function(value, index, array){64 65 if( value.slice(0,11) == this.intelHexEnd || value.length < 2 )66 return;67 68 var size = parseInt( value.slice(1,3), 16 );69 var address = parseInt( value.slice(3,7), 16 );70 71 for(var i=0; i<size; i++)72 view[address+i] = parseInt(value.slice(9+(i*2), 11+(i*2)), 16);73 74 checksumError = !this.checksum(value) ? address : checksumError;75 76 }).bind(this));77 78 79 80 // Checksum error?81 if(checksumError > -1){82 console.log('checksumError', checksumError);83 }84 85 this.length = bufferSize;86 87 }88 89 90 91 92 93 /*94 * Convert buffer back to Intel Hex String95 * @param {Int} size 16 bit or 32 bit lines96 */97 IntelHex.prototype.encode = function(size){98 // TODO99 }100 101 102 103 104 105 106 /*107 * Verify checksum of a line from Intel Hex format.108 * Checksum is verified by adding all hex values, excluding the checksum byte. 109 * Then calculating the 2's complement and checking against the last byte of the value string110 * @param {String} value111 * @return {Boolean} success / fail112 */113 IntelHex.prototype.checksum = function(value){114 115 var sum = 0;116 117 var check = parseInt(value.slice(-2), 16);118 value = value.slice(1, value.length-2)119 120 for(var i=0; i<value.length; i+=2){121 sum += parseInt(value.slice(i, i+2), 16);122 }123 124 if( parseInt((~sum + 1 >>> 0).toString(16).slice(-2), 16) == check ){125 return true126 }else{127 console.log('invalid checksum:', value, check, parseInt((~sum + 1 >>> 0).toString(16).slice(-2), 16));128 return false;129 }130 131 }132 133 134 135 136 /*137 * Return a slice of the ArrayBuffer138 * @param {int} begin139 * @param {int} end Optional140 */141 IntelHex.prototype.slice = function(start, end){142 return this.buffer.slice(start, end);143 }144 145 146 /*147 * Return buffer length148 * @param {int} begin149 * @param {int} end Optional150 */151 IntelHex.prototype.length = function(){152 return this.buffer.length;153 }154 155 156 157 158 return IntelHex;159})();160/*161* Parse loaded Hex into ArrayBuffer162* @param {String} hex163*/164/*165function parseHex(hex){166 167 var deferred = $q.defer(),168 checksumError = -1;169 170 hexHashMap = {};171 172 // Fix any line ending weirdness173 hex = hex.replace(/\r?\n/g, "\r\n");174 175 angular.forEach(hex.split('\r\n'), function(value, key){176 177 if( value.slice(0,11) == intelHexEnd || value[0] != ':' || value.length < 1 )178 return;179 180 181 var size = parseInt( value.slice(1,3), 16 );182 var address = parseInt( value.slice(3,7), 16 );183 var buffer = new ArrayBuffer(size);184 var view = new Uint8Array(buffer);185 186 for(var i=0; i<size; i++)187 view[i] = parseInt(value.slice(9+(i*2), 11+(i*2)), 16);188 189 checksumError = !checksum(value) ? address : checksumError;190 191 hexHashMap[ address ] = view;192 193 194 }, this);195 196 // Checksum error?197 if(checksumError > 0){198 console.log('checksumError', checksumError);199 $rootScope.$broadcast('FirmwareService.INTEL_HEX_INVALID', 'invalid checksum ' );200 deferred.reject();201 }202 203 console.log(hexHashMap);204 deferred.resolve();205 206 return deferred.promise; 207}208*/209 210 211 ...
packetreader.js
Source:packetreader.js
...33 break;34 }35 this.packet.data = this._consume(this.packet.length);36 if (!this.packet.verifyChecksum()) {37 this.emit('error', new PacketReader.ChecksumError(this.packet));38 return;39 }40 this.emit('packet', this.packet);41 this.inBody = false;42 } else {43 if (!(this.buffer.length >= 24)) {44 break;45 }46 header = this._consume(24);47 this.packet = new Packet(header.readUInt32LE(0), header.readUInt32LE(4), header.readUInt32LE(8), header.readUInt32LE(12), header.readUInt32LE(16), header.readUInt32LE(20), new Buffer(0));48 if (!this.packet.verifyMagic()) {49 this.emit('error', new PacketReader.MagicError(this.packet));50 return;51 }52 if (this.packet.length === 0) {53 this.emit('packet', this.packet);54 } else {55 this.inBody = true;56 }57 }58 }59 }60 };61 PacketReader.prototype._appendChunk = function() {62 var chunk;63 if (chunk = this.stream.read()) {64 if (this.buffer) {65 return this.buffer = Buffer.concat([this.buffer, chunk], this.buffer.length + chunk.length);66 } else {67 return this.buffer = chunk;68 }69 } else {70 return null;71 }72 };73 PacketReader.prototype._consume = function(length) {74 var chunk;75 chunk = this.buffer.slice(0, length);76 this.buffer = length === this.buffer.length ? null : this.buffer.slice(length);77 return chunk;78 };79 return PacketReader;80})(EventEmitter);81PacketReader.ChecksumError = (function(superClass) {82 extend(ChecksumError, superClass);83 function ChecksumError(packet) {84 this.packet = packet;85 Error.call(this);86 this.name = 'ChecksumError';87 this.message = "Checksum mismatch";88 Error.captureStackTrace(this, PacketReader.ChecksumError);89 }90 return ChecksumError;91})(Error);92PacketReader.MagicError = (function(superClass) {93 extend(MagicError, superClass);94 function MagicError(packet) {95 this.packet = packet;96 Error.call(this);97 this.name = 'MagicError';...
errors.js
Source:errors.js
1/* jshint node:true */2var util = require('util');3var BadPacketError = exports.BadPacketError = function(msg, constr) {4 Error.captureStackTrace(this, constr || this);5 this.message = msg || 'BadPacketError';6};7util.inherits(BadPacketError, Error);8BadPacketError.prototype.name = 'BadPacketError';9var ChecksumError = exports.ChecksumError = function(msg, packetLength, constr) {10 Error.captureStackTrace(this, constr || this);11 this.message = msg || 'ChecksumError';12 this.packetLength = packetLength || 0;13};14util.inherits(ChecksumError, Error);...
Using AI Code Generation
1var checksum = require('checksum');2var fs = require('fs');3var path = require('path');4var file = path.join(__dirname, 'test.js');5checksum.file(file, function (err, sum) {6 if (err) {7 throw err;8 }9 console.log(sum);10 checksum.file(file, function (err, sum) {11 if (err instanceof checksum.ChecksumError) {12 }13 });14});
Using AI Code Generation
1var fs = require('fs');2var crypto = require('crypto');3var path = require('path');4var util = require('util');5var zlib = require('zlib');6var ReadStream = fs.ReadStream;7var WriteStream = fs.WriteStream;8var Transform = require('stream').Transform;9var ChecksumError = require('./checksum_error');10var readStream = new ReadStream(path.join(__dirname, 'data.txt'));11var checksum = crypto.createHash('sha1');12var transformStream = new Transform({13 transform: function(chunk, encoding, callback) {14 this.push(chunk);15 checksum.update(chunk);16 callback();17 }18});19var writeStream = new WriteStream(path.join(__dirname, 'data-copy.txt'));20var gzipStream = zlib.createGzip();21var unzipStream = zlib.createGunzip();22var checksumStream = new Transform({23 transform: function(chunk, encoding, callback) {24 checksum.update(chunk);25 this.push(chunk);26 callback();27 }28});29var checksumStream2 = new Transform({30 transform: function(chunk, encoding, callback) {31 checksum.update(chunk);32 this.push(chunk);33 callback();34 }35});36 .pipe(transformStream)37 .pipe(gzipStream)38 .pipe(unzipStream)39 .pipe(checksumStream)40 .pipe(writeStream)41 .on('finish', function() {42 var checksumValue = checksum.digest('hex');43 console.log('checksum', checksumValue);44 });45 .pipe(checksumStream2)46 .on('finish', function() {47 var checksumValue = checksum.digest('hex');48 console.log('checksum', checksumValue);49 });
Using AI Code Generation
1var ChecksumError = require('./error').ChecksumError;2var err = new ChecksumError('message', 'expected', 'actual');3console.log(err.message);4console.log(err.expected);5console.log(err.actual);6console.log(err.stack);
Using AI Code Generation
1var ChecksumError = require('./checksumerror.js');2var checksumError = new ChecksumError('ChecksumError', 'Invalid checksum');3console.log(checksumError.name);4console.log(checksumError.message);5console.log(checksumError.stack);6console.log(checksumError.toString());7console.log(checksumError instanceof Error);8console.log(checksumError instanceof ChecksumError);9var FileSizeError = require('./filesizeerror.js');10var fileSizeError = new FileSizeError('FileSizeError', 'File size exceeded');11console.log(fileSizeError.name);12console.log(fileSizeError.message);13console.log(fileSizeError.stack);14console.log(fileSizeError.toString());15console.log(fileSizeError instanceof Error);16console.log(fileSizeError instanceof FileSizeError);17var InvalidInputError = require('./invalidinputerror.js');18var invalidInputError = new InvalidInputError('InvalidInputError', 'Invalid input');19console.log(invalidInputError.name);20console.log(invalidInputError.message);21console.log(invalidInputError.stack);22console.log(invalidInputError.toString());23console.log(invalidInputError instanceof Error);24console.log(invalidInputError instanceof InvalidInputError);25var TimeoutError = require('./timeouterror.js');26var timeoutError = new TimeoutError('TimeoutError', 'Request timed out');27console.log(timeoutError.name);28console.log(timeoutError.message);29console.log(timeoutError.stack);30console.log(timeoutError.toString());31console.log(timeoutError instanceof Error);32console.log(timeoutError instanceof TimeoutError);33var UnknownError = require('./unknownerror.js');34var unknownError = new UnknownError('UnknownError', 'Unknown error occurred');35console.log(unknownError.name);36console.log(unknownError.message);37console.log(unknownError.stack);38console.log(unknownError.toString());39console.log(unknownError instanceof Error);40console.log(unknownError instanceof UnknownError);41var UnsupportedError = require('./unsupportederror.js');42var unsupportedError = new UnsupportedError('UnsupportedError', 'Unsupported operation');43console.log(unsupportedError.name);44console.log(unsupportedError.message);45console.log(unsupportedError.stack);46console.log(unsupportedError.toString());47console.log(unsupportedError instanceof Error);48console.log(unsupportedError instanceof UnsupportedError
Using AI Code Generation
1var fs = require('fs');2var data = 'This is a sample file';3fs.writeFile('sample.txt', data, (err) => {4 if (err) {5 console.log(err);6 } else {7 console.log('File written successfully\n');8 console.log('The written has the following contents:');9 console.log(fs.readFileSync('sample.txt', 'utf8'));10 }11});
Using AI Code Generation
1var checksum = require('./checksum.js');2var checksumError = checksum.ChecksumError;3var checksumError = new checksumError('Error Message');4console.log(checksumError.message);5console.log(checksumError.stack);6console.log(checksumError.name);7console.log(checksumError.toString());8var checksum = require('./checksum.js');9var checksumError = checksum.ChecksumError;10var checksumError = new checksumError('Error Message');11console.log(checksumError.message);12console.log(checksumError.stack);13console.log(checksumError.name);14console.log(checksumError.toString());15var checksum = require('./checksum.js');16var checksumError = checksum.ChecksumError;17var checksumError = new checksumError('Error Message');18console.log(checksumError.message);19console.log(checksumError.stack);20console.log(checksumError.name);21console.log(checksumError.toString());
Using AI Code Generation
1var checksum = require('./checksum.js');2var checksumError = checksum.ChecksumError;3var checksum = checksum.checksum;4var str = '123456789';5var str1 = '123456789';6var str2 = '1234567890';7var sum = checksum(str);8var sum1 = checksum(str1);9var sum2 = checksum(str2);10try {11 if(sum != sum1) {12 throw new checksumError('ChecksumError', 'checksums are not equal');13 }14 if(sum == sum2) {15 throw new checksumError('ChecksumError', 'checksums are equal');16 }17} catch (e) {18 console.log(e.name + ': ' + e.message);19}
Using AI Code Generation
1var ChecksumError = require('machinepack-checksum').errors.ChecksumError;2var newErr = new ChecksumError({3});4var newErr = new ChecksumError({5});6var newErr = new ChecksumError({7});8var newErr = new ChecksumError({9});10var newErr = new ChecksumError({11});12var newErr = new ChecksumError({13});14var newErr = new ChecksumError({15});16var newErr = new ChecksumError({17});
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!