def main(): if len(sys.argv) != 3: print( "Wrong number of arguments: ./project2.py, <path to csv file>, <year for which u want diagrams>" ) exit(1) # Czytanie nazwy/sciezki do pliku try: filename = sys.argv[1] except IndexError as error: print("Problem with reading a path to file:", error) exit(1) open_and_parse_csvfile(filename) # Parsowanie pliku # Czytanie i parsowanie roku try: year = sys.argv[2] year_int = int(year) if year_int < 1998 or year_int > 2012: print("Year should be between 1998 and 2012.") exit(1) except IndexError as error: print("Problem with reading year for diagrams:", error) exit(1) except ValueError as error: print("Year is not a int:", error) exit(1) # Zmienne do rysowania state_array = [] total_production_array = [] production_value_array = [] # Wyciagam dane do wykresu dla danego roku for elem in object_array: if elem.get_state(year_int) is not False: state_array.append(elem.get_state(year_int)) if elem.get_total_production(year_int) is not False: total_production_array.append(elem.get_total_production(year_int)) if elem.get_production_value(year_int) is not False: production_value_array.append(elem.get_production_value(year_int)) # Rysuje wykresy print("In case you forgot, diagrams are for year:", year) drawer1 = Drawer("total production", state_array, total_production_array) drawer1.draw_bar() drawer2 = Drawer("production value", state_array, production_value_array) drawer2.draw_bar()
def initialize(self): self.title = "CGP2" self.toppanel = Tk.Frame(self) self.toppanel.pack(side=Tk.TOP) Tk.Button(self.toppanel, text="Choose an image", command=self.fileselecthandler).pack(side=Tk.LEFT) self.botpanel = Tk.Frame(self) self.botpanel.pack() self.canvas = Tk.Canvas(self.botpanel, width=WIDTH, height=HEIGHT, bg='white') self.img = Tk.PhotoImage(width=WIDTH, height=HEIGHT) self.canvas.create_image((0, 0), image=self.img, anchor="nw") self.canvas.bind('<ButtonRelease-1>', self.onEnd) self.canvas.pack(fill=Tk.BOTH, expand=1) combooptions = ["Polygon Fill", "Region Fill"] neighOptions = [4, 8] self.neighsVar = Tk.StringVar(self) self.filter = Tk.StringVar(self) self.filter.set(combooptions[0]) self.neighsVar.set(neighOptions[0]) self.combobox = apply(Tk.OptionMenu, (self.toppanel, self.filter)+tuple(combooptions)) self.combobox.pack(side=Tk.LEFT) self.neighs = apply(Tk.OptionMenu, (self.toppanel, self.neighsVar)+tuple(neighOptions)) self.neighs.pack(side=Tk.LEFT) self.drawer = Drawer(self.img) Tk.Button(self.toppanel,text='Select Color', command=self.getColor).pack() self.mainloop()
def process_video(): cap = cv2.VideoCapture(VIDEO) hasFrame, frame = cap.read() vid_writer = cv2.VideoWriter('output.avi', cv2.VideoWriter_fourcc('M', 'J', 'P', 'G'), 10, (frame.shape[1], frame.shape[0])) estimator = PoseEstimator() while cv2.waitKey(1) < 0: hasFrame, frame = cap.read() frameCopy = np.copy(frame) if not hasFrame: cv2.waitKey() break drawer = Drawer(frameCopy) prediction = estimator.predict(frame) points = estimator.get_rescaled_points(prediction, frame, 0.2) drawer.draw_skeleton(points) cv2.imshow('Output-Skeleton', frameCopy) vid_writer.write(frameCopy) vid_writer.release()
def __init__(self): pygame.init() # Initializes the pygame class. self.isRunning = True self.model = Model() #3 self.controller = Controller(self.model) #5 self.drawer = Drawer(self.model) #7 self.clock = pygame.time.Clock()
def __init__(self): self.iteration = 0 cfg.load() self.plane = Plane(cfg.get("width"), cfg.get("height"), cfg.get("radius"), cfg.get("map_type")) self.population = Population() self.population.scatter(self.plane) self.drawer = Drawer() pass
def draw_solution_step_by_step(self, solution, k_delta): drawer = Drawer(self.path_planner) N = self.path_planner.parameters.N k = 0 while k < N - 1: drawer.draw_path_for_all_robots_step_by_step( solution.path, self.robots, self.tasks, k) k = k + k_delta drawer.draw_path_for_all_robots_step_by_step(solution.path, self.robots, self.tasks, N - 1)
def main(): worker = DriveAnalyzer() try: data = worker.get_files() except ValueError as e: print(e.args) return if data is None: print('No files found') return drawer = Drawer(data) drawer.run()
def GenOneCertificate(self): Year = self.spinBox.value() Author = self.lineEdit.text() Title = self.lineEdit_2.text() Award = self.comboBox.currentText() Content = self.textEdit.toPlainText() Stamp = self.comboBox_7.currentText() Quarter = self.comboBox_6.currentText() Category = self.comboBox_2.currentText() if Content == "" or Author == "" or Title == "": self.textEdit_3.setText("请输入必要的作品信息!") else: myDrawer = Drawer(Stamp, Category, Quarter, Year) myDrawer.DrawCertificate(Award, Title, Author, Content)
def runSingleSimulation(self, path): reader = FilesReader(path + 'animation_dynamic') mapSize, maxSpeed = reader.readStatic(path + 'animation_static') drawer = Drawer(int(mapSize * 1000), maxSpeed) positions = reader.readNextPosition() drawer.firstUpdate() time.sleep(4) while len(positions) > 0: drawer.update(positions) positions = reader.readNextPosition() skipPositions = 50 while skipPositions > 0: reader.readNextPosition() skipPositions -= 1
def process_image(): estimator = PoseEstimator() frame = cv2.imread(IMG) frameCopy = np.copy(frame) # TODO Why copy? drawer = Drawer(frameCopy) prediction = estimator.predict(frame) points = estimator.get_rescaled_points(prediction, frame, 0.2) drawer.draw_skeleton(points) cv2.imshow('Output-Keypoints', frameCopy) cv2.imwrite('Output-Keypoints.jpg', frameCopy) cv2.waitKey(0) cv2.destroyAllWindows()
def initialize(self): self.title = "CGP5" self.canvas = Tk.Canvas(self.botpanel, width=MainWindow.WIDTH, height=MainWindow.HEIGHT, bg="#F5F1DE") self.canvas.pack() self.raster = Tk.PhotoImage(width=MainWindow.WIDTH, height=MainWindow.HEIGHT) self.canvas.create_image((0, 0), image=self.raster, state="normal", anchor="nw") self.toppanel = Tk.Frame(self) self.toppanel.pack(side=Tk.TOP) self.botpanel = Tk.Frame(self) self.botpanel.pack() Tk.Button(self.toppanel, text="Choose an image", command=self.fileselecthandler).pack(side=Tk.LEFT) Tk.Button(self.toppanel, text="Draw", command=self.draw).pack(side=Tk.LEFT) self.imageLabel = Tk.Label(self.botpanel) self.imageLabel.pack() self.drawer = Drawer(self.raster) self.mainloop()
def __init__(self, main): pygame.init() self.main = main self.clock = pygame.time.Clock() self.display = pygame.display self.window = pygame.display.set_mode((700, 600), pygame.HWSURFACE) self.drawer = Drawer(self) self.keras_switch_false = pygame.image.load( os.path.dirname(os.path.realpath(__file__)) + "/data/images/switch_FALSE.png") self.keras_switch_true = pygame.image.load( os.path.dirname(os.path.realpath(__file__)) + "/data/images/switch_TRUE.png") self.keras = False self.rects_to_update = []
def run_single_simulation(self): # Initialise screen pygame.init() screen = pygame.display.set_mode((0, 0), pygame.FULLSCREEN) #screen = pygame.display.set_mode((500, 500)) # Fill background background = pygame.Surface(screen.get_size()) background = background.convert() background.fill((0, 0, 0)) # Display some text font = pygame.font.Font(None, 30) text = font.render("ESC to exit", 1, (255, 255, 255)) textpos = text.get_rect() textpos.centerx = 60 textpos.centery = 10 background.blit(text, textpos) # Blit everything to the screen screen.blit(background, (0, 0)) pygame.display.flip() drawer = Drawer(screen, self.reader.dimensions) flag = True running = True while running: for event in pygame.event.get(): if event.type == pygame.QUIT: running = False if event.type == pygame.KEYDOWN: if event.key == pygame.K_ESCAPE: running = False particles = self.read_positions() if particles is None: flag = False screen.blit(background, (0, 0)) if flag: drawer.update(particles) pygame.display.flip()
def GenAllCertificate(self): Year = self.spinBox.value() Stamp = self.comboBox_7.currentText() Quarter = self.comboBox_6.currentText() Category = self.comboBox_2.currentText() if self.File == "": self.textEdit_3.setText("请先导入文档!") else: self.ParseDocx3() if len(self.TitleList) == len(self.AuthorList) == len( self.ContentList) == len(self.AwardList): self.textEdit_3.setText("文档格式无误,正在自动生成所有奖状!") myDrawer = Drawer(Stamp, Category, Quarter, Year) for i in range(len(self.TitleList)): result = myDrawer.DrawCertificate(self.AwardList[i], self.TitleList[i], self.AuthorList[i], self.ContentList[i]) self.textEdit_3.setText("正在生成:" + result) else: self.textEdit_3.setText("文档格式不正确,请选择需要打印的输出信息!")
def __init__(self, main): pygame.init() self.main = main self.display = pygame.display self.window = pygame.display.set_mode((800, 480), pygame.FULLSCREEN) self.drawer = Drawer(self) self.keras_switch_false = pygame.image.load( os.path.dirname(os.path.realpath(__file__)) + "/data/images/switch_FALSE.png") self.keras_switch_true = pygame.image.load( os.path.dirname(os.path.realpath(__file__)) + "/data/images/switch_TRUE.png") self.keras = False self.streaming = False self.rects_to_update = [] #needed for webcam-camera, which doesn't work yet. self.camera = None self.camsize = (320, 240) self.clock = pygame.time.Clock()
def main(): drawer = Drawer() drawer.run()
# Instanciate classes player_racket = Racket(( WIDTH - racket_width*2, HEIGHT // 2 - racket_height // 2), racket_width, racket_height) bot_racket = Racket(( racket_width, HEIGHT // 2 - racket_height // 2), racket_width, racket_height) ball = Ball((WIDTH // 2 - racket_width // 2, HEIGHT // 2 - racket_width // 2), racket_width, WIDTH // 80) controller = Controller(WIDTH, HEIGHT, player_racket, bot_racket, ball) drawer = Drawer(screen, WIDTH, HEIGHT, controller, player_racket, bot_racket, ball) # Game loop running = True clock = pygame.time.Clock() framerate = 80 controller.release_ball(time.time()) while running: for event in pygame.event.get(): if event.type == pygame.QUIT: running = False if event.type == pygame.KEYDOWN: pass
infile.close() else: outfile=open(path+parameters_file["Name"],'wb') pickle.dump(parameters,outfile) outfile.close() parameters.parameters_file=parameters_file parameters.samples_file=samples_file parameters.function_frame_file=function_frame_file parameters.solution_file=solution_file # Setting up path_planner=Path_Planner(parameters) path_planner.set_up(path) Drawer(path_planner).draw_full_example() # Function frame if parameters.function_frame_file["Read"]: print("...Reading function frame...") infile=open(path+parameters.function_frame_file["Name"],'rb') function_frame=pickle.load(infile) infile.close() else: function_frame=Function_Frame(parameters,path_planner) print("...Saving function frame...") outfile=open(path+parameters.function_frame_file["Name"],'wb') pickle.dump(function_frame,outfile) outfile.close() # Forward greedy
def draw_solution(self, solution): drawer = Drawer(self.path_planner) drawer.draw_path_for_all_robots(solution.path, self.robots, self.tasks)
from Data import Data from Drawer import Drawer from Neuronas import Perceptron, Adaline data = Data() """ Ahora mostramos como evoluciona el numero de errores con las epocas en nuestro Perceptron Vemos que a la quinta epoca dejamos de tener errores y parece que la neurona esta entrenada """ ppn = Perceptron(m=0.1, n_iter=10) ppn.entrenar(data.X, data.y) """ Ahora hacemos una funcion para dibujar el limite de decision """ drawer = Drawer() drawer.plot_decision_regions(data, classifier=ppn) drawer.draw_plots(data) # se superpone la recta de 0 = w2x2 + w1x1 + w0 => x2 = -w1x1/w2 - w0/w2 con xmin y xmax. drawer.drawLine(-ppn.w[1] / ppn.w[2], -ppn.w[0] / ppn.w[2], data.X[:, 0].min() - 1, data.X[:, 0].max() + 1) drawer.draw()
def run(self): Generator = Generate() importNetwork = load_model(self.networkName) rl = RLsys(4, importNetwork.input_shape[2]) rl.qnet.network = importNetwork rl.changeEpsilon(0) testProbs = [0.1] draw = Drawer() for prob in testProbs: numberOfLogicalErrorsRL = 0 numberOfLogicalErrorsMWPM = 0 Generator.DataGeneration(prob) humRep = np.load('ToricCodeHumanTest.npy') comRep = np.load('ToricCodeComputerTest.npy') size = comRep.shape[0] for i in range(comRep.shape[2]): state = comRep[:, :, i] human = humRep[:, :, i] env = Env(state, human, checkGroundState=True) ''' blossomReward = 0 if np.count_nonzero(state) > 0: state_ = np.copy(state) state_ = self.labelState(state_,size) BlossomObject = Blossom(state_) MWPM = BlossomObject.readResult() Benv = BEnv(state_, human, checkGroundState = True) for element in MWPM: error1 = element[0]+1 error2 = element[1]+1 blossomReward, _ = Benv.blossomCancel(error1, error2) if blossomReward != Benv.correctGsR: numberOfLogicalErrorsMWPM += 1 ''' r = env.correctGsR numIter = 0 if self.graphix: print(f"state before correction {i}: ") draw.Draw(state, human) while len(env.getErrors()) > 0: numIter = numIter + 1 observation = env.getObservation() a, e = rl.choose_action(observation) r = env.moveError(a, e) if numIter > 50: r = -1 break if self.graphix: print(f"state after correction {i}: ") draw.Draw(env.state, env.humanState) if r != env.correctGsR: numberOfLogicalErrorsRL += 1 if ((i + 1) % 100 == 0): print("Iteration: ", str(i)) print("Logical error probability RL agent: ", numberOfLogicalErrorsRL / (i + 1))
def draw(self): if self.chromosome == None: return None Drawer(self)
from Robot import Robot from Rewards import Rewards from Drawer import Drawer import getch import random # Set initial position robot = Robot(3, 9) r1 = Rewards(random.randint(1, 10), random.randint(1, 10), 'Coin') r2 = Rewards(random.randint(1, 10), random.randint(1, 10), 'Gold') r3 = Rewards(random.randint(1, 10), random.randint(1, 10), 'Weapon') rewards = [r1, r2, r3] print(r1, r2, r3, end='\n') drawer = Drawer(robot, rewards) def caller(number): options = { 67: robot.moveRight, 68: robot.moveLeft, 65: robot.moveUp, 66: robot.moveDown } func = options.get(number, '') if (func != ''): func() drawer.draw(robot) while True:
def __init__(self, app): """ MainWindow initialization """ super(MainWindow, self).__init__() ## app self.app = app ## ui object self.ui = QUiLoader().load("mainwindow.ui") self.ui.show() self.ui.setWindowTitle("RoboAide") self.setMinimumHeight(100) self.setMinimumWidth(250) # self.setMaximumHeight(200) # self.setMaximumWidth(800) self.setIcon() self.msgMu = QMutex() self.numberOfMotors = 6 self.s, self.messageSize = makeStruct() # Connect button signals self.ui.calibrateVerticalAxisButton.clicked.connect( self.calibrateVerticalAxis) self.ports_list = scanAvailablePorts() self.populatePortsList() # --------------- ## Dictionnary of all motor objects self.dictMot = dict() for i in range(1, self.numberOfMotors + 1): mot = Motor(self, "motor" + str(i)) self.dictMot[mot.getName()] = mot # --------------- ## List of drawers self.drawersList = [] for i in range(3): self.drawersList.append(Drawer(self, "drawer" + str(i + 1))) self.updateSliderPositions() ## ListOfSequencesHandler object self.listOfSequencesHandler = ListOfSequencesHandler( self, self.dictMot) # load the last save loadSequences(self.listOfSequencesHandler, self.dictMot) # Connect the slider signals self.ui.slider_mot1.sliderMoved.connect(lambda: self.dictMot[ "motor1"].setGoalPosition(self.ui.slider_mot1.value())) self.ui.slider_mot2.sliderMoved.connect(lambda: self.dictMot[ "motor2"].setGoalPosition(self.ui.slider_mot2.value())) self.ui.slider_mot3.sliderMoved.connect(lambda: self.dictMot[ "motor3"].setGoalPosition(self.ui.slider_mot3.value())) self.ui.slider_mot4.sliderMoved.connect(lambda: self.dictMot[ "motor4"].setGoalPosition(self.ui.slider_mot4.value())) self.ui.slider_mot5.sliderMoved.connect(lambda: self.dictMot[ "motor5"].setGoalPosition(self.ui.slider_mot5.value())) self.ui.slider_mot6.sliderMoved.connect(lambda: self.dictMot[ "motor6"].setGoalPosition(self.ui.slider_mot6.value())) # Connect button signals self.ui.calibrateVerticalAxisButton.clicked.connect( self.calibrateVerticalAxis) # Connect drawer buttons signals self.ui.drawer1Open.clicked.connect(self.drawersList[0].open) self.ui.drawer2Open.clicked.connect(self.drawersList[1].open) self.ui.drawer3Open.clicked.connect(self.drawersList[2].open) self.ui.drawer1Close.clicked.connect(self.drawersList[0].close) self.ui.drawer2Close.clicked.connect(self.drawersList[1].close) self.ui.drawer3Close.clicked.connect(self.drawersList[2].close) # Connect the tab changed with updating the sliders self.ui.tabWidget.currentChanged.connect(self.updateSliderPositions) # Serial communication ## Outgoing message deque self.msgDeque = deque(maxlen=3) ## Stop indicator for the motors self.shouldStop = False ## Message reception QThread object self.msgReception = MessageReception(self) ## Message transmission QThread object self.msgTransmission = MessageTransmission(self) self.app.aboutToQuit.connect(self.msgReception.stop) self.app.aboutToQuit.connect(self.msgTransmission.stop) self.comm = None self.serialConnected = None try: with open('SavePort.json') as save: savedPort = json.load(save) for index in range(1, len(self.ports_list)): if self.ports_list[index].device == savedPort: self.ui.portselection.setCurrentIndex(index) self.connect_port(savedPort) else: print("The last port is not available") except FileNotFoundError: print("SavePort file not found") self.ui.portselection.currentIndexChanged.connect(self.connect_port)
BLUE = (0, 0, 255) # Game variables game_size = 5 # set WIDTH and HEIGHT divisor for proper screen grid_width = 4 * game_size grid_height = 3 * game_size head_width = WIDTH // grid_width head_height = HEIGHT // grid_height head_pos = (grid_width // 2, grid_height // 2) orientation = None grid_on = False # Instanciate classes head = Tail(head_pos, True, GREEN) grid = Grid(grid_width, grid_height, head) drawer = Drawer(screen, WIDTH, HEIGHT, grid, head) grid.generate_fruit() # Game loop running = True clock = pygame.time.Clock() moved_in_this_frame = False paused = False framerate = 15 while running: for event in pygame.event.get(): if event.type == pygame.QUIT: running = False if event.type == pygame.KEYDOWN:
def __init__(self, maxN, minN): self.root = None self.maxN = maxN self.minN = minN self.drawer = Drawer(self)
def __init__(self, frame_doc, out): self.__frame = frame_doc self.__out_doc = out self.drawer = Drawer()
from Drawer import Drawer if __name__ == "__main__": Drawer()
note_sum = (ord(note[0].lower()) - 97) * 2 # Convert ABCDEFG to a number 0-7 if len(note) > 1: # then it is a sharp note_sum += 1 # note_sum is 0-13 noteoctave_sum = octave * note_sum # noteoctave_sum is 0-65. We want to get it into the range of 0.0 - 1.0, so... hue = note_sum / 13.0 random_hue = hue + ( r.randint(-self.random_factor, self.random_factor) / 100.0) color = colour.Color(hsl=(random_hue, 1, 0.5)) elif not msg.startswith("note:"): count = int(msg) self.graphics.add_energy_to_system(count, color) self.drawer.draw(self.graphics) if __name__ == "__main__": # need to get height and width as args from Drawer import Drawer from BodyManager import BodyManager, Body WIDTH = int(config['DEFAULT']['SCREEN_WIDTH']) HEIGHT = int(config['DEFAULT']['SCREEN_HEIGHT']) b = Body(WIDTH / 2, HEIGHT / 2, 100) bm = BodyManager(b) bm.generate_bodies(15) d = Drawer() ar = AudioReceiver(bm, d) d.pyglet_clock.schedule_interval(ar.poll, 0.01) d.pyglet.app.run()
screen = pygame.display.set_mode((WIDTH, HEIGHT)) pygame.display.set_caption("Shortest path finder") # Setup sizes width_rectangle_amount = 60 # optional value, WIDTH divisor preferred height_rectangle_amount = 30 # optional value, HEIGHT divisor preferred rectangle_width = WIDTH // width_rectangle_amount rectangle_height = HEIGHT // height_rectangle_amount vertical_line_width = rectangle_width // 10 horizontal_line_width = rectangle_height // 10 # Instantiate classes grid = Grid(width_rectangle_amount, height_rectangle_amount) rectangle_controller = RectangleController(grid) grid.rectangle_controller = rectangle_controller drawer = Drawer(WIDTH, HEIGHT, screen, grid, rectangle_controller, rectangle_width, rectangle_height, vertical_line_width, horizontal_line_width) # Other variables created_first_rectangle = False next_rectangle_group_id = 0 # Program loop running = True user_input_allowed = True clock = pygame.time.Clock() while running: for event in pygame.event.get(): if event.type == pygame.QUIT: running = False