Best Python code snippet using fMBT_python
edit_release.py
Source:edit_release.py
...23 def controller(self):24 self.form = edit_release_form(self.request)25 if self.submitted():26 if self.validate():27 self.update_release()28 else:29 self.edit_release()30 return self.response31 # --- Stages --------------------------------------------------------------32 # --- Conditions ----------------------------------------------------------33 # --- Actions -------------------------------------------------------------34 def edit_release(self):35 release = self.context.release36 # set appstruct37 self.appstruct = {38 'metadata': {39 'release_type':40 release.type,41 'release_title':42 release.title or '',43 'genres':44 [str(genre.id) for genre in release.genres],45 'styles':46 [str(style.id) for style in release.styles],47 'warning':48 release.warning or '',49 },50 'tracks': {51 'media': []52 },53 'production': {54 'grid_code':55 release.get_id_code('GRid') or '',56 'copyright_date':57 release.copyright_date or '',58 'production_date':59 release.production_date or '',60 },61 'distribution': {62 'label_catalog_number':63 release.label_catalog_number or '',64 'ean_upc_code':65 release.get_id_code('EAN/UPC') or '',66 'release_date':67 release.release_date or '',68 'release_cancellation_date':69 release.release_cancellation_date or '',70 'online_release_date':71 release.online_release_date or '',72 'online_cancellation_date':73 release.online_cancellation_date or '',74 'distribution_territory':75 release.distribution_territory or '',76 },77 }78 # artist release: artist79 if release.type == 'artist':80 self.appstruct['metadata']['artist'] = release.artists[0].oid81 # split release: split_artists82 if release.type == 'split':83 self.appstruct['metadata']['split_artists'] = []84 for artist in release.artists:85 self.appstruct['metadata']['split_artists'].append({86 'mode': "add",87 'oid': artist.oid,88 'name': artist.name,89 'code': artist.code or '',90 'description': artist.description or '',91 })92 # tracks93 m = []94 for t in release.tracks: # get list of medium numbers from all tracks95 m.append(t.medium_number)96 media_numbers = sorted(list(set(m)), key=lambda m: m)97 for medium in media_numbers:98 tracks = sorted(release.tracks, key=lambda t: t.track_number)99 a_tracklist = []100 for track in tracks:101 if track.medium_number == medium:102 creation_mode = "add"103 if Creation.is_foreign_track(104 self.request, release, track.creation):105 creation_mode = "edit"106 a_tracklist.append(107 {108 'mode': "edit",109 'oid': track.oid,110 'track_title': track.title,111 'license': track.license.oid,112 # TODO: 'medium_number': track.medium_number,113 # TODO: 'track_number': track.track_number,114 'track': [{115 'mode': creation_mode,116 'oid': track.creation.oid,117 'code': track.creation.code,118 'titlefield': track.creation.title,119 'artist': track.creation.artist.name120 }]121 })122 self.appstruct['tracks']['media'].append(a_tracklist)123 # publisher124 if release.publisher:125 mode = 'add'126 if self.request.party == release.publisher.entity_creator:127 mode = 'edit'128 self.appstruct['production']['publisher'] = [{129 'mode': mode,130 'oid': release.publisher.oid,131 'name': release.publisher.name,132 }]133 # label134 if release.label:135 mode = 'add'136 if self.request.party == release.label.entity_creator:137 mode = 'edit'138 self.appstruct['distribution']['label'] = [{139 'mode': mode,140 'oid': release.label.oid,141 'name': release.label.name,142 'gvl_code': release.label.gvl_code or '',143 }]144 # render145 self.render(self.appstruct)146 @Tdb.transaction(readonly=False)147 def update_release(self):148 appstruct = self.appstruct149 web_user = self.request.web_user150 party = self.request.party151 release = self.context.release152 # generate vlist153 _release = {154 'type':155 appstruct['metadata']['release_type'],156 'title':157 appstruct['metadata']['release_title'],158 'genres':159 [('add', map(int, appstruct['metadata']['genres']))],160 'styles':161 [('add', map(int, appstruct['metadata']['styles']))],...
transfer_pokemon.py
Source:transfer_pokemon.py
1from pokemongo_bot import inventory2from pokemongo_bot.human_behaviour import action_delay3from pokemongo_bot.base_task import BaseTask4from pokemongo_bot.inventory import Attack5from pokemongo_bot.inventory import Pokemon6from pokemongo_bot.inventory import Pokemons7from operator import attrgetter8from random import randrange9class TransferPokemon(BaseTask):10 SUPPORTED_TASK_API_VERSION = 111 def __init__(self, bot, config):12 super(TransferPokemon, self).__init__(bot, config)13 def initialize(self):14 self.min_free_slot = self.config.get('min_free_slot', 5)15 self.transfer_wait_min = self.config.get('transfer_wait_min', 1)16 self.transfer_wait_max = self.config.get('transfer_wait_max', 4)17 self.buddy = self.bot.player_data.get('buddy_pokemon', {})18 self.buddyid = self._get_buddyid()19 def work(self):20 if not self._should_work():21 return22 pokemon_groups = self._release_pokemon_get_groups()23 for pokemon_id, group in pokemon_groups.iteritems():24 pokemon_name = Pokemons.name_for(pokemon_id)25 self._release_pokemon_worst_in_group(group, pokemon_name)26 if self.bot.config.release.get('all'):27 group = [p for p in inventory.pokemons().all()28 if not p.in_fort and not p.is_favorite and not (p.unique_id == self.buddyid)]29 self._release_pokemon_worst_in_group(group, 'all')30 def _should_work(self):31 random_number = randrange (0,20,1) 32 return inventory.Pokemons.get_space_left() <= max(1,self.min_free_slot - random_number)33 def _release_pokemon_get_groups(self):34 pokemon_groups = {}35 for pokemon in inventory.pokemons().all():36 if pokemon.in_fort or pokemon.is_favorite or pokemon.unique_id == self.buddyid:37 continue38 group_id = pokemon.pokemon_id39 if group_id not in pokemon_groups:40 pokemon_groups[group_id] = []41 pokemon_groups[group_id].append(pokemon)42 return pokemon_groups43 def _release_pokemon_worst_in_group(self, group, pokemon_name):44 keep_best, keep_best_cp, keep_best_iv, keep_best_ivcp = self._validate_keep_best_config(45 pokemon_name)46 # TODO continue list possible criteria47 keep_best_possible_criteria = ['cp', 'iv', 'iv_attack', 'iv_defense', 'iv_stamina', 'ivcp',48 'moveset.attack_perfection', 'moveset.defense_perfection', 'hp', 'hp_max']49 keep_best_custom, keep_best_criteria, keep_amount = self._validate_keep_best_config_custom(50 pokemon_name, keep_best_possible_criteria)51 best_pokemon_ids = set()52 order_criteria = 'none'53 if keep_best:54 if keep_best_ivcp > 0:55 ivcp_limit = keep_best_ivcp56 best_ivcp_pokemons = sorted(group, key=lambda x: (57 x.ivcp), reverse=True)[:ivcp_limit]58 best_pokemon_ids = set(59 pokemon.unique_id for pokemon in best_ivcp_pokemons)60 order_criteria = 'ivcp'61 if keep_best_cp > 0:62 cp_limit = keep_best_cp63 best_cp_pokemons = sorted(group, key=lambda x: (64 x.cp, x.iv), reverse=True)[:cp_limit]65 best_pokemon_ids = set(66 pokemon.unique_id for pokemon in best_cp_pokemons)67 if order_criteria != 'none':68 order_criteria = order_criteria + ' and cp'69 else:70 order_criteria = 'cp'71 if keep_best_iv > 0:72 iv_limit = keep_best_iv73 best_iv_pokemons = sorted(group, key=lambda x: (74 x.iv, x.cp), reverse=True)[:iv_limit]75 best_pokemon_ids |= set(76 pokemon.unique_id for pokemon in best_iv_pokemons)77 if order_criteria != 'none':78 order_criteria = order_criteria + ' and iv'79 else:80 order_criteria = 'iv'81 82 elif keep_best_custom:83 limit = keep_amount84 # not sure if the u of unicode will stay, so make it go away85 keep_best_criteria = [str(keep_best_criteria[x])86 for x in range(len(keep_best_criteria))]87 best_pokemons = sorted(group, key=attrgetter(88 *keep_best_criteria), reverse=True)[:limit]89 best_pokemon_ids = set(90 pokemon.unique_id for pokemon in best_pokemons)91 order_criteria = ' then '.join(keep_best_criteria)92 if keep_best or keep_best_custom:93 # remove best pokemons from all pokemons array94 all_pokemons = group95 best_pokemons = []96 for best_pokemon_id in best_pokemon_ids:97 for pokemon in all_pokemons:98 if best_pokemon_id == pokemon.unique_id:99 all_pokemons.remove(pokemon)100 best_pokemons.append(pokemon)101 transfer_pokemons = [102 pokemon for pokemon in all_pokemons if self.should_release_pokemon(pokemon, True)]103 if transfer_pokemons:104 if best_pokemons:105 self.emit_event(106 'keep_best_release',107 formatted="Keeping best {amount} {pokemon}, based on {criteria}",108 data={109 'amount': len(best_pokemons),110 'pokemon': pokemon_name,111 'criteria': order_criteria112 }113 )114 for pokemon in best_pokemons:115 self.emit_event(116 'pokemon_keep',117 data={118 'pokemon': pokemon.name,119 'iv': pokemon.iv,120 'cp': pokemon.cp,121 'ivcp': pokemon.ivcp122 },123 formatted="Kept {} (CP: {}, IV: {}, IVCP: {})".format(pokemon.name, pokemon.cp, pokemon.iv, pokemon.ivcp),124 )125 for pokemon in transfer_pokemons:126 self.release_pokemon(pokemon)127 else:128 group = sorted(group, key=lambda x: x.cp, reverse=True)129 for pokemon in group:130 if self.should_release_pokemon(pokemon):131 self.release_pokemon(pokemon)132 def should_release_pokemon(self, pokemon, keep_best_mode=False):133 release_config = self._get_release_config_for(pokemon.name)134 if (keep_best_mode135 and 'never_release' not in release_config136 and 'always_release' not in release_config137 and 'release_below_cp' not in release_config138 and 'release_below_iv' not in release_config139 and 'release_below_ivcp' not in release_config):140 return True141 cp_iv_logic = release_config.get('logic')142 if not cp_iv_logic:143 cp_iv_logic = self._get_release_config_for(144 'any').get('logic', 'and')145 if release_config.get('never_release', False):146 return False147 if release_config.get('always_release', False):148 return True149 release_cp = release_config.get('release_below_cp', 0)150 release_iv = release_config.get('release_below_iv', 0)151 release_ivcp = release_config.get('release_below_ivcp', 0)152 release_results = {}153 # Check if any rules supplied154 if (release_cp == 0 and release_iv == 0 and release_ivcp == 0): # No rules supplied, assume all false155 release_results = {'cp': False, 'iv': False, 'ivcp': False}156 else: # One or more rules supplied, evaluate157 if (cp_iv_logic == 'and'): # "and" logic assumes true if not provided158 release_results['cp'] = (release_config.get('release_below_cp', -1) != 0) and (not release_cp or pokemon.cp < release_cp)159 release_results['iv'] = (release_config.get('release_below_iv', -1) != 0) and (not release_iv or pokemon.iv < release_iv)160 release_results['ivcp'] = (release_config.get('release_below_ivcp', -1) != 0) and (not release_ivcp or pokemon.ivcp < release_ivcp)161 else: # "or" logic assumes false if not provided162 release_results['cp'] = release_cp and pokemon.cp < release_cp163 release_results['iv'] = release_iv and pokemon.iv < release_iv164 release_results['ivcp'] = release_ivcp and pokemon.ivcp < release_ivcp165 166 logic_to_function = {167 'or': lambda x, y, z: x or y or z,168 'and': lambda x, y, z: x and y and z169 }170 if logic_to_function[cp_iv_logic](*release_results.values()):171 self.emit_event(172 'future_pokemon_release',173 formatted="*Releasing {}* CP: {}, IV: {}, IVCP: {:.2f} | based on rule: CP < {} {} IV < {} IVCP < {}".format(pokemon.name, pokemon.cp, pokemon.iv, pokemon.ivcp,174 release_cp, cp_iv_logic.upper(),release_iv, release_ivcp),175 data={176 'pokemon': pokemon.name,177 'cp': pokemon.cp,178 'iv': pokemon.iv,179 'ivcp': pokemon.ivcp,180 'below_cp': release_cp,181 'cp_iv_logic': cp_iv_logic.upper(),182 'below_iv': release_iv,183 'below_ivcp': release_ivcp184 },185 )186 return logic_to_function[cp_iv_logic](*release_results.values())187 def release_pokemon(self, pokemon):188 """189 :type pokemon: Pokemon190 """191 try:192 if self.bot.config.test:193 candy_awarded = 1194 else:195 request = self.bot.api.create_request()196 request.release_pokemon(pokemon_id=pokemon.unique_id)197 response_dict = request.call()198 199 candy_awarded = response_dict['responses'][200 'RELEASE_POKEMON']['candy_awarded']201 except KeyError:202 return203 # We could refresh here too, but adding 1 saves a inventory request204 candy = inventory.candies().get(pokemon.pokemon_id)205 candy.add(candy_awarded)206 inventory.pokemons().remove(pokemon.unique_id)207 self.bot.metrics.released_pokemon()208 self.emit_event(209 'pokemon_release',210 data={211 'pokemon': pokemon.name,212 'iv': pokemon.iv,213 'cp': pokemon.cp,214 'ivcp': pokemon.ivcp,215 'candy': candy.quantity,216 'candy_type': candy.type217 },218 formatted="Released {} (CP: {}, IV: {}, IVCP: {:.2f}) You now have"219 " {} {} candies".format(pokemon.name, pokemon.cp,220 pokemon.iv, pokemon.ivcp,221 candy.quantity, candy.type)222 )223 with self.bot.database as conn:224 c = conn.cursor()225 c.execute(226 "SELECT COUNT(name) FROM sqlite_master WHERE type='table' AND name='transfer_log'")227 result = c.fetchone()228 while True:229 if result[0] == 1:230 conn.execute('''INSERT INTO transfer_log (pokemon, iv, cp) VALUES (?, ?, ?)''',231 (pokemon.name, pokemon.iv, pokemon.cp))232 break233 else:234 self.emit_event(235 'transfer_log',236 sender=self,237 level='info',238 formatted="transfer_log table not found, skipping log"239 )240 break241 action_delay(self.transfer_wait_min, self.transfer_wait_max)242 def _get_release_config_for(self, pokemon):243 release_config = self.bot.config.release.get(pokemon)244 if not release_config:245 release_config = self.bot.config.release.get('any')246 if not release_config:247 release_config = {}248 return release_config249 def _validate_keep_best_config_custom(self, pokemon_name, keep_best_possible_custom):250 keep_best = False251 release_config = self._get_release_config_for(pokemon_name)252 keep_best_custom = release_config.get('keep_best_custom', '')253 keep_amount = release_config.get('amount', 0)254 if keep_best_custom and keep_amount:255 keep_best = True256 keep_best_custom = keep_best_custom.replace(' ','').split(',')257 for _str in keep_best_custom:258 if _str not in keep_best_possible_custom:259 keep_best = False260 break261 try:262 keep_amount = int(keep_amount)263 except ValueError:264 keep_best = False265 if keep_amount < 0:266 keep_best = False267 return keep_best, keep_best_custom, keep_amount268 def _validate_keep_best_config(self, pokemon_name):269 keep_best = False270 release_config = self._get_release_config_for(pokemon_name)271 keep_best_cp = release_config.get('keep_best_cp', 0)272 keep_best_iv = release_config.get('keep_best_iv', 0)273 keep_best_ivcp = release_config.get('keep_best_ivcp', 0)274 if keep_best_cp or keep_best_iv or keep_best_ivcp:275 keep_best = True276 try:277 keep_best_cp = int(keep_best_cp)278 except ValueError:279 keep_best_cp = 0280 try:281 keep_best_iv = int(keep_best_iv)282 except ValueError:283 keep_best_iv = 0284 try:285 keep_best_ivcp = int(keep_best_ivcp)286 except ValueError:287 keep_best_ivcp = 0288 289 if keep_best_cp < 0 or keep_best_iv < 0 or keep_best_ivcp < 0:290 keep_best = False291 if keep_best_cp == 0 and keep_best_iv == 0 and keep_best_ivcp == 0:292 keep_best = False293 294 return keep_best, keep_best_cp, keep_best_iv, keep_best_ivcp295 296 def _get_buddyid(self):297 if self.buddy and'id' in self.buddy:298 return self.buddy['id']...
idl_release.py
Source:idl_release.py
1#!/usr/bin/env python2# Copyright (c) 2012 The Chromium Authors. All rights reserved.3# Use of this source code is governed by a BSD-style license that can be4# found in the LICENSE file.5"""6IDLRelease for PPAPI7This file defines the behavior of the AST namespace which allows for resolving8a symbol as one or more AST nodes given a Release or range of Releases.9"""10import sys11from idl_log import ErrOut, InfoOut, WarnOut12from idl_option import GetOption, Option, ParseOptions13Option('release_debug', 'Debug Release data')14Option('wgap', 'Ignore Release gap warning')15#16# Module level functions and data used for testing.17#18error = None19warning = None20def ReportReleaseError(msg):21 global error22 error = msg23def ReportReleaseWarning(msg):24 global warning25 warning = msg26def ReportClear():27 global error, warning28 error = None29 warning = None30#31# IDLRelease32#33# IDLRelease is an object which stores the association of a given symbol34# name, with an AST node for a range of Releases for that object.35#36# A vmin value of None indicates that the object begins at the earliest37# available Release number. The value of vmin is always inclusive.38# A vmax value of None indicates that the object is never deprecated, so39# it exists until it is overloaded or until the latest available Release.40# The value of vmax is always exclusive, representing the first Release41# on which the object is no longer valid.42class IDLRelease(object):43 def __init__(self, rmin, rmax):44 self.rmin = rmin45 self.rmax = rmax46 def __str__(self):47 if not self.rmin:48 rmin = '0'49 else:50 rmin = str(self.rmin)51 if not self.rmax:52 rmax = '+oo'53 else:54 rmax = str(self.rmax)55 return '[%s,%s)' % (rmin, rmax)56 def SetReleaseRange(self, rmin, rmax):57 self.rmin = rmin58 self.rmax = rmax59 # True, if Release falls within the interval [self.vmin, self.vmax)60 def IsRelease(self, release):61 if self.rmax and self.rmax <= release:62 return False63 if self.rmin and self.rmin > release:64 return False65 if GetOption('release_debug'):66 InfoOut.Log('%f is in %s' % (release, self))67 return True68 # True, if Release falls within the interval [self.vmin, self.vmax)69 def InReleases(self, releases):70 if not releases: return False71 # Check last release first, since InRange does not match last item72 if self.IsRelease(releases[-1]): return True73 if len(releases) > 1:74 return self.InRange(releases[0], releases[-1])75 return False76 # True, if interval [vmin, vmax) overlaps interval [self.vmin, self.vmax)77 def InRange(self, rmin, rmax):78 assert (rmin == None) or rmin < rmax79 # An min of None always passes a min bound test80 # An max of None always passes a max bound test81 if rmin is not None and self.rmax is not None:82 if self.rmax <= rmin:83 return False84 if rmax is not None and self.rmin is not None:85 if self.rmin >= rmax:86 return False87 if GetOption('release_debug'):88 InfoOut.Log('%f to %f is in %s' % (rmin, rmax, self))89 return True90 def GetMinMax(self, releases = None):91 if not releases:92 return self.rmin, self.rmax93 if not self.rmin:94 rmin = releases[0]95 else:96 rmin = str(self.rmin)97 if not self.rmax:98 rmax = releases[-1]99 else:100 rmax = str(self.rmax)101 return (rmin, rmax)102 def SetMin(self, release):103 assert not self.rmin104 self.rmin = release105 def Error(self, msg):106 ReportReleaseError(msg)107 def Warn(self, msg):108 ReportReleaseWarning(msg)109#110# IDLReleaseList111#112# IDLReleaseList is a list based container for holding IDLRelease113# objects in order. The IDLReleaseList can be added to, and searched by114# range. Objects are stored in order, and must be added in order.115#116class IDLReleaseList(object):117 def __init__(self):118 self._nodes = []119 def GetReleases(self):120 return self._nodes121 def FindRelease(self, release):122 for node in self._nodes:123 if node.IsRelease(release):124 return node125 return None126 def FindRange(self, rmin, rmax):127 assert (rmin == None) or rmin != rmax128 out = []129 for node in self._nodes:130 if node.InRange(rmin, rmax):131 out.append(node)132 return out133 def AddNode(self, node):134 if GetOption('release_debug'):135 InfoOut.Log('\nAdding %s %s' % (node.Location(), node))136 last = None137 # Check current releases in that namespace138 for cver in self._nodes:139 if GetOption('release_debug'): InfoOut.Log(' Checking %s' % cver)140 # We should only be missing a 'release' tag for the first item.141 if not node.rmin:142 node.Error('Missing release on overload of previous %s.' %143 cver.Location())144 return False145 # If the node has no max, then set it to this one146 if not cver.rmax:147 cver.rmax = node.rmin148 if GetOption('release_debug'): InfoOut.Log(' Update %s' % cver)149 # if the max and min overlap, than's an error150 if cver.rmax > node.rmin:151 if node.rmax and cver.rmin >= node.rmax:152 node.Error('Declarations out of order.')153 else:154 node.Error('Overlap in releases: %s vs %s when adding %s' %155 (cver.rmax, node.rmin, node))156 return False157 last = cver158 # Otherwise, the previous max and current min should match159 # unless this is the unlikely case of something being only160 # temporarily deprecated.161 if last and last.rmax != node.rmin:162 node.Warn('Gap in release numbers.')163 # If we made it here, this new node must be the 'newest'164 # and does not overlap with anything previously added, so165 # we can add it to the end of the list.166 if GetOption('release_debug'): InfoOut.Log('Done %s' % node)167 self._nodes.append(node)168 return True169#170# IDLReleaseMap171#172# A release map, can map from an float interface release, to a global173# release string.174#175class IDLReleaseMap(object):176 def __init__(self, release_info):177 self.version_to_release = {}178 self.release_to_version = {}179 self.release_to_channel = {}180 for release, version, channel in release_info:181 self.version_to_release[version] = release182 self.release_to_version[release] = version183 self.release_to_channel[release] = channel184 self.releases = sorted(self.release_to_version.keys())185 self.versions = sorted(self.version_to_release.keys())186 def GetVersion(self, release):187 return self.release_to_version.get(release, None)188 def GetVersions(self):189 return self.versions190 def GetRelease(self, version):191 return self.version_to_release.get(version, None)192 def GetReleases(self):193 return self.releases194 def GetReleaseRange(self):195 return (self.releases[0], self.releases[-1])196 def GetVersionRange(self):197 return (self.versions[0], self.version[-1])198 def GetChannel(self, release):199 return self.release_to_channel.get(release, None)200#201# Test Code202#203def TestReleaseNode():204 FooXX = IDLRelease(None, None)205 Foo1X = IDLRelease('M14', None)206 Foo23 = IDLRelease('M15', 'M16')207 assert FooXX.IsRelease('M13')208 assert FooXX.IsRelease('M14')209 assert FooXX.InRange('M13', 'M13A')210 assert FooXX.InRange('M14','M15')211 assert not Foo1X.IsRelease('M13')212 assert Foo1X.IsRelease('M14')213 assert Foo1X.IsRelease('M15')214 assert not Foo1X.InRange('M13', 'M14')215 assert not Foo1X.InRange('M13A', 'M14')216 assert Foo1X.InRange('M14', 'M15')217 assert Foo1X.InRange('M15', 'M16')218 assert not Foo23.InRange('M13', 'M14')219 assert not Foo23.InRange('M13A', 'M14')220 assert not Foo23.InRange('M14', 'M15')221 assert Foo23.InRange('M15', 'M16')222 assert Foo23.InRange('M14', 'M15A')223 assert Foo23.InRange('M15B', 'M17')224 assert not Foo23.InRange('M16', 'M17')225 print "TestReleaseNode - Passed"226def TestReleaseListWarning():227 FooXX = IDLRelease(None, None)228 Foo1X = IDLRelease('M14', None)229 Foo23 = IDLRelease('M15', 'M16')230 Foo45 = IDLRelease('M17', 'M18')231 # Add nodes out of order should fail232 ReportClear()233 releases = IDLReleaseList()234 assert releases.AddNode(Foo23)235 assert releases.AddNode(Foo45)236 assert warning237 print "TestReleaseListWarning - Passed"238def TestReleaseListError():239 FooXX = IDLRelease(None, None)240 Foo1X = IDLRelease('M14', None)241 Foo23 = IDLRelease('M15', 'M16')242 Foo45 = IDLRelease('M17', 'M18')243 # Add nodes out of order should fail244 ReportClear()245 releases = IDLReleaseList()246 assert releases.AddNode(FooXX)247 assert releases.AddNode(Foo23)248 assert not releases.AddNode(Foo1X)249 assert error250 print "TestReleaseListError - Passed"251def TestReleaseListOK():252 FooXX = IDLRelease(None, None)253 Foo1X = IDLRelease('M14', None)254 Foo23 = IDLRelease('M15', 'M16')255 Foo45 = IDLRelease('M17', 'M18')256 # Add nodes in order should work257 ReportClear()258 releases = IDLReleaseList()259 assert releases.AddNode(FooXX)260 assert releases.AddNode(Foo1X)261 assert releases.AddNode(Foo23)262 assert not error and not warning263 assert releases.AddNode(Foo45)264 assert warning265 assert releases.FindRelease('M13') == FooXX266 assert releases.FindRelease('M14') == Foo1X267 assert releases.FindRelease('M15') == Foo23268 assert releases.FindRelease('M16') == None269 assert releases.FindRelease('M17') == Foo45270 assert releases.FindRelease('M18') == None271 assert releases.FindRange('M13','M14') == [FooXX]272 assert releases.FindRange('M13','M17') == [FooXX, Foo1X, Foo23]273 assert releases.FindRange('M16','M17') == []274 assert releases.FindRange(None, None) == [FooXX, Foo1X, Foo23, Foo45]275 # Verify we can find the correct versions276 print "TestReleaseListOK - Passed"277def TestReleaseMap():278 print "TestReleaseMap- Passed"279def Main(args):280 TestReleaseNode()281 TestReleaseListWarning()282 TestReleaseListError()283 TestReleaseListOK()284 print "Passed"285 return 0286if __name__ == '__main__':...
crashreport_update.py
Source:crashreport_update.py
1from sqlalchemy import create_engine, Column, Boolean, Integer, String2from sqlalchemy import update3from sqlalchemy.ext.declarative import declarative_base4from sqlalchemy.orm import sessionmaker5from sys import argv6import getCrashRate7engine = create_engine("sqlite:///scripts/PoltDemoDB.db", echo=False)8#engine = create_engine("sqlite:///PoltDemoDB.db", echo=False)9Base = declarative_base()10crashRate = 011Session = sessionmaker(bind=engine)12session = Session()13country = argv[1]14# update the crash rate of the last version for AU15class CrashReportAU(Base):16 __tablename__ = 'TestTableForAU'17 Id = Column(Integer,primary_key=True)18 ReleaseBuild = Column(String,nullable=False)19 CrashRate = Column(String, nullable=False)20 ReleaseNumber = Column(String,nullable=False)21 Notes = Column(String, nullable=True)22 # update crash rate up to date23 def updateData(self):24 crashRate,ReleaseBuild,ReleaseNumber = getCrashRate.get_crash_rate_for_country('Gumtree AU')25 query = session.query(CrashReportAU).order_by(CrashReportAU.Id.desc()).first()26 if crashRate == "0%":27 print("Crash Data is 0% ,no need to save into DB")28 if ReleaseBuild == query.ReleaseBuild:29 print("Build not update , Latest version is "+ReleaseBuild+",DB version is "+query.ReleaseBuild+ ", no need to save into DB")30 else:31 newVersion = CrashReportAU(ReleaseBuild=ReleaseBuild, CrashRate=crashRate,ReleaseNumber=ReleaseNumber)32 session.add(newVersion)33 session.commit()34# update the crash rate of the last version for CA35class CrashReportCA(Base):36 __tablename__ = 'TestTableForCA'37 Id = Column(Integer,primary_key=True)38 ReleaseBuild = Column(String,nullable=False)39 CrashRate = Column(String, nullable=False)40 ReleaseNumber = Column(String,nullable=False)41 Notes = Column(String, nullable=True)42 # update crash rate up to date43 def updateData(self):44 crashRate,ReleaseBuild,ReleaseNumber = getCrashRate.get_crash_rate_for_country('Kijiji CA')45 query = session.query(CrashReportCA).order_by(CrashReportCA.Id.desc()).first()46 if crashRate == "0%":47 print("Crash Data is 0% ,no need to save into DB")48 if ReleaseBuild == query.ReleaseBuild:49 print("Build not update , Latest version is "+ReleaseBuild+",DB version is "+query.ReleaseBuild+ ", no need to save into DB")50 else:51 newVersion = CrashReportCA(ReleaseBuild=ReleaseBuild, CrashRate=crashRate,ReleaseNumber=ReleaseNumber)52 session.add(newVersion)53 session.commit()54# update the crash rate of the last version for IT55class CrashReportIT(Base):56 __tablename__ = 'TestTableForIT'57 Id = Column(Integer,primary_key=True)58 ReleaseBuild = Column(String,nullable=False)59 CrashRate = Column(String, nullable=False)60 ReleaseNumber = Column(String,nullable=False)61 Notes = Column(String, nullable=True)62 # update crash rate up to date63 def updateData(self):64 crashRate,ReleaseBuild,ReleaseNumber = getCrashRate.get_crash_rate_for_country('Kijiji IT')65 query = session.query(CrashReportIT).order_by(CrashReportIT.Id.desc()).first()66 if crashRate =="0%":67 print("Crash Rate collect is 0%, no need to save DB")68 if ReleaseBuild == query.ReleaseBuild:69 print("Build not update , Latest version is "+ReleaseBuild+",DB version is "+query.ReleaseBuild+ ", no need to save into DB")70 else:71 newVersion = CrashReportIT(ReleaseBuild=ReleaseBuild, CrashRate=crashRate,ReleaseNumber=ReleaseNumber)72 session.add(newVersion)73 session.commit()74# update the crash rate of the last version for ZA75class CrashReportZA(Base):76 __tablename__ = 'TestTableForZA'77 Id = Column(Integer,primary_key=True)78 ReleaseBuild = Column(String,nullable=False)79 CrashRate = Column(String, nullable=False)80 ReleaseNumber = Column(String,nullable=False)81 Notes = Column(String, nullable=True)82 # update crash rate up to date83 def updateData(self):84 crashRate,ReleaseBuild,ReleaseNumber = getCrashRate.get_crash_rate_for_country('Gumtree ZA')85 query = session.query(CrashReportZA).order_by(CrashReportZA.Id.desc()).first()86 if crashRate =="0%":87 print("Crash Rate collect is 0%, no need to save DB")88 if ReleaseBuild == query.ReleaseBuild:89 print("Build not update , Latest version is "+ReleaseBuild+",DB version is "+query.ReleaseBuild+ ", no need to save into DB")90 else:91 newVersion = CrashReportZA(ReleaseBuild=ReleaseBuild, CrashRate=crashRate,ReleaseNumber=ReleaseNumber)92 session.add(newVersion)93 session.commit()94# update the crash rate of the last version for MX95class CrashReportMX(Base):96 __tablename__ = 'TestTableForMX'97 Id = Column(Integer,primary_key=True)98 ReleaseBuild = Column(String,nullable=False)99 CrashRate = Column(String, nullable=False)100 ReleaseNumber = Column(String,nullable=False)101 Notes = Column(String, nullable=True)102 # update crash rate up to date103 def updateData(self):104 crashRate,ReleaseBuild,ReleaseNumber = getCrashRate.get_crash_rate_for_country('Vivanuncios MX')105 query = session.query(CrashReportMX).order_by(CrashReportMX.Id.desc()).first()106 if crashRate == "0%":107 print("Crash Rate collect is 0%, no need to save DB")108 if ReleaseBuild == query.ReleaseBuild:109 print("Build not update , Latest version is "+ReleaseBuild+",DB version is "+query.ReleaseBuild+ ", no need to save into DB")110 else:111 newVersion = CrashReportMX(ReleaseBuild=ReleaseBuild, CrashRate=crashRate,ReleaseNumber=ReleaseNumber)112 session.add(newVersion)113 session.commit()114# update the crash rate of the last version for PL115class CrashReportPL(Base):116 __tablename__ = 'TestTableForPL'117 Id = Column(Integer,primary_key=True)118 ReleaseBuild = Column(String,nullable=False)119 CrashRate = Column(String, nullable=False)120 ReleaseNumber = Column(String,nullable=False)121 Notes = Column(String, nullable=True)122 # update crash rate up to date123 def updateData(self):124 crashRate,ReleaseBuild,ReleaseNumber = getCrashRate.get_crash_rate_for_country('Gumtree PL')125 query = session.query(CrashReportPL).order_by(CrashReportPL.Id.desc()).first()126 if crashRate == "0%":127 print("Crash Rate collect is 0%, no need to save DB")128 if ReleaseBuild == query.ReleaseBuild:129 print("Build not update , Latest version is "+ReleaseBuild+",DB version is "+query.ReleaseBuild+ ", no need to save into DB")130 else:131 newVersion = CrashReportPL(ReleaseBuild=ReleaseBuild, CrashRate=crashRate,ReleaseNumber=ReleaseNumber)132 session.add(newVersion)133 session.commit()134# update the crash rate of the last version for AR135class CrashReportAR(Base):136 __tablename__ = 'TestTableForAR'137 Id = Column(Integer,primary_key=True)138 ReleaseBuild = Column(String,nullable=False)139 CrashRate = Column(String, nullable=False)140 ReleaseNumber = Column(String,nullable=False)141 Notes = Column(String, nullable=True)142 # update crash rate up to date143 def updateData(self):144 crashRate,ReleaseBuild,ReleaseNumber = getCrashRate.get_crash_rate_for_country('Alamaula AR')145 query = session.query(CrashReportAR).order_by(CrashReportAR.Id.desc()).first()146 if crashRate == "0%":147 print("Crash Rate collect is 0%, no need to save DB")148 if ReleaseBuild == query.ReleaseBuild:149 print("Build not update , Latest version is "+ReleaseBuild+",DB version is "+query.ReleaseBuild+ ", no need to save into DB")150 else:151 newVersion = CrashReportAR(ReleaseBuild=ReleaseBuild, CrashRate=crashRate,ReleaseNumber=ReleaseNumber)152 session.add(newVersion)153 session.commit()154# update the crash rate of the last version for IE155class CrashReportIE(Base):156 __tablename__ = 'TestTableForIE'157 Id = Column(Integer,primary_key=True)158 ReleaseBuild = Column(String,nullable=False)159 CrashRate = Column(String, nullable=False)160 ReleaseNumber = Column(String,nullable=False)161 Notes = Column(String, nullable=True)162 # update crash rate up to date163 def updateData(self):164 crashRate,ReleaseBuild,ReleaseNumber = getCrashRate.get_crash_rate_for_country('Gumtree IE')165 query = session.query(CrashReportIE).order_by(CrashReportIE.Id.desc()).first()166 if crashRate == "0%":167 print("Crash Rate collect is 0%, no need to save DB")168 if ReleaseBuild == query.ReleaseBuild:169 print("Build not update , Latest version is "+ReleaseBuild+",DB version is "+query.ReleaseBuild+ ", no need to save into DB")170 else:171 newVersion = CrashReportIE(ReleaseBuild=ReleaseBuild, CrashRate=crashRate,ReleaseNumber=ReleaseNumber)172 session.add(newVersion)173 session.commit()174if country =="GumtreeAU":175 crashReportAU = CrashReportAU()176 crashReportAU.updateData()177if country =="GumtreeZA":178 crashReportZA = CrashReportZA()179 crashReportZA.updateData()180if country =="GumtreeIE":181 crashReportIE = CrashReportIE()182 crashReportIE.updateData()183if country =="GumtreePL":184 crashReportPL = CrashReportPL()185 crashReportPL.updateData()186if country =="KijijiCA":187 crashReportCA = CrashReportCA()188 crashReportCA.updateData()189if country =="KijijiIT":190 crashReportIT = CrashReportIT()191 crashReportIT.updateData()192if country =="AlamaulaAR":193 crashReportAR = CrashReportAR()194 crashReportAR.updateData()195if country =="VivanunciosMX":196 crashReportMX = CrashReportMX()...
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!