Best Python code snippet using autotest_python
lookup.js
Source:lookup.js
...54 case Enum.LookupMode.ShippingAddress:55 this.Criteria = criteria;56 switch (this.ShippingMode) { 57 case "country":58 this.LoadCountryLookup();59 break;60 case "postal":61 this.LoadPostalLookup();62 break; 63 }64 break;65 default:66 this.LoadTransactions(criteria);67 break;68 69 }70 }71 },72 73 buttonSearch_tap : function(e) {74 var criteria = $("#textSearch").val();75 76 switch (this.LookupMode) {77 case Enum.LookupMode.Box:78 this.IsShowAllBoxes = false;79 this.LoadBoxes(criteria);80 break;81 case Enum.LookupMode.ShippingAddress:82 this.Criteria = criteria;83 switch (this.ShippingMode) { 84 case "country":85 this.LoadCountryLookup();86 break;87 case "postal":88 this.LoadPostalLookup();89 break;90 }91 break;92 default:93 this.LoadTransactions(criteria);94 break;95 } 96 }, 97 98 AnimateLookup: function (isAnimate) {99 this.ProgressScreen = Shared.ShowProgress(this.ProgressScreen, isAnimate, "lookupSection", false); 100 },101 AnimateBoxLookup: function (isAnimate) {102 if (isAnimate) {103 $('#buttonMoreLookup').html("loading..");104 }105 else {106 $('#buttonMoreLookup').html("load more");107 }108 },109 110 ClearCart : function() { 111 this.$("#cartListContainer tbody").html("");112 },113 GeneratePrePackButtonHTML: function () {114 return "<button id=\"buttonPrePack\" class=\"btn-belize\"> \115 <ul> \116 <li><i class=\"icon-archive icon-2\"></i></li> \117 <li><span>prepack</span></li> \118 <li><span id=\"textPrepackQuantities\">(0)</span></li> \119 </ul> \120 </button>";121 },122 123 GoBack : function(e) {124 window.location.hash = "dashboard";125 },126 HighLightItem: function (self, cartItemView, current) { 127 if (self.LookupMode != Enum.LookupMode.Shipment) {128 $("td").removeClass("highlight");129 $("." + cartItemView.cid).addClass("highlight"); 130 } else { 131 $("#icon" + cartItemView.cid).toggleClass("icon-ok shipment-icon-oncheck clear-padding");132 $("." + cartItemView.cid + " ul").toggleClass('listitem-3 listitem-6');133 $("." + cartItemView.cid).toggleClass("highlight");134 135 if ($("#icon" + cartItemView.cid).hasClass('icon-ok')) Global.CurrentTransactions.add(cartItemView.model);136 else Global.CurrentTransactions.remove(cartItemView.model);137 }138 //if (self.myLastTap == null) self.myLastTap = new Date().getTime();139 //var now = new Date().getTime();140 //var timeSince = (now - self.myLastTap);141 //if ((timeSince < 600) && (timeSince > 0)) {142 // var nowCID = cartItemView.cid;143 // var currentCID = null;144 switch (self.LookupMode)145 {146 case Enum.LookupMode.Box:147 self.CurrentBox = current;148 this.trigger("boxSelected", this);149 break;150 case Enum.LookupMode.ShippingAddress:151 this.trigger("itemSelected", current);152 default:153 if (self.CurrentTransaction == null) self.CurrentTransaction = current;154 if (self.LookupMode == Enum.LookupMode.Shipment155 || self.LookupMode == Enum.LookupMode.Pick156 || self.LookupMode == Enum.LookupMode.Pack) {157 Global.CurrentTransactions.add(cartItemView.model);158 }159 self.ProcessSelectedTransaction();160 break;161 }162 if (self.LookupMode != Enum.LookupMode.Box) {163 self.CurrentTransaction = current;164 self.CurrentTransaction.CID = cartItemView.cid;165 }166 self.myLastTap = new Date().getTime();167 },168 InitializeBoxCollection: function () {169 if (this.boxCollection) {170 this.boxCollection.reset();171 }172 else {173 this.boxCollection = new CartCollection();174 this.boxCollection.on("reset", this.ClearCart, this);175 }176 },177 InitializeLookupCollection: function () {178 if (this.lookupCollection) {179 this.lookupCollection.reset();180 }181 else {182 this.lookupCollection = new CartCollection();183 this.lookupCollection.on("reset", this.ClearCart, this);184 }185 },186 InitializeTransactionCollection: function () {187 if (this.transactionCollection) {188 this.transactionCollection.reset();189 }190 else {191 this.transactionCollection = new CartCollection();192 this.transactionCollection.on("reset", this.ClearCart, this);193 }194 },195 InitializeChildViews: function () { 196 if (this.LookupMode == Enum.LookupMode.Box) {197 this.RenderLookup();198 this.InitializeBoxCollection();199 this.LoadBoxes();200 }201 else if (this.LookupMode == Enum.LookupMode.ShippingAddress) {202 this.RenderLookup();203 this.InitializeLookupCollection();204 switch (this.ShippingMode) {205 case "country":206 this.LoadCountryLookup();207 break;208 case "postal":209 this.LoadPostalLookup();210 break;211 }212 }213 else {214 this.$el.html(this._template);215 this.RenderLookup();216 this.WireEvents();217 this.InitializeTransactionCollection();218 this.LoadTransactions();219 }220 Shared.Focus('#textSearch');221 },222 LoadBoxes: function (criteria) {223 var lookupModel = new LookupCriteriaModel();224 var self = this; 225 lookupModel.url = Global.ServiceUrl + Service.SOP + Method.CARRIERPACKAGINGLOOKUP;226 lookupModel.set({227 CarrierCode: this.CarrierCode,228 ShippingMethodCode: this.ShippingMethodCode,229 WarehouseCode: Global.CurrentLocation230 });231 232 if (criteria) lookupModel.set({ CriteriaString: criteria });233 var animateElem = "";234 if (this.IsShowAllBoxes) {235 animateElem = "buttonMoreLookup";236 lookupModel.set({ IsShowAllBoxes: true });237 $('#containerTable').removeClass('iscroll-lookup-2').addClass('iscroll-lookup');238 $('#buttonMoreLookup').hide();239 } else {240 animateElem = "lookupBody";241 lookupModel.set({ IsShowAllBoxes: false });242 this.ShowButtonMoreLookup();243 }244 this.AnimateBoxLookup(true);245 lookupModel.save(null, {246 success: function (model, response, options) {247 self.AnimateBoxLookup(false);248 if (!model.get("hasError")) {249 self.PopulateCartByBoxes(response.Packages);250 }251 },252 error: function (model, error, options) {253 self.ShowButtonMoreLookup();254 self.AnimateBoxLookup(false);255 }256 }); 257 },258 LoadCountryLookup: function () {259 var lookupModel = new LookupCriteriaModel();260 var self = this;261 lookupModel.url = Global.ServiceUrl + Service.CUSTOMER + Method.COUNTRYCODELOOKUP + "30";262 if (this.Criteria) {263 lookupModel.set({264 StringValue: this.Criteria265 });266 }267 this.AnimateLookup(true);268 lookupModel.save(null, {269 success: function (model, response, options) { 270 if (!model.get("hasError")) {271 self.PopulateCartByCountries(response.Countries);272 }273 },274 progress: this.ProgressScreen275 }); 276 },277 LoadPostalLookup: function () {278 var lookupModel = new LookupCriteriaModel();279 var self = this;280 lookupModel.url = Global.ServiceUrl + Service.CUSTOMER + Method.ZIPCODELOOKUP + "30/" + this.CountryCode;281 if (this.Criteria) {282 lookupModel.set({283 StringValue: this.Criteria284 });285 }286 this.AnimateLookup(true);287 lookupModel.save(null, {288 success: function (model, response, options) { 289 if (!model.get("hasError")) {290 self.PopulateCartByPostal(response.Postals);291 }292 },293 progress: this.ProgressScreen294 }); 295 },296 LoadiScroll: function () {297 this.myScroll = Shared.LoadiScroll(this.myScroll, "");298 },299 LoadPrePackItems: function (itemCount) {300 if (itemCount > 0) {301 Global.IsPrePackMode = true;302 Global.TransactionCode = "";303 if (this.LookupMode == Enum.LookupMode.Pick) window.location.hash = "pick";304 else if (this.LookupMode == Enum.LookupMode.Shipment) window.location.hash = "prepack";305 }306 else {307 Shared.BeepError();308 if (this.LookupMode == Enum.LookupMode.Pick) Shared.NotifyError("There are no items to pick.", "Prepack items");309 else if (this.LookupMode == Enum.LookupMode.Shipment) Shared.NotifyError("There are no labels to print.", "Prepack labels"); 310 }311 },312 LoadTransactions: function (criteria) {313 var lookupModel = new LookupCriteriaModel();314 var self = this; 315 316 switch (this.LookupMode) {317 case Enum.LookupMode.Pack:318 lookupModel.url = Global.ServiceUrl + Service.SOP + Method.PACKTRANSACTIONLOOKUP;319 lookupModel.set({ TransactionType: Preference.PackSourceTransaction });320 break;321 case Enum.LookupMode.Pick:322 lookupModel.url = Global.ServiceUrl + Service.SOP + Method.PICKTRANSACTIONLOOKUP; 323 lookupModel.set({324 TransactionType: Preference.PickSourceTransaction,325 IsPrePackMode: Preference.PrePackIsEnable326 }); 327 break;328 case Enum.LookupMode.Receive:329 lookupModel.url = Global.ServiceUrl + Service.PRODUCT + Method.RECEIVELOOKUP;330 break;331 case Enum.LookupMode.Stock:332 lookupModel.url = Global.ServiceUrl + Service.PRODUCT + Method.LOADGOODSRECEIVELOOKUP;333 break;334 case Enum.LookupMode.Shipment:335 lookupModel.url = Global.ServiceUrl + Service.SOP + Method.SHIPMENTLOOKUP;336 lookupModel.set({337 TransactionType: Preference.LabelSourceTransaction,338 HasTrackingNumber: false,339 IsPrePackMode: Preference.PrePackIsEnable340 });341 break; 342 };343 if (criteria) {344 lookupModel.set({ CriteriaString : criteria });345 }346 347 lookupModel.set({ WarehouseCode: Preference.DefaultLocation });348 349 this.AnimateLookup(true);350 lookupModel.save(null, {351 success: function (model, response, options) { 352 if (!model.get("hasError")) { 353 switch (self.LookupMode) {354 case Enum.LookupMode.Pack: 355 self.PopulateCartByTransaction(response.Packs, criteria, 0);356 break;357 case Enum.LookupMode.Pick:358 if (Preference.PrePackIsEnable) self.PopulateCartByTransaction(response.Picks, criteria, response.ItemCount);359 else self.PopulateCartByTransaction(response.Picks, criteria, 0);360 break;361 case Enum.LookupMode.Receive:362 self.PopulateCartByTransaction(response.PurchaseOrders, criteria, 0);363 break;364 case Enum.LookupMode.Stock:365 self.PopulateCartByTransaction(response.PurchaseReceiptCollection, criteria, 0);366 break;367 case Enum.LookupMode.Shipment:368 if (Preference.PrePackIsEnable) self.PopulateCartByTransaction(response.Packs, criteria, response.ItemCount);369 else self.PopulateCartByTransaction(response.Packs, criteria, 0);370 break;371 };372 }373 },374 progress: this.ProgressScreen375 }); 376 },377 378 ProcessSelectedTransaction : function() {379 if (this.CurrentTransaction) { 380 switch (this.LookupMode) {381 case Enum.LookupMode.Pack:382 Global.TransactionCode = this.CurrentTransaction.TransactionCode;383 window.location.hash = "pack";384 break;385 case Enum.LookupMode.Pick:386 Global.TransactionCode = this.CurrentTransaction.TransactionCode;387 window.location.hash = "pick";388 break;389 case Enum.LookupMode.Receive:390 Global.TransactionCode = this.CurrentTransaction.PurchaseOrderCode;391 window.location.hash = "receive";392 break;393 case Enum.LookupMode.Stock:394 Global.TransactionCode = this.CurrentTransaction.PurchaseReceiptCode;395 Global.TransferMode = "Stock";396 Global.PreviousPage = "stocklookup";397 window.location.hash = "stock";398 break;399 case Enum.LookupMode.Shipment:400 Global.TransactionCode = this.CurrentTransaction.TransactionCode;401 Global.PackMode = "Label";402 Global.PreviousPage = "shipmentlookup";403 window.location.hash = "label";404 break;405 }; 406 }407 },408 409 PopulateCartByCountries: function (countries) {410 this.lookupCollection.reset();411 if (countries && countries.length > 0) {412 var self = this;413 var counter = 1;414 _.each(countries, function (current) {415 if (countries.length == 1) { 416 self.trigger("itemSelected", current);417 } else {418 counter = counter + 1;419 var lookupItemModel = new CartItemModel();420 lookupItemModel.set({421 RowData1: current.CountryCode,422 RowData2: current.ThreeISOCode,423 RowData3: "",424 CountryCode: current.CountryCode,425 ThreeISOCode: current.ThreeISOCode,426 RowNumber: counter - 1427 });428 self.lookupCollection.add(lookupItemModel);429 var lookupItemView = new LookupItemView({ model: lookupItemModel });430 self.$("#cartListContainer tbody").append(lookupItemView.render());431 Shared.AddRemoveHandler("." + lookupItemView.cid, 'tap', function (e) { self.HighLightItem(self, lookupItemView, current); });432 }433 });434 this.LoadiScroll();435 }436 else Shared.BeepError();437 },438 PopulateCartByBoxes : function(packages) {439 this.boxCollection.reset();440 441 if (packages && packages.length > 0) {442 var self = this;443 var counter = 1;444 var criteria = $("#textSearch").val();445 var filterToAdd = Array();446 var len = packages.length447 while (len--) {448 var filterValue;449 var packagingType;450 var current = packages[len];451 packagingType = current.PackagingType == undefined ? null : current.PackagingType;452 packagingType = packagingType == null ? 'null' : packagingType.toString().toLowerCase();453 // filter by PackagingType454 filterValue = packagingType;455 if (filterToAdd.indexOf(filterValue) < 0) {456 filterToAdd.push(filterValue);457 }458 else {459 if (len > -1) packages.splice(len, 1);460 }461 }462 _.each(packages, function (current) {463 current.ServiceCode = current.ServiceType;464 current.PackagingCode = current.PackagingType;465 if (criteria && packages.length == 1) {466 self.CurrentBox = current; 467 self.trigger("boxSelected", self);468 } else { 469 counter = counter + 1;470 var boxModel = new CartItemModel();471 var dimension = current.Height + "x" + current.Length + "x" + current.Width472 boxModel.set({473 PackagingCode: current.PackagingCode,474 CarrierCode: current.CarrierCode,475 CarrierDescription: current.CarrierDescription,476 Dimension: dimension,477 Length: current.Length,478 Width: current.Width,479 Height: current.Height,480 WeightInLbs: current.WeightLbs,481 RowNumber: counter - 1, 482 ServiceCode: current.ServiceCode,483 IsCustom: current.IsCustom484 });485 self.boxCollection.add(boxModel);486 var boxItemView = new BoxItemView({ model: boxModel });487 self.$("#cartListContainer tbody").append(boxItemView.render());488 Shared.AddRemoveHandler("." + boxItemView.cid, 'tap', function (e) { self.HighLightItem(self, boxItemView, current); });489 }490 });491 this.LoadiScroll();492 }493 else Shared.BeepError();494 },495 PopulateCartByPostal: function (postals) {496 this.lookupCollection.reset();497 if (postals && postals.length > 0) {498 var self = this;499 var counter = 1;500 _.each(postals, function (current) {501 if (postals.length == 1) { 502 self.trigger("itemSelected", current);503 } else {504 counter = counter + 1;505 var lookupItemModel = new CartItemModel();506 lookupItemModel.set({507 RowData1: current.PostalCode,508 RowData2: current.City,509 RowData3: current.County,510 PostalCode: current.PostalCode,511 City: current.City,512 CountryCode: current.CountryCode,513 County: current.County,514 StateCode: current.StateCode,515 RowNumber: counter - 1516 });517 self.lookupCollection.add(lookupItemModel);518 var lookupItemView = new LookupItemView({ model: lookupItemModel });519 self.$("#cartListContainer tbody").append(lookupItemView.render());520 Shared.AddRemoveHandler("." + lookupItemView.cid, 'tap', function (e) { self.HighLightItem(self, lookupItemView, current); });521 }522 });523 this.LoadiScroll();524 }525 else Shared.BeepError();526 },527 PopulateCartByTransaction : function(transactions, lookupCriteria, itemCount) {528 this.transactionCollection.reset();529 var self = this;530 531 if ((this.LookupMode == Enum.LookupMode.Pick && Preference.PrePackIsEnable) || this.LookupMode == Enum.LookupMode.Shipment && Preference.PrePackIsEnable) {532 this.$("#cartListContainer tbody").append(this.GeneratePrePackButtonHTML());533 this.UpdatePrepackQuantities(itemCount);534 Shared.AddRemoveHandler('#buttonPrePack', 'tap', function () { self.LoadPrePackItems(itemCount); });535 } 536 if (transactions && transactions.length > 0) {537 if (transactions.length == 1) {538 var criteria = $("#textSearch").val();539 if (criteria != null && criteria != "") {540 this.CurrentTransaction = transactions[0];541 this.ProcessSelectedTransaction();542 return true;543 }544 }545 this.$("#textSearch").val("");546 var counter = 1;547 _.each(transactions, function (current) {548 counter = counter + 1;549 var transactionModel = new CartItemModel();550 switch (self.LookupMode) {551 case Enum.LookupMode.Pack:552 case Enum.LookupMode.Pick:553 var dueDate = "Ship: " + Shared.FormatDate(current.ShippingDate, "L");554 var salesOrderDate = Shared.FormatDate(current.TransactionDate, "L");555 transactionModel.set({556 TransactionCode: current.TransactionCode,557 CustomerCode: current.BillToCode,558 Name: current.BillToName,559 BillToCode: current.BillToCode,560 BillToName: current.BillToName,561 ShiptoCode: current.ShiptoCode,562 ShippingDate: current.ShippingDate,563 SalesOrderDate: current.TransactionDate,564 Date: salesOrderDate,565 WarehouseCode: current.WarehouseCode,566 Status: dueDate,567 RowNumber: counter - 1,568 IsPriority: current.IsPriority569 });570 if (self.LookupMode == Enum.LookupMode.Pack) transactionModel.set({ ServiceCode: current.ServiceCode });571 Global.CurrentTransactions = new CartCollection();572 break;573 case Enum.LookupMode.Receive:574 var poDate = Shared.FormatDate(current.PODate, "L");575 transactionModel.set({576 TransactionCode: current.PurchaseOrderCode,577 SupplierCode: current.SupplierCode,578 Name: current.SupplierName,579 Status: current.OrderStatus,580 Date: poDate,581 RowNumber: counter - 1,582 IsPriority: null583 });584 break;585 case Enum.LookupMode.Stock:586 var poDate = Shared.FormatDate(current.PRDate, "L");587 transactionModel.set({588 TransactionCode: current.PurchaseReceiptCode,589 SupplierCode: current.SupplierName,590 Name: current.SupplierName,591 Status: "",592 Date: poDate,593 RowNumber: counter - 1,594 IsPriority: null595 });596 break;597 case Enum.LookupMode.Shipment:598 var shipmentDate = Shared.FormatDate(current.ShipmentDate, "L");599 transactionModel.set({600 TransactionCode: current.TransactionCode, 601 ShipFromName: current.ShipFromName,602 ShipToName: current.ShipToName,603 Date: shipmentDate,604 RowNumber: counter - 1,605 isChecked: false,606 ShipmentView: null,607 IsPriority: null608 });609 Global.CurrentTransactions = new CartCollection();610 break;611 }612 self.transactionCollection.add(transactionModel);613 var itemView = null;614 if (self.LookupMode == Enum.LookupMode.Shipment) itemView = new ShipmentItemView({ model: transactionModel });615 else itemView = new CartItemView({ model: transactionModel });616 self.$("#cartListContainer tbody").append(itemView.render());617 Shared.AddRemoveHandler("." + itemView.cid, 'tap', function (e) { self.HighLightItem(self, itemView, current); });618 });619 }620 else {621 if (lookupCriteria && lookupCriteria != "") {622 Shared.BeepError();623 }624 }625 this.LoadiScroll();626 }, 627 628 Render: function () {629 return this.$el.html(this._template);630 },631 RenderLookup: function () {632 this.$('#buttonNew').hide();633 this.$('#buttonBack').hide();634 this.$('#buttonMoreLookup').hide();635 this.$('#buttonSlideDown').hide();636 switch (this.LookupMode) {637 case Enum.LookupMode.Pick:638 if (Preference.PickSourceTransaction == "invoice") this.$('#lookupTitle').text('select invoice');639 else this.$('#lookupTitle').text('select order');640 break;641 case Enum.LookupMode.Pack:642 if (Preference.PackSourceTransaction == "invoice") this.$('#lookupTitle').text('select invoice');643 else this.$('#lookupTitle').text('select order');644 break;645 case Enum.LookupMode.Receive:646 this.$('#lookupTitle').text('purchase orders');647 break;648 case Enum.LookupMode.Stock:649 this.$('#lookupTitle').text('goods received');650 this.$('#buttonNew').show();651 var newStock = function (e) {652 Global.TransferMode = "NewStock";653 Global.PreviousPage = "stocklookup";654 window.location.hash = "stock";655 };656 Shared.AddRemoveHandler('#buttonNew', 'tap', newStock);657 break;658 case Enum.LookupMode.Shipment:659 this.$('#lookupTitle').text('shipments'); 660 break;661 case Enum.LookupMode.Box:662 var self = this;663 this.$('#lookupTitle').text('select box to add');664 this.$('#buttonMenu').hide();665 this.$('#buttonBack').show();666 this.$('#buttonMoreLookup').show();667 this.$('#containerTable').removeClass('iscroll-lookup').addClass('iscroll-lookup-2');668 this.$('#textSearch').attr('placeholder', 'enter box to search');669 Shared.AddRemoveHandler('#buttonBack', 'tap', function (e) { self.ShowPackSection(e); });670 Shared.AddRemoveHandler('#buttonSearch', 'tap', function (e) { self.buttonSearch_tap(e); });671 Shared.AddRemoveHandler('#buttonMoreLookup', 'tap', function (e) {672 self.IsShowAllBoxes = true;673 self.LoadBoxes(null);674 });675 break;676 case Enum.LookupMode.ShippingAddress:677 var self = this;678 this.$('#lookupSection').addClass("slideDownReady");679 680 switch (this.ShippingMode) {681 case "country":682 this.$('#lookupTitle').text('select a country');683 this.$('#textSearch').attr('placeholder', 'enter country to search');684 break;685 case "postal":686 this.$('#lookupTitle').text('select a postal');687 this.$('#textSearch').attr('placeholder', 'enter postal to search');688 break;689 }690 this.$('#buttonMenu').hide();691 this.$('#buttonSlideDown').show();692 Shared.AddRemoveHandler('#buttonSearch', 'tap', function (e) { self.buttonSearch_tap(e); });693 Shared.AddRemoveHandler('#buttonSlideDown', 'tap', function (e) { self.SlideDownLookup(e); });694 break;695 } 696 },697 ShowButtonMoreLookup: function () {698 $('#containerTable').removeClass('iscroll-lookup').addClass('iscroll-lookup-2');699 $('#buttonMoreLookup').show();700 },701 702 ShowPackSection: function () {703 $('#packSection').show();704 $('#lookupSectionContainer').removeClass('section-show').addClass('section-close');705 $('#boxSectionContainer').removeClass('section-show').addClass('section-close'); 706 },707 SlideDownLookup: function () {...
fieldlookup.js
Source:fieldlookup.js
...298 var prevLookup = null299 if (ACTIVATED_LOOKUP) {300 prevLookup = ACTIVATED_LOOKUP;301 }302 _activateLookup(_lookupId);303 GLOBAL_LOOKUP_REF.getReference(ACTIVATED_LOOKUP).prevLookup = prevLookup;304 }305 function _activateLookup(newAl) {306 if (ACTIVATED_LOOKUP != newAl) {307 ACTIVATED_LOOKUP = newAl;308 }309 }310 function _addCloseEventForClickingOnBackgroundLayer() {311 _backgroundCloseClickEvent = function() {312 if (ACTIVATED_LOOKUP && ACTIVATED_LOOKUP == _lookupId) {313 GLOBAL_LOOKUP_REF.getReference(ACTIVATED_LOOKUP).dialogRef.dialog("close");314 }315 }316 jQuery(".ui-widget-overlay").click(_backgroundCloseClickEvent);317 }318 function _dialogClose() {319 jQuery(".ui-widget-overlay").unbind("click", _backgroundCloseClickEvent)320 var prevLookup = null;321 if (ACTIVATED_LOOKUP) {322 prevLookup = GLOBAL_LOOKUP_REF.getReference(ACTIVATED_LOOKUP).prevLookup;323 }324 if (prevLookup) {325 _activateLookup(prevLookup);326 } else {327 ACTIVATED_LOOKUP = null;328 }329 }330 function _addOpenEvent(dialogReference) {331 jQuery("#" + _lookupId + "_button").click(function() {332 dialogReference.dialog("open");333 GLOBAL_LOOKUP_REF.getReference(_lookupId).target = jQuery(options.dialogTarget);334 if (options.dialogOptionalTarget != null) {335 GLOBAL_LOOKUP_REF.getReference(_lookupId).target2 = jQuery(options.dialogOptionalTarget);336 }337 });338 }339 return {340 init : _init341 }342};343/*******************************************************************************344 * Lookup Counter Object345 ******************************************************************************/346var FieldLookupCounter = function() {347 this.refArr = {};348 this.setReference = function(key, ref) {349 // if key doesn't exist in the array and350 var itm;351 for (itm in this.refArr) {352 if (itm == key) {353 prefix = key.substring(0, key.indexOf("_"));354 key = prefix + "_" + key;355 this.refArr["" + key + ""] = ref;356 return this.refArr[key];357 }358 }359 this.refArr["" + key + ""] = ref;360 return this.refArr[key];361 };362 this.getReference = function(key) {363 // when key does not exist return null?364 return this.refArr[key] != null ? this.refArr[key] : null;365 };366 this.getLastReference = function() {367 return (this.countFields() - 1) + "_lookupId";368 }369 this.createNextKey = function() {370 return this.countFields() + "_lookupId";371 };372 this.countFields = function() {373 var count = 0;374 jQuery.each(this.refArr, function(itm) {375 count++;376 });377 return count;378 };379 this.removeReference = function(key) {380 // deletes the Array entry (doesn't effect the array length)381 delete this.refArr[key];382 };383};384var GLOBAL_LOOKUP_REF = new FieldLookupCounter();385/*******************************************************************************386 * Button Modifier Object387 ******************************************************************************/388var ButtonModifier = function(lookupDiv) {389 function _modifyLookupLinks() {390 if (!lookupDiv) {391 return;392 }393 _modifyCollapseable();394 _modifySubmitButton();395 _modifyPagination();396 _modifyResultTable();397 }398 function _modifyCollapseable() {399 var slTitleBars = jQuery("#" + lookupDiv + " .screenlet-title-bar");400 jQuery.each(slTitleBars, function(index) {401 var slTitleBar = slTitleBars[index];402 var ul = slTitleBar.firstChild;403 if ((typeof ul) != 'object') {404 return true;405 }406 var childElements = ul.childNodes;407 for (j in childElements) {408 if (childElements[j].className == 'expanded' || childElements[j].className == 'collapsed') {409 break;410 }411 }412 _getNextCollapseSeq();413 var childEle = childElements[j].firstChild;414 childEle.setAttribute('onclick', "javascript:toggleScreenlet(this, 'lec" + COLLAPSE_SEQUENCE_NUMBER415 + "', 'true', 'Expand', 'Collapse');");416 childEle.href = "javascript:void(0);"417 jQuery(slTitleBar).next('div').attr('id', 'lec' + COLLAPSE_SEQUENCE_NUMBER);418 });419 }420 function _getNextCollapseSeq() {421 COLLAPSE_SEQUENCE_NUMBER++;422 return COLLAPSE_SEQUENCE_NUMBER;423 }424 function _modifySubmitButton() {425 var lookupForm = jQuery("#" + lookupDiv + " form:first");426 // set new form name and id427 var oldFormName = lookupForm.attr("name");428 lookupForm.attr("name", "form_" + lookupDiv);429 lookupForm.attr("id", "form_" + lookupDiv);430 lookupForm = jQuery("#form_" + lookupDiv);431 // set new links for lookups432 var newLookups = jQuery("#" + lookupDiv + " .field-lookup");433 var formAction = lookupForm.attr("action");434 // remove the form action435 lookupForm.attr("action", "");436 var input = jQuery("#" + lookupDiv + " input[type=submit]").css({437 display : "block"438 });439 // remove the original input button and replace with a new one440 var txt = input.attr("value");441 (input.parent()).append(jQuery("<button/>", {442 id : "lookupSubmitButton",443 href : "javascript:void(0);",444 click : function() {445 lookupFormAjaxRequest(formAction, lookupForm.attr("id"));446 return false;447 },448 text : txt449 }));450 input.remove();451 }452 function _modifyPagination() {453 // modify nav-pager454 var navPagers = jQuery("#" + lookupDiv + " .nav-pager a");455 jQuery.each(navPagers, function(navPager) {456 var onClickEvent = navPagers[navPager].onclick;457 navPagers[navPager].onclick = function(){458 this.setAttribute("data-lookupajax", "true");459 onClickEvent.apply(this);460 }461 });462 var navPagersSelect = jQuery("#" + lookupDiv + " .nav-pager select");463 jQuery.each(navPagersSelect, function(navPager) {464 var onChangeEvent = navPagersSelect[navPager].onchange;465 navPagersSelect[navPager].onchange = function(){466 this.setAttribute("data-lookupajax", "true");467 onChangeEvent.apply(this);468 }469 });470 }471 function _modifyResultTable() {472 var resultTable = jQuery("#" + lookupDiv + " #search-results table:first tbody");473 var tableChilds = resultTable.children();474 jQuery.each(tableChilds, function(tableChild) {475 var childElements = jQuery(tableChilds[tableChild]);476 var tableRows = childElements.children();477 jQuery.each(tableRows, function(cell) {478 var cellChilds = jQuery(tableRows[cell]).children();479 jQuery.each(cellChilds, function(child) {480 if (cellChilds[child].tagName == "A") {481 var link = cellChilds[child].href;482 if (link.indexOf("javascript:set_") != -1) {483 cellChilds[child].href = link;484 } else {485 var liSub = link.substring(link.lastIndexOf('/') + 1, (link.length));486 cellChilds[child].href = "javascript:lookupAjaxRequest('" + liSub + "&presentation=layer')";487 }488 }489 });490 });491 });492 }493 return {494 modifyLookupLinks : _modifyLookupLinks495 }496}497/*******************************************************************************498 * Ajax Request Helper499 ******************************************************************************/500function lookupAjaxRequest(request) {501 // get request arguments502 var arg = request.substring(request.indexOf('?') + 1, (request.length));503 request = request.substring(0, request.indexOf('?'));504 lookupId = GLOBAL_LOOKUP_REF.getReference(ACTIVATED_LOOKUP).lookupId;505 jQuery("#" + lookupId).load(request, arg, function(data) {506 new ButtonModifier(lookupId).modifyLookupLinks();507 });508}509function lookupFormAjaxRequest(formAction, form) {510 var lookupId = GLOBAL_LOOKUP_REF.getReference(ACTIVATED_LOOKUP).lookupId;511 var data = jQuery("#" + form).serialize();512 data = data + "&presentation=" + GLOBAL_LOOKUP_REF.getReference(ACTIVATED_LOOKUP).presentation;513 var screenletTitleBar = jQuery("#" + lookupId + " .screenlet-title-bar :visible:first");514 jQuery.ajax({515 url : formAction,516 type: "POST",517 data : data,518 beforeSend : function(jqXHR, settings) {519 // Here we append the spinner to the lookup screenlet and it will520 // shown till the ajax request is processed.521 var indicator = screenletTitleBar.find("span.indicator");522 // Check that if spinner is already in execution then don't add new523 // spinner524 if (indicator.length == 0) {525 jQuery("<span class='indicator'><img src='/images/ajax-loader.gif' alt='' /></span>").appendTo(screenletTitleBar);526 }527 },528 success : function(result) {529 if (result.search(/loginform/) != -1) {530 window.location.href = window.location.href;531 return;532 }533 // Here we are removing the spinner.534 var indicator = screenletTitleBar.find("span.indicator");535 if (indicator != undefined) {536 jQuery("span.indicator").remove();537 }538 jQuery("#" + lookupId).html(result);539 new ButtonModifier(lookupId).modifyLookupLinks();540 }541 });542}543function lookupPaginationAjaxRequest(navAction, type) {544 var lookupDiv = (GLOBAL_LOOKUP_REF.getReference(ACTIVATED_LOOKUP).divRef);545 var lookupContent = (GLOBAL_LOOKUP_REF.getReference(ACTIVATED_LOOKUP).contentRef);546 var lookupId = GLOBAL_LOOKUP_REF.getReference(ACTIVATED_LOOKUP).lookupId;547 var screenletTitleBar = jQuery("#" + lookupId + " .screenlet-title-bar :visible:first");548 jQuery.ajax({549 url : navAction.substring(0, navAction.indexOf("?")),550 type : "POST",551 data : navAction.substring(navAction.indexOf("?")+1, navAction.length),552 beforeSend : function(jqXHR, settings) {553 // Here we append the spinner to the lookup screenlet and it will554 // shown till the ajax request is processed.555 var indicator = screenletTitleBar.find("span.indicator");556 // Check that if spinner is already in execution then don't add new557 // spinner558 if (indicator.length == 0) {559 jQuery("<span class='indicator'><img src='/images/ajax-loader.gif' alt='' /></span>").appendTo(screenletTitleBar);560 }561 },562 success : function(result) {563 if (result.search(/loginform/) != -1) {564 window.location.href = window.location.href;565 return;566 }567 // Here we are removing the spinner.568 var indicator = screenletTitleBar.find("span.indicator");569 if (indicator != undefined) {570 jQuery("span.indicator").remove();571 }572 jQuery("#" + lookupId).html(result);573 new ButtonModifier(lookupId).modifyLookupLinks();574 }575 });576}577/*******************************************************************************578 * This code inserts the value lookedup by a popup window back into the579 * associated form element580 ******************************************************************************/581var re_id = new RegExp('id=(\\d+)');582var num_id = (re_id.exec(String(window.location)) ? new Number(RegExp.$1) : 0);583var obj_caller;584try {585 obj_caller = (window.opener && window.opener.lookups? window.opener.lookups[num_id]: null);586 if (obj_caller == null && window.opener != null) {587 obj_caller = window.opener;588 } else if (obj_caller == null && window.opener == null) {589 obj_caller = parent;590 }591}592catch (err) {593 obj_caller = parent;594 if (console) {595 console.log(err);596 }597}598function setSourceColor(src) {599 if (src && src != null) {600 src.effect("highlight", {}, 3000);601 }602}603// function passing selected value to calling window, using only in the604// TimeDuration case605function set_duration_value(value) {606 if (GLOBAL_LOOKUP_REF.getReference(ACTIVATED_LOOKUP)) {607 obj_caller.target = GLOBAL_LOOKUP_REF.getReference(ACTIVATED_LOOKUP).target;608 } else {609 obj_caller.target = jQuery(obj_caller.targetW);610 }611 var target = obj_caller.target;612 write_value(value, target);613 closeLookup();614}615// function passing selected value to calling window616function set_value(value) {617 if (GLOBAL_LOOKUP_REF.getReference(ACTIVATED_LOOKUP)) {618 obj_caller.target = GLOBAL_LOOKUP_REF.getReference(ACTIVATED_LOOKUP).target;619 } else {620 obj_caller.target = jQuery(obj_caller.targetW);621 }622 var target = obj_caller.target;623 write_value(value, target);624 closeLookup();625}626// function passing selected value to calling window627function set_values(value, value2) {628 if (GLOBAL_LOOKUP_REF.getReference(ACTIVATED_LOOKUP)) {629 obj_caller.target = GLOBAL_LOOKUP_REF.getReference(ACTIVATED_LOOKUP).target;630 obj_caller.target2 = GLOBAL_LOOKUP_REF.getReference(ACTIVATED_LOOKUP).target2;631 } else {632 obj_caller.target = jQuery(obj_caller.targetW);633 }634 var target = obj_caller.target;635 var target2 = obj_caller.target2;636 write_value(value, target);637 write_value(value2, target2)638 var showDescription = GLOBAL_LOOKUP_REF.getReference(ACTIVATED_LOOKUP) ? GLOBAL_LOOKUP_REF.getReference(ACTIVATED_LOOKUP).showDescription : false;639 if (showDescription) {640 setLookDescription(target.attr("id"), value + " " + value2, "", "", showDescription);641 }642 closeLookup();643}644function write_value(value, target) {645 if (target && target != null) {646 setSourceColor(target);647 target.val(value);648 target.trigger("lookup:changed");649 }650}651function set_multivalues(value) {652 obj_caller.target.value = value;653 field = jQuery("#" + target.attr('id'));654 field.trigger("lookup:changed");655 /*656 * If we decide to keep it (only used in Example, though it's needed also657 * for Themes and Languages but not the same way)658 */659 if (field.change != null) {660 field.click().change()661 }662 var thisForm = obj_caller.target.form;663 var evalString = "";664 if (arguments.length > 2) {665 for ( var i = 1; i < arguments.length; i = i + 2) {666 evalString = "setSourceColor(thisForm." + arguments[i] + ")";667 eval(evalString);668 evalString = "thisForm." + arguments[i] + ".value='" + arguments[i + 1] + "'";669 eval(evalString);670 }671 }672 closeLookup();673}674// close the window after passing the value675function closeLookup() {676 if (window.opener != null && GLOBAL_LOOKUP_REF.getReference(ACTIVATED_LOOKUP) == null) {677 window.close();678 } else {679 var lookupId = GLOBAL_LOOKUP_REF.getReference(ACTIVATED_LOOKUP).lookupId;680 jQuery("#" + lookupId).dialog("close");681 }682}683/*******************************************************************************684 * Lookup Description Helper685 ******************************************************************************/686// load description for lookup fields687var lookupDescriptionLoaded = function(fieldId, url, params, formName) {688 this.init(fieldId, url, params, formName);689}...
dawg.test.js
Source:dawg.test.js
1var test = require('tape');2var request = require('request');3var queue = require('queue-async');4var zlib = require('zlib');5var forOf = require('es6-iterator/for-of');6require('collections/collections.js');7var jsdawg = require("../index");8test('DAWG test invalid usage', function (t) {9 var dawg = new jsdawg.Dawg();10 t.throws(function() { dawg.insert(null) }, /first argument must be a String/, "validates inserted value");11 t.throws(function() { dawg.insert({}) }, /first argument must be a String/, "validates inserted value");12 t.throws(function() { dawg.insert(1.0) }, /first argument must be a String/, "validates inserted value");13 t.throws(function() { dawg.insert(function(){}) }, /first argument must be a String/, "validates inserted value");14 t.throws(function() { dawg.lookup(null) }, /first argument must be a String/, "validates inserted value");15 t.throws(function() { dawg.lookupPrefix(null) }, /first argument must be a String/, "validates inserted value");16 t.throws(function() { dawg.insert('') }, /empty string passed to insert/, "validates inserted value");17 dawg.finish();18 var compactDawg = dawg.toCompactDawg();19 t.assert(compactDawg.lookup() == '');20 t.assert(compactDawg.lookupPrefix() == '');21 t.assert(compactDawg.lookup({}) == '');22 t.assert(compactDawg.lookupPrefix({}) == '');23 t.end();24});25var resp, dawg, wordSet;26var words = [];27test('Prepare for DAWG tet', function (t) {28 var q = queue();29 ['test_words.txt.gz', 'nonlatin_words.txt.gz'].forEach(function(file) {30 q.defer(function(callback) {31 request.get({url: "http://mapbox.s3.amazonaws.com/apendleton/" + file, encoding: null}, function(err, response, body) {32 if (err) throw "S3 fetch failed";33 zlib.gunzip(body, function(err, data) {34 if (err) throw ("Zlib decompression failed: " + err);35 resp = data.toString();36 words = words.concat(resp.trim().split("\n"));37 callback();38 })39 })40 });41 });42 q.awaitAll(function() {43 words.sort();44 t.end();45 });46});47test('Read-write DAWG test', function(t) {48 wordSet = FastSet(words);49 dawg = new jsdawg.Dawg();50 for (var i = 0; i < words.length; i++) {51 dawg.insert(words[i]);52 }53 t.pass("dawg created");54 var exactLookup = true;55 for (var i = 0; i < words.length; i++) {56 exactLookup = exactLookup && dawg.lookup(words[i]);57 }58 t.assert(exactLookup, "dawg contains all words");59 var prefixLookup = true;60 for (var i = 0; i < words.length; i++) {61 prefixLookup = prefixLookup && dawg.lookupPrefix(words[i]);62 }63 t.assert(prefixLookup, "dawg contains all words as prefixes");64 var prefixLookup = true;65 for (var i = 0; i < words.length; i++) {66 if (words[i].length == 1) continue;67 var prefix = words[i].substring(0, words[i].length - 1);68 prefixLookup = prefixLookup && dawg.lookupPrefix(prefix);69 }70 t.assert(prefixLookup, "dawg contains prefixes of all words as prefixes");71 var lookupFailure = true;72 for (var i = 0; i < words.length; i++) {73 if (dawg.lookup(words[i] + "qzz") || dawg.lookupPrefix(words[i] + "qzz")) console.log(words[i]);74 lookupFailure = lookupFailure && (!dawg.lookup(words[i] + "qzz"));75 lookupFailure = lookupFailure && (!dawg.lookupPrefix(words[i] + "qzz"));76 }77 t.assert(lookupFailure, "dawg does not contain any words with 'qzz' added to the end as term or prefix");78 var prefixLookup = true;79 for (var i = 0; i < words.length; i++) {80 if (words[i].length == 1) continue;81 var prefix = words[i].substring(0, words[i].length - 1);82 // if this prefix is also a word, skip83 if (wordSet.contains(prefix)) continue;84 prefixLookup = prefixLookup && (!dawg.lookup(prefix));85 }86 t.assert(prefixLookup, "dawg does not contain prefixes of all words as terms");87 t.assert(!dawg.lookup(""), "dawg does not contain the empty string as a term");88 t.assert(dawg.lookupPrefix(""), "dawg does contain the empty string as a prefix");89 t.end();90});91test('Compact DAWG test', function(t) {92 dawg.finish();93 var compactDawg = dawg.toCompactDawg(false);94 t.pass("compact dawg created")95 var exactLookup = true;96 for (var i = 0; i < words.length; i++) {97 exactLookup = exactLookup && compactDawg.lookup(words[i]);98 }99 t.assert(exactLookup, "compact dawg contains all words");100 var prefixLookup = true;101 for (var i = 0; i < words.length; i++) {102 prefixLookup = prefixLookup && compactDawg.lookupPrefix(words[i]);103 }104 t.assert(prefixLookup, "compact dawg contains all words as prefixes");105 var prefixLookup = true;106 for (var i = 0; i < words.length; i++) {107 if (words[i].length == 1) continue;108 var prefix = words[i].substring(0, words[i].length - 1);109 prefixLookup = prefixLookup && compactDawg.lookupPrefix(prefix);110 }111 t.assert(prefixLookup, "compact dawg contains prefixes of all words as prefixes");112 var compactDawgWords = [];113 var compactDawg = dawg.toCompactDawg();114 forOf(compactDawg, function(value) { compactDawgWords.push(value); });115 var iteratorLookup = true;116 for (var i = 0; i < words.length; i++) {117 iteratorLookup = iteratorLookup && (words[i] == compactDawgWords[i]);118 }119 t.assert(iteratorLookup, "compact dawg iterator reproduces original list");120 var prefixWords = [];121 var prefixIterator = compactDawg.iterator("test");122 var priNext = prefixIterator.next();123 while (!priNext.done) {124 prefixWords.push(priNext.value);125 priNext = prefixIterator.next();126 }127 t.equal(prefixWords.length, 82, "got 82 results for prefix 'test'");128 t.assert(prefixWords.indexOf("test") == 0, "submitted prefix 'test' is included in results");129 var prefixWords = [];130 var prefixIterator = compactDawg.iterator("é¿");131 var priNext = prefixIterator.next();132 while (!priNext.done) {133 prefixWords.push(priNext.value);134 priNext = prefixIterator.next();135 }136 t.equal(prefixWords.length, 9, "got 82 results for prefix 'é¿'");137 t.assert(prefixWords.indexOf("é¿") == -1, "submitted prefix 'é¿' is not included in results");138 var prefixWords = [];139 var prefixIterator = compactDawg.iterator("testac");140 var priNext = prefixIterator.next();141 while (!priNext.done) {142 prefixWords.push(priNext.value);143 priNext = prefixIterator.next();144 }145 t.equal(prefixWords.length, 7, "got 7 results for prefix 'testac'");146 t.assert(prefixWords.indexOf("testac") == -1, "submitted prefix 'testac' is not included in results");147 var prefixWords = [];148 var prefixIterator = compactDawg.iterator("testaaa");149 var priNext = prefixIterator.next();150 while (!priNext.done) {151 prefixWords.push(priNext.value);152 priNext = prefixIterator.next();153 }154 t.equal(prefixWords.length, 0, "got 0 results for prefix 'testaaa'");155 var lookupFailure = true;156 for (var i = 0; i < words.length; i++) {157 lookupFailure = lookupFailure && (!compactDawg.lookup(words[i] + "qzz"));158 lookupFailure = lookupFailure && (!compactDawg.lookupPrefix(words[i] + "qzz"));159 }160 t.assert(lookupFailure, "compact dawg does not contain any words with 'qzz' added to the end as term or prefix");161 var prefixLookup = true;162 for (var i = 0; i < words.length; i++) {163 if (words[i].length == 1) continue;164 var prefix = words[i].substring(0, words[i].length - 1);165 // if this prefix is also a word, skip166 if (wordSet.contains(prefix)) continue;167 prefixLookup = prefixLookup && (!compactDawg.lookup(prefix));168 }169 t.assert(prefixLookup, "compact dawg does not contain prefixes of all words as terms");170 t.assert(!compactDawg.lookup(""), "compact dawg does not contain the empty string as a term");171 t.assert(compactDawg.lookupPrefix(""), "compact dawg does contain the empty string as a prefix");172 t.end();173});174test('Compact DAWG test with embedded counts', function(t) {175 dawg.finish();176 var compactDawg = dawg.toCompactDawg(true);177 t.pass("compact dawg created with counts")178 var exactLookup = true;179 var exactIndexes = true;180 for (var i = 0; i < words.length; i++) {181 var match = compactDawg.lookupCounts(words[i]);182 exactLookup = exactLookup && match.found;183 exactIndexes = exactIndexes && (match.index == i);184 }185 t.assert(exactLookup, "compact dawg contains all words");186 t.assert(exactIndexes, "compact dawg's indexes match insertion word order");187 var inverseLookup = true;188 var inverseText = true;189 for (var i = 0; i < words.length; i++) {190 var match = compactDawg.lookupCounts(i);191 inverseLookup = inverseLookup && match.found;192 inverseText = inverseText && (match.text == words[i]);193 }194 t.assert(inverseLookup, "compact dawg lookup by index retrieves all words");195 t.assert(inverseText, "compact dawg retrieved word text is correct");196 var prefixLookup = true;197 var prefixIndexes = true;198 for (var i = 0; i < words.length; i++) {199 var match = compactDawg.lookupPrefixCounts(words[i]);200 prefixLookup = prefixLookup && match.found;201 prefixIndexes = prefixIndexes && (match.index == i);202 }203 t.assert(prefixLookup, "compact dawg contains all words as prefixes");204 t.assert(prefixIndexes, "compact dawg's indexes match insertion word order on prefix lookup");205 var prefixLookup = true;206 var prefixIndexes = true;207 for (var i = 0; i < words.length; i++) {208 if (words[i].length == 1) continue;209 var prefix = words[i].substring(0, words[i].length - 1);210 var match = compactDawg.lookupPrefixCounts(prefix);211 // here we would expect either the indexes to match, or the index that is returned212 // to be lower and to point to a word that shares a prefix213 prefixIndexes = prefixIndexes && (214 match.index == i ||215 (match.index < i && words[match.index].substring(0, prefix.length) == prefix)216 );217 prefixLookup = prefixLookup && match.found;218 }219 t.assert(prefixLookup, "compact dawg contains prefixes of all words as prefixes");220 t.assert(prefixIndexes, "compact dawg prefixes have expected indexes");221 var testMatch = compactDawg.lookupPrefixCounts("test");222 t.assert(testMatch.found, "'test' found");223 t.assert(testMatch.index == words.indexOf("test"), "'test' index is correct");224 t.assert(testMatch.suffixCount == 82, "'test' has 82 suffixes");225 var blea_idx;226 for (blea_idx = 0; blea_idx < words.length; blea_idx++) {227 if (words[blea_idx].substr(0, 4) == 'blea') break;228 }229 var blea_count = 0;230 while (words[blea_idx + blea_count].substr(0, 4) == 'blea') blea_count += 1;231 testMatch = compactDawg.lookupPrefixCounts("blea");232 t.assert(testMatch.found, "'blea' found");233 t.assert(testMatch.index == blea_idx, "'blea' index is correct");234 t.assert(testMatch.suffixCount == blea_count, "'blea' has correct number of suffixes");235 var compactDawgWords = [];236 var compactDawg = dawg.toCompactDawg();237 forOf(compactDawg, function(value) { compactDawgWords.push(value); });238 var iteratorLookup = true;239 for (var i = 0; i < words.length; i++) {240 iteratorLookup = iteratorLookup && (words[i] == compactDawgWords[i]);241 }242 t.assert(iteratorLookup, "compact dawg iterator reproduces original list");243 var prefixWords = [];244 var prefixIterator = compactDawg.iterator("test");245 var priNext = prefixIterator.next();246 while (!priNext.done) {247 prefixWords.push(priNext.value);248 priNext = prefixIterator.next();249 }250 t.equal(prefixWords.length, 82, "got 82 results for prefix 'test'");251 t.assert(prefixWords.indexOf("test") == 0, "submitted prefix 'test' is included in results");252 var prefixWords = [];253 var prefixIterator = compactDawg.iterator("é¿");254 var priNext = prefixIterator.next();255 while (!priNext.done) {256 prefixWords.push(priNext.value);257 priNext = prefixIterator.next();258 }259 t.equal(prefixWords.length, 9, "got 9 results for prefix 'é¿'");260 t.assert(prefixWords.indexOf("é¿") == -1, "submitted prefix 'é¿' is not included in results");261 var prefixWords = [];262 var prefixIterator = compactDawg.iterator("testac");263 var priNext = prefixIterator.next();264 while (!priNext.done) {265 prefixWords.push(priNext.value);266 priNext = prefixIterator.next();267 }268 t.equal(prefixWords.length, 7, "got 7 results for prefix 'testac'");269 t.assert(prefixWords.indexOf("testac") == -1, "submitted prefix 'testac' is not included in results");270 var prefixWords = [];271 var prefixIterator = compactDawg.iterator("testaaa");272 var priNext = prefixIterator.next();273 while (!priNext.done) {274 prefixWords.push(priNext.value);275 priNext = prefixIterator.next();276 }277 t.equal(prefixWords.length, 0, "got 0 results for prefix 'testaaa'");278 var lookupFailure = true;279 for (var i = 0; i < words.length; i++) {280 lookupFailure = lookupFailure && (!compactDawg.lookup(words[i] + "qzz").found);281 lookupFailure = lookupFailure && (!compactDawg.lookupPrefix(words[i] + "qzz").found);282 }283 t.assert(lookupFailure, "compact dawg does not contain any words with 'qzz' added to the end as term or prefix");284 var prefixLookup = true;285 for (var i = 0; i < words.length; i++) {286 if (words[i].length == 1) continue;287 var prefix = words[i].substring(0, words[i].length - 1);288 // if this prefix is also a word, skip289 if (wordSet.contains(prefix)) continue;290 prefixLookup = prefixLookup && (!compactDawg.lookupCounts(prefix).found);291 }292 t.assert(prefixLookup, "compact dawg does not contain prefixes of all words as terms");293 t.assert(!compactDawg.lookupCounts("").found, "compact dawg does not contain the empty string as a term");294 t.assert(compactDawg.lookupPrefixCounts("").found, "compact dawg does contain the empty string as a prefix");295 t.end();...
proto.js
Source:proto.js
1const fs = require('fs')2const path = require('path')3const protobuf = require('protobufjs')4// A new empty protobuf root instance.5let root = new protobuf.Root()6// Retrieve every protobuf file.7const files = fs8 .readdirSync(path.resolve(__dirname, '../protos'))9 .map(f => path.resolve(__dirname, '../protos', f))10 .filter(f => f.endsWith('.proto'))11// Load synchronously each protobuf file.12root = root.loadSync(files)13// Payload lookup.14const SCPayload = root.lookup('SCPayload')15const SCPayloadActions = root.lookup('Action').values16const SCPayloadFields = root.lookup('Action').parent.fields17// Users lookup.18const SystemAdmin = root.lookup('SystemAdmin')19const CompanyAdmin = root.lookup('CompanyAdmin')20const Operator = root.lookup('Operator')21const CertificationAuthority = root.lookup('CertificationAuthority')22// Types lookup.23const TaskType = root.lookup('TaskType')24const ProductType = root.lookup('ProductType')25const EventParameterType = root.lookup('EventParameterType')26const EventType = root.lookup('EventType')27const PropertyType = root.lookup('PropertyType')28// Entities lookup.29const Company = root.lookup('Company')30const Field = root.lookup('Field')31const Event = root.lookup('Event')32const Batch = root.lookup('Batch')33// Other messages lookup.34const Shared = root.lookup('Shared')35const Proposal = root.lookup('Proposal')36const Certificate = root.lookup('Certificate')37// Actions lookup.38const UpdateSystemAdminAction = root.lookup('UpdateSystemAdminAction')39const CreateTaskTypeAction = root.lookup('CreateTaskTypeAction')40const CreateProductTypeAction = root.lookup('CreateProductTypeAction')41const CreateEventParameterTypeAction = root.lookup('CreateEventParameterTypeAction')42const CreateEventTypeAction = root.lookup('CreateEventTypeAction')43const CreatePropertyTypeAction = root.lookup('CreatePropertyTypeAction')44const CreateCertificationAuthorityAction = root.lookup('CreateCertificationAuthorityAction')45const CreateCompanyAction = root.lookup('CreateCompanyAction')46const CreateFieldAction = root.lookup('CreateFieldAction')47const CreateOperatorAction = root.lookup('CreateOperatorAction')48const CreateDescriptionEventAction = root.lookup('CreateDescriptionEventAction')49const CreateTransformationEventAction = root.lookup('CreateTransformationEventAction')50const AddBatchCertificateAction = root.lookup('AddBatchCertificateAction')51const RecordBatchPropertyAction = root.lookup('RecordBatchPropertyAction')52const CreateProposalAction = root.lookup('CreateProposalAction')53const AnswerProposalAction = root.lookup('AnswerProposalAction')54const FinalizeBatchAction = root.lookup('FinalizeBatchAction')55module.exports = {56 root,57 SCPayload,58 SCPayloadActions,59 SCPayloadFields,60 SystemAdmin,61 CompanyAdmin,62 Operator,63 CertificationAuthority,64 TaskType,65 ProductType,66 EventParameterType,67 EventType,68 PropertyType,69 Company,70 Field,71 Event,72 Batch,73 Proposal,74 Certificate,75 Shared,76 UpdateSystemAdminAction,77 CreateTaskTypeAction,78 CreateProductTypeAction,79 CreateEventParameterTypeAction,80 CreateEventTypeAction,81 CreatePropertyTypeAction,82 CreateCertificationAuthorityAction,83 CreateCompanyAction,84 CreateFieldAction,85 CreateOperatorAction,86 CreateDescriptionEventAction,87 CreateTransformationEventAction,88 AddBatchCertificateAction,89 RecordBatchPropertyAction,90 CreateProposalAction,91 AnswerProposalAction,92 FinalizeBatchAction,...
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!!