Best Python code snippet using pyatom_python
widgets.py
Source:widgets.py  
1# coding=utf-82""" Generic Custom Widgets to use in this module """3from ipywidgets import *4from traitlets import *5class CheckRow(HBox):6    checkbox = Instance(Checkbox)7    widget = Instance(Widget)8    def __init__(self, widget, **kwargs):9        self.checkbox = Checkbox(indent=False,10                                 layout=Layout(flex='1 1 20', width='auto'))11        self.widget = widget12        super(CheckRow, self).__init__(children=(self.checkbox, self.widget),13                                       **kwargs)14        self.layout = Layout(display='flex', flex_flow='row',15                             align_content='flex-start')16    @observe('widget')17    def _ob_wid(self, change):18        new = change['new']19        self.children = (self.checkbox, new)20    def observe_checkbox(self, handler, extra_params={}, **kwargs):21        """ set handler for the checkbox widget. Use the property 'widget' of22        change to get the corresponding widget23        :param handler: callback function24        :type handler: function25        :param extra_params: extra parameters that can be passed to the handler26        :type extra_params: dict27        :param kwargs: parameters from traitlets.observe28        :type kwargs: dict29        """30        # by default only observe value31        name = kwargs.get('names', 'value')32        def proxy_handler(handler):33            def wrap(change):34                change['widget'] = self.widget35                for key, val in extra_params.items():36                    change[key] = val37                return handler(change)38            return wrap39        self.checkbox.observe(proxy_handler(handler), names=name, **kwargs)40    def observe_widget(self, handler, extra_params={}, **kwargs):41        """ set handler for the widget alongside de checkbox42        :param handler: callback function43        :type handler: function44        :param extra_params: extra parameters that can be passed to the handler45        :type extra_params: dict46        :param kwargs: parameters from traitlets.observe47        :type kwargs: dict48        """49        def proxy_handler(handler):50            def wrap(change):51                change['checkbox'] = self.checkbox52                for key, val in extra_params.items():53                    change[key] = val54                return handler(change)55            return wrap56        self.widget.observe(proxy_handler(handler), **kwargs)57class CheckAccordion(VBox):58    # widgets = Tuple()59    widgets = List()60    def __init__(self, widgets, **kwargs):61        # self.widgets = widgets62        super(CheckAccordion, self).__init__(**kwargs)63        self.widgets = widgets64    @observe('widgets')65    def _on_child(self, change):66        new = change['new'] # list of any widget67        newwidgets = []68        for widget in new:69            # constract the widget70            acc = Accordion(children=(widget,))71            acc.selected_index = None # this will unselect all72            # create a CheckRow73            checkrow = CheckRow(acc)74            newwidgets.append(checkrow)75        newchildren = tuple(newwidgets)76        self.children = newchildren77    def set_title(self, index, title):78        """ set the title of the widget at indicated index"""79        checkrow = self.children[index]80        acc = checkrow.widget81        acc.set_title(0, title)82    def set_titles(self, titles):83        """ set the titles for all children, `titles` size must match84        `children` size """85        for i, title in enumerate(titles):86            self.set_title(i, title)87    def get_title(self, index):88        """ get the title of the widget at indicated index"""89        checkrow = self.children[index]90        acc = checkrow.widget91        return acc.get_title(0)92    def get_check(self, index):93        """ get the state of checkbox in index """94        checkrow = self.children[index]95        return checkrow.checkbox.value96    def set_check(self, index, state):97        """ set the state of checkbox in index """98        checkrow = self.children[index]99        checkrow.checkbox.value = state100    def checked_rows(self):101        """ return a list of indexes of checked rows """102        checked = []103        for i, checkrow in enumerate(self.children):104            state = checkrow.checkbox.value105            if state: checked.append(i)106        return checked107    def get_widget(self, index):108        """ get the widget in index """109        checkrow = self.children[index]110        return checkrow.widget111    def set_widget(self, index, widget):112        """ set the widget for index """113        checkrow = self.children[index]114        checkrow.widget.children = (widget,) # Accordion has 1 child115    def set_row(self, index, title, widget):116        """ set values for the row """117        self.set_title(index, title)118        self.set_widget(index, widget)119    def set_accordion_handler(self, index, handler, **kwargs):120        """ set the handler for Accordion in index """121        checkrow = self.children[index]122        checkrow.observe_widget(handler, names=['selected_index'], **kwargs)123    def set_checkbox_handler(self, index, handler, **kwargs):124        """ set the handler for CheckBox in index """125        checkrow = self.children[index]126        checkrow.observe_checkbox(handler, **kwargs)127class ConfirmationWidget(VBox):128    def __init__(self, title='Confirmation', legend='Are you sure?',129                 handle_yes=None, handle_no=None, handle_cancel=None, **kwargs):130        super(ConfirmationWidget, self).__init__(**kwargs)131        # Title Widget132        self.title = title133        self.title_widget = HTML(self.title)134        # Legend Widget135        self.legend = legend136        self.legend_widget = HTML(self.legend)137        # Buttons138        self.yes = Button(description='Yes')139        handler_yes = handle_yes if handle_yes else lambda x: x140        self.yes.on_click(handler_yes)141        self.no = Button(description='No')142        handler_no = handle_no if handle_no else lambda x: x143        self.no.on_click(handler_no)144        self.cancel = Button(description='Cancel')145        handler_cancel = handle_cancel if handle_cancel else lambda x: x146        self.cancel.on_click(handler_cancel)147        self.buttons = HBox([self.yes, self.no, self.cancel])148        self.children = [self.title_widget, self.legend_widget, self.buttons]149class RealBox(Box):150    """ Real Box Layout151    items:152    [[widget1, widget2],153     [widget3, widget4]]154    """155    items = List()156    width = Int()157    border_inside = Unicode()158    border_outside = Unicode()159    def __init__(self, **kwargs):160        super(RealBox, self).__init__(**kwargs)161        self.layout = Layout(display='flex', flex_flow='column',162                             border=self.border_outside)163    def max_row_elements(self):164        maxn = 0165        for el in self.items:166            n = len(el)167            if n>maxn:168                maxn = n169        return maxn170    @observe('items')171    def _ob_items(self, change):172        layout_columns = Layout(display='flex', flex_flow='row')173        new = change['new']174        children = []175        # recompute size176        maxn = self.max_row_elements()177        width = 100/maxn178        for el in new:179            for wid in el:180                if not wid.layout.width:181                    if self.width:182                        wid.layout = Layout(width='{}px'.format(self.width),183                                            border=self.border_inside)184                    else:185                        wid.layout = Layout(width='{}%'.format(width),186                                            border=self.border_inside)187            hbox = Box(el, layout=layout_columns)188            children.append(hbox)189        self.children = children190class ErrorAccordion(Accordion):191    def __init__(self, error, traceback, **kwargs):192        super(ErrorAccordion, self).__init__(**kwargs)193        self.error = '{}'.format(error).replace('<','{').replace('>','}')194        newtraceback = ''195        for trace in traceback[1:]:196            newtraceback += '{}'.format(trace).replace('<','{').replace('>','}')197            newtraceback += '</br>'198        self.traceback = newtraceback199        self.errorWid = HTML(self.error)200        self.traceWid = HTML(self.traceback)201        self.children = (self.errorWid, self.traceWid)202        self.set_title(0, 'ERROR')...stock_performance_mt_non-taxable gain.py
Source:stock_performance_mt_non-taxable gain.py  
1print("Cmt: Importing modules...")23import time, win32com.client, os, re45print("Cmt: Importing modules...Done.")6print("Cmt: Open and connect to file...")78excelApp = win32com.client.gencache.EnsureDispatch('Excel.Application')9excelApp.Visible = True10excelApp.DisplayAlerts = True11filePath = os.path.abspath(os.curdir)12fileName = "Stock_Performance"13fileExtension = ".xlsx"1415excelApp.Workbooks.Open(filePath + "\\" + fileName + fileExtension)16excelApp.Calculation = win32com.client.constants.xlCalculationManual17excelWb = excelApp.Workbooks(fileName + fileExtension)18excelTransactionsSheet = excelWb.Worksheets("Transactions")1920transRow = 121sumRow = 122currentStockBrokerLotDate = ""2324while excelTransactionsSheet.Cells(transRow, 1).Value:2526    if excelTransactionsSheet.Cells(transRow, 1).Value == "Sell Stock" and excelTransactionsSheet.Cells(transRow, 3).Value == "Mt":27        if str(excelTransactionsSheet.Cells(transRow, 2).Value) + str(excelTransactionsSheet.Cells(transRow, 3).Value) + str(excelTransactionsSheet.Cells(transRow, 4).Value) + str(excelTransactionsSheet.Cells(transRow, 6).Value) != currentStockBrokerLotDate:28            currentStockBrokerLotDate = str(excelTransactionsSheet.Cells(transRow, 2).Value) + str(excelTransactionsSheet.Cells(transRow, 3).Value) + str(excelTransactionsSheet.Cells(transRow, 4).Value) + str(excelTransactionsSheet.Cells(transRow, 6).Value)2930            sumRow = transRow31            currentSum = 032            33            while str(excelTransactionsSheet.Cells(sumRow, 2).Value) + str(excelTransactionsSheet.Cells(sumRow, 3).Value) + str(excelTransactionsSheet.Cells(sumRow, 4).Value) + str(excelTransactionsSheet.Cells(sumRow, 6).Value) == currentStockBrokerLotDate and excelTransactionsSheet.Cells(transRow, 1).Value == "Sell Stock":3435                if excelTransactionsSheet.Cells(sumRow, 7).Value == "Sale Fee Expense" or excelTransactionsSheet.Cells(sumRow, 7).Value == "Regulatory Fee Expense" :36                    currentSum = currentSum + excelTransactionsSheet.Cells(sumRow, 8).Value37                38                sumRow = sumRow + 13940            currentSum = round(currentSum, 2)41            42            if currentSum > 0:43                44                print("Gain On Sale (Excluded From Tax): " + str(currentSum))4546                checkRow = transRow47            48                while str(excelTransactionsSheet.Cells(checkRow, 2).Value) + str(excelTransactionsSheet.Cells(checkRow, 3).Value) + str(excelTransactionsSheet.Cells(checkRow, 4).Value) + str(excelTransactionsSheet.Cells(checkRow, 6).Value) == currentStockBrokerLotDate and excelTransactionsSheet.Cells(checkRow, 1).Value == "Sell Stock":4950                    if "Gain On Sale" in excelTransactionsSheet.Cells(checkRow, 7).Value or "Loss On Sale" in excelTransactionsSheet.Cells(checkRow, 7).Value: 51                        excelTransactionsSheet.Cells(checkRow, 8).Value = round(excelTransactionsSheet.Cells(checkRow, 8).Value, 2) + currentSum #+ (-currentSum)5253                        excelTransactionsSheet.Cells(checkRow, 1).EntireRow.Insert()54                        55                        for i in range(1, 7):56                            excelTransactionsSheet.Cells(checkRow, i).Value = excelTransactionsSheet.Cells(checkRow - 1, i).Value5758                        excelTransactionsSheet.Cells(checkRow, 7).Value = "Gain On Sale (Excluded From Tax)" #excelTransactionsSheet.Cells(checkRow, 7).Value # 59                        excelTransactionsSheet.Cells(checkRow, 8).Value = -currentSum #excelTransactionsSheet.Cells(checkRow, 8).Value # 60                        61                        break62                63                    checkRow = checkRow + 164 65    transRow = transRow + 1666768excelApp.Calculation = win32com.client.constants.xlCalculationAutomatic
...n_queens.py
Source:n_queens.py  
1import numpy as np2def printSolution(board):3	n = board.shape[0]4	for i in range(n):5		for j in range(n):6			print(board[i][j], end = ' ')7		print()8def openTile(c, r, n, checkRow, checkD1, checkD2):9	return not (checkRow[r] or checkD1[c + r] or checkD2[c - r + n - 1])10def bnb(board, c, checkRow, checkD1, checkD2):11	n = board.shape[0]12	if c >= n:13		return True14	15	for r in range(n):16		if openTile(c, r, n, checkRow, checkD1, checkD2):17			board[r][c] = 'Q'18			checkRow[r] = True19			checkD1[c + r] = True20			checkD2[c - r + n - 1] = True21			if bnb(board, c + 1, checkRow, checkD1, checkD2):22				return True23			board[r][c] = '.'24			checkRow[r] = False25			checkD1[c + r] = False26			checkD2[c - r + n - 1] = False27	28	return False29def solve(n):30	board = np.full((n, n), '.', dtype = str)31	checkRow = np.full(n, False)32	checkD1 = np.full(2 * n - 1, False)33	checkD2 = np.full(2 * n - 1, False)34	if bnb(board, 0, checkRow, checkD1, checkD2):35		printSolution(board)36	else:37		print("No solution!")38if __name__ == "__main__":...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!!
