Best Python code snippet using robotframework-ioslibrary_python
camera_window.py
Source:camera_window.py  
1import sys2from PyQt5 import QtGui3from PyQt5.QtGui import *4from PyQt5.QtCore import *5from PyQt5.QtGui import *6from PyQt5.QtWidgets import *7from pascal_voc_writer import Writer8from time import sleep9import cv210from pc_utils import capture_data11import pyrealsense2 as rs12import numpy as np13import cv214import pcl15import os16from gui import aig_window_217import copy18import threading19import time20class Thread(QThread):21    changePixmap = pyqtSignal(QImage)22    imagesPixmap = pyqtSignal(np.ndarray)23    def run(self):24        self.pipeline, config = capture_data.init_capture_data()25        profile = self.pipeline.start(config)26        if profile:27            self.loop_break = True28        depth_sensor = profile.get_device().first_depth_sensor()29        depth_scale = depth_sensor.get_depth_scale()30        clipping_distance_in_meters = 131        clipping_distance = clipping_distance_in_meters / depth_scale32        align_to = rs.stream.color33        align = rs.align(align_to)34        while self.loop_break:35            frames = self.pipeline.wait_for_frames()36            aligned_frames = align.process(frames)37            depth_frame = aligned_frames.get_depth_frame()38            color_frame = aligned_frames.get_color_frame()39            spatial = rs.spatial_filter()40            spatial.set_option(rs.option.holes_fill, 3)41            depth_frame = spatial.process(depth_frame)42            Pixel_Coord, segmented_cloud = capture_data.get_object_points(color_frame, depth_frame)43            depth_image = np.asanyarray(depth_frame.get_data(),np.uint8)44            color_image = np.asanyarray(color_frame.get_data())45            color_image_copy = copy.deepcopy(color_image)46            if len(Pixel_Coord) > 0:47                color_image_copy, object_mask, bbox_coordinates = capture_data.get_mask(Pixel_Coord, color_image_copy)48            else:49                object_mask = np.zeros((480, 640, 3), np.uint8)50                bbox_coordinates = [0,0,640,480]51            if not depth_frame or not color_frame:52                continue53            # for i in Pixel_Coord:54            #     cv2.circle(color_image_copy, (int(i[0]), int(i[1])), 2, (0, 255, 0), -1)55            depth_colormap = cv2.applyColorMap(cv2.convertScaleAbs(56                depth_image, alpha=0.03), cv2.COLORMAP_JET)57            images = np.hstack((color_image_copy, object_mask))58            images_raw = np.hstack((color_image, object_mask))59            full_data = [images_raw,bbox_coordinates,segmented_cloud,depth_image]60            full_data = np.array(full_data)61            rgbImage = cv2.cvtColor(images, cv2.COLOR_BGR2RGB)62            h, w, ch = rgbImage.shape63            bytesPerLine = ch * w64            convertToQtFormat = QtGui.QImage(65                rgbImage.data, w, h, bytesPerLine, QtGui.QImage.Format_RGB888)66            p = convertToQtFormat.scaled(640, 240, Qt.KeepAspectRatio)67            self.changePixmap.emit(p)68            self.imagesPixmap.emit(full_data)69    def stop(self):70        self.loop_break = False71        # self.terminate()72class App(QWidget):73    def __init__(self, generator_options, save_folder_path):74        super().__init__()75        self.label_list = []76        self.title = 'b-it-bots -- Data Augmentor'77        self.setWindowIcon(QtGui.QIcon(os.path.dirname(78            os.path.realpath(__file__))+'/data/b-it-bots.jpg'))79        self.left = 10080        self.top = 10081        self.width = 10082        self.height = 10083        self._image_counter = []84        self.object_counter = 085        self.max_objects = 1086        self.generator_options = generator_options87        self.save_folder_path = save_folder_path88        self.initUI()89        self.show()90    @pyqtSlot(QImage)91    def setImage(self, image):92        self.label.setPixmap(QPixmap.fromImage(image))93    @pyqtSlot(np.ndarray)94    def capture_image(self, full_data ):95        if self.flag and full_data[2].size > 0 and self.object_counter<self.max_objects:96            self.time_stamp = time.time()97            print("inside save",self.object_counter+1)98            if self.toggle_switch.text()=="Stop":99                self.object_counter+=1100            # else:101            #     self.toggle_switch.setText("Start")102            #     self.toggle_switch.setStyleSheet("background-color: green")103            #     self.flag = False104            # print(,"point cloud data")105            self._image_counter[self.label_list.index(str(self.label_box.currentText()))] += 1106            name = str(self.label_box.currentText(107            ))+"_{}.png".format(self.time_stamp)108            annotation_name = str(self.label_box.currentText(109                        ))+"_{}.xml".format(self.time_stamp)110            pointcloud_name = str(self.label_box.currentText(111                        ))+"_{}.pcd".format(self.time_stamp)112            frame_name = str(self.label_box.currentText(113                        ))+"_{}".format(self.time_stamp)114            rgb_img = full_data[0][:, :640]115            mask_img = full_data[0][:, 640:]116            bbox_coordinates = full_data[1]117            obj_pixels = np.where(mask_img == 255)118            mask_img[obj_pixels] = self.label_list.index(str(self.label_box.currentText()))+1119            if self.save_rgb:120                cv2.imwrite(self.generator_options.get_image_path()+name, rgb_img)121            if self.save_semantic_label:122                cv2.imwrite(self.generator_options.get_label_path()+name, mask_img)123            if self.save_bbox:124                writer = Writer(self.generator_options.get_image_path()+name,rgb_img.shape[0],rgb_img.shape[1])125                writer.addObject(str(self.label_box.currentText()),bbox_coordinates[0],bbox_coordinates[2],bbox_coordinates[2],bbox_coordinates[3])126                writer.save(self.save_folder_path+"/captured_data/obj_det_label/"+annotation_name)127            if self.save_pointcloud:128                pcl.save(full_data[2],self.save_folder_path+"/captured_data/pointclouds/"+pointcloud_name)129            if self.save_depth:130                # print(full_data[3].get_frame_number())131                # adds frame numer at the end of filename yet to solve the issue132                # saver = rs.save_single_frameset(filename=self.save_folder_path+"/captured_data/depth_frames/"+frame_name)133                # saver.process(full_data[3])134                cv2.imwrite(self.save_folder_path+"/captured_data/depth_frames/"+name,full_data[3])135            self.flag = False136        elif self.object_counter==self.max_objects:137            # print("inside else loop")138            self.toggle_switch_status()139            # self.flag = False140            # sleep(1)141    def initUI(self):142        # capture_data.init_capture_data()143        # images = capture_data.capture_data()144        self.setWindowTitle(self.title)145        self.setGeometry(self.left, self.top, self.width, self.height)146        self.resize(700, 480)147        # create a label148        self.label = QLabel(self)149        self.label.move(30, 10)150        self.label.resize(640, 240)151        self.th = Thread(self)152        self.th.changePixmap.connect(self.setImage)153        self.th.start()154        self.button1 = QPushButton("Add", self)155        self.button1.clicked.connect(self.add_labels)156        self.button1.move(400, 260)157        self.button1.resize(80, 20)158        self.nameLabel_label = QLabel(self)159        self.nameLabel_label.setText('Labels :')160        self.nameLabel_label.move(240, 250)161        self.nameLabel_label.resize(50, 40)162        self.label_box = QComboBox(self)163        self.label_box.move(300, 260)164        for i in self.label_list:165            self.label_box.addItem(i)166        self.rgb_checkbox = QCheckBox("RGB",self)167        self.rgb_checkbox.move(50,300)168        self.rgb_checkbox.setChecked(True)169        self.save_rgb = True170        self.rgb_checkbox.stateChanged.connect(lambda:self.clickbox(self.rgb_checkbox))171        self.semantic_label_checkbox = QCheckBox("Semantic label",self)172        self.semantic_label_checkbox.move(150,300)173        self.semantic_label_checkbox.setChecked(True)174        self.save_semantic_label = True175        self.semantic_label_checkbox.stateChanged.connect(lambda:self.clickbox(self.semantic_label_checkbox))176        self.pointcloud_checkbox = QCheckBox("PointCloud",self)177        self.pointcloud_checkbox.setChecked(True)178        self.save_pointcloud = True179        self.pointcloud_checkbox.move(300,300)180        self.pointcloud_checkbox.stateChanged.connect(lambda:self.clickbox(self.pointcloud_checkbox))181        self.depth_checkbox = QCheckBox("Depth",self)182        self.depth_checkbox.setChecked(True)183        self.save_depth = True184        self.depth_checkbox.move(450,300)185        self.depth_checkbox.stateChanged.connect(lambda:self.clickbox(self.depth_checkbox))186        self.bbox_checkbox = QCheckBox("Bounding Box",self)187        self.bbox_checkbox.setChecked(True)188        self.save_bbox = True189        self.bbox_checkbox.move(550,300)190        self.bbox_checkbox.stateChanged.connect(lambda:self.clickbox(self.bbox_checkbox))191        self.timer_interval_label = QLabel("Capture interval in ms",self)192        self.timer_interval_label.move(100,340)193        self.timer_interval = QLineEdit(self)194        self.timer_interval.move(350,340)195        self.timer_interval.setText(str(1000))196        self.timer_interval.textChanged.connect(self.change_time_interval)197        self.onlyInt = QIntValidator()198        self.timer_interval.setValidator(self.onlyInt)199        self.max_objects_label = QLabel("Max objects per class",self)200        self.max_objects_label.move(100,370)201        self.max_objects_field = QLineEdit(self)202        self.max_objects_field.move(350,370)203        self.max_objects_field.setText(str(100))204        self.max_objects_field.textChanged.connect(self.change_max_objects)205        self.max_objects_field.setValidator(self.onlyInt)206        self.toggle_switch_label = QLabel("Start continous mode",self)207        self.toggle_switch_label.move(100,400)208        self.toggle_switch = QPushButton("Start",self)209        self.toggle_switch.setEnabled(False)210        self.toggle_switch.setStyleSheet("background-color: green")211        self.toggle_switch.move(350,400)212        self.toggle_switch.clicked.connect(self.toggle_switch_status)213        self.button1 = QPushButton("Save", self)214        self.button1.setEnabled(False)215        self.button1.clicked.connect(self.capture_img)216        self.button1.move(200, 440)217        self.button1.resize(80, 20)218        self.button2 = QPushButton("Finish", self)219        self.button2.setEnabled(False)220        self.button2.clicked.connect(self.finish_button)221        self.button2.move(400, 440)222        self.button2.resize(80, 20)223    def toggle_switch_status(self):224        if self.toggle_switch.text() == "Start":225            self.toggle_switch.setText("Stop")226            self.timer = QTimer(self)227            self.timer.start(int(self.timer_interval.text()))228            self.timer.timeout.connect(self.capture_img)229            self.toggle_switch.setStyleSheet("background-color: red")230        elif self.toggle_switch.text() == "Stop":231            self.timer.stop()232            self.toggle_switch.setText("Start")233            self.toggle_switch.setStyleSheet("background-color: green")234            self.object_counter = 0235        self.button_status()236    def change_time_interval(self):237        if self.toggle_switch.text() == "Stop":238            self.timer.stop()239            self.object_counter = 0240            self.toggle_switch.setText("Start")241            self.toggle_switch.setStyleSheet("background-color: green")242        self.button_status()243    def change_max_objects(self):244        if self.toggle_switch.text() == "Stop":245            self.timer.stop()246            self.object_counter = 0247            self.max_objects = int(self.max_objects_field.text())248            self.toggle_switch.setText("Start")249            self.toggle_switch.setStyleSheet("background-color: green")250        self.button_status()251    def add_labels(self):252        if self.toggle_switch.text()=="Stop":253            self.toggle_switch_status()254        text, ok = QInputDialog.getText(self, 'Text Input Dialog', 'Enter your name:')255        self.label_list.append(text)256        self.button_status()257        self.label_box.clear()258        for i in reversed(self.label_list):259            self.label_box.addItem(i)260        if len(self._image_counter) != len(self.label_list):261            self._image_counter.append(0)262        # print("inside add labels ", self._image_counter)263    # def continous_capture(self):264    def capture_img(self):265        self.flag = True266        if self.flag:267            self.th.imagesPixmap.connect(self.capture_image)268            # self.flag = False269    def button_status(self):270        if len(self.label_list) > 0 and (self.save_rgb or self.save_pointcloud271        or self.save_depth or self.save_bbox or self.save_semantic_label) and self.toggle_switch.text() == "Start":272            self.button1.setEnabled(True)273            self.button2.setEnabled(True)274            self.toggle_switch.setEnabled(True)275        elif len(self.label_list) > 0 and (self.save_rgb or self.save_pointcloud276        or self.save_depth or self.save_bbox or self.save_semantic_label) and self.toggle_switch.text() == "Stop":277            self.button1.setEnabled(False)278            self.button2.setEnabled(True)279        else:280            self.button1.setEnabled(False)281            self.button2.setEnabled(False)282    def finish_button(self):283        # self.th.pipeline.stop()284        file1 = open(self.save_folder_path+"/captured_data/labels.txt", "w")285        file1.write("__ignore__ \n_background_\n")286        for i in self.label_list:287            file1.write(i+"\n")288        file1.close()289        self.generator_options.set_labels_file_path(290            self.save_folder_path+"/captured_data/labels.txt")291        self.generator_options.set_max_objects(len(self.label_list))292        self.aig_window = aig_window_2.MainWindow(self.generator_options)293        self.aig_window.show()294        # self.th.pipeline.stop()295        self.th.stop()296        self.hide()297    def clickbox(self,checkbox):298        if checkbox.text() == "RGB":299            if checkbox.isChecked() == True:300                self.save_rgb = True301            elif checkbox.isChecked() == False:302                self.save_rgb = False303        elif checkbox.text() == "Semantic label":304            if checkbox.isChecked() == True:305                self.save_semantic_label = True306            elif checkbox.isChecked() == False:307                self.save_semantic_label = False308        elif checkbox.text() == "PointCloud":309            if checkbox.isChecked() == True:310                self.save_pointcloud = True311            elif checkbox.isChecked() == False:312                self.save_pointcloud = False313        elif checkbox.text() == "Depth":314            if checkbox.isChecked() == True:315                self.save_depth = True316            elif checkbox.isChecked() == False:317                self.save_depth = False318        elif checkbox.text() == "Bounding Box":319            if checkbox.isChecked() == True:320                self.save_bbox = True321            elif checkbox.isChecked() == False:322                self.save_bbox = False323        self.button_status()324if __name__ == '__main__':325    app = QApplication(sys.argv)326    ex = App()...The Lamp_Revisited.py
Source:The Lamp_Revisited.py  
...4class Lamp:5    def __init__(self, color, on=False):6        self.color = color7        self.on = on8    def toggle_switch(self):9        if self.on is False:10            self.on = True11        elif self.on is True:12            self.on = False13    def state(self):14        if self.on:15            return 'The lamp is on.'16        else:17            return 'The lamp is off.'18my_lamp = Lamp("Blue")19Test.assert_equals(my_lamp.color, "Blue")20Test.assert_equals(my_lamp.on, False)21Test.assert_equals(my_lamp.state(), "The lamp is off.")22# now switch it on23my_lamp.toggle_switch()24Test.assert_equals(my_lamp.state(), "The lamp is on.")25'''26Other people's solutions:271.28class Lamp(object):29    def __init__(self, color=None, on=False):30        self.color = color31        self.on = on32    33    def toggle_switch(self):34        self.on = not self.on35        36    def state(self):37        if self.on: s = 'on'38        else: s = 'off'39        return f'The lamp is {s}.'40        412.42class Lamp:43    def __init__(self, s):44        self.color = s45        self.on = 046    47    def toggle_switch(self):48        self.on ^= 149    50    def state(self):51        return f"The lamp is o{'fnf'[self.on::2]}."52        533.54class Lamp:55    def __init__(self, color):56        self.color = color57        self.on = False58    def toggle_switch(self):59        self.on = not self.on60    def state(self):61        return "The lamp is on." if self.on else "The lamp is off."...toggle.py
Source:toggle.py  
...3import sys4sys.stdin = open("../input.txt", "r")5si = sys.stdin.readline6INF = 9876543217def toggle_switch(idx, string):8    if string[idx] == "1":9        string[idx] = "0"10    else:11        string[idx] = "1"12def get_minimum_count(zero, b, a):13    ret = INF14    count = 015    if zero:16        count += 117        toggle_switch(0, b)18        toggle_switch(1, b)19    for i in range(1, N):20        if b[i - 1] == a[i - 1]:21            continue22        count += 123        toggle_switch(i - 1, b)24        toggle_switch(i, b)25        if i + 1 < N:26            toggle_switch(i + 1, b)27    if "".join(b) == "".join(a):28        return min(ret, count)29    return ret30N = int(si())31before = list(si().strip())32after = list(si().strip())33cnt1 = get_minimum_count(False, before[:], after[:])34cnt2 = get_minimum_count(True, before[:], after[:])35answer = min(cnt1, cnt2)...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!!
