Best Python code snippet using robotframework-ioslibrary_python
simulator.py
Source:simulator.py  
...115        116  #  print(held)117        118    if empty or cur_step == MAX_STEPS:119        reset_simulator(None,None)120        121        122    cur_step += 1123    canv.after(10,draw_loop)124def activate(_Bool):125    return -1 if not _Bool else 1126def sign(x):127    return -1 if x < 0 else 1128class Missile:129    def __init__(self, jet, other_jets,speed=50):130        self.flying    = 0131        self.detonated = 0132        self.fuel = 350133        self.jet = jet134        self.other_jets = other_jets135        self.radius = 0.15136        self.dot = canv.create_oval(0,0,0,0,outline='yellow')137        self.speed = speed138        self.centroid=deepcopy(self.jet.centroid)139    140    def launch(self):141        self.flying = 1142        self.direc = normalize(np.array(self.jet.offs[3]) - self.jet.centroid)143        self.centroid = deepcopy(self.jet.centroid)144    145    def time_step(self):146        if not self.flying and not self.detonated: #attached to hardpoint147            self.centroid = deepcopy(self.jet.centroid)148        elif self.flying: #trying to find target149        150            closest_ctr = np.array([999,999,999])151            for jet in self.other_jets:152                s = self.centroid153                if type(s) == type([]): #LMAO154                    s = np.array(s)155            156                if np.linalg.norm(s - jet.centroid) < np.linalg.norm(s - closest_ctr):157                    closest_ctr = jet.centroid158            closest_ctr = closest_ctr[0]        159            #'proportional pursuit'160            #https://en.wikipedia.org/wiki/Proportional_navigation161            162            if self.fuel: #able to 'change' direction163                self.direc = (0.99 * self.direc) + (0.01 * normalize(jet.centroid - s))164                self.fuel -= 1165        166            self.centroid += self.direc * self.speed * TIME_STEP167            168            #pretty colors....woww169            new = 'blue' if self.jet.canv.itemcget(self.dot,'outline') == 'red' else 'red'170            self.jet.canv.itemconfig(self.dot,outline=new)171            172            #should we go boom?173            #first, have we hit boundary?174            if self.centroid[0][0] < Jet.BXYZ[0]:175                self.explode()176            elif self.centroid[0][0] > Jet.BXYZ[1]:177                self.explode()178            elif self.centroid[0][1] < Jet.BXYZ[2]:179                self.explode()180            elif self.centroid[0][1] > Jet.BXYZ[3]:181                self.explode()182            elif self.centroid[0][2] < Jet.BXYZ[4]:183                self.explode()184            elif self.centroid[0][2] > Jet.BXYZ[5]:185                self.explode()186            #otherwise, have we hit a jet?187            for jet in self.other_jets:188                diff = np.linalg.norm(self.centroid - jet.centroid)189                if diff < self.radius:190                    self.explode()191                #print(diff)192            193        ss = to_ss(self.centroid)194        self.jet.canv.coords(self.dot, ss[0]-5, ss[1]-5,195                                       ss[0]+5, ss[1]+5)196    def reset(self):197        self.flying    = 0198        self.detonated = 0199        self.fuel = 350200        self.jet.canv.itemconfig(self.dot,outline='yellow')201    def explode(self):202        self.flying = 0203        self.detonated = 1204        self.jet.canv.itemconfig(self.dot,outline='white')205        206        for jet in self.other_jets:207            if np.linalg.norm(self.centroid - jet.centroid) < self.radius:208                self.centroid = jet.centroid209                reset_simulator(self.jet,jet)210def reset_simulator(winner, failer):211    global all_jets, cur_step212    global halt_sema #gil makes this trivially simple213    214    for jet in all_jets:215        jet.graphical_step_iteration()216    canv.update()217    218    halt_sema = 0219    220    cur_step = 0221    222    if winner or failer:223        res_net = [0.0001 for _ in range(len(all_jets))]224    else:225        res_net = [-0.5 for _ in range(len(all_jets))]226    227    for idx, jet in enumerate(all_jets):228        if jet == winner:229            print("Jet %d won!" % idx)230            res_net[idx] = 2231            for line in jet.plane_lines:232                canv.itemconfig(line, fill='green')233            234        if jet == failer and winner == None:235            print("Jet %d crashed (unforced error)" % idx)236            res_net[idx] = -1.75237            for line in jet.plane_lines:238                canv.itemconfig(line, fill='orange')239            240        elif jet == failer:241            print("Jet %d shot down! (by %d)!" % (idx, 242            all_jets.index(winner))) #expand to N jets, refactor this243            res_net[idx] = -2244            for line in jet.plane_lines:245                canv.itemconfig(line, fill='red')246    canv.update()247    '''248    for i in range(len(res_net)): #stayed alive, gain some points249        global held               #took time for a shootdown, exciting (gain points too!)250        len_held = held[i]251        if res_net[i] < 0:252            res_net[i] /= len_held253        else:254            res_net[i] *= len_held255    '''256    print(res_net)257    #return258    global all_models259    for jet, memory, model, rw, optimizer, auto in zip(all_jets, all_memory, all_models, res_net, all_opts, all_automatic):260        261        if not auto: #don't train on human input!262            continue263        264        inputs = memory265        outputs = [rw * pow(GAMMA,i) for i in range(len(inputs))]266        outputs.reverse()267        268        for epoch in range(3):269            for input_, output_ in zip(inputs, outputs):270                #training passes271                optimizer.zero_grad()272                273                #at such a point, what does the model say?274                model_res = max(model(input_))275                #at such a point, what is the discounted reward we got?276                disc__res = torch.ones(1) * float(output_)277                loss = criterion(model_res, disc__res)278                loss.backward()279                optimizer.step()280        281    for memory in all_memory:282        memory.clear()283        284    held = [MAX_STEPS for _ in range(len(all_jets))]285    286    for jet in all_jets:287        jet.reset()288        for line in jet.plane_lines:289            canv.itemconfig(line, fill='white')290    291    halt_sema = 1292    293TIME_STEP = 0.001294SCALE_CS  = 0.5295N_MISSILES = 4296#input layer297#for every jet: 4 orientation, (p,y,r,t), 3 centroid (x,y,z), N_MISSILES missiles 298#for every missile: 1 flying, 1 detonated, 1 fuel, 3 centroid (x,y,z)299#300#total inputs: N_JETS * ( (4 + 3) + ((1 + 1 + 1 + 3) * N_MISSILES))301#              N_JETS * ( 7 + 6 * N_MISSILES)302#              7*N_JETS + 6 * N_JETS * N_MISSILES303#304#output layer305#306#5 outputs (dPitch, dYaw, dRoll, dThrottle, fire) @ 2 options each = 10 outputs307#2^5 = 32 outputs. LSB=fire / not fire, 2LSB=incease / decrease thrust, etc...308#309#310#in our case, N_JETS=2, N_MISSILES=4. So, go from 62 inputs to 32 outputs. How should we do so?311#312#Let's make 9 layers.313#62->62->52->52->52->42->42->32->32314#315import torch.nn as nn316import torch.nn.functional as F317class Net(nn.Module):318    def __init__(self):319        super().__init__()320        self.fc1 = nn.Linear(62,62)321        self.fc2 = nn.Linear(62,52)322        self.fc3 = nn.Linear(52,52)323        self.fc4 = nn.Linear(52,52)324        self.fc5 = nn.Linear(52,42)325        self.fc6 = nn.Linear(42,42)326        self.fc7 = nn.Linear(42,32)327        self.fc8 = nn.Linear(32,32)328        self.fc9 = nn.Linear(32,32)329    def forward(self, x):330        x = F.gelu(self.fc1(x))331        x = F.gelu(self.fc2(x))332        x = F.gelu(self.fc3(x))333        x = F.gelu(self.fc4(x))334        x = F.relu(self.fc5(x)) #just for funsies335        x = F.gelu(self.fc6(x))336        x = F.gelu(self.fc7(x))337        x = F.gelu(self.fc8(x))338        x = self.fc9(x)339        return x340def state_to_future_array_from_jet(jet):341    global all_jets342    #first, spit out our orientation, and throttle343    344    ajc = jet.centroid345    if len(ajc) == 1:346        ajc = ajc[0]347    feature = [348        ajc[0],349        ajc[1],350        ajc[2],351        jet.pitch, jet.yaw, jet.roll, jet.throttle352    ]353    #now, our missiles354    missile_info = []355    for missile in jet.missiles:356        if missile:357            ajmc = missile.centroid358            if len(ajmc) == 1: #WTF359                ajmc = ajmc[0]360                ajmc = ajmc.tolist()361            missile_info += ajmc362            missile_info += [missile.flying,missile.detonated,missile.fuel]363    feature += missile_info364    365    #now, everyone else and 'their' missiles366    for jet2 in all_jets:367        if jet2 == jet:368            continue369        aj2c = jet2.centroid370        if len(aj2c) == 1:371            aj2c = aj2c[0]372        373        feature += [374            aj2c[0],375            aj2c[1],376            aj2c[2],377            jet2.pitch, jet2.yaw, jet2.roll,jet2.throttle378        ]379        for missile in jet2.missiles:380            missile_info = deepcopy([]) #losing my mind381            if missile:382                ajmc = missile.centroid383                if len(ajmc) == 1: #WTF384                    ajmc = ajmc[0]385                    ajmc = ajmc.tolist()386                missile_info += ajmc387                missile_info += [missile.flying,missile.detonated,missile.fuel]388            feature += missile_info389    390    #print(feature)391    return feature392class Jet:393    394    BXYZ=[-5.5,4.5,0,7,-5.5,4.5]395    396    def auto_input(self,in_):397        dpitch, dyaw, droll, dthrottle, fire = in_398        self.dpitch    = sign(dpitch)399        self.dyaw      = sign(dyaw)400        self.droll     = sign(droll)401        self.dthrottle = sign(dthrottle)402        if(sign(fire) > 0):403            self.fire_missile()404    405    def keydown_gen(self,keys):406        def keydown(e):407            nonlocal self408            if e.char == keys[0]:409                self.droll = -1410            elif e.char == keys[1]: 411                self.droll = 1412            elif e.char == keys[2]:413                self.dpitch = -1414            elif e.char == keys[3]:415                self.dpitch = 1416            elif e.char == keys[4]:417                self.dyaw = -1418            elif e.char == keys[5]:419                self.dyaw = 1420            elif e.char == keys[6]:421                self.dthrottle = -1422            elif e.char == keys[7]:423                self.dthrottle = 1424            elif e.char == keys[8]:425                self.fire_missile()426        return keydown427    def keyup_gen(self,keys):428        def keyup(e):429            nonlocal self 430            431            if e.char == keys[0] and self.droll == -1:432                self.droll = 0433            elif e.char == keys[1] and self.droll == 1: 434                self.droll = 0435            elif e.char == keys[2] and self.dpitch == -1:436                self.dpitch = 0437            elif e.char == keys[3] and self.dpitch == 1:438                self.dpitch = 0439            elif e.char == keys[4] and self.dyaw == -1:440                self.dyaw = 0441            elif e.char == keys[5] and self.dyaw == 1:442                self.dyaw = 0443            elif e.char == keys[6] and self.dthrottle == -1:444                self.dthrottle = 0445            elif e.char == keys[7] and self.dthrottle == 1:446                self.dthrottle = 0447        return keyup 448    def check_bounds(self):449        #hit a wall?450        #return451        452        if self.centroid[0][0] < Jet.BXYZ[0]:453            print("Hit -X")454            reset_simulator(None,self)455        elif self.centroid[0][0] > Jet.BXYZ[1]:456            print("Hit +X")457            reset_simulator(None,self)458        elif self.centroid[0][1] < Jet.BXYZ[2]:459            print("Hit -Y")460            reset_simulator(None,self)461        elif self.centroid[0][1] > Jet.BXYZ[3]:462            print("Hit +Y")463            reset_simulator(None,self)464        elif self.centroid[0][2] < Jet.BXYZ[4]:465            print("Hit -Z")466            reset_simulator(None,self)467        elif self.centroid[0][2] > Jet.BXYZ[5]:468            print("Hit +Z")469            reset_simulator(None,self)470    def fire_missile(self):471        if self.missiles[self.cur_missile_ptr]:472            self.missiles[self.cur_missile_ptr].launch()473            self.cur_missile_ptr+=1474    def reset(self):475        self.centroid = np.array([deepcopy(self.centroid_b)])476        self.pitch=self.cond[0]477        self.roll=self.cond[1]478        self.yaw=self.cond[2]479        self.throttle=100480        self.velocity=deepcopy(self.start_velocity)481        self.force=np.array([0.,0.,0.])482        483        self.offs = deepcopy(offs_b)...app.py
Source:app.py  
...40def stop_simulator():41    if request.method == "POST":42        if spg.state_simulator == spg.STATE_RUNNING:43            spg.stop_simulator()44            spg.reset_simulator()45            return jsonify(success=True)46    return jsonify(success=False)47@app.route("/simulator/reset", methods=["POST"])48def reset_simulator():49    if request.method == "POST":50        if spg.state_simulator == spg.STATE_WAITING:51            spg.reset_simulator()52            return jsonify(success=True)53    return jsonify(success=False)54@app.route("/agents")55def agents():56    if request.method == "GET":57        return jsonify({"data": {"names": spg.get_agents_names()}})58@app.route("/agent/prox-activations")59def agent_sensor_value():60    if request.method == "GET":61        62        data = request.get_json().get('json')63        agent_name = None64        if type(data) is dict:65            agent_name = data.get('agent_name')...lonely_turtle.py
Source:lonely_turtle.py  
...51	rospy.init_node('teer_example_turtle')52	# services53	rospy.wait_for_service('reset')54	reset_simulator = rospy.ServiceProxy('reset', EmptyServiceCall)55	reset_simulator()56	rospy.wait_for_service('clear')57	clear_background = rospy.ServiceProxy('clear', EmptyServiceCall)58	rospy.wait_for_service('turtle1/set_pen')59	turtle1_set_pen = rospy.ServiceProxy('turtle1/set_pen', SetPen)60	rospy.wait_for_service('turtle1/teleport_absolute')61	turtle1_teleport = rospy.ServiceProxy('turtle1/teleport_absolute', TeleportAbsolute)62	# subscriber/publisher63	rospy.Subscriber('turtle1/pose', Pose, turtle1_pose_updated)64	turtle1_velocity = rospy.Publisher('turtle1/command_velocity', Velocity)65	66	# setup environment67	turtle1_set_pen(0,0,0,0,1)68	turtle1_teleport(2,2,0)69	clear_background()...Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!
