How to use condition method in wpt

Best JavaScript code snippet using wpt

conditionCollection.unit.js

Source:conditionCollection.unit.js Github

copy

Full Screen

1import ConditionCollection from 'handsontable-pro/plugins/filters/conditionCollection';2import { conditions } from 'handsontable-pro/plugins/filters/conditionRegisterer';3import { OPERATION_AND, OPERATION_OR } from 'handsontable-pro/plugins/filters/constants';4import { operations } from 'handsontable-pro/plugins/filters/logicalOperationRegisterer';5describe('ConditionCollection', () => {6 it('should be initialized and accessible from the plugin', () => {7 expect(ConditionCollection).toBeDefined();8 });9 it('should create empty bucket for conditions, columnTypes and empty orderStack', () => {10 const conditionCollection = new ConditionCollection();11 expect(conditionCollection.conditions).toEqual(jasmine.any(Object));12 expect(Object.keys(conditionCollection.conditions)).toEqual(Object.keys(operations));13 expect(conditionCollection.orderStack).toEqual(jasmine.any(Array));14 expect(conditionCollection.columnTypes).toEqual(jasmine.any(Object));15 });16 describe('isEmpty', () => {17 it('should return `true` when order stack is equal to 0', () => {18 const conditionCollection = new ConditionCollection();19 expect(conditionCollection.isEmpty()).toBe(true);20 conditionCollection.orderStack.push(1);21 expect(conditionCollection.isEmpty()).toBe(false);22 });23 });24 describe('isMatch', () => {25 it('should check is value is matched to the conditions at specified column index', () => {26 const conditionCollection = new ConditionCollection();27 conditionCollection.columnTypes = { 3: OPERATION_AND };28 const conditionMock = {};29 spyOn(conditionCollection, 'isMatchInConditions').and.returnValue(true);30 spyOn(conditionCollection, 'getConditions').and.returnValue([conditionMock]);31 const result = conditionCollection.isMatch('foo', 3);32 expect(conditionCollection.getConditions).toHaveBeenCalledWith(3);33 expect(conditionCollection.isMatchInConditions).toHaveBeenCalledWith([conditionMock], 'foo', OPERATION_AND);34 expect(result).toBe(true);35 });36 it('should check is value is matched to the conditions for all columns', () => {37 const conditionCollection = new ConditionCollection();38 conditionCollection.columnTypes = { 3: OPERATION_AND, 13: OPERATION_AND };39 const conditionMock = {};40 const conditionMock2 = {};41 conditionCollection.conditions[OPERATION_AND]['3'] = [conditionMock];42 conditionCollection.conditions[OPERATION_AND]['13'] = [conditionMock2];43 spyOn(conditionCollection, 'isMatchInConditions').and.returnValue(true);44 spyOn(conditionCollection, 'getConditions').and.returnValue([conditionMock]);45 const result = conditionCollection.isMatch('foo');46 expect(conditionCollection.getConditions).not.toHaveBeenCalled();47 expect(conditionCollection.isMatchInConditions.calls.argsFor(0)).toEqual([[conditionMock], 'foo', OPERATION_AND]);48 expect(conditionCollection.isMatchInConditions.calls.argsFor(1)).toEqual([[conditionMock2], 'foo', OPERATION_AND]);49 expect(result).toBe(true);50 });51 it('should break checking value when current condition is not matched to the rules', () => {52 const conditionCollection = new ConditionCollection();53 conditionCollection.columnTypes = { 3: OPERATION_AND, 13: OPERATION_AND };54 const conditionMock = {};55 const conditionMock2 = {};56 conditionCollection.conditions[OPERATION_AND]['3'] = [conditionMock];57 conditionCollection.conditions[OPERATION_AND]['13'] = [conditionMock2];58 spyOn(conditionCollection, 'isMatchInConditions').and.returnValue(false);59 spyOn(conditionCollection, 'getConditions').and.returnValue(conditionMock);60 const result = conditionCollection.isMatch('foo');61 expect(conditionCollection.getConditions).not.toHaveBeenCalled();62 expect(conditionCollection.isMatchInConditions.calls.count()).toBe(1);63 expect(conditionCollection.isMatchInConditions.calls.argsFor(0)).toEqual([[conditionMock], 'foo', OPERATION_AND]);64 expect(result).toBe(false);65 });66 });67 describe('isMatchInConditions', () => {68 it('should returns `true` if passed conditions is empty', () => {69 const conditionCollection = new ConditionCollection();70 const result = conditionCollection.isMatchInConditions([], 'foo');71 expect(result).toBe(true);72 });73 describe('OPERATION_AND', () => {74 it('should check if array of conditions is matched to the value', () => {75 const conditionCollection = new ConditionCollection();76 const conditionMock = { func: () => true };77 const conditionMock2 = { func: () => true };78 spyOn(conditionMock, 'func').and.callThrough();79 spyOn(conditionMock2, 'func').and.callThrough();80 const result = conditionCollection.isMatchInConditions([conditionMock, conditionMock2], 'foo');81 expect(conditionMock.func.calls.count()).toBe(1);82 expect(conditionMock.func).toHaveBeenCalledWith('foo');83 expect(conditionMock2.func.calls.count()).toBe(1);84 expect(conditionMock2.func).toHaveBeenCalledWith('foo');85 expect(result).toBe(true);86 });87 it('should break checking value when condition is not matched to the value', () => {88 const conditionCollection = new ConditionCollection();89 const conditionMock = { func: () => false };90 const conditionMock2 = { func: () => true };91 spyOn(conditionMock, 'func').and.callThrough();92 spyOn(conditionMock2, 'func').and.callThrough();93 const result = conditionCollection.isMatchInConditions([conditionMock, conditionMock2], 'foo');94 expect(conditionMock.func.calls.count()).toBe(1);95 expect(conditionMock.func).toHaveBeenCalledWith('foo');96 expect(conditionMock2.func.calls.count()).toBe(0);97 expect(result).toBe(false);98 });99 });100 describe('OPERATION_OR', () => {101 it('should check if one of conditions is matched to the value #1', () => {102 const conditionCollection = new ConditionCollection();103 const conditionMock = { func: () => false };104 const conditionMock2 = { func: () => true };105 spyOn(conditionMock, 'func').and.callThrough();106 spyOn(conditionMock2, 'func').and.callThrough();107 const result = conditionCollection.isMatchInConditions([conditionMock, conditionMock2], 'foo', OPERATION_OR);108 expect(conditionMock.func.calls.count()).toBe(1);109 expect(conditionMock.func).toHaveBeenCalledWith('foo');110 expect(conditionMock2.func.calls.count()).toBe(1);111 expect(conditionMock2.func).toHaveBeenCalledWith('foo');112 expect(result).toBe(true);113 });114 it('should check if one of conditions is matched to the value #2', () => {115 const conditionCollection = new ConditionCollection();116 const conditionMock = { func: () => false };117 const conditionMock2 = { func: () => false };118 spyOn(conditionMock, 'func').and.callThrough();119 spyOn(conditionMock2, 'func').and.callThrough();120 const result = conditionCollection.isMatchInConditions([conditionMock, conditionMock2], 'foo', OPERATION_OR);121 expect(conditionMock.func.calls.count()).toBe(1);122 expect(conditionMock.func).toHaveBeenCalledWith('foo');123 expect(conditionMock2.func.calls.count()).toBe(1);124 expect(conditionMock2.func).toHaveBeenCalledWith('foo');125 expect(result).toBe(false);126 });127 it('should break checking value when condition is matched to the value', () => {128 const conditionCollection = new ConditionCollection();129 const conditionMock = { func: () => false };130 const conditionMock2 = { func: () => true };131 const conditionMock3 = { func: () => false };132 spyOn(conditionMock, 'func').and.callThrough();133 spyOn(conditionMock2, 'func').and.callThrough();134 spyOn(conditionMock3, 'func').and.callThrough();135 const result = conditionCollection.isMatchInConditions([conditionMock, conditionMock2, conditionMock3], 'foo', OPERATION_OR);136 expect(conditionMock3.func.calls.count()).toBe(0);137 expect(result).toBe(true);138 });139 });140 });141 describe('addCondition', () => {142 beforeEach(() => {143 conditions.eq = {144 condition: () => {},145 descriptor: {},146 };147 conditions.contains = {148 condition: () => {},149 descriptor: {},150 };151 });152 afterEach(() => {153 delete conditions.eq;154 delete conditions.contains;155 });156 it('should trigger `beforeAdd` and `afterAdd` hook on adding condition', () => {157 const conditionCollection = new ConditionCollection();158 const conditionMock = { args: [], command: { key: 'eq' } };159 const hookBeforeSpy = jasmine.createSpy('hookBefore');160 const hookAfterSpy = jasmine.createSpy('hookAfter');161 conditionCollection.addLocalHook('beforeAdd', hookBeforeSpy);162 conditionCollection.addLocalHook('afterAdd', hookAfterSpy);163 conditionCollection.addCondition(3, conditionMock);164 expect(hookBeforeSpy).toHaveBeenCalledWith(3);165 expect(hookAfterSpy).toHaveBeenCalledWith(3);166 });167 it('should add column index to the orderStack without duplicate values', () => {168 const conditionCollection = new ConditionCollection();169 const conditionMock = { args: [], command: { key: 'eq' } };170 conditionCollection.addCondition(3, conditionMock);171 conditionCollection.addCondition(3, conditionMock);172 conditionCollection.addCondition(3, conditionMock);173 expect(conditionCollection.orderStack).toEqual([3]);174 });175 it('should add condition to the collection at specified column index.', () => {176 const conditionCollection = new ConditionCollection();177 const conditionMock = { args: [1], command: { key: 'eq' } };178 conditionCollection.addCondition(3, conditionMock);179 expect(conditionCollection.conditions[OPERATION_AND]['3'].length).toBe(1);180 expect(conditionCollection.conditions[OPERATION_AND]['3'][0].name).toBe('eq');181 expect(conditionCollection.conditions[OPERATION_AND]['3'][0].args).toEqual([1]);182 expect(conditionCollection.conditions[OPERATION_AND]['3'][0].func instanceof Function).toBe(true);183 });184 it('should allow to add few condition under the same name and column index #160', () => {185 const conditionCollection = new ConditionCollection();186 const conditionMock = { args: ['A'], command: { key: 'contains' } };187 const conditionMock2 = { args: ['B'], command: { key: 'contains' } };188 const conditionMock3 = { args: ['C'], command: { key: 'contains' } };189 conditionCollection.addCondition(3, conditionMock);190 conditionCollection.addCondition(3, conditionMock2);191 conditionCollection.addCondition(3, conditionMock3);192 expect(conditionCollection.conditions[OPERATION_AND]['3'].length).toBe(3);193 });194 it('should allow to add few condition under the same column index ' +195 'only when they are related to the same operation (throw exception otherwise) #160', () => {196 const conditionCollection = new ConditionCollection();197 const conditionMock = { args: ['A'], command: { key: 'contains' } };198 const conditionMock2 = { args: ['B'], command: { key: 'contains' } };199 const conditionMock3 = { args: ['C'], command: { key: 'contains' } };200 conditionCollection.addCondition(3, conditionMock, OPERATION_AND);201 conditionCollection.addCondition(3, conditionMock2, OPERATION_AND);202 expect(() => {203 conditionCollection.addCondition(3, conditionMock3, OPERATION_OR);204 }).toThrow(/has been already applied/);205 });206 it('should allow to add conditions only when they are related to the known operation ' +207 '(throw exception otherwise) #174', () => {208 const conditionCollection = new ConditionCollection();209 const conditionMock = { args: ['A'], command: { key: 'contains' } };210 expect(() => {211 conditionCollection.addCondition(3, conditionMock, 'unknownOperation');212 }).toThrow(/Unexpected operation/);213 });214 });215 describe('exportAllConditions', () => {216 it('should return an empty array when no conditions was added', () => {217 const conditionCollection = new ConditionCollection();218 conditionCollection.orderStack = [];219 const exportedConditions = conditionCollection.exportAllConditions();220 expect(exportedConditions.length).toBe(0);221 });222 it('should return conditions as an array of objects for all column in the same order as it was added', () => {223 const conditionCollection = new ConditionCollection();224 const conditionMock = { name: 'begins_with', args: ['c'] };225 const conditionMock1 = { name: 'date_tomorrow', args: [] };226 const conditionMock2 = { name: 'eq', args: ['z'] };227 conditionCollection.orderStack = [6, 1, 3];228 conditionCollection.columnTypes = { 1: OPERATION_AND, 3: OPERATION_AND, 6: OPERATION_AND };229 conditionCollection.conditions[OPERATION_AND]['3'] = [conditionMock];230 conditionCollection.conditions[OPERATION_AND]['6'] = [conditionMock1];231 conditionCollection.conditions[OPERATION_AND]['1'] = [conditionMock2];232 const exportedConditions = conditionCollection.exportAllConditions();233 expect(exportedConditions.length).toBe(3);234 expect(exportedConditions[0].column).toBe(6);235 expect(exportedConditions[0].conditions[0].name).toBe('date_tomorrow');236 expect(exportedConditions[0].conditions[0].args).toEqual([]);237 expect(exportedConditions[1].column).toBe(1);238 expect(exportedConditions[1].conditions[0].name).toBe('eq');239 expect(exportedConditions[1].conditions[0].args).toEqual(['z']);240 expect(exportedConditions[2].column).toBe(3);241 expect(exportedConditions[2].conditions[0].name).toBe('begins_with');242 expect(exportedConditions[2].conditions[0].args).toEqual(['c']);243 });244 });245 describe('getConditions', () => {246 it('should return conditions at specified index otherwise should return empty array', () => {247 const conditionCollection = new ConditionCollection();248 conditionCollection.columnTypes = { 3: OPERATION_AND };249 const conditionMock = {};250 conditionCollection.conditions[OPERATION_AND]['3'] = [conditionMock];251 expect(conditionCollection.getConditions(2)).toEqual([]);252 expect(conditionCollection.getConditions(3)).toEqual([conditionMock]);253 });254 });255 describe('removeConditions', () => {256 it('should trigger `beforeRemove` and `afterRemove` hook on removing conditions', () => {257 const conditionCollection = new ConditionCollection();258 const conditionMock = {};259 conditionCollection.orderStack = [3];260 conditionCollection.conditions['3'] = [conditionMock];261 const hookBeforeSpy = jasmine.createSpy('hookBefore');262 const hookAfterSpy = jasmine.createSpy('hookAfter');263 conditionCollection.addLocalHook('beforeRemove', hookBeforeSpy);264 conditionCollection.addLocalHook('afterRemove', hookAfterSpy);265 conditionCollection.removeConditions(3);266 expect(hookBeforeSpy).toHaveBeenCalledWith(3);267 expect(hookAfterSpy).toHaveBeenCalledWith(3);268 });269 it('should remove condition from collection and column index from orderStack', () => {270 const conditionCollection = new ConditionCollection();271 const conditionMock = {};272 spyOn(conditionCollection, 'clearConditions');273 conditionCollection.orderStack = [3];274 conditionCollection.conditions['3'] = [conditionMock];275 conditionCollection.removeConditions(3);276 expect(conditionCollection.orderStack).toEqual([]);277 expect(conditionCollection.clearConditions).toHaveBeenCalledWith(3);278 });279 });280 describe('clearConditions', () => {281 it('should trigger `beforeClear` and `afterClear` hook on clearing conditions', () => {282 const conditionCollection = new ConditionCollection();283 const hookBeforeSpy = jasmine.createSpy('hookBefore');284 const hookAfterSpy = jasmine.createSpy('hookAfter');285 conditionCollection.addLocalHook('beforeClear', hookBeforeSpy);286 conditionCollection.addLocalHook('afterClear', hookAfterSpy);287 conditionCollection.clearConditions(3);288 expect(hookBeforeSpy).toHaveBeenCalledWith(3);289 expect(hookAfterSpy).toHaveBeenCalledWith(3);290 });291 it('should clear all conditions at specified column index', () => {292 const conditionCollection = new ConditionCollection();293 const conditionsMock = [{}, {}];294 spyOn(conditionCollection, 'getConditions').and.returnValue(conditionsMock);295 conditionCollection.clearConditions(3);296 expect(conditionCollection.getConditions).toHaveBeenCalledWith(3);297 expect(conditionsMock.length).toBe(0);298 });299 });300 describe('hasConditions', () => {301 it('should return `true` if at specified column index condition were found', () => {302 const conditionCollection = new ConditionCollection();303 conditionCollection.columnTypes = { 3: OPERATION_AND };304 const conditionsMock = [{}, {}];305 spyOn(conditionCollection, 'getConditions').and.returnValue(conditionsMock);306 const result = conditionCollection.hasConditions(3);307 expect(result).toBe(true);308 });309 it('should return `false` if at specified column index no conditions were found', () => {310 const conditionCollection = new ConditionCollection();311 const conditionsMock = [];312 spyOn(conditionCollection, 'getConditions').and.returnValue(conditionsMock);313 const result = conditionCollection.hasConditions(3);314 expect(result).toBe(false);315 });316 it('should return `true` if at specified column index condition were found under its name', () => {317 const conditionCollection = new ConditionCollection();318 conditionCollection.columnTypes = { 3: OPERATION_AND };319 const conditionsMock = [{ name: 'lte' }, { name: 'eq' }];320 spyOn(conditionCollection, 'getConditions').and.returnValue(conditionsMock);321 const result = conditionCollection.hasConditions(3, 'eq');322 expect(result).toBe(true);323 });324 it('should return `false` if at specified column index no conditions were found under its name', () => {325 const conditionCollection = new ConditionCollection();326 conditionCollection.columnTypes = { 3: OPERATION_AND };327 const conditionsMock = [{ name: 'lte' }, { name: 'eq' }];328 spyOn(conditionCollection, 'getConditions').and.returnValue(conditionsMock);329 const result = conditionCollection.hasConditions(3, 'between');330 expect(conditionCollection.getConditions).toHaveBeenCalledWith(3);331 expect(result).toBe(false);332 });333 });334 describe('clean', () => {335 it('should trigger `beforeClean` and `afterClean` hook on cleaning conditions', () => {336 const conditionCollection = new ConditionCollection();337 conditionCollection.conditions = { 0: [] };338 conditionCollection.conditions = [1, 2, 3, 4];339 const hookBeforeSpy = jasmine.createSpy('hookBefore');340 const hookAfterSpy = jasmine.createSpy('hookAfter');341 conditionCollection.addLocalHook('beforeClean', hookBeforeSpy);342 conditionCollection.addLocalHook('afterClean', hookAfterSpy);343 conditionCollection.clean();344 expect(hookBeforeSpy).toHaveBeenCalled();345 expect(hookAfterSpy).toHaveBeenCalled();346 });347 it('should clear condition collection and orderStack', () => {348 const conditionCollection = new ConditionCollection();349 conditionCollection.conditions = { 0: [] };350 conditionCollection.conditions = [1, 2, 3, 4];351 conditionCollection.clean();352 expect(conditionCollection.conditions).toEqual(jasmine.any(Object));353 expect(Object.keys(conditionCollection.conditions)).toEqual(Object.keys(operations));354 expect(conditionCollection.orderStack.length).toBe(0);355 });356 });357 describe('destroy', () => {358 it('should nullable all properties', () => {359 const conditionCollection = new ConditionCollection();360 conditionCollection.conditions[OPERATION_AND] = { 0: [], 2: [] };361 conditionCollection.conditions[OPERATION_OR] = { 3: [], 4: [] };362 conditionCollection.orderStack = [1, 2, 3, 4];363 conditionCollection.destroy();364 expect(conditionCollection.conditions).toBeNull();365 expect(conditionCollection.orderStack).toBeNull();366 expect(conditionCollection.columnTypes).toBeNull();367 });368 });...

Full Screen

Full Screen

control.py

Source:control.py Github

copy

Full Screen

1## @package control2# Module caffe2.python.control3"""4Implement functions for controlling execution of nets and steps, including5 Do6 DoParallel7 For-loop8 While-loop9 Do-While-loop10 Switch11 If12"""13from __future__ import absolute_import14from __future__ import division15from __future__ import print_function16from __future__ import unicode_literals17from caffe2.python import core18from future.utils import viewitems19# Used to generate names of the steps created by the control functions.20# It is actually the internal index of these steps.21_current_idx = 122_used_step_names = set()23def _get_next_step_name(control_name, base_name):24 global _current_idx, _used_step_names25 concat_name = '%s/%s' % (base_name, control_name)26 next_name = concat_name27 while next_name in _used_step_names:28 next_name = '%s_%d' % (concat_name, _current_idx)29 _current_idx += 130 _used_step_names.add(next_name)31 return next_name32def _MakeList(input):33 """ input is a tuple.34 Example:35 (a, b, c) --> [a, b, c]36 (a) --> [a]37 ([a, b, c]) --> [a, b, c]38 """39 if len(input) == 0:40 raise ValueError(41 'input cannot be empty.')42 elif len(input) == 1:43 output = input[0]44 if not isinstance(output, list):45 output = [output]46 else:47 output = list(input)48 return output49def _IsNets(nets_or_steps):50 if isinstance(nets_or_steps, list):51 return all(isinstance(n, core.Net) for n in nets_or_steps)52 else:53 return isinstance(nets_or_steps, core.Net)54def _PrependNets(nets_or_steps, *nets):55 nets_or_steps = _MakeList((nets_or_steps,))56 nets = _MakeList(nets)57 if _IsNets(nets_or_steps):58 return nets + nets_or_steps59 else:60 return [Do('prepend', nets)] + nets_or_steps61def _AppendNets(nets_or_steps, *nets):62 nets_or_steps = _MakeList((nets_or_steps,))63 nets = _MakeList(nets)64 if _IsNets(nets_or_steps):65 return nets_or_steps + nets66 else:67 return nets_or_steps + [Do('append', nets)]68def GetConditionBlobFromNet(condition_net):69 """70 The condition blob is the last external_output that must71 be a single bool72 """73 assert len(condition_net.Proto().external_output) > 0, (74 "Condition net %s must has at least one external output" %75 condition_net.Proto.name)76 # we need to use a blob reference here instead of a string77 # otherwise, it will add another name_scope to the input later78 # when we create new ops (such as OR of two inputs)79 return core.BlobReference(condition_net.Proto().external_output[-1])80def BoolNet(*blobs_with_bool_value):81 """A net assigning constant bool values to blobs. It is mainly used for82 initializing condition blobs, for example, in multi-task learning, we83 need to access reader_done blobs before reader_net run. In that case,84 the reader_done blobs must be initialized.85 Args:86 blobs_with_bool_value: one or more (blob, bool_value) pairs. The net will87 assign each bool_value to the corresponding blob.88 returns89 bool_net: A net assigning constant bool values to blobs.90 Examples:91 - BoolNet((blob_1, bool_value_1), ..., (blob_n, bool_value_n))92 - BoolNet([(blob_1, net1), ..., (blob_n, bool_value_n)])93 - BoolNet((cond_1, bool_value_1))94 """95 blobs_with_bool_value = _MakeList(blobs_with_bool_value)96 bool_net = core.Net('bool_net')97 for blob, bool_value in blobs_with_bool_value:98 out_blob = bool_net.ConstantFill(99 [],100 [blob],101 shape=[],102 value=bool_value,103 dtype=core.DataType.BOOL)104 bool_net.AddExternalOutput(out_blob)105 return bool_net106def NotNet(condition_blob_or_net):107 """Not of a condition blob or net108 Args:109 condition_blob_or_net can be either blob or net. If condition_blob_or_net110 is Net, the condition is its last external_output111 that must be a single bool.112 returns113 not_net: the net NOT the input114 out_blob: the output blob of the not_net115 """116 if isinstance(condition_blob_or_net, core.Net):117 condition_blob = GetConditionBlobFromNet(condition_blob_or_net)118 else:119 condition_blob = condition_blob_or_net120 not_net = core.Net('not_net')121 out_blob = not_net.Not(condition_blob)122 not_net.AddExternalOutput(out_blob)123 return not_net, out_blob124def _CopyConditionBlobNet(condition_blob):125 """Make a condition net that copies the condition_blob126 Args:127 condition_blob is a single bool.128 returns129 not_net: the net NOT the input130 out_blob: the output blob of the not_net131 """132 condition_net = core.Net('copy_condition_blob_net')133 out_blob = condition_net.Copy(condition_blob)134 condition_net.AddExternalOutput(out_blob)135 return condition_net, out_blob136def MergeConditionNets(name, condition_nets, relation):137 """138 Merge multi condition nets into a single condition nets.139 Args:140 name: name of the new condition net.141 condition_nets: a list of condition nets. The last external_output142 of each condition net must be single bool value.143 relation: can be 'And' or 'Or'.144 Returns:145 - A new condition net. Its last external output is relation of all146 condition_nets.147 """148 if not isinstance(condition_nets, list):149 return condition_nets150 if len(condition_nets) <= 1:151 return condition_nets[0] if condition_nets else None152 merged_net = core.Net(name)153 for i in range(len(condition_nets)):154 net_proto = condition_nets[i].Proto()155 assert net_proto.device_option == merged_net.Proto().device_option156 assert net_proto.type == merged_net.Proto().type157 merged_net.Proto().op.extend(net_proto.op)158 merged_net.Proto().external_input.extend(net_proto.external_input)159 # discard external outputs as we're combining them together160 curr_cond = GetConditionBlobFromNet(condition_nets[i])161 if i == 0:162 last_cond = curr_cond163 else:164 last_cond = merged_net.__getattr__(relation)([last_cond, curr_cond])165 # merge attributes166 for k, v in viewitems(condition_nets[i]._attr_dict):167 merged_net._attr_dict[k] += v168 merged_net.AddExternalOutput(last_cond)169 return merged_net170def CombineConditions(name, condition_nets, relation):171 """172 Combine conditions of multi nets into a single condition nets. Unlike173 MergeConditionNets, the actual body of condition_nets is not copied into174 the combine condition net.175 One example is about multi readers. Each reader net has a reader_done176 condition. When we want to check whether all readers are done, we can177 use this function to build a new net.178 Args:179 name: name of the new condition net.180 condition_nets: a list of condition nets. The last external_output181 of each condition net must be single bool value.182 relation: can be 'And' or 'Or'.183 Returns:184 - A new condition net. Its last external output is relation of all185 condition_nets.186 """187 if not condition_nets:188 return None189 if not isinstance(condition_nets, list):190 raise ValueError('condition_nets must be a list of nets.')191 if len(condition_nets) == 1:192 condition_blob = GetConditionBlobFromNet(condition_nets[0])193 condition_net, _ = _CopyConditionBlobNet(condition_blob)194 return condition_net195 combined_net = core.Net(name)196 for i in range(len(condition_nets)):197 curr_cond = GetConditionBlobFromNet(condition_nets[i])198 if i == 0:199 last_cond = curr_cond200 else:201 last_cond = combined_net.__getattr__(relation)(202 [last_cond, curr_cond])203 combined_net.AddExternalOutput(last_cond)204 return combined_net205def Do(name, *nets_or_steps):206 """207 Execute the sequence of nets or steps once.208 Examples:209 - Do('myDo', net1, net2, ..., net_n)210 - Do('myDo', list_of_nets)211 - Do('myDo', step1, step2, ..., step_n)212 - Do('myDo', list_of_steps)213 """214 nets_or_steps = _MakeList(nets_or_steps)215 if (len(nets_or_steps) == 1 and isinstance(216 nets_or_steps[0], core.ExecutionStep)):217 return nets_or_steps[0]218 else:219 return core.scoped_execution_step(220 _get_next_step_name('Do', name), nets_or_steps)221def DoParallel(name, *nets_or_steps):222 """223 Execute the nets or steps in parallel, waiting for all of them to finish224 Examples:225 - DoParallel('pDo', net1, net2, ..., net_n)226 - DoParallel('pDo', list_of_nets)227 - DoParallel('pDo', step1, step2, ..., step_n)228 - DoParallel('pDo', list_of_steps)229 """230 nets_or_steps = _MakeList(nets_or_steps)231 if (len(nets_or_steps) == 1 and isinstance(232 nets_or_steps[0], core.ExecutionStep)):233 return nets_or_steps[0]234 else:235 return core.scoped_execution_step(236 _get_next_step_name('DoParallel', name),237 nets_or_steps,238 concurrent_substeps=True)239def _RunOnceIf(name, condition_blob_or_net, nets_or_steps):240 """241 Execute nets_or_steps once if condition_blob_or_net evaluates as true.242 If condition_blob_or_net is Net, the condition is its last external_output243 that must be a single bool. And this net will be executed before244 nets_or_steps so as to get the condition.245 """246 condition_not_net, stop_blob = NotNet(condition_blob_or_net)247 if isinstance(condition_blob_or_net, core.Net):248 nets_or_steps = _PrependNets(249 nets_or_steps, condition_blob_or_net, condition_not_net)250 else:251 nets_or_steps = _PrependNets(nets_or_steps, condition_not_net)252 def if_step(control_name):253 return core.scoped_execution_step(254 _get_next_step_name(control_name, name),255 nets_or_steps,256 should_stop_blob=stop_blob,257 only_once=True,258 )259 if _IsNets(nets_or_steps):260 bool_net = BoolNet((stop_blob, False))261 return Do(name + '/_RunOnceIf',262 bool_net, if_step('_RunOnceIf-inner'))263 else:264 return if_step('_RunOnceIf')265def _RunOnceIfNot(name, condition_blob_or_net, nets_or_steps):266 """267 Similar to _RunOnceIf() but Execute nets_or_steps once if268 condition_blob_or_net evaluates as false.269 """270 if isinstance(condition_blob_or_net, core.Net):271 condition_blob = GetConditionBlobFromNet(condition_blob_or_net)272 nets_or_steps = _PrependNets(nets_or_steps, condition_blob_or_net)273 else:274 copy_net, condition_blob = _CopyConditionBlobNet(condition_blob_or_net)275 nets_or_steps = _PrependNets(nets_or_steps, copy_net)276 return core.scoped_execution_step(277 _get_next_step_name('_RunOnceIfNot', name),278 nets_or_steps,279 should_stop_blob=condition_blob,280 only_once=True,281 )282def For(name, nets_or_steps, iter_num):283 """284 Execute nets_or_steps iter_num times.285 Args:286 nets_or_steps: a ExecutionStep or a Net or a list of ExecutionSteps or287 a list nets.288 iter_num: the number times to execute the nets_or_steps.289 Returns:290 A ExecutionStep instance.291 """292 init_net = core.Net('init-net')293 iter_cnt = init_net.CreateCounter([], init_count=iter_num)294 iter_net = core.Net('For-iter')295 iter_done = iter_net.CountDown([iter_cnt])296 for_step = core.scoped_execution_step(297 _get_next_step_name('For-inner', name),298 _PrependNets(nets_or_steps, iter_net),299 should_stop_blob=iter_done)300 return Do(name + '/For',301 Do(name + '/For-init-net', init_net),302 for_step)303def While(name, condition_blob_or_net, nets_or_steps):304 """305 Execute nets_or_steps when condition_blob_or_net returns true.306 Args:307 condition_blob_or_net: If it is an instance of Net, its last308 external_output must be a single bool.309 nets_or_steps: a ExecutionStep or a Net or a list of ExecutionSteps or310 a list nets.311 Returns:312 A ExecutionStep instance.313 """314 condition_not_net, stop_blob = NotNet(condition_blob_or_net)315 if isinstance(condition_blob_or_net, core.Net):316 nets_or_steps = _PrependNets(317 nets_or_steps, condition_blob_or_net, condition_not_net)318 else:319 nets_or_steps = _PrependNets(nets_or_steps, condition_not_net)320 def while_step(control_name):321 return core.scoped_execution_step(322 _get_next_step_name(control_name, name),323 nets_or_steps,324 should_stop_blob=stop_blob,325 )326 if _IsNets(nets_or_steps):327 # In this case, while_step has sub-nets:328 # [condition_blob_or_net, condition_not_net, nets_or_steps]329 # If stop_blob is pre-set to True (this may happen when While() is330 # called twice), the loop will exit after executing331 # condition_blob_or_net. So we use BootNet to set stop_blob to332 # False.333 bool_net = BoolNet((stop_blob, False))334 return Do(name + '/While', bool_net, while_step('While-inner'))335 else:336 return while_step('While')337def Until(name, condition_blob_or_net, nets_or_steps):338 """339 Similar to While() but execute nets_or_steps when340 condition_blob_or_net returns false341 """342 if isinstance(condition_blob_or_net, core.Net):343 stop_blob = GetConditionBlobFromNet(condition_blob_or_net)344 nets_or_steps = _PrependNets(nets_or_steps, condition_blob_or_net)345 else:346 stop_blob = core.BlobReference(str(condition_blob_or_net))347 return core.scoped_execution_step(348 _get_next_step_name('Until', name),349 nets_or_steps,350 should_stop_blob=stop_blob)351def DoWhile(name, condition_blob_or_net, nets_or_steps):352 """353 Execute nets_or_steps when condition_blob_or_net returns true. It will354 execute nets_or_steps before evaluating condition_blob_or_net.355 Args:356 condition_blob_or_net: if it is an instance of Net, tts last external_output357 must be a single bool.358 nets_or_steps: a ExecutionStep or a Net or a list of ExecutionSteps or359 a list nets.360 Returns:361 A ExecutionStep instance.362 """363 condition_not_net, stop_blob = NotNet(condition_blob_or_net)364 if isinstance(condition_blob_or_net, core.Net):365 nets_or_steps = _AppendNets(366 nets_or_steps, condition_blob_or_net, condition_not_net)367 else:368 nets_or_steps = _AppendNets(nets_or_steps, condition_not_net)369 # If stop_blob is pre-set to True (this may happen when DoWhile() is370 # called twice), the loop will exit after executing the first net/step371 # in nets_or_steps. This is not what we want. So we use BootNet to372 # set stop_blob to False.373 bool_net = BoolNet((stop_blob, False))374 return Do(name + '/DoWhile', bool_net, core.scoped_execution_step(375 _get_next_step_name('DoWhile-inner', name),376 nets_or_steps,377 should_stop_blob=stop_blob,378 ))379def DoUntil(name, condition_blob_or_net, nets_or_steps):380 """381 Similar to DoWhile() but execute nets_or_steps when382 condition_blob_or_net returns false. It will execute383 nets_or_steps before evaluating condition_blob_or_net.384 Special case: if condition_blob_or_net is a blob and is pre-set to385 true, then only the first net/step of nets_or_steps will be executed and386 loop is exited. So you need to be careful about the initial value the387 condition blob when using DoUntil(), esp when DoUntil() is called twice.388 """389 if not isinstance(condition_blob_or_net, core.Net):390 stop_blob = core.BlobReference(condition_blob_or_net)391 return core.scoped_execution_step(392 _get_next_step_name('DoUntil', name),393 nets_or_steps,394 should_stop_blob=stop_blob)395 nets_or_steps = _AppendNets(nets_or_steps, condition_blob_or_net)396 stop_blob = GetConditionBlobFromNet(condition_blob_or_net)397 # If stop_blob is pre-set to True (this may happen when DoWhile() is398 # called twice), the loop will exit after executing the first net/step399 # in nets_or_steps. This is not what we want. So we use BootNet to400 # set stop_blob to False.401 bool_net = BoolNet((stop_blob, False))402 return Do(name + '/DoUntil', bool_net, core.scoped_execution_step(403 _get_next_step_name('DoUntil-inner', name),404 nets_or_steps,405 should_stop_blob=stop_blob,406 ))407def Switch(name, *conditions):408 """409 Execute the steps for which the condition is true.410 Each condition is a tuple (condition_blob_or_net, nets_or_steps).411 Note:412 1. Multi steps can be executed if their conditions are true.413 2. The conditions_blob_or_net (if it is Net) of all steps will be414 executed once.415 Examples:416 - Switch('name', (cond_1, net_1), (cond_2, net_2), ..., (cond_n, net_n))417 - Switch('name', [(cond_1, net1), (cond_2, net_2), ..., (cond_n, net_n)])418 - Switch('name', (cond_1, net_1))419 """420 conditions = _MakeList(conditions)421 return core.scoped_execution_step(422 _get_next_step_name('Switch', name),423 [_RunOnceIf(name + '/Switch', cond, step) for cond, step in conditions])424def SwitchNot(name, *conditions):425 """426 Similar to Switch() but execute the steps for which the condition is False.427 """428 conditions = _MakeList(conditions)429 return core.scoped_execution_step(430 _get_next_step_name('SwitchNot', name),431 [_RunOnceIfNot(name + '/SwitchNot', cond, step)432 for cond, step in conditions])433def If(name, condition_blob_or_net,434 true_nets_or_steps, false_nets_or_steps=None):435 """436 condition_blob_or_net is first evaluated or executed. If the condition is437 true, true_nets_or_steps is then executed, otherwise, false_nets_or_steps438 is executed.439 If condition_blob_or_net is Net, the condition is its last external_output440 that must be a single bool. And this Net will be executred before both441 true/false_nets_or_steps so as to get the condition.442 """443 if not false_nets_or_steps:444 return _RunOnceIf(name + '/If',445 condition_blob_or_net, true_nets_or_steps)446 if isinstance(condition_blob_or_net, core.Net):447 condition_blob = GetConditionBlobFromNet(condition_blob_or_net)448 else:449 condition_blob = condition_blob_or_net450 return Do(451 name + '/If',452 _RunOnceIf(name + '/If-true',453 condition_blob_or_net, true_nets_or_steps),454 _RunOnceIfNot(name + '/If-false', condition_blob, false_nets_or_steps)455 )456def IfNot(name, condition_blob_or_net,457 true_nets_or_steps, false_nets_or_steps=None):458 """459 If condition_blob_or_net returns false, executes true_nets_or_steps,460 otherwise executes false_nets_or_steps461 """462 if not false_nets_or_steps:463 return _RunOnceIfNot(name + '/IfNot',464 condition_blob_or_net, true_nets_or_steps)465 if isinstance(condition_blob_or_net, core.Net):466 condition_blob = GetConditionBlobFromNet(condition_blob_or_net)467 else:468 condition_blob = condition_blob_or_net469 return Do(470 name + '/IfNot',471 _RunOnceIfNot(name + '/IfNot-true',472 condition_blob_or_net, true_nets_or_steps),473 _RunOnceIf(name + '/IfNot-false', condition_blob, false_nets_or_steps)...

Full Screen

Full Screen

aws.pyi

Source:aws.pyi Github

copy

Full Screen

...117 "StringLike",118 "StringNotLike",119]120_condition_qualifier_strings = ["ForAnyValue", "ForAllValues"]121def make_condition(type_name: str, condition_name: str) -> None: ...122class ArnEquals(ConditionElement): ...123class ArnNotEquals(ConditionElement): ...124class ArnLike(ConditionElement): ...125class ArnNotLike(ConditionElement): ...126class Bool(ConditionElement): ...127class DateEquals(ConditionElement): ...128class DateNotEquals(ConditionElement): ...129class DateLessThan(ConditionElement): ...130class DateLessThanEquals(ConditionElement): ...131class DateGreaterThan(ConditionElement): ...132class DateGreaterThanEquals(ConditionElement): ...133class IpAddress(ConditionElement): ...134class NotIpAddress(ConditionElement): ...135class Null(ConditionElement): ......

Full Screen

Full Screen

test_condition.py

Source:test_condition.py Github

copy

Full Screen

...23 return factories.RangeFactory(24 name="Some products", products=products_some25 )26@pytest.fixture27def count_condition(range_all):28 return models.CountCondition(range=range_all, type="Count", value=2)29@pytest.fixture30def value_condition(range_all):31 return models.ValueCondition(range=range_all, type="Value", value=D("10.00"))32@pytest.fixture33def coverage_condition(range_some):34 return models.CoverageCondition(range=range_some, type="Coverage", value=2)35@pytest.fixture36def empty_basket():37 return factories.create_basket(empty=True)38@pytest.fixture39def partial_basket(empty_basket):40 basket = empty_basket41 add_product(basket)42 return basket43@pytest.fixture44def mock_offer():45 return mock.Mock()46@pytest.mark.django_db47class TestCountCondition:48 @pytest.fixture(autouse=True)49 def setUp(self, mock_offer):50 self.offer = mock_offer51 def test_description(self, count_condition):52 assert count_condition.description53 def test_is_not_satisfied_by_empty_basket(self, count_condition, empty_basket):54 assert count_condition.is_satisfied(self.offer, empty_basket) is False55 def test_not_discountable_product_fails_condition(56 self, count_condition, empty_basket57 ):58 basket = empty_basket59 prod1, prod2 = factories.create_product(), factories.create_product()60 prod2.is_discountable = False61 prod2.save()62 add_product(basket, product=prod1)63 add_product(basket, product=prod2)64 assert count_condition.is_satisfied(self.offer, basket) is False65 def test_empty_basket_fails_partial_condition(self, count_condition, empty_basket):66 assert count_condition.is_partially_satisfied(self.offer, empty_basket) is False67 def test_smaller_quantity_basket_passes_partial_condition(68 self, count_condition, empty_basket69 ):70 basket = empty_basket71 add_product(basket)72 assert count_condition.is_partially_satisfied(self.offer, basket)73 assert count_condition._num_matches == 174 def test_smaller_quantity_basket_upsell_message(75 self, count_condition, empty_basket76 ):77 basket = empty_basket78 add_product(basket)79 assert "Buy 1 more product from " in count_condition.get_upsell_message(80 self.offer, basket81 )82 def test_matching_quantity_basket_fails_partial_condition(83 self, count_condition, empty_basket84 ):85 basket = empty_basket86 add_product(basket, quantity=2)87 assert count_condition.is_partially_satisfied(self.offer, basket) is False88 def test_matching_quantity_basket_passes_condition(89 self, count_condition, empty_basket90 ):91 basket = empty_basket92 add_product(basket, quantity=2)93 assert count_condition.is_satisfied(self.offer, basket)94 def test_greater_quantity_basket_passes_condition(95 self, count_condition, empty_basket96 ):97 basket = empty_basket98 add_product(basket, quantity=3)99 assert count_condition.is_satisfied(self.offer, basket)100 def test_consumption(self, count_condition, empty_basket):101 basket = empty_basket102 add_product(basket, quantity=3)103 count_condition.consume_items(self.offer, basket, [])104 assert 1 == basket.all_lines()[0].quantity_without_discount105 def test_is_satisfied_accounts_for_consumed_items(106 self, count_condition, empty_basket107 ):108 basket = empty_basket109 add_product(basket, quantity=3)110 count_condition.consume_items(self.offer, basket, [])111 assert count_condition.is_satisfied(self.offer, basket) is False112@pytest.mark.django_db113class TestValueCondition:114 @pytest.fixture(autouse=True)115 def setUp(self, empty_basket, value_condition, mock_offer):116 self.basket = empty_basket117 self.condition = value_condition118 self.offer = mock_offer119 self.item = factories.create_product(price=D("5.00"))120 self.expensive_item = factories.create_product(price=D("15.00"))121 def test_description(self, value_condition):122 assert value_condition.description123 def test_empty_basket_fails_condition(self):124 assert self.condition.is_satisfied(self.offer, self.basket) is False125 def test_empty_basket_fails_partial_condition(self):126 assert self.condition.is_partially_satisfied(self.offer, self.basket) is False127 def test_less_value_basket_fails_condition(self):128 add_product(self.basket, D("5"))129 assert self.condition.is_satisfied(self.offer, self.basket) is False130 def test_not_discountable_item_fails_condition(self):131 product = factories.create_product(is_discountable=False)132 add_product(self.basket, D("15"), product=product)133 assert self.condition.is_satisfied(self.offer, self.basket) is False134 def test_upsell_message(self):135 add_product(self.basket, D("5"))136 assert "Spend" in self.condition.get_upsell_message(self.offer, self.basket)137 def test_matching_basket_fails_partial_condition(self):138 add_product(self.basket, D("5"), 2)139 assert self.condition.is_partially_satisfied(self.offer, self.basket) is False140 def test_less_value_basket_passes_partial_condition(self):141 add_product(self.basket, D("5"), 1)142 assert self.condition.is_partially_satisfied(self.offer, self.basket)143 def test_matching_basket_passes_condition(self):144 add_product(self.basket, D("5"), 2)145 assert self.condition.is_satisfied(self.offer, self.basket)146 def test_greater_than_basket_passes_condition(self):147 add_product(self.basket, D("5"), 3)148 assert self.condition.is_satisfied(self.offer, self.basket)149 def test_consumption(self):150 add_product(self.basket, D("5"), 3)151 self.condition.consume_items(self.offer, self.basket, [])152 assert 1 == self.basket.all_lines()[0].quantity_without_discount153 def test_consumption_with_high_value_product(self):154 add_product(self.basket, D("15"), 1)155 self.condition.consume_items(self.offer, self.basket, [])156 assert 0 == self.basket.all_lines()[0].quantity_without_discount157 def test_is_consumed_respects_quantity_consumed(self):158 add_product(self.basket, D("15"), 1)159 assert self.condition.is_satisfied(self.offer, self.basket)160 self.condition.consume_items(self.offer, self.basket, [])161 assert self.condition.is_satisfied(self.offer, self.basket) is False162@pytest.mark.django_db163class TestCoverageCondition:164 @pytest.fixture(autouse=True)165 def setUp(self, range_some, products_some, empty_basket, coverage_condition):166 self.products = products_some167 self.range = range_some168 self.basket = empty_basket169 self.condition = coverage_condition170 self.offer = mock.Mock()171 def test_empty_basket_fails(self):172 assert self.condition.is_satisfied(self.offer, self.basket) is False173 def test_empty_basket_fails_partial_condition(self):174 assert self.condition.is_partially_satisfied(self.offer, self.basket) is False175 def test_single_item_fails(self):176 add_product(self.basket, product=self.products[0])177 assert self.condition.is_satisfied(self.offer, self.basket) is False178 def test_not_discountable_item_fails(self):179 self.products[0].is_discountable = False180 self.products[0].save()181 add_product(self.basket, product=self.products[0])182 add_product(self.basket, product=self.products[1])183 assert self.condition.is_satisfied(self.offer, self.basket) is False184 def test_single_item_passes_partial_condition(self):185 add_product(self.basket, product=self.products[0])186 assert self.condition.is_partially_satisfied(self.offer, self.basket)187 def test_upsell_message(self):188 add_product(self.basket, product=self.products[0])189 assert "Buy 1 more" in self.condition.get_upsell_message(190 self.offer, self.basket191 )192 def test_duplicate_item_fails(self):193 add_product(self.basket, quantity=2, product=self.products[0])194 assert self.condition.is_satisfied(self.offer, self.basket) is False195 def test_duplicate_item_passes_partial_condition(self):196 add_product(self.basket, quantity=2, product=self.products[0])197 assert self.condition.is_partially_satisfied(self.offer, self.basket)198 def test_covering_items_pass(self):199 add_product(self.basket, product=self.products[0])200 add_product(self.basket, product=self.products[1])201 assert self.condition.is_satisfied(self.offer, self.basket)202 def test_covering_items_fail_partial_condition(self):203 add_product(self.basket, product=self.products[0])204 add_product(self.basket, product=self.products[1])205 assert self.condition.is_partially_satisfied(self.offer, self.basket) is False206 def test_covering_items_are_consumed(self):207 add_product(self.basket, product=self.products[0])208 add_product(self.basket, product=self.products[1])209 self.condition.consume_items(self.offer, self.basket, [])210 assert 0 == self.basket.num_items_without_discount211 def test_consumed_items_checks_affected_items(self):212 # Create new offer213 range = models.Range.objects.create(214 name="All products", includes_all_products=True215 )216 cond = models.CoverageCondition(range=range, type="Coverage", value=2)217 # Get 4 distinct products in the basket218 self.products.extend([factories.create_product(), factories.create_product()])219 for product in self.products:220 add_product(self.basket, product=product)221 assert cond.is_satisfied(self.offer, self.basket)222 cond.consume_items(self.offer, self.basket, [])223 assert 2 == self.basket.num_items_without_discount224 assert cond.is_satisfied(self.offer, self.basket)225 cond.consume_items(self.offer, self.basket, [])226 assert 0 == self.basket.num_items_without_discount227@pytest.mark.django_db228class TestConditionProxyModels(object):229 def test_name_and_description(self, range):230 """231 Tests that the condition proxy classes all return a name and232 description. Unfortunately, the current implementations means233 a valid range and value are required.234 """235 for type, __ in models.Condition.TYPE_CHOICES:236 condition = models.Condition(type=type, range=range, value=5)237 assert all([condition.name, condition.description, str(condition)])238 def test_proxy(self, range):239 for type, __ in models.Condition.TYPE_CHOICES:240 condition = models.Condition(type=type, range=range, value=5)241 proxy = condition.proxy()242 assert condition.type == proxy.type243 assert condition.range == proxy.range244 assert condition.value == proxy.value245class TestCustomCondition(TestCase):246 def setUp(self):247 self.condition = custom.create_condition(BasketOwnerCalledBarry)248 self.offer = models.ConditionalOffer(condition=self.condition)249 self.basket = Basket()250 def test_is_not_satisfied_by_non_match(self):251 self.basket.owner = factories.UserFactory(first_name="Alan")252 assert self.offer.is_condition_satisfied(self.basket) is False253 def test_is_satisfied_by_match(self):254 self.basket.owner = factories.UserFactory(first_name="Barry")...

Full Screen

Full Screen

serializers.py

Source:serializers.py Github

copy

Full Screen

...90 if ng_keyword_condition["ng_keyword"] == "全体":91 print(ng_keywords)92 for ng_keyword in ng_keywords:93 remained_ng_keywords.remove(ng_keyword) if ng_keyword in remained_ng_keywords else remained_ng_keywords94 self.create_ng_keyword_condition(ng_keyword, product_condition, ng_keyword_condition)95 else:96 ng_keyword = ng_keyword_condition["ng_keyword"]97 remained_ng_keywords.remove(ng_keyword) if ng_keyword in remained_ng_keywords else remained_ng_keywords98 self.create_ng_keyword_condition(ng_keyword, product_condition, ng_keyword_condition)99 100 for ng_keyword in remained_ng_keywords:101 self.create_ng_keyword_condition(ng_keyword, product_condition)102 return product_condition103 def create_ng_keyword_condition(self, ng_keyword_name, product_condition, ng_keyword_condition=None):104 ng_keyword,_ = NG_Keyword.objects.get_or_create(name=ng_keyword_name)105 if ng_keyword_condition is not None:106 composite_keyword,_ = Composite_Keyword.objects.get_or_create(name=ng_keyword_condition["composite_keyword"])107 108 ng_keyword_condition_data = {109 "ng_keyword": ng_keyword,110 "composite_keyword": composite_keyword,111 "front_check_word_count": ng_keyword_condition["front_check_word_count"],112 "back_check_word_count": ng_keyword_condition["back_check_word_count"],113 "product_condition": product_condition114 }115 else:116 ng_keyword_condition_data = {117 "ng_keyword": ng_keyword,...

Full Screen

Full Screen

condition_quality.py

Source:condition_quality.py Github

copy

Full Screen

1import os2import sys3sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))4from cakechat.utils.env import init_cuda_env5init_cuda_env()6from cakechat.utils.dataset_loader import load_datasets7from cakechat.utils.data_types import Dataset8from cakechat.utils.logger import get_tools_logger9from cakechat.dialog_model.factory import get_trained_model10from cakechat.dialog_model.model_utils import transform_token_ids_to_sentences11from cakechat.dialog_model.inference import get_nn_responses12from cakechat.dialog_model.quality import calculate_model_mean_perplexity, get_tfidf_vectorizer, \13 calculate_lexical_similarity14from cakechat.config import PREDICTION_MODE_FOR_TESTS, DEFAULT_CONDITION15_logger = get_tools_logger(__file__)16def _make_non_conditioned(dataset):17 return Dataset(x=dataset.x, y=dataset.y, condition_ids=None)18def _slice_condition_data(dataset, condition_id):19 condition_mask = (dataset.condition_ids == condition_id)20 return Dataset(21 x=dataset.x[condition_mask], y=dataset.y[condition_mask], condition_ids=dataset.condition_ids[condition_mask])22def calc_perplexity_metrics(nn_model, eval_datasets):23 return {24 'ppl_cs_test':25 calculate_model_mean_perplexity(nn_model, eval_datasets.cs_test),26 'ppl_cs_test_not_conditioned':27 calculate_model_mean_perplexity(nn_model, _make_non_conditioned(eval_datasets.cs_test)),28 'ppl_cs_test_one_condition':29 calculate_model_mean_perplexity(nn_model, eval_datasets.cs_test_one_condition),30 'ppl_cs_test_one_condition_not_conditioned':31 calculate_model_mean_perplexity(nn_model, _make_non_conditioned(eval_datasets.cs_test_one_condition)),32 'ppl_cf_validation':33 calculate_model_mean_perplexity(nn_model, eval_datasets.cf_validation)34 }35def calc_perplexity_for_conditions(nn_model, dataset):36 cond_to_ppl_conditioned, cond_to_ppl_not_conditioned = {}, {}37 for condition, condition_id in nn_model.condition_to_index.items():38 if condition == DEFAULT_CONDITION:39 continue40 dataset_with_conditions = _slice_condition_data(dataset, condition_id)41 if not dataset_with_conditions.x.size:42 _logger.warning(43 'No dataset samples found with the given condition "{}", skipping metrics.'.format(condition))44 continue45 cond_to_ppl_conditioned[condition] = \46 calculate_model_mean_perplexity(nn_model, _make_non_conditioned(dataset_with_conditions))47 cond_to_ppl_not_conditioned[condition] = \48 calculate_model_mean_perplexity(nn_model, dataset_with_conditions)49 return cond_to_ppl_conditioned, cond_to_ppl_not_conditioned50def predict_for_condition_id(nn_model, x_val, condition_id=None):51 responses = get_nn_responses(x_val, nn_model, mode=PREDICTION_MODE_FOR_TESTS, condition_ids=condition_id)52 return [candidates[0] for candidates in responses]53def calc_lexical_similarity_metrics(nn_model, testset, tfidf_vectorizer):54 """55 For each condition calculate lexical similarity between ground-truth responses and56 generated conditioned responses. Similarly compare ground-truth responses with non-conditioned generated responses.57 If lex_sim(gt, cond_resp) > lex_sim(gt, non_cond_resp), the conditioning on extra information proves to be useful.58 :param nn_model: trained model to evaluate59 :param testset: context-sensitive testset, instance of Dataset60 :param tfidf_vectorizer: instance of scikit-learn TfidfVectorizer, calculates lexical similariry for documents61 according to TF-IDF metric62 :return: two dictionaries:63 {condition: lex_sim(gt, cond_resp)},64 {condition: lex_sim(gt, non_cond_resp)}65 """66 gt_vs_cond_lex_sim, gt_vs_non_cond_lex_sim = {}, {}67 for condition, condition_id in nn_model.condition_to_index.items():68 sample_mask_for_condition = testset.condition_ids == condition_id69 contexts_for_condition = testset.x[sample_mask_for_condition]70 responses_for_condition = testset.y[sample_mask_for_condition]71 if not responses_for_condition.size:72 _logger.warning('No dataset samples found for condition "{}", skip it.'.format(condition))73 continue74 gt_responses = transform_token_ids_to_sentences(responses_for_condition, nn_model.index_to_token)75 conditioned_responses = predict_for_condition_id(nn_model, contexts_for_condition, condition_id)76 non_conditioned_responses = predict_for_condition_id(nn_model, contexts_for_condition, condition_id=None)77 gt_vs_cond_lex_sim[condition] = \78 calculate_lexical_similarity(gt_responses, conditioned_responses, tfidf_vectorizer)79 gt_vs_non_cond_lex_sim[condition] = \80 calculate_lexical_similarity(gt_responses, non_conditioned_responses, tfidf_vectorizer)81 return gt_vs_cond_lex_sim, gt_vs_non_cond_lex_sim82if __name__ == '__main__':83 nn_model = get_trained_model()84 eval_datasets = load_datasets(nn_model.token_to_index, nn_model.condition_to_index)85 print('\nPerplexity on datasets:')86 for dataset, perplexity in calc_perplexity_metrics(nn_model, eval_datasets).items():87 print('\t{}: \t{:.1f}'.format(dataset, perplexity))88 cond_to_ppl_conditioned, cond_to_ppl_not_conditioned = \89 calc_perplexity_for_conditions(nn_model, eval_datasets.cs_test)90 print('\nPerplexity on conditioned testset for conditions:')91 for condition, perplexity in cond_to_ppl_conditioned.items():92 print('\t{}: \t{:.1f}'.format(condition, perplexity))93 print('\nPerplexity on non-conditioned testset for conditions:')94 for condition, perplexity in cond_to_ppl_not_conditioned.items():95 print('\t{}: \t{:.1f}'.format(condition, perplexity))96 gt_vs_cond_lex_sim, gt_vs_non_cond_lex_sim = \97 calc_lexical_similarity_metrics(nn_model, eval_datasets.cs_test, get_tfidf_vectorizer())98 print('\nLexical similarity, ground-truth vs. conditioned responses:')99 for condition, lex_sim in gt_vs_cond_lex_sim.items():100 print('\t{}: \t{:.2f}'.format(condition, lex_sim))101 print('\nLexical similarity, ground-truth vs. non-conditioned responses:')102 for condition, lex_sim in gt_vs_non_cond_lex_sim.items():...

Full Screen

Full Screen

ConditionalProps.js

Source:ConditionalProps.js Github

copy

Full Screen

1'use strict';2var is = require('bpmn-js/lib/util/ModelUtil').is,3 isAny = require('bpmn-js/lib/features/modeling/util/ModelingUtil').isAny,4 getBusinessObject = require('bpmn-js/lib/util/ModelUtil').getBusinessObject,5 escapeHTML = require('../../../Utils').escapeHTML,6 domQuery = require('min-dom').query,7 cmdHelper = require('../../../helper/CmdHelper'),8 elementHelper = require('../../../helper/ElementHelper'),9 eventDefinitionHelper = require('../../../helper/EventDefinitionHelper'),10 scriptImplementation = require('./implementation/Script');11module.exports = function(group, element, bpmnFactory, translate) {12 var bo = getBusinessObject(element);13 if (!bo) {14 return;15 }16 var conditionalEventDefinition = eventDefinitionHelper.getConditionalEventDefinition(element);17 if (!(is(element, 'bpmn:SequenceFlow') && isConditionalSource(element.source))18 && !conditionalEventDefinition) {19 return;20 }21 var script = scriptImplementation('language', 'body', true, translate);22 group.entries.push({23 id: 'condition',24 label: translate('Condition'),25 html: '<div class="bpp-row">' +26 '<label for="cam-condition-type">'+ escapeHTML(translate('Condition Type')) + '</label>' +27 '<div class="bpp-field-wrapper">' +28 '<select id="cam-condition-type" name="conditionType" data-value>' +29 '<option value="expression">'+ escapeHTML(translate('Expression')) + '</option>' +30 '<option value="script">'+ escapeHTML(translate('Script')) + '</option>' +31 '<option value="" selected></option>' +32 '</select>' +33 '</div>' +34 '</div>' +35 // expression36 '<div class="bpp-row">' +37 '<label for="cam-condition" data-show="isExpression">' + escapeHTML(translate('Expression')) + '</label>' +38 '<div class="bpp-field-wrapper" data-show="isExpression">' +39 '<input id="cam-condition" type="text" name="condition" />' +40 '<button class="clear" data-action="clear" data-show="canClear">' +41 '<span>X</span>' +42 '</button>' +43 '</div>' +44 '<div data-show="isScript">' +45 script.template +46 '</div>' +47 '</div>',48 get: function(element, propertyName) {49 var conditionalEventDefinition = eventDefinitionHelper.getConditionalEventDefinition(element);50 var conditionExpression = conditionalEventDefinition51 ? conditionalEventDefinition.condition52 : bo.conditionExpression;53 var values = {},54 conditionType = '';55 if (conditionExpression) {56 var conditionLanguage = conditionExpression.language;57 if (typeof conditionLanguage !== 'undefined') {58 conditionType = 'script';59 values = script.get(element, conditionExpression);60 } else {61 conditionType = 'expression';62 values.condition = conditionExpression.get('body');63 }64 }65 values.conditionType = conditionType;66 return values;67 },68 set: function(element, values, containerElement) {69 var conditionType = values.conditionType;70 var commands = [];71 var conditionProps = {72 body: undefined73 };74 if (conditionType === 'script') {75 conditionProps = script.set(element, values, containerElement);76 } else {77 var condition = values.condition;78 conditionProps.body = condition;79 }80 var conditionOrConditionExpression;81 if (conditionType) {82 conditionOrConditionExpression = elementHelper.createElement(83 'bpmn:FormalExpression',84 conditionProps,85 conditionalEventDefinition || bo,86 bpmnFactory87 );88 var source = element.source;89 // if default-flow, remove default-property from source90 if (source && source.businessObject.default === bo) {91 commands.push(cmdHelper.updateProperties(source, { 'default': undefined }));92 }93 }94 var update = conditionalEventDefinition95 ? { condition: conditionOrConditionExpression }96 : { conditionExpression: conditionOrConditionExpression };97 commands.push(cmdHelper.updateBusinessObject(element, conditionalEventDefinition || bo, update));98 return commands;99 },100 validate: function(element, values) {101 var validationResult = {};102 if (!values.condition && values.conditionType === 'expression') {103 validationResult.condition = translate('Must provide a value');104 }105 else if (values.conditionType === 'script') {106 validationResult = script.validate(element, values);107 }108 return validationResult;109 },110 isExpression: function(element, inputNode) {111 var conditionType = domQuery('select[name=conditionType]', inputNode);112 if (conditionType.selectedIndex >= 0) {113 return conditionType.options[conditionType.selectedIndex].value === 'expression';114 }115 },116 isScript: function(element, inputNode) {117 var conditionType = domQuery('select[name=conditionType]', inputNode);118 if (conditionType.selectedIndex >= 0) {119 return conditionType.options[conditionType.selectedIndex].value === 'script';120 }121 },122 clear: function(element, inputNode) {123 // clear text input124 domQuery('input[name=condition]', inputNode).value='';125 return true;126 },127 canClear: function(element, inputNode) {128 var input = domQuery('input[name=condition]', inputNode);129 return input.value !== '';130 },131 script : script,132 cssClasses: [ 'bpp-textfield' ]133 });134};135// utilities //////////////////////////136var CONDITIONAL_SOURCES = [137 'bpmn:Activity',138 'bpmn:ExclusiveGateway',139 'bpmn:InclusiveGateway',140 'bpmn:ComplexGateway'141];142function isConditionalSource(element) {143 return isAny(element, CONDITIONAL_SOURCES);...

Full Screen

Full Screen

constants.js

Source:constants.js Github

copy

Full Screen

1import { clone } from 'handsontable/helpers/object';2import { arrayEach } from 'handsontable/helpers/array';3import { SEPARATOR } from 'handsontable/plugins/contextMenu/predefinedItems';4import { getConditionDescriptor } from './conditionRegisterer';5import { CONDITION_NAME as CONDITION_NONE } from './condition/none';6import { CONDITION_NAME as CONDITION_EMPTY } from './condition/empty';7import { CONDITION_NAME as CONDITION_NOT_EMPTY } from './condition/notEmpty';8import { CONDITION_NAME as CONDITION_EQUAL } from './condition/equal';9import { CONDITION_NAME as CONDITION_NOT_EQUAL } from './condition/notEqual';10import { CONDITION_NAME as CONDITION_GREATER_THAN } from './condition/greaterThan';11import { CONDITION_NAME as CONDITION_GREATER_THAN_OR_EQUAL } from './condition/greaterThanOrEqual';12import { CONDITION_NAME as CONDITION_LESS_THAN } from './condition/lessThan';13import { CONDITION_NAME as CONDITION_LESS_THAN_OR_EQUAL } from './condition/lessThanOrEqual';14import { CONDITION_NAME as CONDITION_BETWEEN } from './condition/between';15import { CONDITION_NAME as CONDITION_NOT_BETWEEN } from './condition/notBetween';16import { CONDITION_NAME as CONDITION_BEGINS_WITH } from './condition/beginsWith';17import { CONDITION_NAME as CONDITION_ENDS_WITH } from './condition/endsWith';18import { CONDITION_NAME as CONDITION_CONTAINS } from './condition/contains';19import { CONDITION_NAME as CONDITION_NOT_CONTAINS } from './condition/notContains';20import { CONDITION_NAME as CONDITION_DATE_BEFORE } from './condition/date/before';21import { CONDITION_NAME as CONDITION_DATE_AFTER } from './condition/date/after';22import { CONDITION_NAME as CONDITION_TOMORROW } from './condition/date/tomorrow';23import { CONDITION_NAME as CONDITION_TODAY } from './condition/date/today';24import { CONDITION_NAME as CONDITION_YESTERDAY } from './condition/date/yesterday';25import { CONDITION_NAME as CONDITION_BY_VALUE } from './condition/byValue';26import { CONDITION_NAME as CONDITION_TRUE } from './condition/true';27import { CONDITION_NAME as CONDITION_FALSE } from './condition/false';28import { OPERATION_ID as OPERATION_AND } from './logicalOperations/conjunction';29import { OPERATION_ID as OPERATION_OR } from './logicalOperations/disjunction';30import { OPERATION_ID as OPERATION_OR_THEN_VARIABLE } from './logicalOperations/disjunctionWithExtraCondition';31export {32 CONDITION_NONE,33 CONDITION_EMPTY,34 CONDITION_NOT_EMPTY,35 CONDITION_EQUAL,36 CONDITION_NOT_EQUAL,37 CONDITION_GREATER_THAN,38 CONDITION_GREATER_THAN_OR_EQUAL,39 CONDITION_LESS_THAN,40 CONDITION_LESS_THAN_OR_EQUAL,41 CONDITION_BETWEEN,42 CONDITION_NOT_BETWEEN,43 CONDITION_BEGINS_WITH,44 CONDITION_ENDS_WITH,45 CONDITION_CONTAINS,46 CONDITION_NOT_CONTAINS,47 CONDITION_DATE_BEFORE,48 CONDITION_DATE_AFTER,49 CONDITION_TOMORROW,50 CONDITION_TODAY,51 CONDITION_YESTERDAY,52 CONDITION_BY_VALUE,53 CONDITION_TRUE,54 CONDITION_FALSE,55 OPERATION_AND,56 OPERATION_OR,57 OPERATION_OR_THEN_VARIABLE58};59export const TYPE_NUMERIC = 'numeric';60export const TYPE_TEXT = 'text';61export const TYPE_DATE = 'date';62/**63 * Default types and order for filter conditions.64 *65 * @type {Object}66 */67export const TYPES = {68 [TYPE_NUMERIC]: [69 CONDITION_NONE,70 SEPARATOR,71 CONDITION_EMPTY,72 CONDITION_NOT_EMPTY,73 SEPARATOR,74 CONDITION_EQUAL,75 CONDITION_NOT_EQUAL,76 SEPARATOR,77 CONDITION_GREATER_THAN,78 CONDITION_GREATER_THAN_OR_EQUAL,79 CONDITION_LESS_THAN,80 CONDITION_LESS_THAN_OR_EQUAL,81 CONDITION_BETWEEN,82 CONDITION_NOT_BETWEEN,83 ],84 [TYPE_TEXT]: [85 CONDITION_NONE,86 SEPARATOR,87 CONDITION_EMPTY,88 CONDITION_NOT_EMPTY,89 SEPARATOR,90 CONDITION_EQUAL,91 CONDITION_NOT_EQUAL,92 SEPARATOR,93 CONDITION_BEGINS_WITH,94 CONDITION_ENDS_WITH,95 SEPARATOR,96 CONDITION_CONTAINS,97 CONDITION_NOT_CONTAINS,98 ],99 [TYPE_DATE]: [100 CONDITION_NONE,101 SEPARATOR,102 CONDITION_EMPTY,103 CONDITION_NOT_EMPTY,104 SEPARATOR,105 CONDITION_EQUAL,106 CONDITION_NOT_EQUAL,107 SEPARATOR,108 CONDITION_DATE_BEFORE,109 CONDITION_DATE_AFTER,110 CONDITION_BETWEEN,111 SEPARATOR,112 CONDITION_TOMORROW,113 CONDITION_TODAY,114 CONDITION_YESTERDAY,115 ],116};117/**118 * Get options list for conditional filter by data type (e.q: `'text'`, `'numeric'`, `'date'`).119 *120 * @returns {Object}121 */122export default function getOptionsList(type) {123 const items = [];124 let typeName = type;125 if (!TYPES[typeName]) {126 typeName = TYPE_TEXT;127 }128 arrayEach(TYPES[typeName], (typeValue) => {129 let option;130 if (typeValue === SEPARATOR) {131 option = { name: SEPARATOR };132 } else {133 option = clone(getConditionDescriptor(typeValue));134 }135 items.push(option);136 });137 return items;...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1var wpt = require('webpagetest');2var wpt = new WebPageTest('www.webpagetest.org');3var options = {4};5 if (err) return console.error(err);6 console.log('Test submitted to WebPageTest! Waiting for results...');7 wpt.waitForTestResults(data.data.testId, function(err, data) {8 if (err) return console.error(err);9 console.log('Got test results from WebPageTest!');10 console.log(data);11 });12});

Full Screen

Using AI Code Generation

copy

Full Screen

1var wptools = require('wptools');2var condition = wptools.condition;3var options = {4};5var page = wptools.page('Albert Einstein', options);6page.get(function(err, resp) {7 console.log(resp);8});9{10 "extract": "Albert Einstein (14 March 1879 – 18 April 1955) was a German-born theoretical physicist. He developed the theory of relativity, one of the two pillars of modern physics (alongside quantum mechanics). Einstein's work is also known for its influence on the philosophy of science. Einstein is best known in popular culture for his mass–energy equivalence formula E = mc2 (which has been dubbed \"the world's most famous equation\"). He received the 1921 Nobel Prize in Physics \"for his services to theoretical physics, and especially for his discovery of the law of the photoelectric effect\", a pivotal step in the development of quantum theory.",11 "CS1 German-language sources (de)",12 "CS1 German-language sources (de)",

Full Screen

Using AI Code Generation

copy

Full Screen

1var wpt = require('webpagetest');2var wpt = new WebPageTest('www.webpagetest.org');3var options = {4};5 if (err) return console.error(err);6 console.log('Test status check: ' + data.statusText);7 console.log('Test ID: ' + data.data.testId);8 console.log('Test URL: ' + data.data.summary);9 console.log('Test results: ' + data.data.userUrl);10 wpt.getTestResults(data.data.testId, function(err, data) {11 if (err) return console.error(err);12 console.log('Test status check: ' + data.statusText);13 console.log('Test ID: ' + data.data.testId);14 console.log('Test URL: ' + data.data.summary);15 console.log('Test results: ' + data.data.userUrl);16 });17});18 at errnoException (dns.js:28:10)19 at GetAddrInfoReqWrap.onlookup [as oncomplete] (dns.js:76:26)20var wpt = require('webpagetest');21var wpt = new WebPageTest('www.webpagetest.org');22var wpt = require('webpagetest');23var wpt = new WebPageTest('www.webpagetest.org');

Full Screen

Using AI Code Generation

copy

Full Screen

1if (wpt.mobile) {2} else {3}4if (wpt.ios) {5} else {6}7if (wpt.android) {8} else {9}10if (wpt.blackberry) {11} else {12}13if (wpt.windows) {14} else {15}16if (wpt.phone) {17} else {18}19if (wpt.tablet) {20} else {21}

Full Screen

Automation Testing Tutorials

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.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run wpt automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful