def from_binary(cls, b): md5 = hashlib.md5() if len(b) % 32 != 0: raise InputError( "Partition table length must be a multiple of 32 bytes") result = cls() magic, version, nbrOfEntries, result.md5Sum, hash = struct.unpack_from( PartitionTable.HEADER_FORMAT, b) if magic != PartitionTable.MAGIC_BYTES: raise InputError( "Magic number of the partition table header don't match!") if version != PartitionTable.format_version: raise InputError( "Format version of the partition table header missmatch!") for o in range(32, 32 + nbrOfEntries * 32, 32): data = b[o:o + 32] md5.update(data) result.append(PartitionDefinition.from_binary(data)) if result.md5Sum and hash != md5.digest(): raise InputError( "MD5 checksums don't match! (computed: 0x%s, parsed: 0x%s)" % (md5.hexdigest(), binascii.hexlify(hash))) return result
def operationFunc(args, config=None): #if args.binary is None and args.flash_image is None: # raise errors.InputError( # 'Either the binary to execute on the target or the flash image containing the binary must be specified') #if args.target is None: # raise InputError('The target must be specified') config.set('runner/platform', args.platform) if args.binary is not None: config.set('runner/boot-loader', args.binary) module_name = config.get_str(args.platform + '/runner_module') if module_name is None: raise InputError('Invalid platform: ' + args.platform) module = importlib.import_module(module_name) if module is None: raise InputError('Invalid runner module:' + module) runner = module.Runner(args, config) status = runner.run() if status != 0: raise RuntimeError('Runner has failed with value: %d' % status)
def render_GET(self, request): dinamic_rouds_dict = { b"/": MojSajt.home, b"/get_posts": MojSajt.get_posts, b"/post_added": MojSajt.render_POST, b"/view_post": MojSajt.view_post } static_rouds_dict = { b"/new_post": ('templates/new_post.html', "text/html"), } if request.path in static_rouds_dict: try: request.setHeader("Content-Type", static_rouds_dict[request.path][1]) with open(static_rouds_dict[request.path][0], 'r') as file: template_content = file.read() return Post.read_base_template(template_content) except MySQLError as err: template, data = InputError.raise_error(str(err)) template_content = render(template, data) return Post.read_base_template(template_content) elif request.path in dinamic_rouds_dict: return dinamic_rouds_dict[request.path](request) template, data = InputError.raise_error('Unknown rout') template_content = render(template, data) return Post.read_base_template(template_content)
def verify(self, partitionTableOffset = None, flashSectorSize = None, flashSize = None): # verify each partition individually for p in self: p.verify(flashSectorSize) # check on duplicate name names = [p.name for p in self] duplicates = set(n for n in names if names.count(n) > 1) # print sorted duplicate partitions by name if len(duplicates) != 0: print("A list of partitions that have the same name:") for p in sorted(self, key = lambda x: x.name): if len(duplicates.intersection([p.name])) != 0: print("%s" % (p.to_csv())) raise InputError("Partition names must be unique") # check for overlaps last = None for p in sorted(self, key = lambda x: x.offset): if p.offset < partitionTableOffset + self.tableSize(): raise InputError( "%s partition offset 0x%x is below the end of partition table at 0x%x" % ( p.name, p.offset, partitionTableOffset + self.tableSize())) if last is not None and p.offset < last.offset + last.size: raise InputError( "Partition at 0x%x overlaps 0x%x-0x%x" % (p.offset, last.offset, last.offset + last.size - 1)) last = p if (flashSize and flashSize < self.flashSize()): raise InputError( "Partitions occupy %.1fMB of flash which does not fit in configured flash size of %dMB." % (self.flashSize() / 1024.0 / 1024.0, flashSize / 1024 ** 2))
def __init__(self, username, password, comfpassword): if not username or not password: raise InputError('Username and password must have some value') if password != comfpassword: raise InputError("Password's didn't mach") self.username = username self.password = password self.comfpassword = comfpassword
def close_trade(user, trade_id): trade_data = djson.loads( db_client.get_item( TableName=table_name, Key=djsonify({"pk": trade_id, "sk": user}), ) ) if trade_data.get("Item") is None: raise InputError("Invalid trade ID") trade_symbol = trade_data["Item"]["symbol"] trade_amount = trade_data["Item"]["amount"] open_price = trade_data["Item"]["open_price"] current_price = get_price(trade_symbol) action_multipler = 1 if trade_data["Item"]["action"] == "long" else -1 commission = current_price * trade_amount * 0.001 profit = float( "{:.2f}".format( (current_price - open_price) * trade_amount * action_multipler - commission ) ) bp_change = float("{:.2f}".format(current_price * trade_amount - commission)) try: db_client.update_item( TableName=table_name, Key=djsonify({"pk": trade_id, "sk": user}), UpdateExpression="REMOVE is_open SET closed_at=:value1, close_price=:value2, profit=:value3", ConditionExpression="attribute_exists(is_open)", ExpressionAttributeValues=djsonify( { ":value1": int(time.time()), ":value2": current_price, ":value3": profit, } ), ) except ClientError as e: if e.response["Error"]["Code"] == "ConditionalCheckFailedException": raise InputError("Trade already closed") else: raise if profit <= 0: update_string = "losses" else: update_string = "wins" db_client.update_item( TableName=table_name, Key=djsonify({"pk": user, "sk": "user"}), UpdateExpression=f"SET buying_power=buying_power+:value1, {update_string}={update_string}+:value2, realised_pnl=realised_pnl+:value3", ExpressionAttributeValues=djsonify( {":value1": bp_change, ":value2": 1, ":value3": profit,} ), ) return profit, current_price, trade_symbol
def __init__(self, book, author, book_num): if not book or not author or not book_num: raise InputError("Every positional argument: 'book', 'author', \ 'book_num', must have some value") if not book.isalpha() or not author.isalpha(): raise InputError('Book and author name must be alpha ') self.book = book self.author = author self.book_num = abs(int(book_num))
def get_news_type(url): """ Given the news url, find out the kind of editorial it is""" if url is None: raise InputError("URL", url, "None url") l = url.split('/') if len(l) < 6: raise InputError("Proper URL", url, "The URL seems to be wrong") typ = l[4] logging.debug("Got a news item of type : " + typ) return typ
def post_added(): try: new_post = PostCreate.read_post(request) Storage.add_post(new_post) return render_template('post_added.html', title=new_post.title, post=new_post.post) except InputError as err: return InputError.raise_error(str(err)) except Exception as err: return InputError.raise_error(str(err))
def from_csv(cls, csv_contents, partitionTableOffset = None, sectorSize = None, md5Sum = True): res = PartitionTable(md5Sum) lines = csv_contents.splitlines() def expand_vars(f): f = os.path.expandvars(f) m = re.match(r'(?<!\\)\$([A-Za-z_][A-Za-z0-9_]*)', f) if m: raise InputError("unknown variable '%s'" % m.group(1)) return f for line_no in range(len(lines)): line = expand_vars(lines[line_no]).strip() if line.startswith("#") or len(line) == 0: continue try: res.append(PartitionDefinition.from_csv(line, line_no + 1, sectorSize)) except InputError as e: raise InputError("Error at line %d: %s" % (line_no + 1, e)) except Exception: raise InputError("Unexpected error parsing CSV line %d: %s" % (line_no + 1, line)) # To fill automaticaly partition offset fields, partition table offset and sector size must be know. if (not (partitionTableOffset and sectorSize)): for e in res: if (e.offset is None): raise InputError("Flash offset of the `%s' partition is empty in the CSV input file.\n" "So that the gen_partition script automaticaly calculates this offset, you must specify partition table offset (--offset) " "and flash sector size (--flash-sector-size) from the command line." % e.name) return res # fix up missing offsets last_end = partitionTableOffset + res.tableSize() # first offset after partition table last_end = binary.align(last_end, sectorSize) for e in res: if e.offset is not None and e.offset < last_end: if e == res[0]: raise InputError("CSV Error: First partition offset 0x%x overlaps end of partition table 0x%x" % (e.offset, last_end)) else: raise InputError( "CSV Error: Partitions overlap. Partition at line %d sets offset 0x%x. Previous partition ends 0x%x" % (e.line_no, e.offset, last_end)) if e.offset is None: if last_end % sectorSize != 0: last_end = binary.align(last_end, sectorSize) e.offset = last_end last_end = e.offset + e.size return res
def get_raid(self, raid_id_str): if not raid_id_str.isdigit(): raise InputError('Raid #{} does not exist.'.format(raid_id_str)) raid_id_int = int(raid_id_str) if raid_id_int not in self.raid_map: if raid_id_int <= self.raid_seed: raise InputError('Raid #{} has expired.'.format(raid_id_str)) else: raise InputError('Raid #{} does not exist.'.format(raid_id_str)) return self.raid_map[raid_id_int]
def get_posts_from_to(request, page, page_size): if page < 1 or page_size < 1: template, data = InputError.raise_error( 'Page must be positive nuber') template_content = render(template, data) return Post.read_base_template(template_content) page_previous_num = page - 1 link_next_template = '<a href="/get_posts?page={}&page_size={}"> Next </a>' link_next = link_next_template.format(str(page + 1), str(page_size)) link_prev_template = '<a href="/get_posts?page={}&page_size={}"> Previous </a>' link_previous = link_prev_template.format(str(page_previous_num), str(page_size)) post_len = Storage.post_len() if page * page_size >= post_len: link_next = '' if page == 1: link_previous = '' all_posts = Storage.select_posts((page - 1) * page_size, page_size) if not all_posts: template, data = InputError.raise_error('No more posts to show') template_content = render(template, data) return Post.read_base_template(template_content) all_posts_list = [] for post in all_posts: post_dict = { 'title': post[0], 'post': post[3], 'date': str(post[1]), 'id': str(post[2]) } all_posts_list.append(post_dict) data_small = { 'posts': all_posts_list, 'next': link_next, 'previous': link_previous } with open('templates/home.html', 'r') as file: template_small = file.read() template_content = render(template_small, data_small) return Post.read_base_template(template_content)
def user_added(): try: new_user = UserCreate.read_user(request) Storage.add_user(new_user) except InputError as err: return InputError.raise_error(str(err)) except MySQLError as err: return InputError.raise_error(str(err)) except Exception as err: return InputError.raise_error(str(err)) return render_template('post_added.html', title='Welcome! you have signed up successfully. ', post=new_user.username)
def get_posts(): try: page = request.args.get("page") page_size = request.args.get("page_size") except Exception: return InputError.raise_error( "Something get wrong whit:'page' or 'page_size'") if not page or not page_size: return InputError.raise_error("Check:'page' and 'page_size'") if not page.isnumeric() or not page_size.isnumeric(): return InputError.raise_error( 'Page and page_size must be positive numbers') return get_posts_from_to(int(page), int(page_size))
def __init__(self, filename): if not type(filename) == str: raise InputError(f"Wrong argument type passed to Input constructor: exp=str, got={type(filename)}") self.name = filename try: with open(self.name) as f: self.text = ''.join(f.readlines()) except IOError as e: raise InputError(e) self.size = len(self.text) self.curr_ln = 1 self.offset = 0 self.offset_prev_line = 0 self.offset_token_start = 0
def __init__(self, first_name, last_name, user_address, phone_numb): if not first_name or not last_name \ or not user_address or not phone_numb: raise InputError("Every positional argument: 'first_name'" "'last_name', 'user_address', 'phone_num', " "must have some value") if not phone_numb.isnumeric(): raise InputError('Phone number must be integer') if not first_name.isalpha() or not last_name.isalpha(): raise InputError('First and last name must be alpha ') self.first_name = first_name self.last_name = last_name self.user_address = user_address self.phone_numb = phone_numb
def __errorAnalysis(self): """ It uses tableauI and tableauV to check errors. """ for i in self.__tableauv: if sum(i)!= 0: raise InputError("wrong circuit")
def get_product_code(pattern, url): product_code = re.findall( pattern, url)[0] if len(re.findall(pattern, url)) > 0 else '' if not product_code: raise InputError( 'Given URL contains invalid product code. Please retry.') return product_code
def mean_value(self): self.reading_in_progress = open( self.path, 'r' ) # to be able to read file line by line using read_one_line function comment = True # In case there is only one data point we want to return it's abscissa, so we will add a tiny rectangle around this point to our integral, but we want it to be tiny, so it normally won't affect the results dt = 0.00001 while (comment): x0, y0, y_error, isline, comment = self.read_one_line() if not (isline): raise InputError('RV file %s contains no data!' % self.name) else: # S will be our integral, t0 is going to be the beginning of the interval over which we calculate our integral S = y0 * dt t0 = x0 - dt while 1: # now we have the starting point, let's go through the rest of the file x, y, y_error, isline, comment = self.read_one_line() if not (isline): break # the file is over, we finish elif (comment): continue else: S = S + (x - x0) * (y + y0) / 2 # add a trapezoid to the integral x0 = x y0 = y self.reading_in_progress.close() return S / (x0 - t0) # divide integral by interval length
def parse_int(v, keywords = {}, sectorSize = None): """Generic parser for integer fields - int(x,0) with provision for k/m/K/M suffixes and 'keyword' value lookup. """ try: for letter, multiplier in [("k", 1024), ("m", 1024 * 1024), ("kb", 1024), ("mb", 1024 * 1024), ('sec', sectorSize)]: if v.lower().endswith(letter): return parse_int(v[:-len(letter)], keywords, sectorSize) * multiplier return int(v, 0) except ValueError: if len(keywords) == 0: raise InputError("Invalid field value %s" % v) try: return keywords[v.lower()] except KeyError: raise InputError("Value '%s' is not valid. Known keywords: %s" % (v, ", ".join(keywords)))
def add_participant(self, raid, user_id, user_name, party_size='1', notes=None): if not party_size.isdigit(): raise InputError( "The party size entered [{}] is not a number. If you're attending alone, please use 1.".format( party_size)) party_size = int(party_size) participant = RaidParticipant(raid=raid, user_id=user_id, user_name=user_name, party_size=party_size, notes=notes) already_in_raid = participant in self.participant_map[raid.display_id] if already_in_raid: self.participant_map[raid.display_id].remove(participant) participant = RaidParticipant.objects.get(raid=raid, user_id=user_id) participant.party_size = party_size participant.notes = notes participant.save() self.participant_map[raid.display_id].add(participant) self.update_embed_participants(raid) party_descriptor = (' +{} '.format(str(party_size - 1)) if party_size > 1 else '') if already_in_raid: return participant, "{} {}has __modified__ their RSVP to {} Raid #{} at {}".format(user_name, party_descriptor, raid.pokemon_name, raid.display_id, raid.gym_name) else: return participant, "{} {}has RSVP'd to {} Raid #{} at {}".format(user_name, party_descriptor, raid.pokemon_name, raid.display_id, raid.gym_name)
def get_posts(request): try: page = request.args[b"page"][0].decode('UTF-8') page_size = request.args[b"page_size"][0].decode('UTF-8') except Exception: template, data = InputError.raise_error( "Check:'page' and 'page_size'") template_content = render(template, data) return Post.read_base_template(template_content) if not page.isnumeric() or not page_size.isnumeric(): template, data = InputError.raise_error( 'Page and page_size must be positive numbers') template_content = render(template, data) return Post.read_base_template(template_content) return MojSajt.get_posts_from_to(request, int(page), int(page_size))
def validate_pluginid(plg_id, LEN_PLGID=32): """ raises an cli.InputError in case of invalid plugin id """ valid = re.compile("[a-fA-F0-9]{32,}") if not len(plg_id) == LEN_PLGID or \ valid.match(plg_id) is None: raise InputError("Invalid plugin id %s!" % str(plg_id))
def get_posts_from_to(page, page_size): li_home = Markup('<li class="nav-item" >') li_new_post = Markup('<li class="nav-item " >') if page < 1 or page_size < 1: return InputError.raise_error('Page must be positive nuber') link_next_template = Markup( '<a class="page-link" href="/get_posts?page={}&page_size={}"> Next </a>' ) link_next = link_next_template.format(str(page + 1), str(page_size)) link_prev_template = Markup( '<a class="page-link" href="/get_posts?page={}&page_size={}"> Previous </a>' ) link_previous = link_prev_template.format(str(page - 1), str(page_size)) post_len = Storage.post_len() if page * page_size >= post_len: link_next = '' if page == 1: link_previous = '' li_home = Markup('<li class="nav-item active" >') posts_from_to = Storage.select_posts((page - 1) * page_size, page_size) # ovde pravim listu objekata, da bi posle mogao lepo da prikazem u for petlji posts = [] for post in posts_from_to: if not post[4]: image = '' else: image = redirect(url_for('slika', ime_slike=post[2])) posts.append(Post(post[0], post[1], post[2], post[3], image)) if not posts_from_to: return InputError.raise_error('No more posts to show') return render_template('home.html', li_home=li_home, li_new_post=li_new_post, posts=posts, next=link_next, previous=link_previous)
def get_orientation(self): orientation = input("Horizontal [h] or Vertical [v]? > ").lower() if orientation != 'v' and orientation != 'h': InputError('orientation', orientation) self.player_board.print_board(self.player_board.game_board) return self.get_orientation() else: return orientation
def get_price(symbol): response = requests.get( "https://fapi.binance.com/fapi/v1/ticker/price", params={"symbol": symbol} ) if response.status_code == 200: return float(response.json()["price"]) raise InputError("Invalid symbol")
def get_selection(self): self.player_board.print_board(self.player_board.game_board) self.battleship.print_ships() selection = input("Choose the index (e.g. 1)? > ") try: selection = int(selection) - 1 except ValueError: InputError('value', selection) return self.get_selection() else: if selection not in list(range(0, len(self.battleship.ship_info))): selection = selection + 1 InputError('index_selection', selection) return self.get_selection() else: return selection
def from_binary(cls, b): if len(b) != 32: raise InputError("Partition definition length must be exactly 32 bytes. Got %d bytes." % len(b)) res = cls() (magic, res.type, res.subtype, res.offset, res.size, res.name, flags) = struct.unpack(cls.STRUCT_FORMAT, b) if b"\x00" in res.name: # strip null byte padding from name string res.name = res.name[:res.name.index(b"\x00")] res.name = res.name.decode() if magic != cls.MAGIC_BYTES: raise InputError("Invalid magic bytes (%r) for partition definition" % magic) for flag, bit in cls.FLAGS.items(): if flags & (1 << bit): setattr(res, flag, True) flags &= ~(1 << bit) if flags != 0: traces.critical("WARNING: Partition definition had unknown flag(s) 0x%08x. Newer binary format?" % flags) return res
def view_post(): try: post_id = request.args.get("post_id") post = Storage.select_post(post_id) return render_template('post_selected.html', title=post[0], post=post[3], date=post[1]) except Exception as err: return InputError.raise_error(str(err))
def attacked(self): if self.already_attacked: raise InputError('Square already attacked!') if self.setting == self.dictionary['ship']: self.set_hit() self.set_already_attacked() elif self.setting == self.dictionary['free']: self.set_miss() self.set_already_attacked()