Best Python code snippet using localstack_python
function-jim-event-data.js
Source:function-jim-event-data.js
1/*!2 * Copyright 2013 Justinmind. All rights reserved.3 */4(function(window, undefined) {5 6 7 function getInstances($target) {8 return $target.find(".datarow, .gridcell")9 .filter(function (i,e) {return $($(e).closest(".datagrid, .datalist")).attr("id") == $target.attr("id");});10 }11 12 jQuery.extend(jimEvent.fn, {13 "jimCreateData": function(args, callback) {14 var self = this, datamaster, newInstance, field, value;15 if (args && args.datamaster && args.fields) {16 datamaster = args.datamaster;17 if (jimData.datamasters.hasOwnProperty(datamaster)) {18 /*get last data master id*/19 var lastId = 1;20 for(var instanceIndex in jimData.datamasters[datamaster]){21 if(jimData.datamasters[datamaster][instanceIndex].id >= lastId)22 lastId = jimData.datamasters[datamaster][instanceIndex].id + 1;23 } 24 newInstance = {25 "id": lastId,26 "datamaster": datamaster,27 "userdata": {}28 };29 30 for(field in args.fields) {31 if(args.fields.hasOwnProperty(field)) {32 value = args.fields[field];33 newInstance.userdata[field] = (jQuery.isEmptyObject(value)) ? "" : self.evaluateExpression(value);34 }35 }36 37 jimData.datamasters[datamaster].push(newInstance);38 }39 40 if(callback) { callback(); }41 }42 },43 "jimUpdateData": function(args, callback) {44 var self = this, datamaster, instances, instance, i, iLen, j, jLen, variable, records, record, value, $dataViews, g, gLen, k, kLen, $datarows, field, $field;45 if (args && args.fields) {46 /* update data */47 instances = jimUtil.toArray(self.evaluateExpression(args));48 if(instances!==undefined && instances[0] !== "") { 49 for(i = 0, iLen = instances.length; i < iLen; i += 1) {50 instance = instances[i];51 52 /* establish association with data master record, may have been lost on unload */53 datamaster = jimData.datamasters[instance.datamaster];54 for(j = 0, jLen = datamaster.length; j < jLen; j += 1) {55 if(datamaster[j].id === instance.id) {56 datamaster[j] = instance;57 break;58 }59 }60 61 /* establish association with variable, may have been lost on unload */62 for(variable in jimData.variables) {63 if(jimData.variables.hasOwnProperty(variable)) {64 records = jimData.variables[variable];65 if(jimUtil.isArray(records)) {66 for(j = 0, jLen = records.length; j < jLen; j += 1) {67 record = records[j]; 68 if(record.datamaster === instance.datamaster && record.id === instance.id) {69 jimData.variables[variable][j] = instance;70 break;71 }72 }73 }74 }75 }76 77 for(field in args.fields) {78 if(args.fields.hasOwnProperty(field)) {79 value = args.fields[field];80 if(!jQuery.isEmptyObject(value)) {81 instance.userdata[field] = self.evaluateExpression(value, instance);82 }83 }84 }85 }86 87 /* update data grid */88 datamaster = args.datamaster || args.parameter && args.parameter.datamaster || instance.datamaster;89 $dataViews = jQuery(".datalist[datamaster='" + datamaster +"'], .datagrid[datamaster='" + datamaster +"']");90 for(g=0, gLen=$dataViews.length; g < gLen; g += 1) {91 var $dataView = jQuery($dataViews[g]);92 for (k=0, kLen=instances.length; k < kLen; k += 1) {93 instance = instances[k];94 var $rowOrGridCell;95 if($dataView.is(".datagrid")){96 $rowOrGridCell = $dataView.find(".gridcell[instance='" + instance.id + "']");97 } else {98 var $datarows = $dataView.find("[name='id'][value='" + instance.id + "']").parents(".datarow");99 if($datarows.length)100 $rowOrGridCell = jQuery($datarows[0]);101 }102 103 if($rowOrGridCell) {104 for (field in instance.userdata) {105 if (instance.userdata.hasOwnProperty(field)) {106 value = instance.userdata[field];107 $field = $rowOrGridCell.find("[name='" + field + "']");108 $field.val(value);109 switch($field.jimGetType()) {110 case itemType.dropdown:111 case itemType.nativedropdown:112 case itemType.selectionlist:113 case itemType.multiselectionlist:114 case itemType.radiobuttonlist:115 case itemType.checkboxlist:116 self.jimSetSelection({"target": $field, "value": value});117 break;118 /* intentional fall-through */ 119 default:120 self.jimSetValue({"target": $field, "value": value});121 break;122 }123 }124 }125 $rowOrGridCell.closest(".datachange").trigger("datachange");126 }127 }128 }129 }130 131 if(callback) { callback(); }132 }133 },134 "jimDeleteData": function(args, callback) {135 var self = this, datamaster, $grid,$gridCell, variable, instances, removeInstances, removeInstance, removeID, i, iLen, j, id;136 if (args) {137 datamaster = args.datamaster || args.parameter && args.parameter.datamaster;138 if (args.datatype === "datamaster") {139 /* delete data master */140 jimData.datamasters[datamaster] = [];141 /* update data grid */142 jQuery(".datalist[datamaster='" + datamaster +"']").each(function(index, grid) {143 jQuery(grid).find("table:first").children("tbody").html("<tr><td></td></tr>");144 });145 /* update variable */146 for(variable in jimData.variables) {147 if(jimData.variables.hasOwnProperty(variable)) {148 instances = jimData.variables[variable];149 if(jimUtil.isArray(instances)) {150 for(i=instances.length-1; i>=0; i-=1) {151 removeInstance = instances[i];152 if(removeInstance.datamaster === datamaster) {153 instances.splice(i,1);154 }155 }156 }157 }158 }159 } else {160 /* delete data master */161 removeInstances = jimUtil.toArray(self.evaluateExpression(args));162 datamaster = datamaster || removeInstances.length && removeInstances[0].datamaster;163 instances = jimData.datamasters[datamaster];164 removeID = [];165 if(instances && removeInstances) {166 for (i=instances.length-1; i>=0 && removeInstances.length; i-=1) {167 for (j=removeInstances.length-1; j>=0; j-=1) {168 id = removeInstances[j].id;169 if (instances[i].id === id) {170 removeID.push(id);171 removeInstances.splice(j, 1);172 instances.splice(i, 1);173 break;174 }175 }176 }177 /* update data grid */178 jQuery(".datalist[datamaster='" + datamaster +"']").each(function(index, grid) {179 $grid = jQuery(grid);180 for (i=0, iLen=removeID.length; i<iLen; i+=1) {181 $grid.find(".datarow:has([name='id'][value='" + removeID[i] + "'])").remove();182 }183 $grid.dataview("updateDataListPage");184 $grid.dataview("updateDataListBounds");185 $grid.trigger("update.dataview");186 });187 188 jQuery(".datagrid[datamaster='" + datamaster +"']").each(function(index, grid) {189 $grid = jQuery(grid);190 191 for (i=0, iLen=removeID.length; i<iLen; i+=1) {192 var $dataViewInstances = $grid.find(".gridcell");193 $gridCell = $grid.find(".gridcell[instance='" + removeID[i] + "']");194 var $visibleCells = $dataViewInstances.filter(":not(.hidden)");195 var maxIndex = 0;196 var j,jLen;197 for (j=0, jLen=$visibleCells.length; j<jLen; j+=1) {198 var instanceNumber = jQuery($visibleCells.get(j)).attr("instance");199 maxIndex = Math.max(maxIndex,instanceNumber);200 }201 maxIndex= maxIndex+1;202 var $nextVisibleCell = $grid.find(".gridcell[instance='" + maxIndex + "']");203 $gridCell.remove();204 $nextVisibleCell.removeClass("hidden");205 }206 $grid.dataview("rebuildDataGridHierarchy");207 $grid.trigger("update.dataview");208 });209 210 211 /* update variable */212 for(variable in jimData.variables) {213 if(jimData.variables.hasOwnProperty(variable)) {214 instances = jimData.variables[variable];215 if(jimUtil.isArray(instances)) {216 for(i=0, iLen=removeID.length; i<iLen; i+=1) {217 for(j=instances.length-1; j>=0; j-=1) {218 removeInstance = instances[j];219 if(removeInstance.datamaster === datamaster && removeInstance.id === removeID[i]) {220 instances.splice(j,1);221 }222 }223 }224 }225 }226 }227 }228 }229 230 if(callback) { callback(); }231 }232 },233 "jimFilterData": function(args) {234 var self = this, filteredInstances = [], instances, i, len, result, searchTokens, searchExpression, search, property;235 if (args) {236 instances = jimUtil.toArray(self.evaluateExpression(args));237 for(i=0, len=instances.length; i < len; i += 1) {238 result = self.evaluateExpression(args.value, instances[i]);239 instance = instances[i]; /* prevent overwrite from other inner filter instances */240 if (typeof (result) === "string") {241 searchTokens = jimUtil.escapeRegex(result).split(' ');242 searchExpression = '^(?=.*?' + searchTokens.join(')(?=.*?') + ').*$';243 search = new RegExp(searchExpression, "i");244 245 /* TODO: apply over whole instance not attributes246 * values = jimUtil.getValues(instance, ["id", "datamaster"]).join(" ");247 * if (search.test(values)) {248 * filteredInstances.push(instance);249 * }250 */251 252 for(property in instance.userdata) {253 if(instance.userdata.hasOwnProperty(property)) {254 if (search.test(instance.userdata[property])) {255 filteredInstances.push(instance);256 break;257 }258 }259 }260 } else if (result) {261 filteredInstances.push(instance);262 }263 }264 }265 return filteredInstances;266 },267 "jimSumData": function(args) {268 var self = this, instances, result = 0, i, len, tmpResult;269 if (args) {270 instances = jimUtil.toArray(self.evaluateExpression(args));271 for(i=0, len=instances.length; i < len; i += 1) {272 tmpResult = jimEvent.tryNumberConversion(self.evaluateExpression(args.value, instances[i]));273 if (jimUtil.exists(tmpResult) && !isNaN(tmpResult)) {274 if(!isNaN(Number(tmpResult)))275 result = (result * 10 + Number(tmpResult) * 10) / 10; //0.2 + 0.1 = 0.30000000000000004276 } else {277 result = null;278 break;279 }280 }281 return result;282 }283 },284 "jimAvgData": function(args) {285 var self = this, result = null, sum, length;286 if (args) {287 length = jimUtil.toArray(self.evaluateExpression(args)).length;288 if (length !== 0) {289 sum = self.jimSumData(args);290 if (sum !== null && !isNaN(sum)) {291 result = sum / length;292 }293 }294 }295 return result;296 },297 "jimMaxData": function(args) {298 var self = this, values = [], instances, i, len;299 if (args) {300 instances = jimUtil.toArray(self.evaluateExpression(args));301 for(i=0, len=instances.length; i < len; i += 1) {302 values.push(self.evaluateExpression(args.value, instances[i]));303 }304 }305 return self.jimMax(values);306 },307 "jimMinData": function(args) {308 var self = this, values = [], instances, i, len;309 if (args) {310 instances = jimUtil.toArray(self.evaluateExpression(args));311 for(i=0, len=instances.length; i < len; i += 1) {312 values.push(self.evaluateExpression(args.value, instances[i]));313 }314 }315 return self.jimMin(values);316 },317 "jimCountData": function(args) {318 var self = this, tmpResult, result = null;319 if (args) {320 tmpResult = self.evaluateExpression(args);321 result = (tmpResult === "") ? 0 : jimUtil.toArray(tmpResult).length;322 }323 return result;324 },325 "jimSelectData": function(args) {326 var self = this, result = [], instances, i, len;327 if (args) {328 instances = jimUtil.toArray(self.evaluateExpression(args));329 for(i=0, len=instances.length; i < len; i += 1) {330 result.push(self.evaluateExpression(args.value, instances[i]));331 }332 }333 return result.join(",");334 },335 "jimSelectDistinctData": function(args) {336 var self = this, result = [], instances, i, len;337 if (args) {338 instances = jimUtil.toArray(self.evaluateExpression(args));339 for(i=0, len=instances.length; i < len; i += 1) {340 instance = {341 "key": self.evaluateExpression(args.value, instances[i]),342 "value": ""343 };344 result.push(instance);345 }346 var aux = jimUtil.unique(result);347 result = [];348 for(i=0, len=aux.length; i < len; i++) {349 result.push(aux[i].key);350 }351 }352 return result.join(",");353 },354 "jimFilterDistinctData": function(args) {355 var self = this, result = [], instances, i, len;356 if(args) {357 instances = jimUtil.toArray(self.evaluateExpression(args));358 for(i=0, len=instances.length; i < len; i += 1) {359 instance = {360 "key": self.evaluateExpression(args.value, instances[i]),361 "value": instances[i]362 };363 result.push(instance);364 }365 var aux = jimUtil.unique(result);366 result = [];367 for(i=0, len=aux.length; i < len; i++) {368 result.push(aux[i].value);369 }370 }371 return result;372 },373 "jimAddToData": function(args) {374 var self = this, result = [], sourceA, datamasterA, sourceB, datamasterB, instances;375 if (jimUtil.exists(args) && jimUtil.exists(args[0]) && jimUtil.exists(args[1])) {376 sourceA = jimUtil.toArray(self.evaluateExpression(args[0]));377 sourceB = jimUtil.toArray(self.evaluateExpression(args[1]));378 379 if(args[0].datamaster) {380 datamasterA = args[0].datamaster;381 } else if (sourceA.length) {382 datamasterA = sourceA[0].datamaster;383 }384 if(args[1].datamaster) {385 datamasterB = args[1].datamaster;386 } else if (sourceB.length) {387 datamasterB = sourceB[0].datamaster;388 }389 390 if(datamasterA && datamasterB && datamasterA === datamasterB || datamasterA === undefined && datamasterB === undefined) {391 result = jQuery.merge(sourceA, sourceB);392 } else if (datamasterA === undefined && datamasterB) {393 result = sourceB;394 } else {395 result = sourceA;396 }397 }398 return result;399 },400 "jimRemoveFromData": function(args) {401 var self = this, result = [], sourceA, sourceB, i, j;402 if (jimUtil.exists(args) && jimUtil.exists(args[0]) && jimUtil.exists(args[1])) {403 sourceA = jimUtil.toArray(self.evaluateExpression(args[0]));404 sourceB = jimUtil.toArray(self.evaluateExpression(args[1]));405 for (i = sourceB.length - 1; i >= 0 && sourceA.length; i -= 1) {406 for (j = sourceA.length - 1; j >= 0; j -= 1) {407 if (sourceB[i] === sourceA[j]) {408 sourceA.splice(j, 1);409 sourceB.splice(i, 1);410 break;411 }412 }413 }414 result = sourceA;415 }416 return result;417 },418 "jimFirstPageData": function(args, callback) {419 var self = this, size, $dataViewInstances;420 if (args && args.target) {421 var $targets = self.getEventTargets(args.target);422 for (var i in $targets) {423 var $target = $targets[i];424 if ($target.length) {425 size = parseInt($target.attr("size"), 10);426 if(size > 0) {427 $dataViewInstances = getInstances($target);428 $dataViewInstances.addClass("hidden").filter(":lt(" + size + ")").removeClass("hidden");429 $target.trigger("update.dataview");430 }431 }432 }433 if(callback) { callback(); }434 }435 },436 "jimPrevPageData": function(args, callback) {437 var self = this, size, $dataViewInstances, $prev,index;438 if (args && args.target) {439 var $targets = self.getEventTargets(args.target);440 for (var i in $targets) {441 var $target = $targets[i];442 if ($target.length) {443 size = parseInt($target.attr("size"), 10);444 $dataViewInstances = getInstances($target);445 index = $dataViewInstances.index($dataViewInstances.filter(":visible").first())-1;446 if (index>=0) {447 $dataViewInstances.addClass("hidden");448 $prev = jQuery($dataViewInstances[index]);449 while (size>0 && $prev.length) {450 $prev.removeClass("hidden");451 if (index>=0){452 index -=1;453 $prev = jQuery($dataViewInstances[index]);454 }455 size -= 1;456 }457 $target.trigger("update.dataview");458 }459 }460 }461 if(callback) { callback(); }462 }463 },464 "jimNextPageData": function(args, callback) {465 var self = this, size, $dataViewInstances, $next,index;466 if (args && args.target) {467 var $targets = self.getEventTargets(args.target);468 for (var i in $targets) {469 var $target = $targets[i];470 if ($target.length) {471 size = parseInt($target.attr("size"), 10);472 $dataViewInstances = getInstances($target);473 index = $dataViewInstances.index($dataViewInstances.filter(":visible").last())+1;474 if (index<$dataViewInstances.length) {475 $dataViewInstances.addClass("hidden");476 $next = jQuery($dataViewInstances[index]);477 while (size>0 && $next.length) {478 $next.removeClass("hidden");479 if (index<$dataViewInstances.length){480 index +=1;481 $next = jQuery($dataViewInstances[index]);482 }483 size -= 1;484 }485 }486 $target.trigger("update.dataview");487 }488 }489 if(callback) { callback(); }490 }491 },492 "jimLastPageData": function(args, callback) {493 var self = this, $dataViewInstances, gridSize, filterSize, index;494 if (args && args.target) {495 $targets = self.getEventTargets(args.target);496 for (var i in $targets) {497 var $target = $targets[i];498 if ($target.length) {499 $dataViewInstances = getInstances($target);500 gridSize = $dataViewInstances.length;501 filterSize = parseInt($target.attr("size"), 10);502 index = (gridSize % filterSize === 0) ? gridSize - filterSize - 1 : gridSize - (gridSize % filterSize) - 1;503 if(!isNaN(index) && index>0) {504 $dataViewInstances.addClass("hidden").filter(":gt(" + index + ")").removeClass("hidden");505 $target.trigger("update.dataview");506 }507 }508 if(callback) { callback(); }509 }510 }511 },512 "getDataInstancesById": function(instances, ids) {513 var result=[], i, ilen, j, jlen, instance;514 for (i=0, ilen=ids.length; i<ilen; i+=1) {515 for (j=0, jlen=instances.length; j<jlen; j+=1) {516 instance = instances[j];517 if (jimEvent.tryNumberConversion(ids[i]) === instance.id) {518 result.push(instance);519 break;520 }521 }522 }523 return result;524 },525 "jimSortDataAscendant": function(args) {526 var self = this, instances = [];527 if (args) {528 instances = jimUtil.toArray(self.evaluateExpression(args));529 if(instances !== []) {530 instances.sort(function(a, b) {531 if(typeof(jimEvent.tryNumberConversion(a.userdata[args.value.field])) === "number") {532 return a.userdata[args.value.field] - b.userdata[args.value.field]533 }534 else if(typeof(jimEvent.tryDateConversion(a.userdata[args.value.field])) === "object" && typeof(a.userdata[args.value.field]) === "string") {535 return new Date(a.userdata[args.value.field]) - new Date(b.userdata[args.value.field])536 }537 else if(typeof(jimEvent.tryStringConversion(a.userdata[args.value.field])) === "string") {538 if (a.userdata[args.value.field] < b.userdata[args.value.field]) {539 return -1540 }541 if (a.userdata[args.value.field] > b.userdata[args.value.field]) {542 return 1543 }544 return 0545 }546 });547 }548 }549 return instances;550 },551 "jimSortDataDescendant": function(args) {552 var self = this, instances = [];553 if (args) {554 instances = jimUtil.toArray(self.evaluateExpression(args));555 if(instances !== []) {556 instances.sort(function(a, b) {557 if(typeof(jimEvent.tryNumberConversion(a.userdata[args.value.field])) === "number") {558 return b.userdata[args.value.field] - a.userdata[args.value.field]559 }560 else if(typeof(jimEvent.tryDateConversion(a.userdata[args.value.field])) === "object" && typeof(a.userdata[args.value.field]) === "string") {561 return new Date(b.userdata[args.value.field]) - new Date(a.userdata[args.value.field])562 }563 else if(typeof(jimEvent.tryStringConversion(a.userdata[args.value.field])) === "string") {564 if (b.userdata[args.value.field] < a.userdata[args.value.field]) {565 return -1566 }567 if (b.userdata[args.value.field] > a.userdata[args.value.field]) {568 return 1569 }570 return 0571 }572 });573 }574 }575 return instances;576 }577 });...
test_instances.py
Source:test_instances.py
...89 settings_page.change_pagesize()90 self.assertTrue(91 settings_page.find_message_and_dismiss(messages.SUCCESS))92 instances_page = self.instances_page93 instances_page.delete_instances(instance_list)94 self.assertTrue(95 instances_page.find_message_and_dismiss(messages.SUCCESS))96 self.assertTrue(instances_page.are_instances_deleted(instance_list))97 def test_instances_pagination_and_filtration(self):98 """This test checks instance pagination and filtration99 Steps:100 1) Login to Horizon Dashboard as regular user101 2) Go to to user settings page102 3) Change 'Items Per Page' value to 1103 4) Go to Project > Compute > Instances page104 5) Create 2 instances105 6) Go to appropriate page (depends on user)106 7) Check filter by Name of the first and the second instance in order107 to have one instance in the list (and it should have correct name)108 and no 'Next' link is available109 8) Check filter by common part of Name of in order to have one instance110 in the list (and it should have correct name) and 'Next' link is111 available on the first page and is not available on the second page112 9) Go to user settings page and restore 'Items Per Page'113 10) Delete created instances via proper page (depends on user)114 """115 items_per_page = 1116 instance_count = 2117 instance_list = ["{0}-{1}".format(self.INSTANCE_NAME, item)118 for item in range(1, instance_count + 1)]119 first_page_definition = {'Next': True, 'Prev': False,120 'Count': items_per_page,121 'Names': [instance_list[1]]}122 second_page_definition = {'Next': False, 'Prev': False,123 'Count': items_per_page,124 'Names': [instance_list[0]]}125 filter_first_page_definition = {'Next': False, 'Prev': False,126 'Count': items_per_page,127 'Names': [instance_list[1]]}128 settings_page = self.home_pg.go_to_settings_usersettingspage()129 settings_page.change_pagesize(items_per_page)130 self.assertTrue(131 settings_page.find_message_and_dismiss(messages.SUCCESS))132 instances_page = self.home_pg.go_to_compute_instancespage()133 instances_page.create_instance(self.INSTANCE_NAME,134 instance_count=instance_count)135 self.assertTrue(136 instances_page.find_message_and_dismiss(messages.SUCCESS))137 self.assertTrue(instances_page.is_instance_active(instance_list[1]))138 instances_page = self.instances_page139 instances_page.instances_table.set_filter_value('name')140 instances_page.instances_table.filter(instance_list[1])141 instances_page.instances_table.assert_definition(142 filter_first_page_definition, sorting=True)143 instances_page.instances_table.filter(instance_list[0])144 instances_page.instances_table.assert_definition(145 second_page_definition, sorting=True)146 instances_page.instances_table.filter(self.INSTANCE_NAME)147 instances_page.instances_table.assert_definition(148 first_page_definition, sorting=True)149 instances_page.instances_table.filter('')150 settings_page = self.home_pg.go_to_settings_usersettingspage()151 settings_page.change_pagesize()152 self.assertTrue(153 settings_page.find_message_and_dismiss(messages.SUCCESS))154 instances_page = self.instances_page155 instances_page.delete_instances(instance_list)156 self.assertTrue(157 instances_page.find_message_and_dismiss(messages.SUCCESS))158 self.assertTrue(instances_page.are_instances_deleted(instance_list))159 def test_filter_instances(self):160 """This test checks filtering of instances by Instance Name161 Steps:162 1) Login to Horizon dashboard as regular user163 2) Go to Project > Compute > Instances164 3) Create 2 instances165 4) Go to appropriate page (depends on user)166 5) Use filter by Instance Name167 6) Check that filtered table has one instance only (which name is equal168 to filter value) and no other instances in the table169 7) Check that filtered table has both instances (search by common part170 of instance names)171 8) Set nonexistent instance name. Check that 0 rows are displayed172 9) Clear filter and delete instances via proper page (depends on user)173 """174 instance_count = 2175 instance_list = ["{0}-{1}".format(self.INSTANCE_NAME, item)176 for item in range(1, instance_count + 1)]177 instances_page = self.home_pg.go_to_compute_instancespage()178 instances_page.create_instance(self.INSTANCE_NAME,179 instance_count=instance_count)180 self.assertTrue(181 instances_page.find_message_and_dismiss(messages.SUCCESS))182 self.assertTrue(instances_page.is_instance_active(instance_list[0]))183 instances_page = self.instances_page184 instances_page.instances_table.set_filter_value('name')185 instances_page.instances_table.filter(instance_list[0])186 self.assertTrue(instances_page.is_instance_present(instance_list[0]))187 for instance in instance_list[1:]:188 self.assertFalse(instances_page.is_instance_present(instance))189 instances_page.instances_table.filter(self.INSTANCE_NAME)190 for instance in instance_list:191 self.assertTrue(instances_page.is_instance_present(instance))192 nonexistent_instance_name = "{0}_test".format(self.INSTANCE_NAME)193 instances_page.instances_table.filter(nonexistent_instance_name)194 self.assertEqual(instances_page.instances_table.rows, [])195 instances_page.instances_table.filter('')196 instances_page.delete_instances(instance_list)197 self.assertTrue(198 instances_page.find_message_and_dismiss(messages.SUCCESS))199 self.assertTrue(instances_page.are_instances_deleted(instance_list))200class TestAdminInstances(helpers.AdminTestCase, TestInstances):201 INSTANCE_NAME = helpers.gen_random_resource_name('instance',202 timestamp=False)203 @property204 def instances_page(self):205 return self.home_pg.go_to_system_instancespage()206 @decorators.skip_because(bugs=['1584057'])207 def test_instances_pagination_and_filtration(self):208 super(TestAdminInstances, self).\...
bbox_iou_tracker.py
Source:bbox_iou_tracker.py
...108 self._matched_idx.add(idx)109 self._matched_ID.add(prev_id)110 self._untracked_prev_idx.remove(bbox_pair["prev_idx"])111 instances = self._assign_new_id(instances)112 instances = self._merge_untracked_instances(instances)113 self._prev_instances = copy.deepcopy(instances)114 return instances115 def _create_prediction_pairs(116 self, instances: Instances, iou_all: np.ndarray117 ) -> List:118 """119 For all instances in previous and current frames, create pairs. For each120 pair, store index of the instance in current frame predcitions, index in121 previous predictions, ID in previous predictions, IoU of the bboxes in this122 pair, period in previous predictions.123 Args:124 instances: D2 Instances, for predictions of the current frame125 iou_all: IoU for all bboxes pairs126 Return:127 A list of IoU for all pairs128 """129 bbox_pairs = []130 for i in range(len(instances)):131 for j in range(len(self._prev_instances)):132 bbox_pairs.append(133 {134 "idx": i,135 "prev_idx": j,136 "prev_id": self._prev_instances.ID[j],137 "IoU": iou_all[i, j],138 "prev_period": self._prev_instances.ID_period[j],139 }140 )141 return bbox_pairs142 def _initialize_extra_fields(self, instances: Instances) -> Instances:143 """144 If input instances don't have ID, ID_period, lost_frame_count fields,145 this method is used to initialize these fields.146 Args:147 instances: D2 Instances, for predictions of the current frame148 Return:149 D2 Instances with extra fields added150 """151 if not instances.has("ID"):152 instances.set("ID", [None] * len(instances))153 if not instances.has("ID_period"):154 instances.set("ID_period", [None] * len(instances))155 if not instances.has("lost_frame_count"):156 instances.set("lost_frame_count", [None] * len(instances))157 if self._prev_instances is None:158 instances.ID = list(range(len(instances)))159 self._id_count += len(instances)160 instances.ID_period = [1] * len(instances)161 instances.lost_frame_count = [0] * len(instances)162 return instances163 def _reset_fields(self):164 """165 Before each uodate call, reset fields first166 """167 self._matched_idx = set()168 self._matched_ID = set()169 self._untracked_prev_idx = set(range(len(self._prev_instances)))170 def _assign_new_id(self, instances: Instances) -> Instances:171 """172 For each untracked instance, assign a new id173 Args:174 instances: D2 Instances, for predictions of the current frame175 Return:176 D2 Instances with new ID assigned177 """178 untracked_idx = set(range(len(instances))).difference(self._matched_idx)179 for idx in untracked_idx:180 instances.ID[idx] = self._id_count181 self._id_count += 1182 instances.ID_period[idx] = 1183 instances.lost_frame_count[idx] = 0184 return instances185 def _merge_untracked_instances(self, instances: Instances) -> Instances:186 """187 For untracked previous instances, under certain condition, still keep them188 in tracking and merge with the current instances.189 Args:190 instances: D2 Instances, for predictions of the current frame191 Return:192 D2 Instances merging current instances and instances from previous193 frame decided to keep tracking194 """195 untracked_instances = Instances(196 image_size=instances.image_size,197 pred_boxes=[],198 pred_masks=[],199 pred_classes=[],...
hungarian_tracker.py
Source:hungarian_tracker.py
1#!/usr/bin/env python32# Copyright 2004-present Facebook. All Rights Reserved.3import copy4import numpy as np5import torch6from detectron2.structures import Boxes, Instances7from .base_tracker import BaseTracker8from scipy.optimize import linear_sum_assignment9from ..config.config import CfgNode as CfgNode_10from typing import Dict11from detectron2.config import configurable12class BaseHungarianTracker(BaseTracker):13 """14 A base class for all Hungarian trackers15 """16 @configurable17 def __init__(18 self,19 video_height: int,20 video_width: int,21 max_num_instances: int = 200,22 max_lost_frame_count: int = 0,23 min_box_rel_dim: float = 0.02,24 min_instance_period: int = 1,25 **kwargs26 ):27 """28 Args:29 video_height: height the video frame30 video_width: width of the video frame31 max_num_instances: maximum number of id allowed to be tracked32 max_lost_frame_count: maximum number of frame an id can lost tracking33 exceed this number, an id is considered as lost34 forever35 min_box_rel_dim: a percentage, smaller than this dimension, a bbox is36 removed from tracking37 min_instance_period: an instance will be shown after this number of period38 since its first showing up in the video39 """40 super().__init__(**kwargs)41 self._video_height = video_height42 self._video_width = video_width43 self._max_num_instances = max_num_instances44 self._max_lost_frame_count = max_lost_frame_count45 self._min_box_rel_dim = min_box_rel_dim46 self._min_instance_period = min_instance_period47 @classmethod48 def from_config(cls, cfg: CfgNode_) -> Dict:49 raise NotImplementedError("Calling HungarianTracker::from_config")50 def build_cost_matrix(self, instances: Instances, prev_instances: Instances) -> np.ndarray:51 raise NotImplementedError("Calling HungarianTracker::build_matrix")52 def update(self, instances: Instances) -> Instances:53 if instances.has("pred_keypoints"):54 raise NotImplementedError("Need to add support for keypoints")55 instances = self._initialize_extra_fields(instances)56 if self._prev_instances is not None:57 self._untracked_prev_idx = set(range(len(self._prev_instances)))58 cost_matrix = self.build_cost_matrix(instances, self._prev_instances)59 matched_idx, matched_prev_idx = linear_sum_assignment(cost_matrix)60 instances = self._process_matched_idx(instances, matched_idx, matched_prev_idx)61 instances = self._process_unmatched_idx(instances, matched_idx)62 instances = self._process_unmatched_prev_idx(instances, matched_prev_idx)63 self._prev_instances = copy.deepcopy(instances)64 return instances65 def _initialize_extra_fields(self, instances: Instances) -> Instances:66 """67 If input instances don't have ID, ID_period, lost_frame_count fields,68 this method is used to initialize these fields.69 Args:70 instances: D2 Instances, for predictions of the current frame71 Return:72 D2 Instances with extra fields added73 """74 if not instances.has("ID"):75 instances.set("ID", [None] * len(instances))76 if not instances.has("ID_period"):77 instances.set("ID_period", [None] * len(instances))78 if not instances.has("lost_frame_count"):79 instances.set("lost_frame_count", [None] * len(instances))80 if self._prev_instances is None:81 instances.ID = list(range(len(instances)))82 self._id_count += len(instances)83 instances.ID_period = [1] * len(instances)84 instances.lost_frame_count = [0] * len(instances)85 return instances86 def _process_matched_idx(87 self,88 instances: Instances,89 matched_idx: np.ndarray,90 matched_prev_idx: np.ndarray91 ) -> Instances:92 assert matched_idx.size == matched_prev_idx.size93 for i in range(matched_idx.size):94 instances.ID[matched_idx[i]] = self._prev_instances.ID[matched_prev_idx[i]]95 instances.ID_period[matched_idx[i]] = \96 self._prev_instances.ID_period[matched_prev_idx[i]] + 197 instances.lost_frame_count[matched_idx[i]] = 098 return instances99 def _process_unmatched_idx(self, instances: Instances, matched_idx: np.ndarray) -> Instances:100 untracked_idx = set(range(len(instances))).difference(set(matched_idx))101 for idx in untracked_idx:102 instances.ID[idx] = self._id_count103 self._id_count += 1104 instances.ID_period[idx] = 1105 instances.lost_frame_count[idx] = 0106 return instances107 def _process_unmatched_prev_idx(108 self,109 instances: Instances,110 matched_prev_idx:111 np.ndarray112 ) -> Instances:113 untracked_instances = Instances(114 image_size=instances.image_size,115 pred_boxes=[],116 pred_masks=[],117 pred_classes=[],118 scores=[],119 ID=[],120 ID_period=[],121 lost_frame_count=[],122 )123 prev_bboxes = list(self._prev_instances.pred_boxes)124 prev_classes = list(self._prev_instances.pred_classes)125 prev_scores = list(self._prev_instances.scores)126 prev_ID_period = self._prev_instances.ID_period127 if instances.has("pred_masks"):128 prev_masks = list(self._prev_instances.pred_masks)129 untracked_prev_idx = set(range(len(self._prev_instances))).difference(set(matched_prev_idx))130 for idx in untracked_prev_idx:131 x_left, y_top, x_right, y_bot = prev_bboxes[idx]132 if (133 (1.0 * (x_right - x_left) / self._video_width < self._min_box_rel_dim)134 or (1.0 * (y_bot - y_top) / self._video_height < self._min_box_rel_dim)135 or self._prev_instances.lost_frame_count[idx] >= self._max_lost_frame_count136 or prev_ID_period[idx] <= self._min_instance_period137 ):138 continue139 untracked_instances.pred_boxes.append(list(prev_bboxes[idx].numpy()))140 untracked_instances.pred_classes.append(int(prev_classes[idx]))141 untracked_instances.scores.append(float(prev_scores[idx]))142 untracked_instances.ID.append(self._prev_instances.ID[idx])143 untracked_instances.ID_period.append(self._prev_instances.ID_period[idx])144 untracked_instances.lost_frame_count.append(145 self._prev_instances.lost_frame_count[idx] + 1146 )147 if instances.has("pred_masks"):148 untracked_instances.pred_masks.append(prev_masks[idx].numpy().astype(np.uint8))149 untracked_instances.pred_boxes = Boxes(torch.FloatTensor(untracked_instances.pred_boxes))150 untracked_instances.pred_classes = torch.IntTensor(untracked_instances.pred_classes)151 untracked_instances.scores = torch.FloatTensor(untracked_instances.scores)152 if instances.has("pred_masks"):153 untracked_instances.pred_masks = torch.IntTensor(untracked_instances.pred_masks)154 else:155 untracked_instances.remove("pred_masks")156 return Instances.cat(157 [158 instances,159 untracked_instances,160 ]...
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!!