def execute(self, input_registers): """ Execute code for each input """ if len(self.instructions_without_introns_) == 0: self.instructions_without_introns_ = Program.remove_introns(self.instructions) self.inputs_list_ = self._inputs_list() instructions = self.instructions_without_introns_ general_registers = [0] * Config.RESTRICTIONS['genotype_options']['total_registers'] if_instruction = None skip_next = False for instruction in instructions: if if_instruction and not Operation.execute_if(if_instruction.op, if_instruction.target, if_instruction.source): if_instruction = None if instruction.op in Config.RESTRICTIONS['genotype_options']['if-instructions']: skip_next = True elif skip_next: if instruction.op in Config.RESTRICTIONS['genotype_options']['if-instructions']: skip_next = True else: skip_next = False elif instruction.op in Config.RESTRICTIONS['genotype_options']['if-instructions']: if_instruction = instruction elif instruction.op in Config.RESTRICTIONS['genotype_options']['one-operand-instructions']: general_registers[instruction.target] = Operation.execute(instruction.op, general_registers[instruction.target]) else: if instruction.mode == 'read-register': source = general_registers[instruction.source] else: source = input_registers[instruction.source] general_registers[instruction.target] = Operation.execute(instruction.op, general_registers[instruction.target], source) return general_registers[0] # get bid output
def run_cycle(self): rip = self.context.registers['rip'] op_code = struct.unpack('<H', bytes(self.context.memory[rip:rip + 2]))[0] rip += 2 try: op_info = self.op_table[op_code] except: print('Unknown opcode') print(self.context.registers) print(self.context.memory[self.context.registers['rip']:self. context.registers['rip'] + 10]) print(self.context.memory) exit() op_args = [] for i in range(op_info[1]): # for each argument arg_code = op_info[2 + i] value = 0 if 10 <= arg_code <= 11: value = self.context.memory[ rip:rip + 4] # struct.unpack('<I', bytes(self.context.memory[rip:rip + 4])) rip += 4 op_args.append(MemOperand(self.context, arg_code, value)) operation = Operation(self.context, op_info[0]) self.context.registers['rip'] = rip operation.exec(op_args)
def setup(test=False): from databases.Database import Database from logger.Logger import Logger from realms import Realm from config import REALMS, DATABASE from operations import Operation from Requests import Request from config import CREDENTIALS logger = Logger(os.getcwd(), "d") logger.log(msg="\n" * 3, timestamped=False, level_display=False) logger.log(msg="*" * 150, timestamped=False, level_display=False) logger.log(msg="*" * 65 + "Started new session!" + "*" * 65, timestamped=False, level_display=False) logger.log(msg="*" * 150, timestamped=False, level_display=False) db = Database(DATABASE, logger, test) request = Request(CREDENTIALS, db, logger) operation = Operation(db, logger) for realm_id in REALMS: realm = Realm(realm_id, db, logger, request) operation.realms.append(realm) operation.setLiveData(request) return operation, request
def execute(self, input_registers, force_reset=False): """ Execute code for each input """ if len(self.instructions_without_introns_) == 0: self.instructions_without_introns_ = Program.remove_introns( self.instructions) self.inputs_list_ = self._inputs_list() instructions = self.instructions_without_introns_ if Config.USER['task'] == 'classification' or force_reset: self.reset_registers() if_instruction = None skip_next = False for instruction in instructions: if if_instruction and not Operation.execute_if( if_instruction.op, if_instruction.target, if_instruction.source): if_instruction = None if instruction.op in Config.RESTRICTIONS['genotype_options'][ 'if-instructions']: skip_next = True elif skip_next: if instruction.op in Config.RESTRICTIONS['genotype_options'][ 'if-instructions']: skip_next = True else: skip_next = False elif instruction.op in Config.RESTRICTIONS['genotype_options'][ 'if-instructions']: if_instruction = instruction elif instruction.op in Config.RESTRICTIONS['genotype_options'][ 'one-operand-instructions']: self.general_registers_[ instruction.target] = Operation.execute( instruction.op, self.general_registers_[instruction.target]) else: if instruction.mode == 'read-register': source = self.general_registers_[instruction.source] else: source = input_registers[instruction.source] self.general_registers_[ instruction.target] = Operation.execute( instruction.op, self.general_registers_[instruction.target], source) return self.general_registers_[0] # get bid output
def from_intcode(cls, intcode_slice: Intcode) -> "Modes": opcode_str: str = intcode_slice[0] # opcode (operation) is in the two last element of string opcode: int = int(opcode_str[-2:]) additional_values: int = 0 if opcode in [1, 2, 7, 8]: additional_values = 3 elif opcode in [5, 6]: additional_values = 2 elif opcode in [3, 4, 9]: additional_values = 1 elif opcode == 99: pass else: raise ValueError( f"Opcode ({opcode}) can only be 1, 2, 3, 4, 5, 6, 7, 8, 9 or 99." ) values_parameters: List[int] = list(map(int, opcode_str[:-2])) values_parameters.reverse() # add zeros omitted due to being a leading zero values_parameters += (additional_values - len(values_parameters)) * [0] return cls(Operation(opcode), tuple(map(Parameters, values_parameters)))
def cast_operations_to_array_of_opklass(operations): if all([not isinstance(a, Operation) for a in operations]): result = Array([Operation(a) for a in operations]) else: result = Array(operations) return result
def pressDownAdjustButton(self): for point in self.spreadPoints: self.y_values[point] -= self.adjustAmt # Add operation to operations list for more generation if self.adjustAmt > 0: op = Operation("inc/dec", -1 * self.adjustAmt, self.spreadPoints) self.operations.append(op) self.plotPoints()
def execute(self, input_registers, force_reset = False): """ Execute code for each input """ if len(self.instructions_without_introns_) == 0: self.instructions_without_introns_ = Program.remove_introns(self.instructions) self.inputs_list_ = self._inputs_list() instructions = self.instructions_without_introns_ if Config.USER['task'] == 'classification' or force_reset: self.reset_registers() if_instruction = None skip_next = False for instruction in instructions: if if_instruction and not Operation.execute_if(if_instruction.op, if_instruction.target, if_instruction.source): if_instruction = None if instruction.op in Config.RESTRICTIONS['genotype_options']['if-instructions']: skip_next = True elif skip_next: if instruction.op in Config.RESTRICTIONS['genotype_options']['if-instructions']: skip_next = True else: skip_next = False elif instruction.op in Config.RESTRICTIONS['genotype_options']['if-instructions']: if_instruction = instruction elif instruction.op in Config.RESTRICTIONS['genotype_options']['one-operand-instructions']: self.general_registers_[instruction.target] = Operation.execute(instruction.op, self.general_registers_[instruction.target]) else: if instruction.mode == 'read-register': source = self.general_registers_[instruction.source] else: source = input_registers[instruction.source] self.general_registers_[instruction.target] = Operation.execute(instruction.op, self.general_registers_[instruction.target], source) return self.general_registers_[0] # get bid output
def init(): from logger.Logger import Logger from databases.Database import Database from operations import Operation from config import DATABASE as db_data from Requests import Request from config import CREDENTIALS as data logger = Logger(os.getcwd()) db = Database(db_data, logger, test=True) request = Request(data, db, logger) operation = Operation(db, logger) return data, db, logger, request, operation
def bulk_State( startId ): api_bulk_state = '/dataservice/data/device/state/' + data_type_parameter[data_type_ID-1]+ '?startId='+ str(startId) +'&count=' + str(count) url_bulk_state = url(vmanage_host,vmanage_port,api_bulk_state) bulk_state = Operation.get_method(url_bulk_state,header) if data_type_ID == 1: for state in bulk_state['data']: print (f'''system-ip : {state['system-ip']} site-id : {state['site-id']} color : {state['local-color']} src-ip : {state['src-ip']} dst-ip : {state['dst-ip']} src-port : {state['src-port']} dst-port : {state['dst-port']} state : {state['state']} ''') print(bulk_state['pageInfo']) if bulk_state['pageInfo']['moreEntries'] == True: bulk_State(bulk_state['pageInfo']['endId'])
def init(): from mounts import Mount from operations import Operation from logger.Logger import Logger from databases.Database import Database from Requests import Request from config import DATABASE, CREDENTIALS logger = Logger(os.getcwd()) db = Database(DATABASE, logger, test=True) operation = Operation(db, logger) request = Request(CREDENTIALS, db, logger) new_mount = Mount(operation, request, _id=69) rebuild_mount = Mount(_id=85, **{"name":"Swift Mistsaber", "source":"Vendor", "faction":"Alliance"}) return new_mount, rebuild_mount, operation, request
def adding(method, a, b): obj_1 = Operation(a, b) if method == 'add': try: if a < 10 and b < 10: resp = obj_1.add() return str(resp) else: raise AddError("values are large") except AddError as v: return str(v) if method == 'sub': try: if a > b: resp = obj_1.sub() return str(resp) else: raise SubError("value of b is always lesser than a ") except SubError as v: return str(v) if method == 'mul': try: if a < 10 and b < 10: resp = obj_1.mul() return str(resp) else: raise MulError("values are large") except MulError as v: return str(v) if method == 'div': try: if b != 0: resp = obj_1.div() return str(resp) else: raise DivError("the value of b is non zero value") except DivError as v: return str(v)
def main(): routeManager = rm.RouteManager() citiesList = fl.tspValueCatcher() for i in citiesList: city = ct.Cities(i["x"], i["y"]) routeManager.addCity(city) pop = pp.Population(routeManager, 100, True) initialDistance = str(round(pop.getFittest().getDistance(), 2)) print("Initial distance: " + str(initialDistance)) ga = op.Operations(routeManager) pop = ga.createPopulation(pop) for i in range(0, 100): pop = ga.createPopulation(pop) finalDistance = str(round(pop.getFittest().getDistance(), 2)) print("Final distance: " + finalDistance)
def main(): garageObj = Garage() file = input("enter the name of the file which contains garage operation.") try: filehandle = open(file) for line in filehandle: line = line.strip() data = line.split() if len(data) == 3: n = Operation(data[0],data[1],data[2]) garageObj.insertHeap(n) print(n) else: if data[0]=='Cathy': job=garageObj.popCathyHeap() print("Cathy starting job ",job.name) elif data[0]=='Howard': job=garageObj.popHowardHeap() print("Howard starting job ",job.name) except FileNotFoundError: print("please enter valid file name.") sys.exit(0)
def new_batch_operation(self): dialog = OperationDialog(parent=self) ok = dialog.exec_() if not ok: return source = dialog.source # Determine the correct source if source == 'All Vendor products': query = self.dbsession.query(Listing).filter(Listing.vendor_id != 0) else: vendor_id = self.dbsession.query(Vendor.id).filter_by(name=source).scalar() if vendor_id: query = self.dbsession.query(Listing).filter_by(vendor_id=vendor_id) else: list_id = self.dbsession.query(List.id).filter_by(name=source).scalar() if list_id is None: QMessageBox.critical(self, 'Error', 'Source \'%s\' could not be found.' % source) return query = self.dbsession.query(Listing).join(ListMembership).filter_by(list_id=list_id) if dialog.no_linked_products: query = query.filter(and_(~Listing.amz_links.any(), ~Listing.vnd_links.any())) if dialog.filter_price: query = query.filter(Listing.price.between(dialog.min_price, dialog.max_price)) # Add to the operation table for row in query: op = Operation.GenericOperation(operation=dialog.operation, params=dialog.params, listing_id=row.id) self.dbsession.add(op) self.dbsession.commit() self.update_counts()
def adding(method,a,b): obj=Operation(a,b) if method=="add": try: if a<10 and b<10 : res=obj.add() return str(res) else: raise adderror("more than 10 add will not performed") except adderror as e: return str(e) if method=="sub": try: if a>b: res1=obj.sub() return str(res1) else: raise suberror("b is greater") except suberror as f: return str(f) if method=="mul": try: if a<10 and b<10 : res2=obj.mul() return str(res2) else: raise mulerror("more than 10 mutiplication is not possible") except mulerror as g: return str(g) if method=="div": try: if b!=0: res2=obj.div() return str(res2) else: raise diverror("provide b as non zero value") except diverror as h: return str(h)
def appointmentHandler(): if g.user: opList = dbGetAllOperations() if not opList: app.logger.info("Could not retrive operations from database") return render_template('/') opDiscountList = dbGetAllDiscountOperations(g.user) operations = [] for oper in opList: operations.append(Operation(oper[0], oper[1], oper[2], oper[3])) operationsDiscount = [] if opDiscountList != None: for oper in opDiscountList: operationsDiscount.append( DiscountOperation(oper[0], oper[1], oper[2], oper[3], oper[4])) if request.method == "POST": app.logger.info(request.method) req = request.form # Logout if 'logoutBtn' in req: app.logger.info("Logout user: "******"New appointment request for Bob.") date = req["appointment-bob"] medic_email = "*****@*****.**" elif 'appointment-jean' in req: app.logger.info("New appointment request for Jean.") date = req["appointment-jean"] medic_email = "*****@*****.**" elif 'appointment-rick' in req: app.logger.info("New appointment request for Rick.") date = req["appointment-rick"] medic_email = "*****@*****.**" opId = req["operationSelector"] if opId == 0: app.logger.error("No operation selected!") # user must be logged in to get here, so we can retrive his email from session`s g.user client_id = dbGetClientId(g.user) if client_id == 0: app.logger.error("Failed to get client id!") return redirect('/login') medic_id = dbGetMedicId(medic_email) if medic_id == 0: app.logger.error("Failed to get medic id!") return redirect('/calendar') app.logger.info("New appointment for client: " + g.user + "to doctor " + medic_email + "on " + date) crParseDate(date) dbNewAppointment(medic_id, client_id, date, opId) else: app.logger.info(request.method) return render_template('calendar.html', operationList=operations, operationDiscountList=operationsDiscount) else: return redirect('/')
self.assertEqual({}, operation.insert_data) self.assertEqual({}, operation.update_data) def test_setTimePosted(self): from operations import setTimePosted #testing test case test_time = setTimePosted(test=True) self.assertEqual(12, test_time.hour) self.assertEqual(30, test_time.minute) self.assertEqual(30, test_time.second) self.assertEqual(500000, test_time.microsecond) # testing not testcase now = dt.now() time = setTimePosted() self.assertEqual(now.hour, time.hour) @unittest.skip def test_setTimeSold(self): pass if __name__ == "__main__": logger = Logger(os.getcwd()) db = Database(DATABASE, logger, test=True) operation = Operation(db, logger) request = Request(CREDENTIALS, db, logger) realm = Realm(1096, db, logger, request) unittest.main()
def pressSmoothButton(self): self.y_values = scipy.ndimage.gaussian_filter1d( self.y_values, self.sigma_smooth) op = Operation("smooth", self.sigma_smooth, []) self.operations.append(op) self.plotPoints()
auction_pet.last_updated = auction_pet.time_posted auction_mount.last_updated = auction_mount.time_posted sold_auction_item = SoldAuction(operation, False, *(auction_item, 1, 25, 0, 1, buyout, "LONG", 45, buyout, auction_item.time_posted, False)) sold_auction_pet = SoldAuction(operation, False, *(auction_pet, 2, 82800, 39, 2, buyout*2, "MEDIUM", 45, buyout*2, auction_pet.time_posted, False)) sold_auction_mount = SoldAuction(operation, False, *(auction_mount, 3, 34060, 0, 3, buyout*3, "SHORT", 45, buyout*3, auction_mount.time_posted, False)) item_item = new_items[0] item_pet = new_items[1] item_mount = new_items[2] item_item.updateMean(sold_auction_item, operation) item_pet.updateMean(sold_auction_pet, operation) item_mount.updateMean(sold_auction_mount, operation) self.assertEqual(50, item_item.mean_price) self.assertEqual(50, item_pet.mean_price) self.assertEqual(50, item_mount.mean_price) if __name__ == "__main__": logger = Logger(os.getcwd()) db = Database(DATABASE, logger, test=True) operation = Operation(db, logger) operation.live_data = {"auctions":{}, "items":{}, "classes":{}, "subclasses":{}, "pets":{}, "mounts":{}} request = Request(CREDENTIALS, db, logger) realm = Realm(1096, db, logger, request) new_items, rebuild_items = ItemTest.init() unittest.main()