def fac_enter(fid, v=1): if fid not in facilities.keys(): errors.print_error(43, xact.curblk+1, [fid]) if facilities[fid].isQueued: queued = [q[0] for q in queues[fid].queuedxacts] if xact.index not in queued: queue_enter(fid) toklines[xact.curblk][-1][2] -= 1 xact.curblk -= 1 if facilities[fid].curplaces - v >= 0 and facilities[fid].isAvail: facilities[fid].curplaces -= v facilities[fid].enters_f += 1 if xact.index in facilities[fid].busyxacts: errors.print_error(41, xact.curblk+1) facilities[fid].busyxacts[xact.index] = [v, ints['curticks'].value] if config.log_xact_blocking: print 'Added xact '+str(xact.index)+' to facility '+fid if facilities[fid].isQueued: queue_leave(fid) toklines[xact.curblk][-1][2] -= 1 xact.curblk -= 1 xact.curblk += 1 xact.cond = 'canmove' toklines[xact.curblk][-1][2] += 1 else: xact.cond = 'blocked'
def queue_leave(qid): global toklines if qid not in queues.keys(): errors.print_error(44, xact.curblk+1, [qid]) queued = [q[0] for q in queues[qid].queuedxacts] if xact.index not in queued: errors.print_error(40, xact.curblk+1) queues[qid].curxacts -= 1 index = 0 enter_time = 0 for queued_xact in queues[qid].queuedxacts: if queued_xact[0] == xact.index: enter_time = queued_xact[1] break index += 1 del queues[qid].queuedxacts[index] time_in_queue = ints['curticks'].value - enter_time queues[qid].sum_for_avg_time_in_queue += time_in_queue if time_in_queue > queues[qid].max_time_in_queue: queues[qid].max_time_in_queue = time_in_queue xact.curblk += 1 xact.cond = 'canmove' toklines[xact.curblk][-1][2] += 1
def to_float(val): ret = 0 try: ret = float(val) except ValueError: errors.print_error(31, parser.lineindex, [val, 'float']) return ret
def tocodelines(program): parsed = [['padding', [0, 0, 0]]] i = 0 li = 1 while i < len(program): token = program[i] if token[0] in 'lbrace' + 'rbrace' + 'lexec' + 'rexec': parsed.append([token, [li, 0, 0]]) i += 1 li += 1 continue line = [] while True: token = program[i] line.append(token) i += 1 if token[0] == 'eocl' or token == ['block', 'else'] or \ (token == ['rparen', ''] and program[i] == ['lbrace', ''] and \ ['block', 'inject'] not in line and ['typedef', 'function'] not in line): line.append([li, 0, 0]) parsed.append(line) li += 1 break if i >= len(program): errors.print_error(2, '') return parsed
def date(inv_date): if len(str(inv_date)) != 0: inv_date = formathelp.format_date(inv_date) if not inv_date: return errors.print_error("val_date_syntax") return True return errors.print_error("val_date_missing")
def find_platforms(root_dir: str) -> List[Platform]: platforms: List[Platform] = [] all_unsupported_elems: Set[str] = set() theme_xmls = find_theme_xmls(root_dir) for platform_name, xml_path in theme_xmls.items(): print_info(f"Processing platform `{platform_name}` (`{xml_path}`)") try: variables: Dict[str, str] = {} views: Dict[str, Dict[str, Element]] = create_default_views(root_dir) unsupported_elems = read_theme_xml(root_dir, xml_path, variables, views) except RuntimeError as err: print_error(err) warn(f"Platform `{platform_name}` skipped") continue platforms.append(Platform(platform_name, views)) all_unsupported_elems.update(unsupported_elems) if all_unsupported_elems: warn( "The following unknown or unsupported items were found in this theme:" ) for elem in all_unsupported_elems: warn(f" - {elem}") return platforms
def move(self, new_path, sqlconn=sql.getconn()): """ Moves invoice and changes the object and SQL data """ if len(self.pages) == 1: old_path = self.pages[0] self.pages = [] self.pages.append(new_path + str(self.number) + "_1") if sql.execute(sql.move_query(self)): try: shutil.move(old_path, new_path + str(self.number) + "_1") sqlconn.commit() sqlconn.close() return True except Exception as e: sqlconn.rollback() sqlconn.close() return errors.print_error("inv_move_move", e) else: sqlconn.rollback() sqlconn.close() return errors.print_error("inv_move_sql") else: #TODO move multiple pages sqlconn.rollback() sqlconn.close() return errors.print_error("inv_move_nyi")
def fac_goaway(fid): if fid not in facilities.keys(): errors.print_error(43, xact.curblk+1, [fid]) # Because this xact could skip fac_irrupt() block because it's too "fat" # to irrupt that facility: if xact.index not in facilities[fid].busyxacts: move() return # Delete this xact from facility. # go: [vol, enter time] go = facilities[fid].busyxacts[xact.index] facilities[fid].curplaces += go[0] del facilities[fid].busyxacts[xact.index] review_cec() # Move xacts to freed places from irrupt chain. for i in range(len(facilities[fid].irruptch)): # xainfo: [xact, elapsed time, [xact vol, enter time]] xainfo = facilities[fid].irruptch[i] if facilities[fid].curplaces < xainfo[2][0]: continue if xainfo[1] == 0: tempCurrentChain.append(copy.deepcopy(xainfo[0])) else: futureChain.append([xainfo[1], copy.deepcopy(xainfo[0])]) facilities[fid].busyxacts[xainfo[0].index] = xainfo[2] if config.log_facility_entering: print 'added xact '+str(xainfo[0].index)+' back to facility '+fid facilities[fid].curplaces += xainfo[2][0] facilities[fid].irruptch[i] = [] facilities[fid].irruptch = [el for el in facilities[fid].irruptch if el != []]
def price(price): if len(str(price)) != 0: try: float(price) return True except ValueError: return errors.print_error("val_sum_syntax") return errors.print_error("val_sum_missing")
def hist_sample(hist, weight=1): if hist not in hists.keys(): errors.print_error(53, xact.curblk+1, [hist]) parser.tokline = hists[hist].param parser.pos = 0 val = parser.parseExpression() hists[hist].sample(val, weight) move()
def chain_enter(chid): if chid not in chains.keys(): errors.print_error(48, xact.curblk+1, [chid]) global toklines chains[chid].xacts.append(xact) chains[chid].length = len(chains[chid].xacts) xact.cond = 'chained' toklines[xact.curblk+1][-1][2] += 1
def parseBuiltin(): name = peek(0)[1] fun = getattr(builtins, name) args = [] nexttok() consume('lparen') if name == 'find_minmax': if peek(0)[1] != 'min' and peek(0)[1] != 'max': errors.print_error(21, lineindex, ['min/max', peek(0)[1]], 'D') args.append(peek(0)[1]) nexttok() consume('comma') if name == 'find' or name == 'find_minmax': toks = [] depth = 0 while True: if peek(0)[0] == 'rparen': depth -= 1 elif peek(0)[0] == 'lparen': depth += 1 if depth == -1: consume('rparen') break toks.append(peek(0)) nexttok() args.append(toks) if len(inspect.getargspec(fun).args) != len(args): errors.print_error( 55, lineindex, [name, len(inspect.getargspec(fun).args), len(args)]) return fun(*args) # For other builtins: while True: if matchtok('rparen'): break args.append(parseExpression()) if peek(0)[0] == 'comma': consume('comma') continue elif peek(0)[0] == 'rparen': consume('rparen') break else: errors.print_error(16, lineindex, [peek(0)], 'B') if name == 'round_to' and (len(args) != 1 or len(args) != 2): errors.print_error(55, lineindex, ['round_to', '1 or 2', len(args)]) elif len(inspect.getargspec(fun).args) != len(args): errors.print_error( 55, lineindex, [name, len(inspect.getargspec(fun).args), len(args)]) return fun(*args)
def exp_distr(x, l): if type(x) is not int and type(x) is not float: errors.print_error(18, parser.lineindex, [x]) if type(l) is not int and type(l) is not float: errors.print_error(18, parser.lineindex, [l]) if x < 0: return 0 else: return 1 - math.exp(-l * x)
def fac_leave(fid): if xact.index not in facilities[fid].busyxacts: errors.print_error(42, xact.curblk+1) if fid not in facilities.keys(): errors.print_error(43, xact.curblk+1, [fid]) leaving = facilities[fid].busyxacts[xact.index] facilities[fid].curplaces += leaving[0] facilities[fid].processedxactsticks += ints['curticks'].value - leaving[1] del facilities[fid].busyxacts[xact.index] review_cec()
def to_bool(val): if type(val) is not int and type(val) is not float and \ type(val) is not bool and val != 'true' and val != 'false': errors.print_error(31, parser.lineindex, [val, 'bool']) if val == 'true': return True if val == 'false': return False if val != 0: return True return False
def getMatrixElementName(matrixname, index1, index2): horlbound = matrices_info[matrixname][0][0] horrbound = matrices_info[matrixname][0][1] vertlbound = matrices_info[matrixname][1][0] vertrbound = matrices_info[matrixname][1][1] if vertlbound <= index1 <= vertrbound and \ horlbound <= index2 <= horrbound: return arrayname + '&&(' + str(index1) + ',' + str(index2) + ')' errors.print_error( 56, lineindex, [[index1, index2], [vertlbound, vertrbound], [horlbound, horrbound]])
def attachFileWithFunctions(line): global attachables filename = line[1][1] newlib = None if filename in attachables: errors.print_warning(5, line[-1][0], [filename]) return try: newlib = importlib.import_module(filename) except ImportError: errors.print_error(57, line[-1][0], [filename]) attachables[filename] = newlib
def graph_sample(graph): if graph not in graphs.keys(): errors.print_error(59, xact.curblk+1, [graph]) parser.tokline = graphs[graph].paramX parser.pos = 0 x = parser.parseExpression() parser.tokline = graphs[graph].paramY parser.pos = 0 y = parser.parseExpression() graphs[graph].sample(x, y) move()
def consume(toktype, toktext=''): global pos global lineindex if peek(0)[0] != toktype: if toktext != '': if peek(0)[1] != toktext: errors.print_error( 21, lineindex, [[toktype, toktext], peek(0)], 'A') else: errors.print_error(21, lineindex, [toktype, peek(0)], 'A') pos += 1
def update_data(self, new_invoice_number=""): if new_invoice_number == "": new_invoice_number = self.number print("Update Initiated") try: if sql.update_entry(self, new_invoice_number): print("Update Worked") return True except sqlite3.OperationalError as e: return errors.print_error("Inv_Upd_1", e) except Exception as e: return errors.print_error("Inv_Upd_2", e) return False
def parseMult(): result = parseUnary() while True: if matchtok('mult'): result1 = parseUnary() if type(result1) is str or type(result) is str: errors.print_error(8, lineindex, ['*']) result *= result1 continue if matchtok('div'): result1 = parseUnary() if type(result1) is str or type(result) is str: errors.print_error(8, lineindex, ['/']) result /= result1 continue if matchtok('remain'): result1 = parseUnary() if type(result1) is str or type(result) is str: errors.print_error(8, lineindex, ['%']) result = result % result1 continue if matchtok('pwr'): result1 = parseUnary() if type(result1) is str or type(result) is str: errors.print_error(8, lineindex, ['**']) result = result**result1 continue break return result
def tokenizeNumber(): result = '' cur = peek(0) while True: if cur == '.': if '.' in result: errors.print_error(9, '', [result + '.']) result += cur elif cur in numbers: result += cur else: break cur = nextchar() addToken('number', result)
def copy_block(cnt, toblk=''): global ints if toblk != '': if toblk not in marks.keys(): errors.print_error(29, xact.curblk+1, [toblk]) if marks[toblk].block == -1: errors.print_error(30, xact.curblk+1, [toblk]) move() for i in range(cnt): xa = copy.deepcopy(xact) if toblk != '': xa.curblk = marks[toblk].block - 1 else: xa.curblk += 1 xa.cond = 'canmove' xa.index = ints['injected'].value ints['injected'].value += 1 tempCurrentChain.append(xa)
def parsePrimaryWord(word): global pos if word == 'true': val = True elif word == 'false': val = False elif word in interpreter.functions: val = parseConditionalFunction(word) pos -= 1 elif word in interpreter.attachables: val = parseAttachableFunction(word) pos -= 1 elif word in interpreter.ints: val = interpreter.ints[word].value elif word in interpreter.floats: val = interpreter.floats[word].value elif word in interpreter.strs: val = interpreter.strs[word].value elif word in interpreter.bools: val = interpreter.bools[word].value elif word in interpreter.facilities: val = interpreter.facilities[word].name elif word in interpreter.queues: val = interpreter.queues[word].name elif word in interpreter.marks: val = interpreter.marks[word].name elif word in interpreter.chains: val = interpreter.chains[word].name elif word in interpreter.hists: val = interpreter.hists[word].name elif word in fac_params+queue_params+xact_params+ \ chain_params+hist_params+['xact', 'chxact']+ \ arrays_info.keys()+matrices_info.keys(): val = word elif type(interpreter.xact.params.keys()) is not None and \ word in interpreter.xact.params.keys(): val = word else: errors.print_error(6, lineindex, [word]) return val
def queue_enter(qid): global toklines global queues if qid not in queues.keys(): errors.print_error(44, xact.curblk+1, [qid]) queued = [q[0] for q in queues[qid].queuedxacts] if xact.index in queued: errors.print_error(39, xact.curblk+1) if queues[qid].curxacts == 0: queues[qid].zero_entries += 1 queues[qid].enters_q += 1 queues[qid].curxacts += 1 if queues[qid].curxacts > queues[qid].maxxacts: queues[qid].maxxacts = queues[qid].curxacts queues[qid].queuedxacts.append([xact.index, ints['curticks'].value]) xact.curblk += 1 xact.cond = 'canmove' toklines[xact.curblk][-1][2] += 1
def parseAdd(): result = parseMult() while True: if matchtok('plus'): result1 = parseMult() if type(result1) is str and type(result) is not str or \ type(result) is str and type(result1) is not str: errors.print_error(20, lineindex) result += result1 continue if matchtok('minus'): result1 = parseMult() if type(result1) is str or type(result) is str: errors.print_error(8, lineindex, ['-']) result -= result1 continue break return result
def while_block(cond): global toklines if cond: xact.curblk += 1 toklines[xact.curblk][-1][2] += 1 move() return depth = 0 for i in range(xact.curblk+2, len(toklines)): if toklines[i][0][0] == 'lbrace': depth += 1 elif toklines[i][0][0] == 'rbrace': depth -= 1 if depth == 0: break if depth != 0: errors.print_error(37, i) xact.curblk = i xact.cond = 'canmove' toklines[xact.curblk][-1][2] += 1
def checkAssignmentTypes(l, r, asg): if type(l) is int: if type(r) is int: return r if type(r) is float: return int(r) errors.print_error(33, lineindex, [asg, type(l), type(r)]) if type(l) is float: if type(r) is int or type(r) is float: return r errors.print_error(33, lineindex, [asg, type(l), type(r)]) if type(l) is str: if type(r) is not str: errors.print_error(33, lineindex, [asg, type(l), type(r)]) if asg != 'eq' and asg != 'add': errors.print_error(33, lineindex, [asg, type(l), type(r)]) return r if type(l) is bool: if type(r) is not bool: errors.print_error(33, lineindex, [asg, type(l), type(r)]) return r
def parseAttachableFunction(modulename): nexttok() consume('dot') functionname = peek(0)[1] func = None try: func = getattr(interpreter.attachables[modulename], functionname) except AttributeError: errors.print_error(58, lineindex, [modulename, functionname]) nexttok() consume('lparen') args = [] while True: if matchtok('rparen'): break args.append(parseExpression()) if peek(0)[0] == 'comma': consume('comma') continue elif peek(0)[0] == 'rparen': consume('rparen') break else: errors.print_error(16, lineindex, [peek(0)], 'A') if len(inspect.getargspec(func).args) != len(args): errors.print_error( 55, lineindex, [name, len(inspect.getargspec(func).args), len(args)]) return func(*args)
def parse_param(basedir: str, prop_type: PropType, prop_str: str) -> Optional[Property]: assert (basedir) assert (prop_str) try: if prop_type == PropType.NORMALIZED_PAIR: return NormPair(prop_str) if prop_type == PropType.NORMALIZED_RECT: return NormRect(prop_str) if prop_type == PropType.STRING: return prop_str if prop_type == PropType.PATH: return os.path.normpath(os.path.join(basedir, prop_str)) if prop_type == PropType.COLOR: return Color(prop_str) if prop_type == PropType.FLOAT: return float(prop_str) if prop_type == PropType.BOOLEAN: return prop_str.lower()[0] in ['1', 't', 'y'] except ValueError as err: print_error(err) return None
def getAttrsForDotOperator(lh, rh): val = None if config.log_dot_operator: print 'Dot attrs:', lh, rh if rh in fac_params and lh in interpreter.facilities: val = getattr(interpreter.facilities[lh], rh) elif rh in queue_params and lh in interpreter.queues: val = getattr(interpreter.queues[lh], rh) elif rh in chain_params and lh in interpreter.chains: val = getattr(interpreter.chains[lh], rh) elif rh in hist_params and lh in interpreter.hists: val = getattr(interpreter.hists[lh], rh) elif lh == 'xact': if rh not in xact_params: #parameters from 'params' dict if rh not in interpreter.xact.params.keys(): errors.print_error(25, lineindex, [interpreter.xact.group, rh]) val = interpreter.xact.params[rh] else: #direct parameters val = getattr(interpreter.xact, rh) elif lh == 'chxact': if rh not in xact_params: #parameters from 'params' dict if rh not in interpreter.chxact.params.keys(): errors.print_error(25, lineindex, [interpreter.chxact.group, rh]) val = interpreter.chxact.params[rh] else: #direct parameters val = getattr(interpreter.xact, rh) elif rh == 'name': if lh in interpreter.ints: val = interpreter.ints[lh].name elif lh in interpreter.floats: val = interpreter.floats[lh].name elif lh in interpreter.strs: val = interpreter.strs[lh].name elif lh in interpreter.bools: val = interpreter.bools[lh].name else: errors.print_error(28, lineindex, [lh]) else: errors.print_error( 21, lineindex, ["name of parameter of defined variable", lh + ' ' + rh], 'B') return val
def parseConditionalFunction(functionName): func = interpreter.functions[functionName] argvalues = [] nexttok() consume('lparen') while True: if matchtok('rparen'): break argvalues.append(parseExpression()) if peek(0)[0] == 'comma': consume('comma') continue elif peek(0)[0] == 'rparen': consume('rparen') break else: errors.print_error(16, lineindex, [peek(0)], 'C') if len(argvalues) != len(func.args): errors.print_error( 55, lineindex, [functionName, len(func.args), len(argvalues)]) return func.call(argvalues)
def transport_if(block, cond, addblock=''): global toklines xact.cond = 'canmove' if block not in marks.keys(): errors.print_error(29, xact.curblk+1, [block]) if marks[block].block == -1: errors.print_error(30, xact.curblk+1, [block]) if cond: xact.curblk = marks[block].block-1 else: if addblock == '': xact.curblk += 1 else: if addblock not in marks.keys(): errors.print_error(29, xact.curblk+1, [addblock]) if marks[block].block == -1: errors.print_error(30, xact.curblk+1, [addblock]) xact.curblk = marks[addblock].block-1 toklines[xact.curblk][-1][2] += 1
def find(line): # find(facilities.curplaces > 0) ==> name of facility # find(chains.length < 10) ==> name of chain # find(chains.xacts.p2 == 5) ==> xact index parserline = copy.deepcopy(parser.tokline) oldpos = parser.pos if line[0][1] == 'facilities' or line[0][1] == 'queues' or \ line[0][1] == 'chains': attr = getattr(interpreter, line[0][1]) if line[0][1] == 'chains' and line[2][1] == 'xacts': buf = getattr(attr, line[2][1]) for xa in buf: xa_attr = None try: xa_attr = getattr(xa, line[4][1]) except AttributeError: errors.print_error(50, parser.lineindex, [line[4][1]]) nl = [['number', xa_attr]] + line[5:] parser.tokline = nl parser.pos = 0 if parser.parseExpression(): parser.tokline = copy.deepcopy(parserline) parser.pos = oldpos return xa.index return -1 for item in attr.keys(): val = 0 try: val = getattr(attr, line[2][1]) except AttributeError: errors.print_error(50, parser.lineindex, [line[2][1]]) nl = [['number', val]] + line[3:] parser.tokline = nl parser.pos = 0 if parser.parseExpression(): parser.tokline = copy.deepcopy(parserline) parser.pos = oldpos return '~'+item return '' else: errors.print_error(49, parser.lineindex, [line[0][1]+'.'+line[2][1]])
def cost_center(cost_center): if len(str(cost_center)) != 0: if cost_center not in ["0", "1", "2", "3", "4", "5", "6", 0, 1, 2, 3, 4, 5, 6] or len(str(cost_center)) == 0: return errors.print_error("val_cc_syntax") return True return errors.print_error("val_cc_missing")
def vendor(vendor): if len(vendor) != 0: if any(i in vendor for i in ["|", ">", ":", "<", "\\", "?", "*", '"', "'", "/", ","]): return errors.print_error("val_sup_syntax") return True return errors.print_error("val_sup_missing")
def inv_nr(inv_nr): if len(str(inv_nr)) != 0: if any(i in inv_nr for i in ["|", ">", ":", "<", "\\", "?", "*", '"', "'", "/", ","]): return errors.print_error("val_nr_syntax") return True return errors.print_error("val_nr_missing")
def notes(notes): if "'" in notes: return errors.print_error("Val_Dat_Notes_1") return True
step = 0.05 function = fun x = np.arange(start, end, step) y = list(map(function, x)) x_len = len(x) #points = get_regular_interpolation_nodes(N, function, start, end) points = get_czebyshev_interpolation_nodes(N, function, start, end) x_nodes, y_nodes = zip(*points) polynomial = polynomial_approximate(points, N) trigonometric = trigonometric_approximate(points, N) polynomial_y = list(map(polynomial, x)) trigonometric_y = list(map(trigonometric, x)) print('label,N,mean_sqaure_error,max_error') print_error(N, x_len, y, polynomial_y, 'polynomial') print_error(N, x_len, y, trigonometric_y, 'trigonometric') plt.plot(x, y, "b--", linewidth=1, label='function') plt.plot(x, polynomial_y, "r--", linewidth=1, label='polynomial') plt.plot(x, trigonometric_y, "g--", linewidth=1, label='trigonometric') plt.plot(x_nodes, y_nodes, 'yo') plt.legend(loc='upper left', prop={'size': 8}) plt.grid(True) plt.show()