def testDeleteTraducere(self): con=controller() con.addTraducere("Ro","cuv","En","bla") con.addTraducere("Ro","abc","En","def") con.addTraducere("Ro","lala","En","baba") self.assertEqual(len(con.repo.traduceri),3) con.stergeTraducere("cuv") self.assertEqual(len(con.repo.traduceri),2) con2=controller() con2.addTraducere("Ro","cuv","En","bla") con2.addTraducere("Ro","abc","En","def") con2.addTraducere("Ro","lala","En","cuv") con2.stergeTraducere("cuv") self.assertEqual(len(con2.repo.traduceri),1)
def testAddTraducere(self): con=controller() self.assertEqual(con.addTraducere("Ro","cuv","En","bla").succes,True) self.assertEqual(con.addTraducere("Ro","cuv","En","bla").succes,False) self.assertEqual(con.addTraducere("Ro","cuv","Fr","bla").succes,True) self.assertEqual(con.addTraducere("Ro","","En","bla").succes,False) self.assertEqual(con.addTraducere("En","cuv","En","bla").succes,False)
def step(time_idx,lstm_hidden): M_pad = repeat(P.memory_init.dimshuffle((0,'x',1)) , lstm_hidden.shape[1] , axis=1 ) M_curr_temp = T.concatenate([M_pad , lstm_hidden[:time_idx,:,:]] , axis=0) M_curr = M_curr_temp.transpose((1,0,2)) input_curr = lstm_hidden[time_idx,:,:] weight_prev = T.zeros([input_curr.shape[0] , time_idx+1]) weight_inter = weight_prev for head in heads: weight_inter, att_w_inter = build_head_curr( weight_inter, M_curr , head, input_curr) weight_curr = weight_inter pad_matrix = T.zeros((input_curr.shape[0],lstm_hidden.shape[0]-weight_curr.shape[1]),dtype='float32') weight_pad = T.concatenate([weight_curr,pad_matrix],axis=1) entropy_temp = -1*(weight_curr*T.log(weight_curr)) entropy = T.sum(entropy_temp , axis=1) att_w_curr = att_w_inter att_M_curr = att_w_curr.dimshuffle(0,'x',1)*M_curr read_curr = build_read(att_M_curr, weight_curr) output = controller(input_curr, read_curr) return output,entropy,weight_pad
def testCautaTraducere(self): con=controller() con.addTraducere("Ro","om","En","man") con.addTraducere("Ro","abc","En","def") con.addTraducere("Ro","lala","En","baba") self.assertEqual(con.cautaTraducerea("om","Ro","En"),"man") self.assertEqual(con.cautaTraducerea("omz","Ro","En"),"")
def __init__(self): self.__isRunning = True self.__repository = repository() self.__populationSize = 80 self.__individualSize = 15 self.__startPos = (0, 0) self.__bestIndividualsNr = 40 self.__crossoverProbability = 0.5 self.__mutationProbability = 0.02 self.__maxIterations = 10000 self.__dummyMap = Map() self.__dummyMap.randomMap() self.__controller = controller([ self.__repository, self.__populationSize, self.__individualSize, self.__startPos, self.__bestIndividualsNr, self.__crossoverProbability, self.__mutationProbability, self.__maxIterations, self.__dummyMap ]) self.__stoppingFitness = 1000 self.__lastBest = Individual() self.__statistics = [] self.__repository.cmap = self.__dummyMap self.__lastRunStartTime = time() self.__lastRunEndTime = time()
def step(time_idx,lstm_hidden): M_pad = repeat(P.memory_init.dimshuffle((0,'x',1)) , lstm_hidden.shape[1] , axis=1 ) M_curr_temp = T.concatenate([M_pad , lstm_hidden[:time_idx,:,:]] , axis=0) M_curr = M_curr_temp.transpose((1,0,2)) input_curr = lstm_hidden[time_idx,:,:] weight_prev = T.zeros([input_curr.shape[0] , time_idx+1]) weight_inter = weight_prev for head in heads: weight_inter, att_w_inter, key = build_head_curr( weight_inter, M_curr , head, input_curr) weight_curr = weight_inter entropy_temp = -1*(weight_curr*T.log(weight_curr)) entropy = T.sum(entropy_temp , axis=1) key_normalize = T.nnet.softmax(key) key_entropy_temp = -1*(key_normalize*T.log(key_normalize)) key_entropy = T.sum(key_entropy_temp , axis=1) att_w_curr = att_w_inter att_M_curr = att_w_curr.dimshuffle(0,'x',1)*M_curr read_curr = build_read(att_M_curr, weight_curr) output = controller(input_curr, read_curr) return output,entropy,key_entropy
def setup_controllers(self): # self.cav_controller = controller(self.CAV, True) self.cav_controller = CAV_controller(self.CAV) self.ldhv_controller = LHDV_controller( self.LHDV, False, self.LHDV_control_files[self.LHDV_FLAGS]) self.bhdv_controller = controller(self.BHDV, True)
def on_start_button_clicked (self, start_button): input_array = [] control = controller(self) for i in self.elems: if(i.get_text().isnumeric()): input_array.append(int(i.get_text())) control.sort_array(input_array, self.sort_algo)
def __init__(self, isBaseStation, droneConnectionStr='', portNum=55655, bsAddr="localhost", hostName="localhost", default_filename='attributes_default.ini', curr_filename='attributes_curr.ini', changesThreshold=20): self.isBaseStation = isBaseStation self.hostName = hostName self.portNum = portNum self.bsAddr = bsAddr self.socket = None self.buddy = None self.currMode = 0 self.clientSocket = None self.clientAddress = None if isBaseStation: self.buddy = controller(5.117) else: self.buddy = droneStats( droneConnectionStr) # put in stuff for drone() class self.powerLevels = {0: 0, 1: 50, 2: 50, 3: 50} self.powers = { 'VERTICAL': 0, 'ROTATIONAL': 1, 'LATERAL': 2, 'FORWARD': 3 } self.powerCodes = { 0: 'VERTICAL', 1: 'ROTATIONAL', 2: 'LATERAL', 3: 'FORWARD' } self.modes = { 'LANDED': 0, 'TAKEOFF': 1, 'LANDING': 2, 'IDLE': 3, 'FLYING': 4, 'CRASH': 5 } self.modeCodes = { 0: 'LANDED', 1: 'TAKEOFF', 2: 'LANDING', 3: 'IDLE', 4: 'FLYING', 5: 'CRASH' } self.socket = None
def test_controller_delete_tip(self): ctrl=controller() ctrl.repo.add_bicicleta(1,'tip1',5) ctrl.repo.add_bicicleta(5,'tip2',5) ctrl.repo.add_bicicleta(9,'tip2',5) ctrl.sterge_biciclete_tip('tip2') lungime=len(ctrl.repo.get_all()) self.assertEquals(lungime,1)
def test_controller_sterge_max(self): ctrl=controller() ctrl.repo.add_bicicleta(1,'tip1',5) ctrl.repo.add_bicicleta(5,'tip2',588) ctrl.repo.add_bicicleta(9,'tip2',588) ctrl.repo.add_bicicleta(8,'tip2',150) ctrl.sterge_max() lungime=len(ctrl.repo.get_all()) self.assertEquals(lungime,2)
def step(input_curr, M_prev, weight_prev): read_prev = build_read(M_prev, weight_prev) output, controller_hidden = controller(input_curr, read_prev) weight_inter, M_inter = weight_prev, M_prev for head in heads: weight_inter, erase, add = build_head_curr(weight_inter, M_inter, head, controller_hidden) M_inter = build_memory_curr(M_inter, erase, add, weight_inter) weight_curr, M_curr = weight_inter, M_inter return M_curr, weight_curr, output
def testTraducere(self): con=controller() text = "un om destept" text2 = "un om foarte destept" con.addTraducere("Ro","om","En","man") con.addTraducere("Ro","un","En","one") con.addTraducere("Ro","destept","En","smart") self.assertEqual(con.traduceText(text,"Ro","En"),"one man smart") self.assertEqual(con.traduceText(text2,"Ro","En"),"one man {foarte} smart")
def step(input_curr, M_prev, weight_prev): read_prev = build_read(M_prev, weight_prev) output, controller_hidden = controller(input_curr, read_prev) weight_inter, M_inter = weight_prev, M_prev for head in heads: weight_inter, erase, add = build_head_curr( weight_inter, M_inter, head, controller_hidden) M_inter = build_memory_curr(M_inter, erase, add, weight_inter) weight_curr, M_curr = weight_inter, M_inter return M_curr, weight_curr, output
def ctrl(name): import controller try: for name in name.split('.'): assert (hasattr(controller, name)) controller = getattr(controller, name) except: print 'the name is', name print 'the controller name is', name raise return controller()
def userdetails(): userid = int(input("Enter your id : ")) username = input("Enter your name : ") usercompany = input("Enter your company : ") usersal = int(input("Enter your salary :")) data = controller(userid, username, usercompany, usersal) print("Registered Successfully") for d in data: print(d)
def getController(ctrl_name): import controller try: for name in ctrl_name.split('.'): assert( hasattr(controller, name) ) controller = getattr(controller, name) except: print 'the name is', name print 'the controller name is', ctrl_name raise return controller()
def step(input_curr,M_prev,weight_prev): #print read_prev.type read_prev = build_read(M_prev,weight_prev) output,controller_hidden = controller(input_curr,read_prev) weight_curr,erase,add = build_head_curr(weight_prev,M_prev,heads[0],controller_hidden) M_curr = build_memory_curr(M_prev,erase,add,weight_curr) #print [i.type for i in [erase_curr,add_curr,key_curr,shift_curr,beta_curr,gamma_curr,g_curr,output]] #print weight_curr.type return M_curr,weight_curr,output
def main(): m = Map(mapLengh, mapLengh) m.randomMap() # init = setUpParamsManually(m) init = setUpParamsRandom(m) if init is None: print( "Incorrect data introduced. Sensors/Drone may overlap forbidden positions." ) return drone = init[0] droneEnergy = init[1] sensors = init[2] repo = repository(m, drone, droneEnergy, sensors) c = controller(repo) c.initializeDistanceMatrix() dm = c.getDistanceMatrix() antColonyDistanceMatrix = np.zeros((SENSORS + 1, SENSORS + 1)) for i in range(SENSORS): antColonyDistanceMatrix[i][SENSORS] = drone.distances[i] antColonyDistanceMatrix[SENSORS][i] = drone.distances[i] for i in range(SENSORS): for j in range(SENSORS): antColonyDistanceMatrix[i][j] = dm[i][j] for i in range(len(antColonyDistanceMatrix)): for j in range(len(antColonyDistanceMatrix)): if antColonyDistanceMatrix[i][j] == 0.0 and i != j: print("One or more sensors is/are unreachable") return """ for i in range(SENSORS + 1): for j in range(SENSORS + 1): print(antColonyDistanceMatrix[i][j], end=" ") print() """ aco = AntColonyOptimization(antColonyDistanceMatrix) pathLength, path = aco.run() finalPath = c.makePath(pathLength, path) path, result = c.adjustBatteryToPath(finalPath) for e in result: print("Sensor (" + str(e[0]) + ", " + str(e[1]) + ") : " + str(e[2]) + " seen squares using " + str(e[3]) + " battery") movingDrone(m, path, sensors, drone, 0.1)
def runSolver(self): controllerArgs = [ self.__repository, self.__populationSize, self.__individualSize, self.__startPos, self.__bestIndividualsNr, self.__crossoverProbability, self.__mutationProbability, self.__maxIterations, self.__dummyMap ] self.__controller = controller(controllerArgs) solverArgs = [self.__stoppingFitness] (self.__lastBest, self.__statistics, self.__lastRunStartTime, self.__lastRunEndTime) = self.__controller.solver(solverArgs)
def ctrl(name): import controller if CACHED_CTRLS.has_key(name): return CACHED_CTRLS[name] else: try: for name in name.split('.'): assert hasattr(controller, name), name controller = getattr(controller, name) CACHED_CTRLS[name] = controller() except: print 'the name is', name print 'the controller name is', name raise return CACHED_CTRLS[name]
def step(input_curr,M_prev,weight_prev): """ Update the weights and memory from the previous time step given the current input """ # Get read vector r_t read_prev = build_read(M_prev,weight_prev) # Feed current input and read input to controller to get # controller output and hidden layer of controller output,controller_hidden = controller(input_curr,read_prev) # Obtain new weight vector (as described in figure 2) and erase and add vectors weight_curr,erase,add = build_head_curr(weight_prev,M_prev,heads,controller_hidden) # Update memory with current weight, erase, and add vectors (Section 3.2 in paper) M_curr = build_memory_curr(M_prev,erase,add,weight_curr) return M_curr,weight_curr,output
def step(input_curr, M_prev, weight_prev): """ Update the weights and memory from the previous time step given the current input """ # Get read vector r_t read_prev = build_read(M_prev, weight_prev) # Feed current input and read input to controller to get # controller output and hidden layer of controller output, controller_hidden = controller(input_curr, read_prev) # Obtain new weight vector (as described in figure 2) and erase and add vectors weight_curr, erase, add = build_head_curr(weight_prev, M_prev, heads, controller_hidden) # Update memory with current weight, erase, and add vectors (Section 3.2 in paper) M_curr = build_memory_curr(M_prev, erase, add, weight_curr) return M_curr, weight_curr, output
def step(time_idx,lstm_hidden): M_pad = repeat(P.memory_init.dimshuffle((0,'x',1)) , lstm_hidden.shape[1] , axis=1 ) M_curr_temp = T.concatenate([M_pad , lstm_hidden[:time_idx,:,:]] , axis=0) M_curr = M_curr_temp.transpose((1,0,2)) input_curr = lstm_hidden[time_idx,:,:] weight_prev = T.zeros([input_curr.shape[0] , time_idx+1]) weight_inter = weight_prev for head in heads: weight_inter = build_head_curr( weight_inter, M_curr , head, input_curr) weight_curr = weight_inter read_curr = build_read(M_curr, weight_curr) output = controller(input_curr, read_curr) return output
def __init__(self): super(sender, self).__init__() self.ack = 1 self.packetList = [] self.sender_socket = socket(AF_INET,SOCK_DGRAM) self.sender_socket.bind(listen) self.logFile = open("Sender_log.txt","w") self.totalSize = 0 with open(filename) as Source: self.content = Source.read() self.totalSize = len(self.content) Source.close() self.iniTime = 0 self.controller = controller(self.content,self.sender_socket,dest,self.logFile,MWS,MSS,timeout,pdrop) self.ISN = random.randint(0,1000) self.ISNR = 0 #save the ISN for receiver self.wavehand = False self.begin()
def initializations(): IopTlmQueue = Queue(50) # Start the image processing task(s) # Vehicle State holds everything known about the current vehicle state vehState = vehicleState() # initialize vehicle state vehState.mode.setMode(raceModes.INIT) # start and initialize the RPLidar lidar = init_lidar_scan() # The vehicle occupancy grid and histogram occGrid = Grid(ogResolution, ogNrows, ogNcols, ogStartDist, ogStartAngle) occGrid.sendUDP_init(OCC_IPADD, UDP_OCCPORT) cont = controller() time.sleep(0.5) printOut("INITIALIZATIONS: initializations complete") return lidar, occGrid, vehState, cont
def index(): """ Recieves Post Data """ """ Short forms of what Chafuel provides lcbn : last clicked button name lufi : last user freeform input mui : messenger user id fn : first name ln : last name """ # data = request.args.to_dict() data = request.get_json() if request.args.get('lcbn') == 'Get Started' and request.args.get( 'lufi') == '': message = '/start' else: message = request.args.get('lufi') uid = request.args.get('mui') fname = request.args.get('fn') lname = request.args.get('ln') name = fname + ' ' + lname if fname != lname else lname return json.dumps({"messages": [{"text": controller(message, uid, name)}]})
#!/usr/bin/env python import tf import rospy import roslib import math import numpy as np import time from controller import * from path import * #pull path info and create path p1 = path() #get path path = p1.get_path() #send path to controller to move jorge cont = controller(path, True) #second arg determines whether it gives output
import numpy as np import cv2 import copy from collections import deque from controller import * import matplotlib.pyplot as plt H, W = 600, 1300 # screen N = 120 # pop E = 5 # dim ind pix ctrl = controller(W, H, N, E) ctrl.initPop() ctrl.randomInfection(10) # draw border and star/end point rect def draw(img): shape = img.shape H, W = shape[0], shape[1] cv2.line(img, (10, 10), (10, H - 10), (255, 255, 255), 10) cv2.line(img, (10, 10), (W - 10, 10), (255, 255, 255), 10) cv2.line(img, (W - 10, H - 10), (10, H - 10), (255, 255, 255), 10) cv2.line(img, (W - 10, H - 10), (W - 10, 10), (255, 255, 255), 10) return img def main(): global H, W, N, E # simulate
""" Routes and views for the flask application. """ from controller import * from model import * from datetime import datetime from flask import render_template from Herkansing6B import app from os import environ #Make the WSGI interface available at the top level so wfastcgi can get it. wsgi_app = app.wsgi_app #create a new instance of the controller class controller = controller() @app.route('/') @app.route('/home') def home(): return controller.index() @app.route('/easy', methods=['GET', 'POST']) def Ex_easy(): return controller.Ex_easy() @app.route('/medium', methods=['GET', 'POST']) def Ex_medium(): return controller.Ex_medium()
import socket import RF24 import RPi.GPIO as GPIO import time import struct # User libraries from controller import * #Set up wifi stuff IPADDRESS = '192.168.1.65' print("Starting our server") s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.bind((IPADDRESS,5005)) s.listen(1) conn, addr = s.accept() #Set up transceiver stuff radio = RF24.RF24(25, 0) pipe = bytes("1Node","ASCII") radio.begin() radio.setRetries(5,15) #Set up as transmitter radio.openWritingPipe(pipe) con = controller(conn, radio) con.run() print("Shutting down server") s.close() conn.close()
''' Created on Jan 22, 2016 @author: tudorstanila ''' from domain import * from repo import * from fileRepo import * from controller import * from ui import * r=repository() f=fileRepo(r) ctrl=controller(f,r) ui=ui(ctrl,r) ui.menu()
def testFisier(self): con=controller() con.addTraducere("Ro","om","En","man") con.addTraducere("Ro","un","En","one") con.addTraducere("Ro","destept","En","smart") con.traduceDinFisier("test_intrare.txt","text_iesire.txt","Ro","En")
phi = [] phid = [] deltad = [] F = [] minDist = [] ''' your code starts here ''' # preprocess the trajectory passMiddlePoint = False nearGoal = False cur_state = np.zeros(7) for i in range(n): command, error = controller(traj, vehicle, curv, x_p, y_p) vehicle.update(command=command) # termination check disError, nearIdx = closest_node(vehicle.state.X, vehicle.state.Y, traj) stepToMiddle = nearIdx - len(traj) / 2.0 if abs(stepToMiddle) < 100.0: passMiddlePoint = True print('middle point passed') nearGoal = nearIdx >= len(traj) - 50 if nearGoal and passMiddlePoint: print('destination reached!') break # record states X.append(vehicle.state.X)
delta = [] xd = [] yd = [] phi = [] phid = [] deltad = [] F = [] minDist =[] # preprocess the trajectory passMiddlePoint = False nearGoal = False # Instantiate an object for the controller class controlV=controller(traj,vehicle) for i in range(n): command = controlV.control_update() vehicle.update(command = command) # termination check disError,nearIdx = closest_node(vehicle.state.X, vehicle.state.Y, traj) stepToMiddle = nearIdx - len(traj)/2.0 if abs(stepToMiddle) < 100.0 and passMiddlePoint==False: passMiddlePoint = True print('middle point passed') nearGoal = nearIdx >= len(traj)-50 if nearGoal and passMiddlePoint: print('...... destination reached!.............') break
e2 = [] k = [] e1 = [] e1d = [] e2 = [] e2d = [] ''' your code starts here ''' # preprocess the trajectory passMiddlePoint = False nearGoal = False for i in range(n): command, error = controller(vehicle) vehicle.update(command=command) if i % 80 == 0: print('X', vehicle.state.X) print('Y', vehicle.state.Y) _, minIdx = find_nearest_points(vehicle.state.X, vehicle.state.Y, traj) print('Traj', traj[minIdx]) print(' ') # termination check disError, nearIdx = find_nearest_points(vehicle.state.X, vehicle.state.Y, traj) stepToMiddle = nearIdx - len(traj) / 2.0 if abs(stepToMiddle) < 100.0: passMiddlePoint = True print('middle point passed')
from controller import * ctrl=controller() ctrl.repo.incarca_din_fisier() def show_menu(): print('1-sterge tip') print('2-sterge max') print('3-exit') alegere=int(input('Alegeti optiunea: ')) return alegere def sterge_tip(): tip=raw_input('Alegeti tipul: ') ctrl.sterge_biciclete_tip(tip) while True: alegere=show_menu() if alegere==3: break if alegere==2: ctrl.sterge_max() ctrl.repo.salveaza() if alegere==1: sterge_tip() ctrl.repo.salveaza()
def __init__(self): self.controller = controller()
e1 = np.inner(diffPos, normalVec) print(e1) #print(idx) aheadPos = traj[ahead] aheadDiff = (aheadPos - currentPos) psiDes = np.arctan2(aheadDiff[1], aheadDiff[0]) e2 = wrap2pi(vehicle.state.phi - psiDes) #e2 = wrap2pi(vehicle.state.phi) - psiDesired e1d = vehicle.state.yd + vehicle.state.xd * e2 e2d = vehicle.state.phid - vehicle.state.xd * KCurve[ahead] eV = Vx - vehicle.state.xd Fout, currDeltad, deltaPrev = controller(e1, e1d, e2, e2d, K, eV, evPrev, vehicle.state.delta) command = vehicle.command(Fout, currDeltad) vehicle.update(command = command) evPrev = -(vehicle.state.xd - Vx) # termination check disError,nearIdx = closest_node(vehicle.state.X, vehicle.state.Y, traj) stepToMiddle = nearIdx - len(traj)/2.0 if abs(stepToMiddle) < 100.0: passMiddlePoint = True print('middle point passed') nearGoal = nearIdx >= len(traj)-50 if nearGoal and passMiddlePoint:
#print("MEDICINE CREATED") conn.execute("""create table IF NOT EXISTS employee (EMP_ID varchar(10) primary key, EMP_NAME varchar(20)not null, SEX varchar(10) not null, AGE int(5) not null, DESIG varchar(20) not null, SAL float(10) not null, EXP varchar(100) not null, EMAIL varcahr(20) not null, PHONE int(12))""") #print ("EMPLOYEE CREATED") conn.execute("""create table IF NOT EXISTS appointment ( PATIENT_ID int(20) not null, EMP_ID varchar(10) not null, AP_NO varchar(10) primary key, AP_TIME time, AP_DATE date, description varchar(100), foreign key(PATIENT_ID) references patient(PATIENT_ID), foreign key(EMP_ID) references doctor(EMP_ID));""") #print("APPOINTMENT CREATED") if __name__ == '__main__': controller()
def main(): officeController = controller("Office", "192.168.1.248", "Off", 4998) officeSensor = sensor("Office", "192.168.1.249") officeAC = ac("Office", "Off", 80) try: opts, args = getopt.getopt(sys.argv[1:], "m:", ["mode"]) except getopt.GetoptError as err: print str(err) sys.exit() for o,a in opts: if o in ("-m","--mode"): if a == "on": officeAC.state = "On" print "[*] AC is already turned on." server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) server.bind(("0.0.0.0", 8080)) server.listen(5) command_server = socket.socket(socket.AF_INET,socket.SOCK_STREAM) command_server.bind(("0.0.0.0", 8081)) command_server.listen(5) change_counter = 0 while True: client, addr = server.accept() if (addr[0] == officeSensor.address): q = Queue(1) officeSensor.thread = threading.Thread(target=receiveTemperature, args=(client,q)) officeSensor.thread.start() #Get inside and outside temperatures officeSensor.insideTemp = q.get(1) officeSensor.outsideTemp = getWeather() #Print inside and outside temperatures officeSensor.printTempStats() now = datetime.datetime.now() now_time = now.time() if officeAC.state == "On" and change_counter <= 0: #If between 10PM and 7AM set temperature to 82 and outside temp is greater than 73 if isNowInTimePeriod(datetime.datetime.strptime("22:00",'%H:%M'),datetime.datetime.strptime("7:00",'%H:%M'),now_time): print("Night time mode.") if officeSensor.outsideTemp < float(86) and officeSensor.insideTemp < float(88): officeAC.setTemperature(officeController, 82) print("Action: Set temperature to 82.") change_counter = 20 # If Outside temp is below 74 degrees turn off AC if AC is on elif officeSensor.outsideTemp <= float(73) and officeSensor.insideTemp < float(84): officeAC.setPower(officeController,"Off") print("Action: Turn off.") change_counter = 20 # If inside temperature is high and outside temperature is high turn down temp setting elif officeSensor.outsideTemp >= float(90) and officeSensor.insideTemp >= float(88): officeAC.setTemperature(officeController, (officeAC.temperature - 2)) print("Action: reduce temperature.") change_counter = 20 #If day time, AC is on, but temperature is high, reduce thermostat elif officeSensor.insideTemp >= float(88): officeAC.setTemperature(officeController,(officeAC.temperature - 2)) change_counter = 20 print("Action: Increase temperature setting to %" % (officeAC.temperature)) #If daytime, AC is on, but temperature is very low, increase thermostat elif officeSensor.insideTemp <= 80 and officeAC.temperature >= float(82): officeAC.setTemperature(officeController,(officeAC.temperature + 2)) change_counter = 20 print("Action: Reduce temperature setting to %." % (officeAC.temperature)) elif officeSensor.outsideTemp <= float(73) and officeSensor.insideTemp < float(84): print "Action: Turn off AC." officeAC.setPower(officeController,"Off") change_counter = 20 else: print "Action: Nothing to do." if officeAC.state == "Off" and change_counter <= 0: if officeSensor.outsideTemp > float(73) and officeSensor.insideTemp > float(86): print "Action: Turn on AC." officeAC.setPower(officeController,"On") change_counter = 20 elif officeSensor.insideTemp > float(88.5): print "Action: Turn on AC." officeAC.setPower(officeController,"On") change_counter = 20 #If change_counter was previously set, decrement counter by 1 every minute if change_counter > 0: change_counter -= 1 print change_counter print "\n"
def __init__(self): self.__service = controller() self.path = Population(0, 0) self.fitnesses = []
def startGame(self, mode: int): #E3, M4, H5 self.control = controller(mode) self.g_score = tkinter.StringVar() self.h_score = tkinter.StringVar() self.g_score.set(f'Ghost {self.control.AIScore}') self.h_score.set(f'User {self.control.UserScore}') self.vocb = '' self._title = tkinter.Label(master=self._dialog, text="Ghost Game", font=('Old Europe', 48), background='#F06824') self._title.grid(row=0, column=0, columnspan=3, padx=20, pady=20, sticky=tkinter.N) button_frame = tkinter.Frame(master=self._dialog, background='#F06824') button_frame.grid(row=0, column=2, padx=8, pady=20, sticky=tkinter.E + tkinter.N) restart = tkinter.Button(master=button_frame, text="RESTART", font=('Old Europe', 18), command=self._restartCommand) restart.grid(row=0, column=0, padx=5, pady=5) exit = tkinter.Button(master=button_frame, text="EXIT", font=('Old Europe', 18), command=self._exitCommand) exit.grid(row=1, column=0, padx=5, pady=5) self.canvas = tkinter.Canvas( master=self._dialog, width=500, height=200, background='orange', ) self.canvas.grid(row=1, column=0, sticky=tkinter.W + tkinter.E + tkinter.N + tkinter.S) self.canvas.bind("<Configure>", self._on_canvas_revized) score_board = tkinter.Frame(master=self._dialog, background='#F16F29') score_board.grid(row=0, column=0, padx=20, pady=20, sticky=tkinter.W + tkinter.N) score_H = tkinter.Label( master=score_board, textvariable=self.h_score, font=DEFAULT_FONT, background='#F16F29', ) score_H.grid( row=0, column=0, columnspan=3, padx=20, pady=20, ) score_G = tkinter.Label(master=score_board, textvariable=self.g_score, font=DEFAULT_FONT, background='#F16F29') score_G.grid( row=1, column=0, columnspan=3, padx=20, pady=20, ) self.g_image = Image.open("ghost_picture.jpg") self.g_image = ImageTk.PhotoImage(self.g_image) ghost_l = Label(master=button_frame, image=self.g_image) # ghost_l.image = self.g_image # ghost_l.pack() ghost_l.grid( row=2, column=0, columnspan=3, padx=8, pady=20, ) # ghost_l.place(x=0, y=0, relwidth=1, relheight=1) self._dialog.bind('<Key>', self.get_key) self._dialog.rowconfigure(5, weight=1) self._dialog.columnconfigure(1, weight=1)
def __init__(self): self.control = controller(self) self.input_array = []
"группа", "добавленно" ) self.form_add_group.destroy() def send_data_day(self): """ добавление в файл дни :return: """ get_date_from_button = self.textDay.get() check = int(self.textDay.get()) if check < 1: print("error") else: if adapter.set_day_in_semester(get_date_from_button): messagebox.showwarning( "дни", "добавленно" ) self.form_day_semester.destroy() adapter = controller() start = gui() # создание контроллера
passMiddlePoint = False nearGoal = False #defining the radius at every trajectory point dx = np.gradient(traj[:,0]) dy = np.gradient(traj[:,1]) tangent = np.arctan2(dy,dx) xp = gaussian_filter1d(traj[:,0], sigma = 10, order =1) yp = gaussian_filter1d(traj[:,1], sigma = 10, order =1) xpp = gaussian_filter1d(traj[:,0], sigma = 10, order =2) ypp = gaussian_filter1d(traj[:,1], sigma = 10, order =2) curvature = np.abs(xp*ypp - yp*xpp)/(xp**2 + yp**2)**1.5 for i in range(n): command = controller(traj, vehicle, tangent, curvature, i) vehicle.update(command = command) # termination check disError,nearIdx = closest_node(vehicle.state.X, vehicle.state.Y, traj) stepToMiddle = nearIdx - len(traj)/2.0 if abs(stepToMiddle) < 100.0: passMiddlePoint = True print('middle point passed') nearGoal = nearIdx >= len(traj)-50 if nearGoal and passMiddlePoint: print('destination reached!') break # record states X.append(vehicle.state.X) Y.append(vehicle.state.Y)