How to use Counter method in storybook-root

Best JavaScript code snippet using storybook-root

random-teams.ts

Source:random-teams.ts Github

copy

Full Screen

1import type {PRNG} from '../../../sim';2import RandomTeams, {MoveCounter} from '../../random-teams';3export class RandomLetsGoTeams extends RandomTeams {4 constructor(format: Format | string, prng: PRNG | PRNGSeed | null) {5 super(format, prng);6 this.moveEnforcementCheckers = {7 Dark: (movePool, moves, abilities, types, counter) => !counter.get('Dark'),8 Dragon: (movePool, moves, abilities, types, counter) => !counter.get('Dragon'),9 Electric: (movePool, moves, abilities, types, counter) => !counter.get('Electric'),10 Fighting: (movePool, moves, abilities, types, counter) => (11 !counter.get('Fighting') && (!!counter.setupType || !counter.get('Status'))12 ),13 Fire: (movePool, moves, abilities, types, counter) => !counter.get('Fire'),14 Ghost: (movePool, moves, abilities, types, counter) => !types.has('Dark') && !counter.get('Ghost'),15 Ground: (movePool, moves, abilities, types, counter) => !counter.get('Ground'),16 Ice: (movePool, moves, abilities, types, counter) => !counter.get('Ice'),17 Water: (movePool, moves, abilities, types, counter) => !counter.get('Water') || !counter.get('stab'),18 };19 }20 shouldCullMove(21 move: Move,22 types: Set<string>,23 moves: Set<string>,24 abilities: Set<string>,25 counter: MoveCounter,26 movePool: string[],27 teamDetails: RandomTeamsTypes.TeamDetails,28 ): {cull: boolean, isSetup?: boolean} {29 switch (move.id) {30 // Set up once and only if we have the moves for it31 case 'bulkup': case 'swordsdance':32 return {33 cull: (34 counter.setupType !== 'Physical' ||35 counter.get('physicalsetup') > 1 ||36 counter.get('Physical') + counter.get('physicalpool') < 237 ),38 isSetup: true,39 };40 case 'calmmind': case 'nastyplot': case 'quiverdance':41 return {42 cull: (43 counter.setupType !== 'Special' ||44 counter.get('specialsetup') > 1 ||45 counter.get('Special') + counter.get('specialpool') < 246 ),47 isSetup: true,48 };49 case 'growth': case 'shellsmash':50 return {51 cull: (52 counter.setupType !== 'Mixed' ||53 (counter.damagingMoves.size + counter.get('physicalpool') + counter.get('specialpool')) < 254 ),55 isSetup: true,56 };57 case 'agility':58 return {59 cull: counter.damagingMoves.size < 2 && !counter.setupType,60 isSetup: !counter.setupType,61 };62 // Bad after setup63 case 'dragontail':64 return {cull: (65 !!counter.setupType || !!counter.get('speedsetup') || ['encore', 'roar', 'whirlwind'].some(m => moves.has(m))66 )};67 case 'fakeout': case 'uturn': case 'teleport':68 return {cull: !!counter.setupType || !!counter.get('speedsetup') || moves.has('substitute')};69 case 'haze': case 'leechseed': case 'roar': case 'whirlwind':70 return {cull: !!counter.setupType || !!counter.get('speedsetup') || moves.has('dragontail')};71 case 'protect':72 return {cull: !!counter.setupType || ['rest', 'lightscreen', 'reflect'].some(m => moves.has(m))};73 case 'seismictoss':74 return {cull: counter.damagingMoves.size > 1 || !!counter.setupType};75 case 'stealthrock':76 return {cull: !!counter.setupType || !!counter.get('speedsetup') || !!teamDetails.stealthRock};77 // Bit redundant to have both78 case 'leechlife': case 'substitute':79 return {cull: moves.has('uturn')};80 case 'dragonpulse':81 return {cull: moves.has('dragontail') || moves.has('outrage')};82 case 'thunderbolt':83 return {cull: moves.has('thunder')};84 case 'flareblitz': case 'flamethrower':85 return {cull: moves.has('fireblast') || moves.has('firepunch')};86 case 'megadrain':87 return {cull: moves.has('petaldance') || moves.has('powerwhip')};88 case 'bonemerang':89 return {cull: moves.has('earthquake')};90 case 'icebeam':91 return {cull: moves.has('blizzard')};92 case 'rockslide':93 return {cull: moves.has('stoneedge')};94 case 'hydropump': case 'willowisp':95 return {cull: moves.has('scald')};96 case 'surf':97 return {cull: moves.has('hydropump') || moves.has('scald')};98 }99 // Increased/decreased priority moves are unneeded with moves that boost only speed100 if (move.priority !== 0 && !!counter.get('speedsetup')) return {cull: true};101 // This move doesn't satisfy our setup requirements:102 if (103 (move.category === 'Physical' && counter.setupType === 'Special') ||104 (move.category === 'Special' && counter.setupType === 'Physical')105 ) {106 // Reject STABs last in case the setup type changes later on107 if (!types.has(move.type) || counter.get('stab') > 1 || counter.get(move.category) < 2) return {cull: true};108 }109 return {cull: false};110 }111 randomSet(species: string | Species, teamDetails: RandomTeamsTypes.TeamDetails = {}): RandomTeamsTypes.RandomSet {112 species = this.dex.species.get(species);113 let forme = species.name;114 if (typeof species.battleOnly === 'string') {115 // Only change the forme. The species has custom moves, and may have different typing and requirements.116 forme = species.battleOnly;117 }118 const movePool = (species.randomBattleMoves || Object.keys(this.dex.species.getLearnset(species.id)!)).slice();119 const types = new Set(species.types);120 const moves = new Set<string>();121 let counter;122 do {123 // Choose next 4 moves from learnset/viable moves and add them to moves list:124 while (moves.size < this.maxMoveCount && movePool.length) {125 const moveid = this.sampleNoReplace(movePool);126 moves.add(moveid);127 }128 counter = this.queryMoves(moves, species.types, new Set(), movePool);129 // Iterate through the moves again, this time to cull them:130 for (const moveid of moves) {131 const move = this.dex.moves.get(moveid);132 let {cull, isSetup} = this.shouldCullMove(move, types, moves, new Set(), counter, movePool, teamDetails);133 if (134 !isSetup &&135 counter.setupType && counter.setupType !== 'Mixed' &&136 move.category !== counter.setupType &&137 counter.get(counter.setupType) < 2 && (138 // Mono-attacking with setup and RestTalk is allowed139 // Reject Status moves only if there is nothing else to reject140 move.category !== 'Status' || (141 counter.get(counter.setupType) + counter.get('Status') > 3 &&142 counter.get('physicalsetup') + counter.get('specialsetup') < 2143 )144 )145 ) {146 cull = true;147 }148 const moveIsRejectable = !move.damage && (move.category !== 'Status' || !move.flags.heal) && (149 move.category === 'Status' ||150 !types.has(move.type) ||151 move.selfSwitch ||152 move.basePower && move.basePower < 40 && !move.multihit153 );154 // Pokemon should have moves that benefit their Type, as well as moves required by its forme155 if (moveIsRejectable && !cull && !isSetup && counter.get('physicalsetup') + counter.get('specialsetup') < 2 && (156 !counter.setupType || counter.setupType === 'Mixed' ||157 (move.category !== counter.setupType && move.category !== 'Status') ||158 counter.get(counter.setupType) + counter.get('Status') > 3159 )) {160 if (161 (counter.damagingMoves.size === 0 || !counter.get('stab')) &&162 (counter.get('physicalpool') || counter.get('specialpool'))163 ) {164 cull = true;165 } else {166 for (const type of types) {167 if (this.moveEnforcementCheckers[type]?.(movePool, moves, new Set(), types, counter, species, teamDetails)) cull = true;168 }169 }170 }171 // Remove rejected moves from the move list172 if (cull && movePool.length) {173 moves.delete(moveid);174 break;175 }176 }177 } while (moves.size < this.maxMoveCount && movePool.length);178 const ivs = {hp: 31, atk: 31, def: 31, spa: 31, spd: 31, spe: 31};179 // Minimize confusion damage180 if (!counter.get('Physical') && !moves.has('transform')) ivs.atk = 0;181 const requiredItem = species.requiredItem || (species.requiredItems ? this.sample(species.requiredItems) : null);182 return {183 name: species.baseSpecies,184 species: forme,185 level: this.adjustLevel || 100,186 gender: species.gender,187 happiness: 70,188 shiny: this.randomChance(1, 1024),189 item: (requiredItem || ''),190 ability: 'No Ability',191 evs: {hp: 20, atk: 20, def: 20, spa: 20, spd: 20, spe: 20},192 moves: Array.from(moves),193 ivs,194 };195 }196 randomTeam() {197 this.enforceNoDirectCustomBanlistChanges();198 const pokemon: RandomTeamsTypes.RandomSet[] = [];199 const pokemonPool: string[] = [];200 for (const id in this.dex.data.FormatsData) {201 const species = this.dex.species.get(id);202 if (203 species.num < 1 ||204 (species.num > 151 && ![808, 809].includes(species.num)) ||205 species.gen > 7 ||206 species.nfe ||207 !species.randomBattleMoves?.length ||208 (this.forceMonotype && !species.types.includes(this.forceMonotype))209 ) {210 continue;211 }212 pokemonPool.push(id);213 }214 const typeCount: {[k: string]: number} = {};215 const typeComboCount: {[k: string]: number} = {};216 const baseFormes: {[k: string]: number} = {};217 const teamDetails: RandomTeamsTypes.TeamDetails = {};218 while (pokemonPool.length && pokemon.length < this.maxTeamSize) {219 const species = this.dex.species.get(this.sampleNoReplace(pokemonPool));220 if (!species.exists) continue;221 // Limit to one of each species (Species Clause)222 if (baseFormes[species.baseSpecies]) continue;223 const types = species.types;224 // Once we have 2 Pokémon of a given type we reject more Pokémon of that type 80% of the time225 let skip = false;226 for (const type of species.types) {227 if (typeCount[type] > 1 && this.randomChance(4, 5)) {228 skip = true;229 break;230 }231 }232 if (skip) continue;233 // Limit 1 of any type combination234 const typeCombo = types.slice().sort().join();235 if (!this.forceMonotype && typeComboCount[typeCombo] >= 1) continue;236 // Okay, the set passes, add it to our team237 const set = this.randomSet(species, teamDetails);238 pokemon.push(set);239 // Now that our Pokemon has passed all checks, we can increment our counters240 baseFormes[species.baseSpecies] = 1;241 // Increment type counters242 for (const type of types) {243 if (type in typeCount) {244 typeCount[type]++;245 } else {246 typeCount[type] = 1;247 }248 }249 if (typeCombo in typeComboCount) {250 typeComboCount[typeCombo]++;251 } else {252 typeComboCount[typeCombo] = 1;253 }254 // Team details255 if (set.moves.includes('stealthrock')) teamDetails.stealthRock = 1;256 if (set.moves.includes('rapidspin')) teamDetails.rapidSpin = 1;257 }258 return pokemon;259 }260}...

Full Screen

Full Screen

database.py

Source:database.py Github

copy

Full Screen

1import MySQLdb as sql2import os3import sys4import re5from tqdm import tqdm6import csv7def showing_percentage(counter_percentage, counter_perc_print):8 9 if counter_percentage >= 5.00 and counter_perc_print == 0:10 counter_perc_print = counter_perc_print + 111 print '5%'12 if counter_percentage >= 10.00 and counter_perc_print == 1:13 counter_perc_print = counter_perc_print + 114 print '10%'15 if counter_percentage >= 15.00 and counter_perc_print == 2:16 counter_perc_print = counter_perc_print + 117 print '15%'18 if counter_percentage >= 20.00 and counter_perc_print == 3:19 counter_perc_print = counter_perc_print + 120 print '20%'21 if counter_percentage >= 25.00 and counter_perc_print == 4:22 counter_perc_print = counter_perc_print + 123 print '25%'24 if counter_percentage >= 30.00 and counter_perc_print == 5:25 counter_perc_print = counter_perc_print + 126 print '30%'27 if counter_percentage >= 35.00 and counter_perc_print == 6:28 counter_perc_print = counter_perc_print + 129 print '35%'30 if counter_percentage >= 40.00 and counter_perc_print == 7:31 counter_perc_print = counter_perc_print + 132 print '40%'33 if counter_percentage >= 45.00 and counter_perc_print == 8:34 counter_perc_print = counter_perc_print + 135 print '45%'36 if counter_percentage >= 50.00 and counter_perc_print == 9:37 counter_perc_print = counter_perc_print + 138 print '50%'39 if counter_percentage >= 55.00 and counter_perc_print == 10:40 counter_perc_print = counter_perc_print + 141 print '55%'42 if counter_percentage >= 60.00 and counter_perc_print == 11:43 counter_perc_print = counter_perc_print + 144 print '60%'45 if counter_percentage >= 65.00 and counter_perc_print == 12:46 counter_perc_print = counter_perc_print + 147 print '65%'48 if counter_percentage >= 70.00 and counter_perc_print == 13:49 counter_perc_print = counter_perc_print + 150 print '70%'51 if counter_percentage >= 75.00 and counter_perc_print == 14:52 counter_perc_print = counter_perc_print + 153 print '75%'54 if counter_percentage >= 80.00 and counter_perc_print == 15:55 counter_perc_print = counter_perc_print + 156 print '80%'57 if counter_percentage >= 85.00 and counter_perc_print == 16:58 counter_perc_print = counter_perc_print + 159 print '85%'60 if counter_percentage >= 90.00 and counter_perc_print == 17:61 counter_perc_print = counter_perc_print + 162 print '90%'63 if counter_percentage >= 95.00 and counter_perc_print == 18:64 counter_perc_print = counter_perc_print + 165 print '95%'66 return counter_perc_print67 68def connect_db(db_name):69 """70 Connects to db db_name71 Args:72 db_name: path to the db to connect to73 Returns:74 connection: A connection to db_name75 """76 # Connect to the database77 # if not os.path.isfile(db_name):78 # print("Database '" + str(db_name) + "' does not exist. Please create to continue")79 # print("Exiting...")80 # sys.exit()81 # print("Connecting to database...")82 return sql.connect(host="localhost", user="root", db=db_name)83def model_change_name(list_model):84 """85 This format the name of the models to be found in the database86 """87 list_correct_model_names=[]88 for model_name in list_model:89 list_correct_model_names.append("tf-"+model_name)90 return list_correct_model_names91def searching_top_5(db_name):92 """93 Prints the top-5 elements of each database94 """95 connection = connect_db(db_name)96 cursor = connection.cursor()97 #cmd = "SELECT * FROM exec_data as E Limit 5"98 #cursor.execute(cmd)99 #result = cursor.fetchall()100 #col_names = [i[0] for i in cursor.description]101 #print(col_names)102 for model in list_model:103 output = open(model+'-top_5_complete.csv', 'w')104 headers = 'filename,label,pred_1,pred_2,pred_3,pred_4,pred_5,predictedOnTop,performance\n'105 output.write(headers)106 row_count = 0107 print(model)108 with open(DATA_FILE, 'rb') as csvfile:109 lines = [line.decode('utf-8-sig') for line in csvfile]110 for row in tqdm(csv.reader(lines), total=len(lines)):111 # Remove the headers of csv file112 if row_count is 0:113 row_count = 1114 continue115 cmd = "SELECT E.pred_1, E.pred_2, E.pred_3, E.pred_4, E.pred_5, E.performance FROM exec_data as E, images as I WHERE E.model_name='" + str(model) + "' AND I.filename='" + str(row[0]) +"' AND E.img_num=I.img_num"116 cursor.execute(cmd)117 result = cursor.fetchall()118 for pred_1, pred_2, pred_3, pred_4, pred_5, performance in result:119 predicted_1 = re.sub('[()\',!@#$]', '', str(pred_1))120 predicted_2 = re.sub('[()\',!@#$]', '', str(pred_2))121 predicted_3 = re.sub('[()\',!@#$]', '', str(pred_3))122 predicted_4 = re.sub('[()\',!@#$]', '', str(pred_4))123 predicted_5 = re.sub('[()\',!@#$]', '', str(pred_5))124 if pred_1 == row[1]:125 which_top = 1126 #predictedByOtherModel = re.sub('[()\',!@#$]', '', str(pred_1))127 elif pred_2 == row[1]:128 which_top = 2129 #predictedByOtherModel = re.sub('[()\',!@#$]', '', str(pred_2))130 elif pred_3 == row[1]:131 which_top = 3132 #predictedByOtherModel = re.sub('[()\',!@#$]', '', str(pred_3))133 elif pred_4 == row[1]:134 which_top = 4135 #predictedByOtherModel = re.sub('[()\',!@#$]', '', str(pred_4))136 elif pred_5 == row[1]:137 which_top = 5138 #predictedByOtherModel = re.sub('[()\',!@#$]', '', str(pred_5))139 else:140 # In case of 0 means that it fails in top-5141 which_top = 0142 #predictedByOtherModel = re.sub('[()\',!@#$]', '', str(pred_1))143 headers = 'filename,label,pred_1,pred_2,pred_3,pred_4,pred_5,predictedOnTop,performance\n'144 output.write(str(row[0]) + ',' + str(row[1]) + ',' + str(predicted_1) + ',' + str(predicted_2) + ',' + str(predicted_3) + ',' + str(predicted_4) + ',' + str(predicted_5) + ','+ str(which_top) + ',' + str(performance) + '\n')145 #[print("RESULT:",x) for x in result]146 output.close()147 148def determine_best_top_n_model(db_name, img_num, list_model, n):149 """150 Return the name of the model which is deemed best for img_num151 Args:152 db_name (string): path to the db to connect to153 img_num (int): number of the image154 n (int): 1 or 5 - can only use these values155 Returns:156 string: Name of the best model for img_num, or failed if failure157 """158 if n not in [1, 5]:159 print(str(n) + "is not a valid number, must be 1 or 5")160 print("Exiting...")161 sys.exit()162 163 connection = connect_db(db_name)164 cursor = connection.cursor()165 query = "SELECT model_name, top_" + str(n)166 query += ", performance FROM exec_data WHERE img_num=(%s)"167 potential = list()168 169 cursor.execute(query, (img_num,))170 for row in cursor.fetchall():171 model_name, top_n, performance = row172 173 if model_name in list_model and top_n == 1:174 potential.append((model_name, performance))175 176 if potential == list():177 return 'failed'178 return min(potential, key=lambda x: x[1])[0]179def get_img_num_database(db_name, img_filename):180 #print("Connecting to database...")181 connection = connect_db(db_name)182 cursor = connection.cursor()183 184 cmd = 'SELECT img_num, filename FROM images WHERE filename=\''+str(img_filename)+'\''185 cursor.execute(cmd)186 result = cursor.fetchall()187 for img_num, filename in result:188 return img_num, filename189 190def get_best_models(db_name, list_images, list_model):191 """192 Return the data to be show in a plot193 Args:194 db_name (string): path to the db to connect to195 """196 #if not os.path.isfile(db_name):197 # print("Database2 '" + str(db_name) + "' does not exist. Please create to continue")198 # print("Exiting...")199 # sys.exit()200 if len(list_model) == 0:201 print("No models were selected")202 return [], []203 204 if len(list_images) == 0:205 print("No images were selected")206 return [], []207 208 #print("Connecting to database...")209 connection = connect_db(db_name)210 cursor = connection.cursor()211 tmp_results=[]212 213 list_correct_model_names=model_change_name(list_model)214 215 list_correct_model_names.append("failed")216 217 percentage = 100.0/len(list_images)218 counter_percentage = 0.0219 counter_perc_print = 0220 221 for img_filename in list_images:222 cmd = 'SELECT img_num, filename FROM images WHERE filename=\''+str(img_filename)+'\''223 cursor.execute(cmd)224 result = cursor.fetchall()225 226 for img_num, filename in result:227 best_top_1_model = determine_best_top_n_model(db_name, img_num, list_correct_model_names, 1)228 #print(img_num, filename, best_top_1_model)229 tmp_results.append((filename, best_top_1_model))230 231 counter_percentage = counter_percentage + percentage232 counter_perc_print = showing_percentage(counter_percentage, counter_perc_print)233 234 # The last one is failed235 results_to_plot = [0]*len(list_correct_model_names)236 237 for counter, model in enumerate(list_correct_model_names):238 for filename, best_top_1_model in tmp_results:239 if best_top_1_model == model:240 results_to_plot[counter] = results_to_plot[counter] + 1241 242 return list_correct_model_names, results_to_plot243 244 245 ...

Full Screen

Full Screen

cmanager_win32.py

Source:cmanager_win32.py Github

copy

Full Screen

...76 pdh.PdhEnumObjectsA(None, None, 0, 1, 0, True)77 for counter in self.registeredCounters:78 try:79 # Add the counter path for the default process.80 self._addCounter(process_name, 'process', counter)81 except TalosError:82 # Assume that this is a memory counter for the system,83 # not a process counter84 # If we got an error that has nothing to do with that,85 # the exception will almost certainly be re-raised86 self._addCounter(process_name, 'Memory', counter)87 self._updateCounterPathsForChildProcesses(counter)88 def _addCounter(self, processName, counterType, counterName):89 pCounterPathElements = _PDH_COUNTER_PATH_ELEMENTS_A(90 LPSTR(None),91 LPSTR(counterType),92 LPSTR(processName),93 LPSTR(None),94 DWORD(-1),95 LPSTR(counterName)96 )97 pcchbufferSize = DWORD(0)98 # First run we just try to get the buffer size so we can allocate a99 # string big enough to fill it100 if pdh.PdhMakeCounterPathA(pointer(pCounterPathElements),101 LPCSTR(0), pointer(pcchbufferSize),102 DWORD(0)) != _PDH_MORE_DATA:...

Full Screen

Full Screen

test_clock.py

Source:test_clock.py Github

copy

Full Screen

...10 def __call__(self, *args, **kwargs):11 self.counter += 112@pytest.fixture()13def clock_counter():14 yield ClockCounter()15def test_schedule_once(kivy_clock, clock_counter):16 kivy_clock.schedule_once(clock_counter)17 kivy_clock.tick()18 assert clock_counter.counter == 119def test_schedule_once_twice(kivy_clock, clock_counter):20 kivy_clock.schedule_once(clock_counter)21 kivy_clock.schedule_once(clock_counter)22 kivy_clock.tick()23 assert clock_counter.counter == 224def test_schedule_once_draw_after(kivy_clock, clock_counter):25 kivy_clock.schedule_once(clock_counter, 0)26 kivy_clock.tick_draw()27 assert clock_counter.counter == 028 kivy_clock.tick()29 assert clock_counter.counter == 130def test_schedule_once_draw_before(kivy_clock, clock_counter):31 kivy_clock.schedule_once(clock_counter, -1)32 kivy_clock.tick_draw()33 assert clock_counter.counter == 134 kivy_clock.tick()35 assert clock_counter.counter == 136def test_unschedule(kivy_clock, clock_counter):37 kivy_clock.schedule_once(clock_counter)38 kivy_clock.unschedule(clock_counter)39 kivy_clock.tick()40 assert clock_counter.counter == 041def test_unschedule_event(kivy_clock, clock_counter):42 ev = kivy_clock.schedule_once(clock_counter)43 kivy_clock.unschedule(ev)44 kivy_clock.tick()45 assert clock_counter.counter == 046def test_unschedule_after_tick(kivy_clock, clock_counter):47 kivy_clock.schedule_once(clock_counter, 5.)48 kivy_clock.tick()49 kivy_clock.unschedule(clock_counter)50 kivy_clock.tick()51 assert clock_counter.counter == 052def test_unschedule_draw(kivy_clock, clock_counter):53 kivy_clock.schedule_once(clock_counter, 0)54 kivy_clock.tick_draw()55 assert clock_counter.counter == 056 kivy_clock.unschedule(clock_counter)57 kivy_clock.tick()58 assert clock_counter.counter == 059def test_trigger_create(kivy_clock, clock_counter):60 trigger = kivy_clock.create_trigger(clock_counter, 0)61 trigger()62 assert clock_counter.counter == 063 kivy_clock.tick()64 assert clock_counter.counter == 165def test_trigger_cancel(kivy_clock, clock_counter):66 trigger = kivy_clock.create_trigger(clock_counter, 5.)67 trigger()68 trigger.cancel()69 kivy_clock.tick()70 assert clock_counter.counter == 071def test_trigger_interval(kivy_clock, clock_counter):72 trigger = kivy_clock.create_trigger(clock_counter, 0, interval=True)73 trigger()74 kivy_clock.tick()75 assert clock_counter.counter == 176 kivy_clock.tick()77 assert clock_counter.counter == 278def test_trigger_decorator(kivy_clock, clock_counter):79 from kivy.clock import triggered80 @triggered()81 def triggered_callback():82 clock_counter(dt=0)83 triggered_callback()84 assert clock_counter.counter == 085 kivy_clock.tick()86 assert clock_counter.counter == 187def test_trigger_decorator_cancel(kivy_clock, clock_counter):88 from kivy.clock import triggered89 @triggered()90 def triggered_callback():91 clock_counter(dt=0)92 triggered_callback()93 triggered_callback.cancel()94 kivy_clock.tick()95 assert clock_counter.counter == 096def test_exception_caught(kivy_clock, clock_counter):97 exception = None98 def handle_test_exception(e):99 nonlocal exception100 exception = str(e)101 # monkey patch to ignore exception102 kivy_clock.handle_exception = handle_test_exception103 def raise_exception(*args):104 raise ValueError('Stooooop')105 kivy_clock.schedule_once(raise_exception)106 kivy_clock.schedule_once(clock_counter)107 kivy_clock.tick()108 assert clock_counter.counter == 1109 assert exception == 'Stooooop'110def test_exception_ignored(kivy_clock, clock_counter):111 def raise_exception(*args):112 raise ValueError('Stooooop')113 kivy_clock.schedule_once(raise_exception)114 kivy_clock.schedule_once(clock_counter)115 with pytest.raises(ValueError):116 kivy_clock.tick()117 assert clock_counter.counter == 0118def test_exception_caught_handler(119 kivy_clock, clock_counter, kivy_exception_manager):120 from kivy.base import ExceptionHandler121 exception = None122 class KivyHandler(ExceptionHandler):123 def handle_exception(self, e):124 nonlocal exception125 exception = str(e)126 return kivy_exception_manager.PASS127 kivy_exception_manager.add_handler(KivyHandler())128 def raise_exception(*args):129 raise ValueError('Stooooop')130 kivy_clock.schedule_once(raise_exception)131 kivy_clock.schedule_once(clock_counter)132 kivy_clock.tick()133 assert clock_counter.counter == 1134 assert exception == 'Stooooop'135def test_clock_ended_callback(kivy_clock, clock_counter):136 counter2 = ClockCounter()137 counter_schedule = ClockCounter()138 kivy_clock.schedule_once(counter_schedule)139 event = kivy_clock.create_lifecycle_aware_trigger(clock_counter, counter2)140 event()141 kivy_clock.stop_clock()142 assert counter_schedule.counter == 0143 assert clock_counter.counter == 0144 assert counter2.counter == 1145def test_clock_ended_del_safe(kivy_clock, clock_counter):146 counter2 = ClockCounter()147 kivy_clock.schedule_lifecycle_aware_del_safe(clock_counter, counter2)148 kivy_clock.stop_clock()149 assert clock_counter.counter == 0150 assert counter2.counter == 1151def test_clock_ended_raises(kivy_clock, clock_counter):152 from kivy.clock import ClockNotRunningError153 event = kivy_clock.create_lifecycle_aware_trigger(154 clock_counter, clock_counter)155 kivy_clock.stop_clock()156 with pytest.raises(ClockNotRunningError):157 event()158 assert clock_counter.counter == 0159 # we should be able to create the event160 event = kivy_clock.create_lifecycle_aware_trigger(161 clock_counter, clock_counter)162 with pytest.raises(ClockNotRunningError):163 event()164 assert clock_counter.counter == 0165 kivy_clock.schedule_once(clock_counter)166 assert clock_counter.counter == 0167def test_clock_ended_del_safe_raises(kivy_clock, clock_counter):168 from kivy.clock import ClockNotRunningError169 counter2 = ClockCounter()170 kivy_clock.stop_clock()171 with pytest.raises(ClockNotRunningError):172 kivy_clock.schedule_lifecycle_aware_del_safe(clock_counter, counter2)173 assert clock_counter.counter == 0174def test_clock_stop_twice(kivy_clock, clock_counter):175 counter2 = ClockCounter()176 event = kivy_clock.create_lifecycle_aware_trigger(177 clock_counter, counter2)178 event()179 kivy_clock.stop_clock()180 assert clock_counter.counter == 0181 assert counter2.counter == 1182 kivy_clock.stop_clock()183 assert clock_counter.counter == 0184 assert counter2.counter == 1185def test_clock_restart(kivy_clock):186 kivy_clock.stop_clock()187 # with pytest.raises(TypeError):188 # kivy_clock.start_clock()189 # for now it doesn't yet raise a error190 kivy_clock.start_clock()191def test_clock_event_trigger_ref(kivy_clock):192 value = None193 class Counter:194 def call(self, *args, **kwargs):195 nonlocal value196 value = 42197 event = kivy_clock.create_trigger(Counter().call)198 gc.collect()199 event()200 kivy_clock.tick()201 assert value is None202 kivy_clock.schedule_once(Counter().call)203 event()204 kivy_clock.tick()205 assert value is None206 event = kivy_clock.create_trigger(Counter().call, release_ref=False)207 gc.collect()208 event()209 kivy_clock.tick()...

Full Screen

Full Screen

test_caching.py

Source:test_caching.py Github

copy

Full Screen

1"""Test caching extension."""2from __future__ import with_statement3import tempfile4from _tools import *5requires_joblib = skip_on_condition(6 "not mdp.config.has_joblib",7 "This test requires the 'joblib' module.")8_counter = 09class _CounterNode(mdp.Node):10 def __init__(self):11 super(_CounterNode, self).__init__()12 def is_trainable(self):13 return False14 def _execute(self, x):15 """The execute method has the side effect of increasing16 a global counter by one."""17 global _counter18 _counter += 119 return x20@requires_joblib21def test_caching_extension():22 """Test that the caching extension is working at the global level."""23 global _counter24 _counter = 025 node = _CounterNode()26 # before decoration the global counter is incremented at every call27 k = 028 for i in range(3):29 x = mdp.numx.array([[i]], dtype='d')30 for j in range(2):31 k += 132 assert mdp.numx.all(node.execute(x) == x)33 assert _counter == k34 # reset counter35 _counter = 036 # activate the extension37 cachedir = tempfile.mkdtemp(prefix='mdp-tmp-joblib-cache.',38 dir=py.test.mdp_tempdirname)39 mdp.caching.activate_caching(cachedir=cachedir)40 assert mdp.get_active_extensions() == ['cache_execute']41 # after decoration the global counter is incremented for each new 'x'42 for i in range(3):43 x = mdp.numx.array([[i]], dtype='d')44 for _ in range(2):45 assert mdp.numx.all(node.execute(x) == x)46 assert _counter == i + 147 # after deactivation48 mdp.caching.deactivate_caching()49 assert mdp.get_active_extensions() == []50 # reset counter51 _counter = 052 k = 053 for i in range(3):54 x = mdp.numx.array([[i]], dtype='d')55 for j in range(2):56 k += 157 assert mdp.numx.all(node.execute(x) == x)58 assert _counter == k59@requires_joblib60def test_different_instances_same_content():61 global _counter62 x = mdp.numx.array([[100.]], dtype='d')63 cachedir = tempfile.mkdtemp(prefix='mdp-tmp-joblib-cache.',64 dir=py.test.mdp_tempdirname)65 mdp.caching.activate_caching(cachedir=cachedir)66 node = _CounterNode()67 _counter = 068 # add attribute to make instance unique69 node.attr = 'unique'70 # cache x71 node.execute(x)72 assert _counter == 173 # should be cached now74 node.execute(x)75 assert _counter == 176 # create new instance, make it also unique and check that77 # result is still cached78 _counter = 079 node = _CounterNode()80 node.attr = 'unique and different'81 node.execute(x)82 assert _counter == 183 mdp.caching.deactivate_caching()84@requires_joblib85def test_caching_context_manager():86 global _counter87 node = _CounterNode()88 _counter = 089 assert mdp.get_active_extensions() == []90 cachedir = tempfile.mkdtemp(prefix='mdp-tmp-joblib-cache.',91 dir=py.test.mdp_tempdirname)92 with mdp.caching.cache(cachedir=cachedir):93 assert mdp.get_active_extensions() == ['cache_execute']94 for i in range(3):95 x = mdp.numx.array([[i]], dtype='d')96 for _ in range(2):97 assert mdp.numx.all(node.execute(x) == x)98 assert _counter == i + 199 assert mdp.get_active_extensions() == []100@requires_joblib101def test_class_caching():102 """Test that we can cache individual classes."""103 cached = mdp.nodes.PCANode()104 notcached = mdp.nodes.SFANode()105 with mdp.caching.cache(cache_classes=[mdp.nodes.PCANode]):106 assert cached.is_cached()107 assert not notcached.is_cached()108@requires_joblib109def test_class_caching_functionality():110 """Test that cached classes really cache."""111 global _counter112 x = mdp.numx.array([[210]], dtype='d')113 node = _CounterNode()114 # here _CounterNode is not cached115 _counter = 0116 with mdp.caching.cache(cache_classes=[mdp.nodes.PCANode]):117 node.execute(x)118 assert _counter == 1119 node.execute(x)120 assert _counter == 2121 # here _CounterNode is cached122 _counter = 0123 with mdp.caching.cache(cache_classes=[_CounterNode]):124 node.execute(x)125 assert _counter == 1126 node.execute(x)127 assert _counter == 1128@requires_joblib129def test_instance_caching():130 """Test that we can cache individual instances."""131 cached = mdp.nodes.PCANode()132 notcached = mdp.nodes.PCANode()133 with mdp.caching.cache(cache_instances=[cached]):134 assert cached.is_cached()135 assert not notcached.is_cached()136@requires_joblib137def test_instance_caching_functionality():138 """Test that cached instances really cache."""139 global _counter140 x = mdp.numx.array([[130]], dtype='d')141 node = _CounterNode()142 othernode = _CounterNode()143 # here _CounterNode is not cached144 _counter = 0145 with mdp.caching.cache(cache_instances=[othernode]):146 node.execute(x)147 assert _counter == 1148 node.execute(x)149 assert _counter == 2150 # here _CounterNode is cached151 _counter = 0152 with mdp.caching.cache(cache_instances=[node]):153 node.execute(x)154 assert _counter == 1155 node.execute(x)156 assert _counter == 1157@requires_joblib158def test_preexecution_problem():159 """Test that automatic setting of e.g. input_dim does not stop160 the caching extension from caching on the first run."""161 global _counter162 x = mdp.numx.array([[102.]])163 node = _CounterNode()164 # here _CounterNode is cached165 _counter = 0166 with mdp.caching.cache():167 # on the first execution, input_dim and dtype are set ...168 node.execute(x)169 assert _counter == 1170 # ... yet the result is cached171 node.execute(x)172 assert _counter == 1173@requires_joblib174def test_switch_cache():175 """Test changing cache directory while extension is active."""176 global _counter177 dir1 = tempfile.mkdtemp(prefix='mdp-tmp-joblib-cache.',178 dir=py.test.mdp_tempdirname)179 dir2 = tempfile.mkdtemp(prefix='mdp-tmp-joblib-cache.',180 dir=py.test.mdp_tempdirname)181 x = mdp.numx.array([[10]], dtype='d')182 mdp.caching.activate_caching(cachedir=dir1)183 node = _CounterNode()184 _counter = 0185 node.execute(x)186 assert _counter == 1187 node.execute(x)188 assert _counter == 1189 # now change path190 mdp.caching.set_cachedir(cachedir=dir2)191 node.execute(x)192 assert _counter == 2193 node.execute(x)194 assert _counter == 2195 mdp.caching.deactivate_caching()196@requires_joblib197def test_execute_magic():198 """Test calling execute with magic while caching."""199 x = mdp.numx_rand.rand(100, 10)200 node = mdp.nodes.PCANode()201 with mdp.caching.cache():202 y = node(x)203 y2 = node(x)...

Full Screen

Full Screen

winperf.py

Source:winperf.py Github

copy

Full Screen

1# Generated by h2py from winperf.h2PERF_DATA_VERSION = 13PERF_DATA_REVISION = 14PERF_NO_INSTANCES = -15PERF_SIZE_DWORD = 0x000000006PERF_SIZE_LARGE = 0x000001007PERF_SIZE_ZERO = 0x000002008PERF_SIZE_VARIABLE_LEN = 0x000003009PERF_TYPE_NUMBER = 0x0000000010PERF_TYPE_COUNTER = 0x0000040011PERF_TYPE_TEXT = 0x0000080012PERF_TYPE_ZERO = 0x00000C0013PERF_NUMBER_HEX = 0x0000000014PERF_NUMBER_DECIMAL = 0x0001000015PERF_NUMBER_DEC_1000 = 0x0002000016PERF_COUNTER_VALUE = 0x0000000017PERF_COUNTER_RATE = 0x0001000018PERF_COUNTER_FRACTION = 0x0002000019PERF_COUNTER_BASE = 0x0003000020PERF_COUNTER_ELAPSED = 0x0004000021PERF_COUNTER_QUEUELEN = 0x0005000022PERF_COUNTER_HISTOGRAM = 0x0006000023PERF_TEXT_UNICODE = 0x0000000024PERF_TEXT_ASCII = 0x0001000025PERF_TIMER_TICK = 0x0000000026PERF_TIMER_100NS = 0x0010000027PERF_OBJECT_TIMER = 0x0020000028PERF_DELTA_COUNTER = 0x0040000029PERF_DELTA_BASE = 0x0080000030PERF_INVERSE_COUNTER = 0x0100000031PERF_MULTI_COUNTER = 0x0200000032PERF_DISPLAY_NO_SUFFIX = 0x0000000033PERF_DISPLAY_PER_SEC = 0x1000000034PERF_DISPLAY_PERCENT = 0x2000000035PERF_DISPLAY_SECONDS = 0x3000000036PERF_DISPLAY_NOSHOW = 0x4000000037PERF_COUNTER_COUNTER = \38 (PERF_SIZE_DWORD | PERF_TYPE_COUNTER | PERF_COUNTER_RATE |\39 PERF_TIMER_TICK | PERF_DELTA_COUNTER | PERF_DISPLAY_PER_SEC)40PERF_COUNTER_TIMER = \41 (PERF_SIZE_LARGE | PERF_TYPE_COUNTER | PERF_COUNTER_RATE |\42 PERF_TIMER_TICK | PERF_DELTA_COUNTER | PERF_DISPLAY_PERCENT)43PERF_COUNTER_QUEUELEN_TYPE = \44 (PERF_SIZE_DWORD | PERF_TYPE_COUNTER | PERF_COUNTER_QUEUELEN |\45 PERF_TIMER_TICK | PERF_DELTA_COUNTER | PERF_DISPLAY_NO_SUFFIX)46PERF_COUNTER_LARGE_QUEUELEN_TYPE = \47 (PERF_SIZE_LARGE | PERF_TYPE_COUNTER | PERF_COUNTER_QUEUELEN |\48 PERF_TIMER_TICK | PERF_DELTA_COUNTER | PERF_DISPLAY_NO_SUFFIX)49PERF_COUNTER_BULK_COUNT = \50 (PERF_SIZE_LARGE | PERF_TYPE_COUNTER | PERF_COUNTER_RATE |\51 PERF_TIMER_TICK | PERF_DELTA_COUNTER | PERF_DISPLAY_PER_SEC)52PERF_COUNTER_TEXT = \53 (PERF_SIZE_VARIABLE_LEN | PERF_TYPE_TEXT | PERF_TEXT_UNICODE |\54 PERF_DISPLAY_NO_SUFFIX)55PERF_COUNTER_RAWCOUNT = \56 (PERF_SIZE_DWORD | PERF_TYPE_NUMBER | PERF_NUMBER_DECIMAL |\57 PERF_DISPLAY_NO_SUFFIX)58PERF_COUNTER_LARGE_RAWCOUNT = \59 (PERF_SIZE_LARGE | PERF_TYPE_NUMBER | PERF_NUMBER_DECIMAL |\60 PERF_DISPLAY_NO_SUFFIX)61PERF_COUNTER_RAWCOUNT_HEX = \62 (PERF_SIZE_DWORD | PERF_TYPE_NUMBER | PERF_NUMBER_HEX |\63 PERF_DISPLAY_NO_SUFFIX)64PERF_COUNTER_LARGE_RAWCOUNT_HEX = \65 (PERF_SIZE_LARGE | PERF_TYPE_NUMBER | PERF_NUMBER_HEX |\66 PERF_DISPLAY_NO_SUFFIX)67PERF_SAMPLE_FRACTION = \68 (PERF_SIZE_DWORD | PERF_TYPE_COUNTER | PERF_COUNTER_FRACTION |\69 PERF_DELTA_COUNTER | PERF_DELTA_BASE | PERF_DISPLAY_PERCENT)70PERF_SAMPLE_COUNTER = \71 (PERF_SIZE_DWORD | PERF_TYPE_COUNTER | PERF_COUNTER_RATE |\72 PERF_TIMER_TICK | PERF_DELTA_COUNTER | PERF_DISPLAY_NO_SUFFIX)73PERF_COUNTER_NODATA = \74 (PERF_SIZE_ZERO | PERF_DISPLAY_NOSHOW)75PERF_COUNTER_TIMER_INV = \76 (PERF_SIZE_LARGE | PERF_TYPE_COUNTER | PERF_COUNTER_RATE |\77 PERF_TIMER_TICK | PERF_DELTA_COUNTER | PERF_INVERSE_COUNTER | \78 PERF_DISPLAY_PERCENT)79PERF_SAMPLE_BASE = \80 (PERF_SIZE_DWORD | PERF_TYPE_COUNTER | PERF_COUNTER_BASE |\81 PERF_DISPLAY_NOSHOW |\82 0x00000001)83PERF_AVERAGE_TIMER = \84 (PERF_SIZE_DWORD | PERF_TYPE_COUNTER | PERF_COUNTER_FRACTION |\85 PERF_DISPLAY_SECONDS)86PERF_AVERAGE_BASE = \87 (PERF_SIZE_DWORD | PERF_TYPE_COUNTER | PERF_COUNTER_BASE |\88 PERF_DISPLAY_NOSHOW |\89 0x00000002)90PERF_AVERAGE_BULK = \91 (PERF_SIZE_LARGE | PERF_TYPE_COUNTER | PERF_COUNTER_FRACTION |\92 PERF_DISPLAY_NOSHOW)93PERF_100NSEC_TIMER = \94 (PERF_SIZE_LARGE | PERF_TYPE_COUNTER | PERF_COUNTER_RATE |\95 PERF_TIMER_100NS | PERF_DELTA_COUNTER | PERF_DISPLAY_PERCENT)96PERF_100NSEC_TIMER_INV = \97 (PERF_SIZE_LARGE | PERF_TYPE_COUNTER | PERF_COUNTER_RATE |\98 PERF_TIMER_100NS | PERF_DELTA_COUNTER | PERF_INVERSE_COUNTER |\99 PERF_DISPLAY_PERCENT)100PERF_COUNTER_MULTI_TIMER = \101 (PERF_SIZE_LARGE | PERF_TYPE_COUNTER | PERF_COUNTER_RATE |\102 PERF_DELTA_COUNTER | PERF_TIMER_TICK | PERF_MULTI_COUNTER |\103 PERF_DISPLAY_PERCENT)104PERF_COUNTER_MULTI_TIMER_INV = \105 (PERF_SIZE_LARGE | PERF_TYPE_COUNTER | PERF_COUNTER_RATE |\106 PERF_DELTA_COUNTER | PERF_MULTI_COUNTER | PERF_TIMER_TICK |\107 PERF_INVERSE_COUNTER | PERF_DISPLAY_PERCENT)108PERF_COUNTER_MULTI_BASE = \109 (PERF_SIZE_LARGE | PERF_TYPE_COUNTER | PERF_COUNTER_BASE |\110 PERF_MULTI_COUNTER | PERF_DISPLAY_NOSHOW)111PERF_100NSEC_MULTI_TIMER = \112 (PERF_SIZE_LARGE | PERF_TYPE_COUNTER | PERF_DELTA_COUNTER |\113 PERF_COUNTER_RATE | PERF_TIMER_100NS | PERF_MULTI_COUNTER |\114 PERF_DISPLAY_PERCENT)115PERF_100NSEC_MULTI_TIMER_INV = \116 (PERF_SIZE_LARGE | PERF_TYPE_COUNTER | PERF_DELTA_COUNTER |\117 PERF_COUNTER_RATE | PERF_TIMER_100NS | PERF_MULTI_COUNTER |\118 PERF_INVERSE_COUNTER | PERF_DISPLAY_PERCENT)119PERF_RAW_FRACTION = \120 (PERF_SIZE_DWORD | PERF_TYPE_COUNTER | PERF_COUNTER_FRACTION |\121 PERF_DISPLAY_PERCENT)122PERF_RAW_BASE = \123 (PERF_SIZE_DWORD | PERF_TYPE_COUNTER | PERF_COUNTER_BASE |\124 PERF_DISPLAY_NOSHOW |\125 0x00000003)126PERF_ELAPSED_TIME = \127 (PERF_SIZE_LARGE | PERF_TYPE_COUNTER | PERF_COUNTER_ELAPSED |\128 PERF_OBJECT_TIMER | PERF_DISPLAY_SECONDS)129PERF_COUNTER_HISTOGRAM_TYPE = -2147483648 # 0x80000000130PERF_COUNTER_DELTA = \131 (PERF_SIZE_DWORD | PERF_TYPE_COUNTER | PERF_COUNTER_VALUE |\132 PERF_DELTA_COUNTER | PERF_DISPLAY_NO_SUFFIX)133PERF_COUNTER_LARGE_DELTA = \134 (PERF_SIZE_LARGE | PERF_TYPE_COUNTER | PERF_COUNTER_VALUE |\135 PERF_DELTA_COUNTER | PERF_DISPLAY_NO_SUFFIX)136PERF_DETAIL_NOVICE = 100137PERF_DETAIL_ADVANCED = 200138PERF_DETAIL_EXPERT = 300139PERF_DETAIL_WIZARD = 400...

Full Screen

Full Screen

characterCounter.js

Source:characterCounter.js Github

copy

Full Screen

...20 */21 this.options = $.extend({}, CharacterCounter.defaults, options)22 this.isInvalid = false23 this.isValidLength = false24 this._setupCounter()25 this._setupEventHandlers()26 }27 static get defaults() {28 return _defaults29 }30 static init(els, options) {31 return super.init(this, els, options)32 }33 /**34 * Get Instance35 */36 static getInstance(el) {37 let domElem = !!el.jquery ? el[0] : el38 return domElem.M_CharacterCounter39 }40 /**41 * Teardown component42 */43 destroy() {44 this._removeEventHandlers()45 this.el.CharacterCounter = undefined46 this._removeCounter()47 }48 /**49 * Setup Event Handlers50 */51 _setupEventHandlers() {52 this._handleUpdateCounterBound = this.updateCounter.bind(this)53 this.el.addEventListener('focus', this._handleUpdateCounterBound, true)54 this.el.addEventListener('input', this._handleUpdateCounterBound, true)55 }56 /**57 * Remove Event Handlers58 */59 _removeEventHandlers() {60 this.el.removeEventListener('focus', this._handleUpdateCounterBound, true)61 this.el.removeEventListener('input', this._handleUpdateCounterBound, true)62 }63 /**64 * Setup counter element65 */66 _setupCounter() {67 this.counterEl = document.createElement('span')68 $(this.counterEl)69 .addClass('character-counter')70 .css({71 float: 'right',72 'font-size': '12px',73 height: 1,74 })75 this.$el.parent().append(this.counterEl)76 }77 /**78 * Remove counter element79 */80 _removeCounter() {81 $(this.counterEl).remove()82 }83 /**84 * Update counter85 */86 updateCounter() {87 let maxLength = +this.$el.attr('data-length'),88 actualLength = this.el.value.length89 this.isValidLength = actualLength <= maxLength90 let counterString = actualLength91 if (maxLength) {92 counterString += '/' + maxLength93 this._validateInput()94 }95 $(this.counterEl).html(counterString)96 }97 /**98 * Add validation classes99 */100 _validateInput() {...

Full Screen

Full Screen

StatBox.js

Source:StatBox.js Github

copy

Full Screen

1class StatBox {2 constructor(domId) {3 this.domBox = document.createElement("div")4 this.domBox.setAttribute("id", `${domId}-stats`)5 this.domBox.classList.add("stat-box")6 this.rwCounterContainer = document.createElement("div")7 this.rCounterContainer = document.createElement("div")8 this.wCounterContainer = document.createElement("div")9 this.rwCounterContainer.classList.add("counter-container")10 this.rCounterContainer.classList.add("counter-container")11 this.wCounterContainer.classList.add("counter-container")12 this.rwCounterText = document.createElement("h1")13 this.rCounterText = document.createElement("h1")14 this.wCounterText = document.createElement("h1")15 this.rwCounterText.classList.add("stat-h1s-sloppy-dop")16 this.rCounterText.classList.add("stat-h1s-sloppy-dop")17 this.wCounterText.classList.add("stat-h1s-sloppy-dop")18 this.rwCounterText.innerHTML = "Read/Write"19 this.rCounterText.innerHTML = "Read"20 this.wCounterText.innerHTML = "Write"21 this.rwCounter = document.createElement("h2")22 this.rCounter = document.createElement("h2")23 this.wCounter = document.createElement("h2")24 this.rwCounter.id = `${domId}-read-write`25 this.rCounter.id = `${domId}-read`26 this.wCounter.id = `${domId}-write`27 this.rwCounter.innerHTML = 028 this.rCounter.innerHTML = 029 this.wCounter.innerHTML = 030 this.rwCounterContainer.appendChild(this.rwCounter)31 this.rCounterContainer.appendChild(this.rCounter)32 this.wCounterContainer.appendChild(this.wCounter)33 this.rwCounterContainer.appendChild(this.rwCounterText)34 this.rCounterContainer.appendChild(this.rCounterText)35 this.wCounterContainer.appendChild(this.wCounterText)36 this.domBox.appendChild(this.rwCounterContainer)37 this.domBox.appendChild(this.rCounterContainer)38 this.domBox.appendChild(this.wCounterContainer)39 document.getElementById(domId).appendChild(this.domBox)40 }...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1import React from 'react';2import { Counter } from 'storybook-root';3const App = () => {4 return <Counter />;5};6export default App;7import React from 'react';8import ReactDOM from 'react-dom';9import App from './test';10ReactDOM.render(<App />, document.getElementById('root'));

Full Screen

Using AI Code Generation

copy

Full Screen

1import { Counter } from 'storybook-root';2import { Counter } from 'storybook-root';3import { Counter } from 'storybook-root';4import { Counter } from 'storybook-root';5import { Counter } from 'storybook-root';6import { Counter } from 'storybook-root';7import { Counter } from 'storybook-root';8import { Counter } from 'storybook-root';9import { Counter } from 'storybook-root';10import { Counter } from 'storybook-root';11import { Counter } from 'storybook-root';12import { Counter } from 'storybook-root';13import { Counter } from 'storybook-root';14import { Counter } from 'storybook-root';15import { Counter } from 'storybook-root';16import { Counter } from 'storybook-root';17import { Counter } from 'storybook-root';18import { Counter } from 'storybook-root';19import { Counter } from 'storybook-root';20import { Counter } from 'storybook-root';21import { Counter } from 'storybook-root';22import { Counter } from 'storybook-root';

Full Screen

Using AI Code Generation

copy

Full Screen

1import React from 'react';2import { Counter } from 'storybook-root';3export default function App() {4 return (5 );6}7import React from 'react';8import ReactDOM from 'react-dom';9import App from './test';10ReactDOM.render(<App />, document.getElementById('root'));11import React, { useState } from 'react';12export default function Counter() {13 const [count, setCount] = useState(0);14 return (15 <p>You clicked {count} times</p>16 <button onClick={() => setCount(count + 1)}>17 );18}19import React from 'react';20import ReactDOM from 'react-dom';21import App from './test';22ReactDOM.render(<App />, document.getElementById('root'));23import React, { useState } from 'react';24export default function Counter() {25 const [count, setCount] = useState(0);26 return (27 <p>You clicked {count} times</p>28 <button onClick={() => setCount(count + 1)}>29 );30}31import React, { useState } from 'react';32import Counter from './Counter';33export default function App() {34 const [showCounter, setShowCounter] = useState(true);35 return (36 <button onClick={() => setShowCounter(!showCounter)}>37 {showCounter ? 'Hide' : 'Show'} Counter38 {showCounter ? <Counter /> : null}39 );40}41import React, { useState } from 'react';42export default function Counter() {43 const [count, setCount] = useState(0);44 return (45 <p>You clicked {count} times</p>46 <button onClick={() => setCount(count + 1)}>47 );48}49import React from 'react';50import ReactDOM from 'react-dom';51import App from './App';52ReactDOM.render(<App />, document.getElementById('root'));

Full Screen

Using AI Code Generation

copy

Full Screen

1import { Counter } from 'storybook-root';2const App = () => {3 return (4 );5};6export default App;

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 storybook-root 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