def _instr_cmp(self, instr, cf): rhs = cf.stack_pop() lhs = cf.stack_pop() it = Target.get_instr(instr) if it == Target.CON_INSTR_EQ: r = lhs.eq(self, rhs) elif it == Target.CON_INSTR_LE: r = lhs.le(self, rhs) elif it == Target.CON_INSTR_NEQ: r = lhs.neq(self, rhs) elif it == Target.CON_INSTR_LE_EQ: r = lhs.le_eq(self, rhs) elif it == Target.CON_INSTR_GR_EQ: r = lhs.gr_eq(self, rhs) elif it == Target.CON_INSTR_GT: r = lhs.gt(self, rhs) else: raise Exception("XXX") if r: cf.stack_push(rhs) cf.bc_off += Target.INTSIZE else: self._fail_now(cf)
def __init__(self, window): self.window = window self.frogs = [] self.popsize = 300 self.dna = DNA() self.target = Target(self.window) self.lilly_pads = [] self.matingpool = [] self.count = 0 for lillypad in range(0, 30): self.lilly_pads.append( LillyPad(self.window, (random.randrange( 0, window.width), random.randrange(0, window.height)))) self.lilly_pads.append( LillyPad(self.window, (self.window.width / 2, self.window.height - 50))) self.lilly_pads.append( LillyPad(self.window, (self.target.cord[0], self.target.cord[1]))) for frog in xrange(self.popsize): self.frogs.append( Frogs(self.window, self.dna.get_random_dna(), self.lilly_pads, self.target)) frog_nodes = (lambda x, y: [(x - 10, y - 10), (x + 10, y - 10), (x + 10, y + 10), (x - 10, y + 10)]) self.frogs[frog].add_nodes( frog_nodes(self.window.width / 2, self.window.height - 50))
def _instr_assign_slot(self, instr, cf): o = cf.stack_pop() v = cf.stack_get(cf.stackpe - 1) nm_start, nm_size = Target.unpack_assign_slot(instr) nm = Target.extract_str(cf.pc.mod.bc, nm_start + cf.bc_off, nm_size) o.set_slot(self, nm, v) cf.bc_off += Target.align(nm_start + nm_size)
def start(): aTarget = Target() #initializes both objects aPursuer = Pursuer() interactions = interactionsChecker( ) #calling these two functions to check user is stupid aTarget.xIntProb = probabilityChecker() interactionsCount = STARTING_COUNTER numTotMatches = STARTING_COUNTER while (interactionsCount < interactions): #runs while interactions are all complete targXBhvr = aTarget.behaviorGeneration( ) #generates Target behavior, returns it is variable to pass xCount, yCount = aTarget.tallyTarget( ) #tallies results each loop, returns it as variable to pass aPursuer.behaviorGeneration() #generates Pursuer behavior aPursuer.tallyPursuer() #tally results each loop aPursuer.tallySuccessful( targXBhvr) #checks each interaction, tallies successful ones aPursuer.probabilityShift( ) #calls shifting probability function from Pursuer to adjust x based on successful interactions interactionsCount = interactionsCount + 1 #update loop control aPursuer.displayEnd(interactions, xCount, yCount) #finalresults after loop done
def _instr_exbi(self, instr, cf): class_ = Builtins.type_check_class(self, cf.stack_pop()) bind_o = cf.stack_pop() nm_start, nm_size = Target.unpack_exbi(instr) nm = Target.extract_str(cf.pc.mod.bc, nm_start + cf.bc_off, nm_size) pa = Builtins.Con_Partial_Application(self, class_.get_field(self, nm), [bind_o]) cf.stack_push(pa) cf.bc_off += Target.align(nm_start + nm_size)
def _instr_module_lookup(self, instr, cf): o = cf.stack_pop() nm_start, nm_size = Target.unpack_mod_lookup(instr) nm = Target.extract_str(cf.pc.mod.bc, cf.bc_off + nm_start, nm_size) if isinstance(o, Builtins.Con_Module): v = o.get_defn(self, nm) else: v = self.get_slot_apply(o, "get_defn", [Builtins.Con_String(self, nm)]) cf.stack_push(v) cf.bc_off += Target.align(nm_start + nm_size)
def _instr_unpack_assign(self, instr, cf): o = cf.stack_get(cf.stackpe - 1) o = Builtins.type_check_list(self, o) ne = len(o.l) if ne != Target.unpack_unpack_assign(instr): self.raise_helper("Unpack_Exception", \ [Builtins.Con_Int(self, Target.unpack_unpack_assign(instr)), \ Builtins.Con_Int(self, ne)]) for i in range(ne - 1, -1, -1): cf.stack_push(o.l[i]) cf.bc_off += Target.INTSIZE
def probabilityChecker(): #this function checks user input by recursion aTarget = Target() try: aTarget.xIntProb = int(input("Enter the probability of x (0 - 100): ")) if aTarget.xIntProb < LOWER_BOUND_RANDOM or aTarget.xIntProb > UPPER_BOUND_RANDOM: print("Number must be between 0 - 100, try again!") aTarget.xIntProb = probabilityChecker() except: print("Non numerical input - Try again!") aTarget.xIntProb = probabilityChecker() return (aTarget.xIntProb)
def _instr_is_assigned(self, instr, cf): closure_off, var_num = Target.unpack_var_lookup(instr) closure = cf.closure while closure_off > 0: closure = closure.parent closure_off -= 1 v = closure.vars[var_num] if closure.vars[var_num] is not None: pc = cf.pc assert isinstance(pc, BC_PC) mod_bc = pc.mod.bc instr2 = Target.read_word(mod_bc, cf.bc_off + Target.INTSIZE) cf.bc_off += Target.unpack_is_assigned(instr2) else: cf.bc_off += Target.INTSIZE + Target.INTSIZE
def KeyWord(journal): Keyword = tk.Tk() Keyword.title("Getting the Keyword") keys = Target.CollectTweets(journal) max = Target.max(keys[1]) text = keys[0][max] parsed = text.split(' ') for i in range(len(parsed)): if (('/' not in parsed[i]) and (len(parsed[i]) > 2)): button = tk.Button(Keyword, text=parsed[i], bg="SkyBlue2", width=10, command=lambda x=parsed[i]: Collect(x)) button.pack()
def var_init(self, amount_of_sensors, amount_of_targets, range_of_sensor, capacity, map_high, map_width): self.amount_of_sensors = amount_of_sensors self.amount_of_targets = amount_of_targets self.range_of_sensor = range_of_sensor self.capacity = capacity self.map_high = map_high self.map_width = map_width self.sensor_list = [] self.target_list = [] for x in range(0, amount_of_sensors): self.sensor_list.append( Sensor.Sensor( capacity, range_of_sensor, Point.Point( randrange(range_of_sensor, map_width - range_of_sensor), randrange(range_of_sensor, map_high - range_of_sensor)))) for x in range(0, amount_of_targets): self.target_list.append( Target.Target( Point.Point( randrange(map_width - 2 * 0.1 * map_width) + 0.1 * map_width, randrange(map_high - 2 * 0.1 * map_high) + 0.1 * map_width)))
def readTargetFile(targetFilePath, apidMap): targets = [] f = open(targetFilePath, 'r+') for line in f.readlines(): line = line.replace('\r', '').replace('\n', '').replace(':', ',') if len(line) == 0: continue columns = line.split(' ') # require at least 3 dimensions (APs or beacons) if len(columns) < 4: continue # x, y values = columns[0].split(',') x = float(values[0]) y = float(values[1]) pos = Position(x, y) # ap tInfoMap = {} for column in columns[1:]: if len(column) == 0: continue values = column.split(',') bssid = values[0].upper() apid = apidMap.getApid(bssid) level = float(values[1]) tInfoMap[apid] = TargetInfo(level, True) targets.append(Target(len(targets), pos, tInfoMap)) f.close() return targets
def letsgobaby(anchor, targetfromflask): host = 'localhost' port = 1883 con = MQTT_READ.MQTT(broker_address=host, port=port, clientname='Dzungar1') anchorlist = [] targetlist = targetfromflask for item in anchor: _anchor = Target.Beacon(item['x'], item['y']) anchorlist.append(_anchor) for target in targetlist: target.distanceTab = [] for i, anchor in enumerate(anchorlist): topic = "test/" + str(target.targetID) + "/" + str(i + 1) print(f'Topic we read from for {target}', topic) v = con.read(topic) target.distanceTab.append(float(v.msg)) l = idxfor3smallest(target.distanceTab) print(f'Indexes for trilateration of {target}', l) print(f'Target{target} distance tab', target.distanceTab) target.Update(l) print("Target XY ", target.x, target.y) t = 'test/front/' + str(target.targetID) print('Topic published to : ', t) con.publish(t, str(math.floor(target.x)) + " " + str(math.floor(target.y)) + " " + str(target.targetID), retain=False) print("Python calculated position and send it")
def recursive_input_taker(self): if self.p == 0: print( "Entering probabilities for the Pursure type of Tim. The sum of the two probabilities must equal 100%" ) print("Enter the X probabilty for pursuer without the % sign") x = eval(input()) print("Enter the Y probability for pursuer without the % sign") y = eval(input()) if ((x + y) != 100): print("Probabilities must sum to 100%. Try again\n") self.recursive_input_taker() else: self.p = Pursuer.pursuer(x, y) if self.t == 0: print( "Entering probabilities for the Target type of Tim. The sum of hte two probabilities must equal 100%" ) print("Enter the X probabilty for target without the % sign") x = eval(input()) print("Enter the Y probability for target without the % sign") y = eval(input()) if ((x + y) != 100): print("Probabilities must equal to 100. Try again") self.recursive_input_taker() else: self.t = Target.target(x, y)
def formatTarget(rawTarget, apidMap): tInfoMap = {} for bssid in rawTarget: if int(bssid, 16) not in apidMap.bssid2Apid: continue tInfoMap[apidMap.getApid(bssid)] = TargetInfo(rawTarget[bssid], True) return Target(0, Position(0, 0), tInfoMap)
def execute_agama(self, data_agama): #cek operator operator = data_agama[2] if operator == 'INS': try: #set id agama, anama agama id_agama = data_agama[0] nama_agama = data_agama[1] data_agama_2 = (id_agama, nama_agama) #calling insert method inserting_data = myTarget.Target() result = inserting_data.insert_agama(data_agama_2) #result = 'Calling insert method successed' except: result = 'Calling Error' elif operator == 'DEL': try: result = 'Callinf insert method' except: result = 'Calling error' else: try: result = 'Calling update method' except: result = 'Calling error' return result
def initWidget(self, master): self.widget = Tkinter.PanedWindow(master, orient=Tkinter.HORIZONTAL) self.content = Tkinter.StringVar() self.content.set(self.__class__.__name__) self.content.trace("w", self.isChanged) name_wid = getSpellMenu(master, self.content) #name_wid.pack() self.widget.add(name_wid) self.value = Tkinter.StringVar() self.value.set(str(self.level)) level_wid = Tkinter.Spinbox(self.widget, from_=1, to=1000, textvariable=self.value, command=self.modifyLevel) level_wid.icursor(5) self.widget.add(level_wid) if self.__class__.has_target: #Target selector if not (hasattr(self, "target")): self.target = Target.UneCibleAuChoix() self.add_target = Tkinter.StringVar(self.widget) self.add_target.set( self.target.__class__.__name__) # default value self.addTarget_wid = getTargetMenu(self.widget, self.add_target) self.add_target.trace('w', self.modifyTarget) self.widget.add(self.addTarget_wid) #ENd of target selector return self.widget
def calibrate(target, cf): if not cf.needCalibration: return target tInfoMap = {} for apid in target.tInfoMap: level = target.tInfoMap[apid].level tInfoMap[apid] = TargetInfo(level + cf.offset, True) return Target(target.tid, Position(target.pos.x, target.pos.y), tInfoMap)
def _instr_var_assign(self, instr, cf): closure_off, var_num = Target.unpack_var_assign(instr) closure = cf.closure while closure_off > 0: closure = closure.parent closure_off -= 1 closure.vars[var_num] = cf.stack_get(cf.stackpe - 1) cf.bc_off += Target.INTSIZE
def radar(width, height, color): #radar display config screen_width = width screen_height = height x = pygame.init() pygame.font.init() defaultFont = pygame.font.get_default_font() fontRenderer = pygame.font.Font(defaultFont, 20) #screen_width = 800 #screen_height =500 radarDisplay = pygame.display.set_mode((screen_width, screen_height)) pygame.display.set_caption('Radar Screen') #GPIO setup RangerRead = GroveUltrasonicRanger(5) # targets list targets = {} a = 0 #radar read and write to dict while True: for angle in range(0, 180): distance = RangerRead.get_distance() distance = round(distance, 2) if distance != -1 and distance <= 50: targets[angle] = Target(angle, distance) draw(radarDisplay, targets, angle, distance, fontRenderer, screen_width, screen_height, color) time.sleep(0.0001) #draw_bck(radarDisplay, fontRenderer, screen_width, screen_height) targets = {} for angle in range(180, 0, -1): distance = RangerRead.get_distance() distance = round(distance, 2) if distance != -1 and distance <= 50: targets[angle] = Target(angle, distance) draw(radarDisplay, targets, angle, distance, fontRenderer, screen_width, screen_height, color) time.sleep(0.0001) #draw_bck(radarDisplay, fontRenderer, screen_width, screen_height) targets = {}
def __init__(self, key): # e.g. np.array( [1992, 6, 23] ) self.key = key self.key_str = DateType.key_to_str(key) self.transactions = Transaction.TransactionContainer() self.targets = Target.TargetContainer() # Map<date_key, DateType>, sub datetypes e.g. this==Month --> children are Days self.children = {}
def __init__(self, spell=None, target=Target.UneCibleAuChoix()): from Bonus import PasDeBonus if not spell: spell = PasDeBonus() self.target = target self.spell = spell self.parent = None self.positive = True
def main(): rad = 2 time_step = 0.05 win_x = 200.0 win_y = 100.0 # create window m_win = GraphWin("My Application", 1000, 500) # set up coordinate system m_win.setCoords(0, 0, win_x, win_y) # fill in background m_win.setBackground("light blue") wall_a = Wall(Point(80, 20), Point(85, 80), m_win) wall_b = Wall(Point(150, 0), Point(152, 20), m_win) wall_c = Wall(Point(150, 80), Point(152, 100), m_win) walls = [wall_a, wall_b, wall_c] m_sim = Simulation(time_step, win_x, win_y, walls, m_win) aim_tool = Aimer(m_win) m_sim.set_vel(aim_tool.aim_loop()) # goal setup llx = 80 lly = 0 urx = 85 ury = 4 m_target = Target(Point(llx, lly), Point(urx, ury), m_win, True) # run loop for i in range(1000): # plot one pixel m_sim.loop() if m_target.hit_target(m_sim.ball, m_win): message = Text(Point(50, 50), "YOU WON!") message.setSize(30) message.setStyle("bold") message.setTextColor("green") message.draw(m_win) print("YOU WON! CONGRATULATIONS!") break time.sleep(time_step / 10) # wait for click m_win.getMouse()
def __init__(self): Skill.__init__(self) self.name = 'attack' self.target = Target.CaC() #the Target object who handle targetting self.power = 1 #the damage/heal/power of the skill self.type = 'enemy' # use/enemy/team/self self.cost = 0
def __init__(self, monster=None, target=Target.UneCibleAuChoix()): if not monster: from Card import Card monster = Card('Mouton', 1, 1) self.monster = monster self.level = 1 self.monster.parent = self self.parent = None self.target = target
def string2Target(apidMap, fingerprint): tInfoMap = {} for bssidRssi in fingerprint.split('__'): pair = bssidRssi.split('_') bssid = pair[0].upper() rssi = float(pair[1]) apid = apidMap.getApid(bssid) tInfoMap[apid] = TargetInfo(rssi, True) return Target(0, Position(0, 0), tInfoMap)
def __init__(self, target_lat, target_lon, target_char): self.target = Target.Target(target_lon, target_lat, target_char) self.conn = sqlite3.connect("training_data.db") self.c = self.conn.cursor() self.c.execute('''CREATE TABLE IF NOT EXISTS data (id INTEGER PRIMARY KEY AUTOINCREMENT, DATETIME, uas_height DOUBLE, uas_long DOUBLE, uas_lat DOUBLE, uas_heading DOUBLE, uas_pitch DOUBLE, uas_roll DOUBLE, target_long DOUBLE, target_lat DOUBLE, target_letter CHAR, img_name TEXT)''') self.conn.commit()
def new_game(self): """Само тело игры""" print("HERE") for i in range(len(self.t)): self.t[i] = Tg.Target(self.canv) self.t[i].new_target(400 + 110 * i) self.t[i].live = 1 Tg.lives += 1 return
def __init__(self, level_num, difficulty, moving_target): self.curr_time = int(round(time.time() * 1000)) self.a_curr_time = int(round(time.time() * 1000)) self.difficulty = difficulty self.moves = moving_target self.level_num = level_num self.rad = 1 self.time_step = 0.05 self.win_x = 200.0 self.win_y = 100.0 self.center = Point(self.win_x / 2, self.win_y / 2) # create window self.m_win = GraphWin(("Level" + str(self.level_num)), 1000, 500, autoflush=False) # set up coordinate system self.m_win.setCoords(0, 0, self.win_x, self.win_y) self.prime_msg() # fill in background self.m_win.setBackground("light blue") # make walls self.walls = self.get_walls() # start simulation self.sim = Simulation(self.time_step, self.win_x, self.win_y, self.walls, 0.8, "orange", self.m_win) # static target for now self.target = Target(Point(175, 0), Point(180, 5), False, self.m_win) # if no moving target if (self.moves == False): # create aiming tool self.aim_tool = Aimer(self.m_win) self.sim.set_vel(self.aim_tool.aim_loop()) self.target.set_moves(False) else: # dont use aimer vel = [random.randint(15, 30), random.randint(15, 30)] self.sim.set_vel(vel) # make target move self.target.set_moves(True)
def main(): rad = 2 time_step = 0.05 win_x = 200.0 win_y = 100.0 xv = 25.0 yv = 20.0 m_sim = Simulation(time_step, win_x, win_y, xv, yv) # create window m_win = GraphWin("My Application", 1000, 500) # set up coordinate system m_win.setCoords(0, 0, win_x, win_y) # fill in background m_win.setBackground("light blue") # goal setup llx = 80 lly = 0 urx = 85 ury = 4 m_target = Target(Point(llx, lly), Point(urx, ury), m_win) c = Circle(Point(m_sim.ball.getX(), m_sim.ball.getY()), rad) c.setFill("orange") c.draw(m_win) # run loop for i in range(1000): # plot one pixel c.undraw() c = Circle(Point(m_sim.ball.getX(), m_sim.ball.getY()), rad) c.setFill("orange") c.draw(m_win) m_sim.loop() if m_target.hit_target(m_sim.ball, m_win): message = Text(Point(50, 50), "YOU WON!") message.setSize(30) message.setStyle("bold") message.setTextColor("green") message.draw(m_win) print("YOU WON! CONGRATULATIONS!") break time.sleep(.005) # wait for click m_win.getMouse()
def _instr_var_lookup(self, instr, cf): closure_off, var_num = Target.unpack_var_lookup(instr) closure = cf.closure while closure_off > 0: closure = closure.parent closure_off -= 1 v = closure.vars[var_num] if not v: self.raise_helper("Unassigned_Var_Exception") cf.stack_push(v) cf.bc_off += Target.INTSIZE
def _instr_calc(self, instr, cf): rhs = cf.stack_pop() lhs = cf.stack_pop() it = Target.get_instr(instr) if it == Target.CON_INSTR_ADD: r = lhs.add(self, rhs) else: assert it == Target.CON_INSTR_SUBTRACT r = lhs.subtract(self, rhs) cf.stack_push(r) cf.bc_off += Target.INTSIZE
def _instr_func_defn(self, instr, cf): is_bound, max_stack_size, has_loop = Target.unpack_func_defn(instr) np_o = cf.stack_pop() assert isinstance(np_o, Builtins.Con_Int) nv_o = cf.stack_pop() assert isinstance(nv_o, Builtins.Con_Int) name = cf.stack_pop() new_pc = BC_PC(cf.pc.mod, cf.bc_off + 2 * Target.INTSIZE) container = cf.func.get_slot(self, "container") f = Builtins.Con_Func(self, name, is_bound, new_pc, max_stack_size, np_o.v, nv_o.v, \ container, cf.closure, has_loop=has_loop) cf.stack_push(f) cf.bc_off += Target.INTSIZE
def set_target(self, crop_x, crop_y): self.target = Target(self) # need these for rendering the target self.target.x_coord = crop_x self.target.y_coord = crop_y # need this stuff for calculating latitude and longitude # * needs pitch, yaw, roll, pan, tilt from picture, etc. gps_x = float(self.picture.gps_x) gps_y = float(self.picture.gps_y) pan = self.picture.pan tilt = self.picture.tilt yaw = self.picture.yaw pitch = self.picture.pitch roll = self.picture.roll plane_orientation = self.picture.plane_orientation altitude = self.picture.altitude # * needs intrinsic camera matrix (should be in picture) # -> in picture constructor put a bloggie = Camera() part # -> right now all pictures should use the default image size of # fully zoomed out, and the corresponding intrinsic params. # If this were to change the image station would have to get # the zoom level and use it to calculate new intrinsic params M_int = self.picture.bloggie.get_intrinsic_matrix() # * needs to determine real coordinates from crop coordinates # -> for this define a seperate function. # -> e.g. (real_x, real_y) = self.calculate_real_coordinates( # crop_x + self.x_offset, # crop_y + self.y_offset) # # *** to get x_offset and y_offset # --> look at '_execute_generate_crop' and make it so xa and ya are stored (real_x, real_y) = self.calculate_real_coordinates(crop_x, crop_y) print "lat is: %f and long is %f" % (gps_x, gps_y,) print "crop_coords are x: %d, y: %d" % (crop_x, crop_y,) print "real coords are x: %d, y: %d" % (real_x, real_y,) # FINALLY: pass all this info to the calculate_gps function, which # will do matrix mults and math described in the blue notebook # self.target.calculate_gps(M_int, real_x, real_y, gps_x, gps_y, \ pan, tilt, yaw, pitch, roll, plane_orientation, altitude)
def _instr_apply(self, instr, cf): ff = cf.stack_get(cf.ffp) assert isinstance(ff, Stack_Failure_Frame) num_args = Target.unpack_apply(instr) fp = cf.stackpe - num_args - 1 func = cf.stack_get(fp) if isinstance(func, Builtins.Con_Partial_Application): new_cf = self._add_continuation_frame(func.f, num_args + 1) new_cf.stack_extend(func.args) i = 1 else: new_cf = self._add_continuation_frame(func, num_args) i = 0 for j in range(0, num_args): k = i + num_args - j - 1 assert k >= 0 jit.promote(k) new_cf.stack[k] = cf.stack_pop() new_cf.stackpe = i + num_args if ff.is_fail_up: gf = Stack_Generator_Frame(cf.gfp, cf.bc_off + Target.INTSIZE) cf.stack_set(fp, gf) cf.gfp = fp o = self.apply_pump() else: cf.stack_pop() # Function pointer o = self.execute_proc(new_cf) self._remove_continuation_frame() if o is self.get_builtin(Builtins.BUILTIN_FAIL_OBJ): o = None if o is None: self._fail_now(cf) return cf.stack_push(o) cf.bc_off += Target.INTSIZE
class TestTargetFunctions (unittest.TestCase): def setUp (self): """ Initializes a green and red target """ self.redTarget = Target () self.greenTarget = Target (isRed = False) def tearDown (self): """ Nothing to tear down """ pass def test_update (self): """ Tests that update increments the counter. Then tests when counter resets, image is changed """ # Test that update increments the counter self.redTarget.update() self.assertEqual(self.redTarget._counter, 1) # Test that when counter resets, currentImage increments while self.redTarget._counter > 0: self.redTarget.update() self.assertEqual (self.redTarget._currentImage, 3) def test_timedOut (self): """ Tests that a target successfully times out """ for x in range (0, COUNTDOWN_FRAME * 5): self.greenTarget.update () self.assertTrue (self.greenTarget.timedOut) def test_isRed (self): """ Tests isRed """ self.assertTrue (self.redTarget.isRed ())
def _instr_unpack_args(self, instr, cf): num_fargs, has_vargs = Target.unpack_unpack_args(instr) num_fargs = jit.promote(num_fargs) has_vargs = jit.promote(has_vargs) if not has_vargs: nargs = jit.promote(cf.nargs) else: nargs = cf.nargs if nargs > num_fargs and not has_vargs: msg = "Too many parameters (%d passed, but a maximum of %d allowed)." % \ (nargs, num_fargs) self.raise_helper("Parameters_Exception", [Builtins.Con_String(self, msg)]) if num_fargs > 0: arg_offset = cf.bc_off + Target.INTSIZE + num_fargs * Target.INTSIZE for i in range(num_fargs - 1, -1, -1): arg_offset -= Target.INTSIZE arg_info = Target.read_word(cf.pc.mod.bc, arg_offset) if i >= nargs: if not Target.unpack_unpack_args_is_mandatory(arg_info): msg = "No value passed for parameter %d." % (i + 1) self.raise_helper("Parameters_Exception", [Builtins.Con_String(self, msg)]) else: if nargs > num_fargs: o = cf.stack_pop_n(nargs - num_fargs) else: o = cf.stack_pop() assert isinstance(o, Builtins.Con_Object) cf.closure.vars[Target.unpack_unpack_args_arg_num(arg_info)] = o if has_vargs: arg_offset = cf.bc_off + Target.INTSIZE + num_fargs * Target.INTSIZE arg_info = Target.read_word(cf.pc.mod.bc, arg_offset) if nargs <= num_fargs: l = [] else: j = cf.stackpe i = j - (nargs - num_fargs) assert i >= 0 and j >= 0 l = cf.stack_get_slice(i, j) cf.stackpe = i + 1 cf.closure.vars[Target.unpack_unpack_args_arg_num(arg_info)] = Builtins.Con_List(self, l) cf.bc_off += Target.INTSIZE + (num_fargs + 1) * Target.INTSIZE else: cf.bc_off += Target.INTSIZE + num_fargs * Target.INTSIZE
def _instr_const_get(self, instr, cf): const_num = Target.unpack_constant_get(instr) cf.stack_push(cf.pc.mod.get_const(self, const_num)) cf.bc_off += Target.INTSIZE
def _instr_set(self, instr, cf): ne = Target.unpack_set(instr) l = cf.stack_get_slice_del(cf.stackpe - ne) cf.stack_push(Builtins.Con_Set(self, l)) cf.bc_off += Target.INTSIZE
def _instr_add_exception_frame(self, instr, cf): j = Target.unpack_add_exception_frame(instr) self._add_exception_frame(cf, cf.bc_off + j) cf.bc_off += Target.INTSIZE
def subclassHandleMessage(self, msg): if(msg.msgType==2): # New target # tgtData = [tgtID 0,tgtIntelValue 1,tgtIntelPriority 2,tgtType 3,tgtStealth 4,tgtSpeed 5,tgtPredLoc 6,tgtGoalTrackTime 7,tgtActualTrackTime 8,tgtTrackAttempts 9] Data=msg.data if(debug==1): msg.printData(1) tgt=Target(Data[6]) tgt.ID=Data[0] tgt.intelVal=Data[1] tgt.intelPriority=Data[1] tgt.Type=Data[3] tgt.Stealth=Data[4] tgt.speed=Data[5] tgt.ObsTime=Data[7]-Data[8] tgt.ActTractTime=Data[8] tgt.goalTime=Data[7] tgt.trackAttempts=Data[9] self.target=tgt self.updateTime(msg.timestamp - self.LocalSimTime)
def setUp (self): """ Initializes a green and red target """ self.redTarget = Target () self.greenTarget = Target (isRed = False)
def _instr_import(self, instr, cf): mod = self.get_mod(cf.pc.mod.imps[Target.unpack_import(instr)]) mod.import_(self) cf.stack_push(mod) cf.bc_off += Target.INTSIZE
def _instr_pull(self, instr, cf): i = Target.unpack_pull(instr) cf.stack_push(cf.stack_pop_n(i)) cf.bc_off += Target.INTSIZE
def buildData(self, search): lst = [] counter = 0 counterTotal = 0 t = Target.mkTarget(search) add_food = ("INSERT INTO food " "(name, price, weight, location) " "VALUES (%s, %s, %s, %s)") add_search = ("INSERT INTO search_type " "(id, search, points) " "VALUES (%s, %s, %s)") add_fc = ("INSERT INTO fc " "(category, count, search, feature) " "VALUES (%s, %s, %s, %s)") add_cc = ("INSERT INTO cc " "(count, search, category) " "VALUES (%s, %s, %s)") self.cursor.execute(add_cc, (0, search,1)) self.database.commit() self.cursor.execute(add_cc, (0, search,0)) self.database.commit() print("hi") for i in t: counterTotal += 1 # print(i.n +' '+ str(i.p)) if self.findDuplicate(i,search) == 1: print("i'm in here all ready") else: print("i'm here to stay bitches") lst.append(i) try: food_data = (i.n, float(i.p), float(i.w), "target") self.cursor.execute(add_food,food_data) self.database.commit() foodID = self.cursor.lastrowid search_data = (foodID, search, 0) self.cursor.execute(add_search,search_data) counter += 1 print("holy f**k I worked") except: print("i have failed") w = walmart.mkWalmart(search) for i in w: counterTotal += 1 if self.findDuplicate(i,search) == 1: print("i'm in here all ready") else: print("i'm here to stay bitches") lst.append(i) try: food_data = (i.n, float(i.p), float(i.w), "walmart") self.cursor.execute(add_food,food_data) foodID = self.cursor.lastrowid search_data = (foodID, search, 0) self.cursor.execute(add_search, search_data) self.database.commit() print(i.n) counter += 1; except: print("i have failed") try: add_searchs = ("INSERT INTO search " "(name, popularity)" "VALUE (%s, %s)") self.cursor.execute(add_searchs, (search, 0)) self.database.commit() except: print("boo") # cursor.close() # database.close print(counter) print(counterTotal) try: for i in lst: print(i.n) except: print("it couldn't f*****g print!")
def _instr_branch(self, instr, cf): cf.bc_off += Target.unpack_branch(instr)
def _instr_slot_lookup(self, instr, cf): o = cf.stack_pop() nm_start, nm_size = Target.unpack_slot_lookup(instr) nm = Target.extract_str(cf.pc.mod.bc, nm_start + cf.bc_off, nm_size) cf.stack_push(o.get_slot(self, nm)) cf.bc_off += Target.align(nm_start + nm_size)
class Crop: """image""" def __init__(self, \ picture, \ x_offset = 0, \ y_offset = 0, \ name = "", \ available = False, \ completed = False, \ inqueue = False, \ segments_downloaded = 0, \ segments_total = 0, \ size = 0, \ path = ""): """constructor""" # the picture this crop belongs to self.picture = picture # various program relevent attributes self.name = name self.available = available self.completed = completed self.inqueue = inqueue self.size = size self.segments_downloaded = segments_downloaded self.segments_total = segments_total self.path = path # resolution attributes self.x_offset = x_offset self.y_offset = y_offset self.target = None #picture data self.segment_size = 250 def set_for_redownload(self): """reset crop properties for redownloading""" self.completed = False self.inqueue = False self.segments_downloaded = 0 self.segments_total = 0 self.size = 0 self.target = None def set_for_manual(self): """set crop to be completed for manually picture dragging""" self.available = True self.completed = True self.segments_downloaded = 1 self.segments_total = 1 self.size = self.segment_size def calculate_total_segments(self): self.segments_total = math.ceil(float(self.size)/float(self.segment_size)) def total_segments(self): return math.ceil(float(self.size)/float(self.segment_size)) def save_segment(self, segment_data, segment_num): #make sure the file exists fout = open(self.path, 'a') fout.close() #save the data (you can't use seek with 'a') fout = open(self.path, 'r+') fout.seek(segment_num * self.segment_size) fout.write(segment_data) fout.truncate(fout.tell()) fout.close() #update info self.segments_downloaded = self.segments_downloaded + 1; def get_percent_complete(self): if self.total_segments() == 0: return 0 else: percent_complete = \ math.floor( (self.segments_downloaded*100) / (self.total_segments()) ) return percent_complete def calculate_real_coordinates(self, crop_x, crop_y): """ takes the actual coordinates on the crop and returns the correspondin coordinates on the full size image""" real_x = int((self.x_offset + crop_x) * (self.picture.x_resolution / self.picture.x_thumbnail_resolution)) real_y = int((self.y_offset + crop_y) * (self.picture.y_resolution / self.picture.y_thumbnail_resolution)) return (real_x, real_y) def set_target(self, crop_x, crop_y): self.target = Target(self) # need these for rendering the target self.target.x_coord = crop_x self.target.y_coord = crop_y # need this stuff for calculating latitude and longitude # * needs pitch, yaw, roll, pan, tilt from picture, etc. gps_x = float(self.picture.gps_x) gps_y = float(self.picture.gps_y) pan = self.picture.pan tilt = self.picture.tilt yaw = self.picture.yaw pitch = self.picture.pitch roll = self.picture.roll plane_orientation = self.picture.plane_orientation altitude = self.picture.altitude # * needs intrinsic camera matrix (should be in picture) # -> in picture constructor put a bloggie = Camera() part # -> right now all pictures should use the default image size of # fully zoomed out, and the corresponding intrinsic params. # If this were to change the image station would have to get # the zoom level and use it to calculate new intrinsic params M_int = self.picture.bloggie.get_intrinsic_matrix() # * needs to determine real coordinates from crop coordinates # -> for this define a seperate function. # -> e.g. (real_x, real_y) = self.calculate_real_coordinates( # crop_x + self.x_offset, # crop_y + self.y_offset) # # *** to get x_offset and y_offset # --> look at '_execute_generate_crop' and make it so xa and ya are stored (real_x, real_y) = self.calculate_real_coordinates(crop_x, crop_y) print "lat is: %f and long is %f" % (gps_x, gps_y,) print "crop_coords are x: %d, y: %d" % (crop_x, crop_y,) print "real coords are x: %d, y: %d" % (real_x, real_y,) # FINALLY: pass all this info to the calculate_gps function, which # will do matrix mults and math described in the blue notebook # self.target.calculate_gps(M_int, real_x, real_y, gps_x, gps_y, \ pan, tilt, yaw, pitch, roll, plane_orientation, altitude)
def _instr_add_failure_frame(self, instr, cf): off = Target.unpack_add_failure_frame(instr) self._add_failure_frame(cf, False, cf.bc_off + off) cf.bc_off += Target.INTSIZE
def _instr_branch_if_fail(self, instr, cf): if cf.stack_pop() is not self.get_builtin(Builtins.BUILTIN_FAIL_OBJ): cf.bc_off += Target.INTSIZE else: j = Target.unpack_branch_if_not_fail(instr) cf.bc_off += j
def _instr_builtin_lookup(self, instr, cf): bl = Target.unpack_builtin_lookup(instr) cf.stack_push(self.get_builtin(bl)) cf.bc_off += Target.INTSIZE
def bc_loop(self, cf): pc = cf.pc mod_bc = pc.mod.bc prev_bc_off = -1 while 1: bc_off = cf.bc_off if prev_bc_off != -1 and prev_bc_off > bc_off: jitdriver.can_enter_jit(bc_off=bc_off, mod_bc=mod_bc, cf=cf, prev_bc_off=prev_bc_off, pc=pc, self=self) jitdriver.jit_merge_point(bc_off=bc_off, mod_bc=mod_bc, cf=cf, prev_bc_off=prev_bc_off, pc=pc, self=self) assert cf is self.cur_cf prev_bc_off = bc_off instr = Target.read_word(mod_bc, bc_off) it = Target.get_instr(instr) try: #x = cf.stackpe; assert x >= 0; print "%s %s %d [stackpe:%d ffp:%d gfp:%d xfp:%d]" % (Target.INSTR_NAMES[instr & 0xFF], str(cf.stack[:x]), bc_off, cf.stackpe, cf.ffp, cf.gfp, cf.xfp) if it == Target.CON_INSTR_EXBI: self._instr_exbi(instr, cf) elif it == Target.CON_INSTR_VAR_LOOKUP: self._instr_var_lookup(instr, cf) elif it == Target.CON_INSTR_VAR_ASSIGN: self._instr_var_assign(instr, cf) elif it == Target.CON_INSTR_ADD_FAILURE_FRAME: self._instr_add_failure_frame(instr, cf) elif it == Target.CON_INSTR_ADD_FAIL_UP_FRAME: self._instr_add_fail_up_frame(instr, cf) elif it == Target.CON_INSTR_REMOVE_FAILURE_FRAME: self._instr_remove_failure_frame(instr, cf) elif it == Target.CON_INSTR_IS_ASSIGNED: self._instr_is_assigned(instr, cf) elif it == Target.CON_INSTR_IS: self._instr_is(instr, cf) elif it == Target.CON_INSTR_FAIL_NOW: self._instr_fail_now(instr, cf) elif it == Target.CON_INSTR_POP: self._instr_pop(instr, cf) elif it == Target.CON_INSTR_LIST: self._instr_list(instr, cf) elif it == Target.CON_INSTR_SLOT_LOOKUP: self._instr_slot_lookup(instr, cf) elif it == Target.CON_INSTR_APPLY: self._instr_apply(instr, cf) elif it == Target.CON_INSTR_FUNC_DEFN: self._instr_func_defn(instr, cf) elif it == Target.CON_INSTR_RETURN: cf.returned = True return cf.stack_pop() elif it == Target.CON_INSTR_BRANCH: self._instr_branch(instr, cf) elif it == Target.CON_INSTR_YIELD: cf.bc_off += Target.INTSIZE return cf.stack_get(cf.stackpe - 1) elif it == Target.CON_INSTR_IMPORT: self._instr_import(instr, cf) elif it == Target.CON_INSTR_DICT: self._instr_dict(instr, cf) elif it == Target.CON_INSTR_DUP: self._instr_dup(instr, cf) elif it == Target.CON_INSTR_PULL: self._instr_pull(instr, cf) elif it == Target.CON_INSTR_BUILTIN_LOOKUP: self._instr_builtin_lookup(instr, cf) elif it == Target.CON_INSTR_ASSIGN_SLOT: self._instr_assign_slot(instr, cf) elif it == Target.CON_INSTR_EYIELD: self._instr_eyield(instr, cf) elif it == Target.CON_INSTR_ADD_EXCEPTION_FRAME: self._instr_add_exception_frame(instr, cf) elif it == Target.CON_INSTR_REMOVE_EXCEPTION_FRAME: self._instr_remove_exception_frame(instr, cf) elif it == Target.CON_INSTR_RAISE: self._instr_raise(instr, cf) elif it == Target.CON_INSTR_UNPACK_ARGS: self._instr_unpack_args(instr, cf) elif it == Target.CON_INSTR_SET: self._instr_set(instr, cf) elif it == Target.CON_INSTR_CONST_GET: self._instr_const_get(instr, cf) elif it == Target.CON_INSTR_PRE_SLOT_LOOKUP_APPLY: # In the C Converge VM, this instruction is used to avoid a very expensive path # through the VM; it's currently unclear whether this VM will suffer from the # same problem. Until we are more sure, we simply use the normal slot lookup # function, which has the correct semantics, but may perhaps not be fully # optimised. self._instr_slot_lookup(instr, cf) elif it == Target.CON_INSTR_UNPACK_ASSIGN: self._instr_unpack_assign(instr, cf) elif it == Target.CON_INSTR_BRANCH_IF_NOT_FAIL: self._instr_branch_if_not_fail(instr, cf) elif it == Target.CON_INSTR_BRANCH_IF_FAIL: self._instr_branch_if_fail(instr, cf) elif it == Target.CON_INSTR_EQ or it == Target.CON_INSTR_LE \ or it == Target.CON_INSTR_NEQ or it == Target.CON_INSTR_LE_EQ \ or it == Target.CON_INSTR_GR_EQ or it == Target.CON_INSTR_GT: self._instr_cmp(instr, cf) elif it == Target.CON_INSTR_ADD or it == Target.CON_INSTR_SUBTRACT: self._instr_calc(instr, cf) elif it == Target.CON_INSTR_MODULE_LOOKUP: self._instr_module_lookup(instr, cf) else: #print it, cf.stack raise Exception("XXX") except Con_Raise_Exception, e: # An exception has been raised and is working its way up the call chain. Each bc_loop # catches the Con_Raise_Exception and either a) kills its continuation and passes the # exception up a level b) deals with it. if cf.xfp == -1: # There is no exception handler, so kill this continuation frame and propagate # the exception self._remove_continuation_frame() raise # We have an exception handler, so deal with it. ef = cf.stack_get(cf.xfp) assert isinstance(ef, Stack_Exception_Frame) self._remove_exception_frame(cf) cf.stack_push(e.ex_obj) cf.bc_off = ef.bc_off
def get_printable_location(bc_off, mod_bc, pc, self): assert isinstance(pc, BC_PC) instr = Target.read_word(mod_bc, bc_off) it = Target.get_instr(instr) return "%s:%s at offset %s. bytecode: %s" % (pc.mod, pc.off, bc_off, Target.INSTR_NAMES[it])