def __init__(self, *args): super().__init__(*args) plants = [Plant("Plant 1", 0xa0), Plant("Plant 2", 0xb0)] available_ports = list([port.device for port in comports()]) self.portSelector = PortSelector(available_ports) self.portSelector.show() self.portSelector.portSelected.connect(self.set_port) self.portSelector.canceled.connect(self.quit) self.main_win = MainWindow()
def initplants(plants): # init three groups of plants with different sizes for i in range(3): loc = PVector(random(170, 220), height) tall = int(random(80, 130)) plants.append(Plant(loc, tall)) for j in range(3): loc = PVector(random(120, 150), height) tall = int(random(40, 80)) plants.append(Plant(loc, tall)) for k in range(2): loc = PVector(random(220, 240), height) tall = int(random(40, 60)) plants.append(Plant(loc, tall)) return plants
def getAllPlants(self): records = self.sheet.getAllRecords() plants = [ Plant(int(record[self.columnNames[0]]), record[self.columnNames[1]], datetime.datetime.strptime(record[self.columnNames[2]], '%Y-%m-%d').date(), int(record[self.columnNames[3]])) for record in records ] return plants
def get_filtered_plants(self, species, dec_or_evg): print("species is", len(species)) print("doe is", len(dec_or_evg)) if len(species) == 0 and len(dec_or_evg) == 0: print("not filtering") return self.get_all_plants() cursor = self._connection.cursor() print("filtering") stmtStr, vals = self.create_filter_stmt(species, dec_or_evg) cursor.execute(stmtStr, vals) plants = [] row = cursor.fetchone() while row is not None: plant = Plant(str(row[0]), str(row[1]), str(row[2]), str(row[3]), str(row[4])) plant = Plant.getDict(plant) plants.append(plant) row = cursor.fetchone() cursor.close() return plants
def evaluate(self): """runs the plant sim and returns (score, run_data)""" plant = Plant(lead_relevancy=self.lead_relevancy, speed=self.speed, distance_lead=self.distance_lead) last_live100 = None event_queue = sorted(self.cruise_button_presses, key=lambda a: a[1])[::-1] plot = ManeuverPlot(self.title) buttons_sorted = sorted(self.cruise_button_presses, key=lambda a: a[1]) current_button = 0 while plant.current_time() < self.duration: while buttons_sorted and plant.current_time( ) >= buttons_sorted[0][1]: current_button = buttons_sorted[0][0] buttons_sorted = buttons_sorted[1:] print "current button changed to", current_button grade = np.interp(plant.current_time(), self.grade_breakpoints, self.grade_values) speed_lead = np.interp(plant.current_time(), self.speed_lead_breakpoints, self.speed_lead_values) distance, speed, acceleration, distance_lead, brake, gas, steer_torque, fcw, live100 = plant.step( speed_lead, current_button, grade) if live100: last_live100 = live100[-1] d_rel = distance_lead - distance if self.lead_relevancy else 200. v_rel = speed_lead - speed if self.lead_relevancy else 0. if last_live100: # print last_live100 #develop plots plot.add_data(time=plant.current_time(), gas=gas, brake=brake, steer_torque=steer_torque, distance=distance, speed=speed, acceleration=acceleration, up_accel_cmd=last_live100.upAccelCmd, ui_accel_cmd=last_live100.uiAccelCmd, uf_accel_cmd=last_live100.ufAccelCmd, d_rel=d_rel, v_rel=v_rel, v_lead=speed_lead, v_target_lead=last_live100.vTargetLead, pid_speed=last_live100.vPid, cruise_speed=last_live100.vCruise, jerk_factor=last_live100.jerkFactor, a_target=last_live100.aTarget, fcw=fcw) print "maneuver end" return (None, plot)
def build(self): # display a button with the text : Hello QPython #return btn1 # return Button(text='Hello QPython') layout = GridLayout(rows=2) flayout = GridLayout(cols=3, row_force_default=False, size_hint_y =0.8) global buttons buttons = [] for x in range(1,13): btn = Plant(text='Plot %s' % x, background_color=[0,1,0,1]) btn.bind(on_press=callback) flayout.add_widget(btn, ) buttons.append(btn) layout.add_widget(flayout) s_button = Button(text="sow", border = [16,16,16,16]) s_button.bind(on_press=sow) w_button = Button(text="water") w_button.bind(on_press=water) clayout = GridLayout(cols=3,size_hint_y=0.2) clayout.add_widget(s_button) clayout.add_widget(w_button) layout.add_widget(clayout) Clock.schedule_interval(self.mytime, 1.0/1.0) return layout
def place_plant(self, row, col): if not self._board[row][col].is_empty() or col >= self.width: print("cannot place plant there") return if not self.cash >= Plant.cost: print("you don't have enough cash") return self.cash -= Plant.cost self._board[row][col].enqueue(Plant())
def place_plant(self, row, col): if col < self.width-1 and self.board[row][col].isEmpty(): if self.cash >= Plant.cost: self.board[row][col].enqueue(Plant()) self.cash -= Plant.cost else: print("Bruh. You ain't got da dough for a plant") else: print("Nani deska? You can't place a plant there!")
def handle_event(self, e): if self.state != STATE_ON or sun.sun_score < self.score: return if e.type == SDL_MOUSEBUTTONDOWN and e.button == SDL_BUTTON_LEFT: pos = gobj.mouse_xy(e) if gobj.pt_in_rect(pos, self.get_bb()): # 식물 추가하기 m = Plant((e.x, get_canvas_height() - e.y), self.name) gfw.world.add(gfw.layer.plant, m) sun.sun_score -= self.score return True return False
def get_plant_by_id(self, id_num): cursor = self._connection.cursor() stmt = "SELECT * FROM plant_indiv WHERE primary_id = %s;" cursor.execute(stmt, [id_num]) row = cursor.fetchone() if row is not None: plant = Plant(str(row[0]), str(row[1]), str(row[2]), str(row[3]), str(row[4])) plant = Plant.getDict(plant) cursor.close() return plant
def create_random_plants(self, num): death_age = random.randint(1, 100) proliferation = random.randint(5, 10) space_req = random.randint(2, 6) energy_supplied = random.randint(10, 20) ID = self.generate_new_id(Plant) for i in range(num): x = random.randint(1, self.width - 1) y = random.randint(1, self.height - 1) self.objects.append( Plant(death_age, proliferation, space_req, energy_supplied, x, y, ID, self))
def vegetate(self): # grow a new plant if random.uniform(0, 100) < self.vegetation_rate: pos = (int(random.uniform(10, Simulation.window_width - 10)), int(random.uniform(10, Simulation.window_height - 10))) plant = Plant(pygame.Rect(pos[0], pos[1], 6, 6)) self.vegetation.append(plant) # check whether or not the plant was eaten and grow over time for plant in self.vegetation: eaten = self.eat(plant) if not eaten: if plant.bounds.width < 10 and random.uniform(0, 100) < 1: plant.bounds.width += 1 plant.bounds.height += 1
def search_in_range(self, south, north, east, west): cursor = self._connection.cursor() stmt, values = self.create_range_stmt(south, north, east, west) cursor.execute(stmt, values) plants = [] row = cursor.fetchone() while row is not None: plant = Plant(str(row[0]), str(row[1]), str(row[2]), str(row[3]), str(row[4])) plant = Plant.getDict(plant) plants.append(plant) row = cursor.fetchone() cursor.close() return plants
def get_all_plants(self): cursor = self._connection.cursor() stmt = "SELECT * FROM plant_indiv;" cursor.execute(stmt) plants = [] row = cursor.fetchone() while row is not None: plant = Plant(str(row[0]), str(row[1]), str(row[2]), str(row[3]), str(row[4])) plant = Plant.getDict(plant) plants.append(plant) row = cursor.fetchone() cursor.close() return plants
def load_from_proto(proto, db): logger = logging.getLogger() i2c = I2cController() pumps = { proto_pump.name: Pump(proto_pump, db, i2c) for proto_pump in proto.pumps } plants = {} for proto_plant in proto.plants: if proto_plant.pump_name not in pumps: logger.error("No pump found with name: " + proto_plant.pump_name) sys.exit(1) plants[proto_plant.name] = Plant(proto_plant, pumps[proto_plant.pump_name]) actions = [Action(action) for action in proto.actions] return Config(plants, pumps, actions, db, i2c)
def click(self, keys): pos = pygame.mouse.get_pos() result = self.get_organism(pos) # print the contents of the location if result is not None: print(result) else: if keys[pygame.K_o]: new_organism = Organism(pos[0], pos[1]) new_organism.randomize() self.population.append(new_organism) elif keys[pygame.K_f]: new_plant = Plant(pygame.Rect(pos[0], pos[1], 6, 6)) self.vegetation.append(new_plant) elif keys[pygame.K_p]: new_predator = Predator(pos[0], pos[1]) new_predator.randomize() self.population.append(new_predator)
def place_plant(self, row, col): if row >= self.height or col >= self.width or row < 0 or col < 0: raise ValueError( str(row) + " " + str(col) + " aint no coordinates I ever heard of! do they speak english in " + str(row) + " " + str(col) + "?!") elif self.board[row][col] is self.board[row][-1]: raise ValueError( "you're out on the edge, yeah! and the HOA says no planting on the edge." ) elif self.is_plant(row, col) or self.is_nonplant(row, col): raise ValueError( "easy there xhibit, you've already got something in that spot." ) if self.cash <= Plant.cost: raise ValueError( "poor boy from a poor family, spare not their lives so you can afford me." ) self.cash -= Plant.cost self.board[row][col].enqueue(Plant())
def __init__(self, name, max_time_period, max_plant_size): """ This is a game constructor. It is called to create a new Game :param name: string containing the name of the game :param max_time_period: integer containing the number of "rounds" (time periods) in a game """ # name of the game attribute if name is not None: self.game_name = str(name) else: self.ame_name = 'Plant' # current time period of the game. This value will be incremented as # the game goes on self.time_period = 1 # game duration in terms maximum number of time periods if max_time_period > 0: self.max_time_period = max_time_period else: self.max_time_period = 20 # plant's size to achieve before the end of the game (in inches) if max_plant_size > 0: self.max_plant_size = max_plant_size else: self.max_plant_size = 10 # the plant object to grow in the game self.plant = Plant() # the available water for the plant to use at current time period self.available_water = 0 # the available light for the plant to use at current time period self.available_light = 0 # the available nutrients for the plant to use at current time period self.available_nutrients = 0
logging.basicConfig(filename='app.log', filemode='w', format='%(name)s - %(levelname)s - %(message)s', level=logging.DEBUG) plants = [] # To Do # for each page # for num in range(1,449): response = requests.get( 'https://www.monrovia.com/plant-catalog/search/?start_page=14') soup = BeautifulSoup(response.text, 'html.parser') # Go through each link on page and create a plant object # Add plant to plant list plant_links = soup.find_all(class_='list-plant') for i in range(0, len(plant_links)): link = plant_links[i].find('a')['href'] logging.debug(i) logging.debug('Link: ' + link) # plant = Plant() plant = Plant(link) plants.append(plant) # Create CSV with plant data logging.debug('Plant data') logging.debug(plants) new_csv = CSV(plants, 'test.csv')
def test_game(file=None): print(style(HEADER, "---Start: Game Class checking---")) if file == None: print( style( WARNING, "You need to pass in a valid example file to check the Game Class" )) return erron = 0 o = Game(file) w = Wave(0, 0, 0) for r in range(o.height): for c in range(o.width): if (type(o.board[r][c]).__name__ != "Queue"): print(style(FAIL, "Your Board is not initialized properly")) return o.board[0][0].enqueue(Non_Plant()) if (hasattr(o, "is_nonplant")) == 1: UT_game.is_nonplant(o) else: print(style(WARNING, "No is_nonplant method in class")) erron += 1 o.board[1][1].enqueue(Plant()) if (hasattr(o, "is_plant")) == 1: erron += UT_game.is_plant(o) else: print(style(WARNING, "No is_plant method in class")) erron += 1 old_cash = o.cash if (hasattr(o, "is_nonplant") & hasattr(o, "remove")) == 1: o.remove(0, 0) UT_game.remove(o, old_cash) else: print(style(WARNING, "No remove method in class")) erron += 1 if (hasattr(o, "place_plant") & hasattr(o, "is_plant")) == 1: UT_game.place_plant(o) else: erron += 1 print(style(WARNING, "No place_plant method in class")) if (hasattr(o, "place_nonplant")) == 1: o.place_nonplant(0) UT_game.place_nonplant(o, 0) else: erron += 1 print(style(WARNING, "No place_nonplant method in class")) if (hasattr(o, "place_wave")) == 1: UT_game.place_wave() else: erron += 1 print(style(WARNING, "No place_wave method in class")) if (hasattr(o, "plant_turn")) == 1: UT_game.plant_turn() else: erron += 1 print(style(WARNING, "No plant_turn method in class")) if (hasattr(o, "nonplant_turn")) == 1: UT_game.nonplant_turn() else: erron += 1 print(style(WARNING, "No nonplant_turn method in class")) if (hasattr(o, "run_turn")) == 1: UT_game.run_turn() else: erron += 1 print(style(WARNING, "No run_turn method in class")) if (hasattr(o, "draw_card")) == 1: UT_game.draw_card(o) else: erron += 1 print(style(WARNING, "No draw_card method in class")) if erron == 0: print( style( OKGREEN, "Game Class, within tests perfect! Otherwise...good luck with the last 4 functions!!" )) else: print(style(OKBLUE, "\n--------(:P for the lack of error details ^_^)")) print( style( WARNING, "--------∆ IF YOU GET ALOT OF UNEXPECTED ERRORS, MAKE SURE YOU PROPERLY COPIED AND PASTED THE CODE GIVEN TO YOU #_#" ) + end_style())
def place_plant(self, row, col): if col != self.width - 1 and self.is_nonplant(row, col) == False and self.is_plant(row, col) == False: plant = Plant() self.board.item[row][col].enqueue(plant) self.cash -= Plant.cost
def createPlant(args): """ Creates a new Plant XML file from the plantName. """ Plant().toXmlFile(plantFileNoExists(args[0]))
def test_plant(): print(style(HEADER, "---Start: Plant Class checking---")) erron = 0 o = Plant() o2 = Plant() if (hasattr(o, "dmg") & hasattr(o, "hp")) == 0: print( style( WARNING, "Your Plant class doesn't inherit the properties of the Non_Plant" )) return if hasattr(o, "powerup") == 0: print( style(WARNING, "You didn't initialize your ") + style(UNDERLINE, "Plant") + end_style() + style(WARNING, " class properly")) return if hasattr(o, "cost") == 0: print( style( WARNING, "You didn't create a " + style(UNDERLINE, "cost") + end_style() + style(WARNING, " class variable for your function"))) return if (o.cost != 35): erron += 1 print( style(FAIL, "You didn't initialize" " the plant classes ") + style(UNDERLINE, "cost") + end_style() + style(FAIL, " class variable to ") + style(BOLD, "35") + end_style()) if o.powerup != 0: erron += 1 print( style(FAIL, "You didn't initialize" " the plant's ") + style(UNDERLINE, "powerup") + end_style() + style(FAIL, " to ") + style(BOLD, "0") + end_style()) prev_hp = o2.hp if hasattr(o, "attack") == 1: o.attack(o2) if (prev_hp - o2.hp) != (o.dmg + o.powerup): erron += 1 print( style(FAIL, "The ") + style(UNDERLINE, "attack") + end_style() + style(FAIL, " method, doesn't reduce the nonplant's hp enough") ) else: erron += 1 print( style(FAIL, "No ") + style(UNDERLINE, "attack") + end_style() + style(FAIL, " method in class")) if iscard: c = Card(10) prev_powerup = o.powerup if hasattr(o, "apply_powerup") == 1: o.apply_powerup(c) if (o.powerup != prev_powerup + c.power): erron += 1 print( style(FAIL, "The ") + style(UNDERLINE, "apply_powerup") + end_style() + style( FAIL, " method, doesn't increase the plant's powerup")) else: erron += 1 print( style(FAIL, "No ") + style(UNDERLINE, "apply_powerup") + end_style() + style(FAIL, " method in class")) else: erron += 1 print( style(FAIL, "Make a ") + style(UNDERLINE, "Card") + end_style() + style(FAIL, " class then we'll test the apply_powerup method")) prev_powerup = o.powerup if hasattr(o, "weaken_powerup") == 1: o.weaken_powerup() if (o.powerup != prev_powerup / 2): erron += 1 print( style(FAIL, "The ") + style(UNDERLINE, "weaken_powerup") + end_style() + style( FAIL, " method, doesn't decrease the plant's powerup appropriately" )) else: erron += 1 print( style(FAIL, "No ") + style(UNDERLINE, "weaken_powerup") + end_style() + style(FAIL, " method in class")) if erron == 0: print(style(OKGREEN, "Plant Class, perfect."))
def place_plant(self, row, col): dict1 = self.board[0] new_plant = Plant(35, 10) assert self.cash >= 0 self.cash -= new_plant.cost assert dict1[(row, col)] == None
self.channel = channel self.adc = ADC() @property def moisture(self): ''' Get the moisture strength value/voltage Returns: (int): voltage, in mV ''' value = self.adc.read_voltage(self.channel) return value Grove = GroveMoistureSensor Potato = Plant(300, 700) def moisture_level(m, plant): if 0 <= m and m < plant.minimum_moisture: result = 'Dry' elif plant.minimum_moisture <= m and m < plant.maximum_moisture: result = 'Moist' else: result = 'Wet' return result def sensor_readings(): from grove.helper import SlotHelper
screen = pygame.display.set_mode((SCREEN_SIZE)) # define plant preferences plant_1_pref = {'opt_sun': 50, 'opt_h2o': 20, 'h2o_loss_rate': 5} plant_2_pref = {'opt_sun': 100, 'opt_h2o': 20, 'h2o_loss_rate': 1} plant_prefs = [plant_1_pref, plant_2_pref] plant_1_voc = {'strength': 3, 'emittance': 50} plant_2_voc = {'strength': 5, 'emittance': 100} plant_voc = [plant_1_voc, plant_2_voc] # construct plants rect_list = [] for i in range(NUM_PLANT_TYPES): for j in range(int(NUM_AGENTS / NUM_PLANT_TYPES)): sprite = pygame.image.load("../assets/plant_" + str(i) + ".bmp") p = Plant(plant_prefs[i], randint(0, SCREEN_SIZE[0]), randint(0, SCREEN_SIZE[1]), mode.LIGHT, sprite, plant_voc[i]) while (len(agents) != 0 and p.rect.collidelist(rect_list) != -1): p.rect.centerx = randint(0, SCREEN_SIZE[0]) p.rect.centery = randint(0, SCREEN_SIZE[1]) rect_list.append(p.rect) agents.append(p) # Update loop running = True while (running): time.sleep(STEP_TIME) # clear screen screen.fill(WHITE) #update all agents for i in range(len(agents)): # update if not dead
from typing import Optional import httpx import json import asyncio from fastapi import FastAPI from plant import Plant from config import config plant = Plant(config) plant.start() app = FastAPI() @app.get('/') def read_root(): return {'yo': 'sup?'}
def on_enter_setup(self, event): print(Fore.BLUE + 'Setting up') self.led_controller.switch_green(False) self.led_controller.switch_blue(True) self.motor_controller.return_to_origin() self.plant = Plant()
car.fill((10,10,10)) car.set_alpha(128) pygame.draw.rect(car, c, (METER*1.25, 0, METER*CAR_WIDTH, METER*CAR_LENGTH), 1) return car if __name__ == "__main__": pygame.init() display = pygame.display.set_mode((1000, 1000)) pygame.display.set_caption('Plant UI') car = car_w_color((255,0,255)) leadcar = car_w_color((255,0,0)) carx, cary, heading = 10.0, 50.0, 0.0 plant = Plant(100, distance_lead = 40.0) control_offset = 2.0 control_pts = zip(np.arange(0, 100.0, 10.0), [50.0 + control_offset]*10) def pt_to_car(pt): x,y = pt x -= carx y -= cary rx = x * math.cos(-heading) + y * -math.sin(-heading) ry = x * math.sin(-heading) + y * math.cos(-heading) return rx, ry def pt_from_car(pt): x,y = pt rx = x * math.cos(heading) + y * -math.sin(heading)
import csv from ast import literal_eval from simulator_params import * """ Preset values for plant parameters and locations, for convenience when testing. To do a non-deterministic simulation setup, use the `random` preset. Each preset has a name as the key (used as the command line argument for --setup when running the simulator), and a dictionary of setup params as the value. Setup params must at minimum include: - A seed to allow deterministic runs (or None if randomness is desired) - A FUNCTION that returns a list of initial plants (so we don't create all the plants unnecessarily) """ PLANT_PRESETS = { "single-plant": { "seed": 12345, "plants": lambda: [Plant(2, 2, color='g')] }, "control-and-3": { "seed": 38572912, "plants": lambda: [ Plant(20, 20, color='g'), Plant(23, 23, color='b'), Plant(22, 22, color='k'), Plant(40, 40, color='c') ] }, "greedy-plant-limited": { "seed": 6937103,