Best Python code snippet using autotest_python
_command_line_dialog.py
Source:_command_line_dialog.py
1import sqlite32import typing as typ3import PyQt5.QtCore as QtC4import PyQt5.QtGui as QtG5import PyQt5.QtWidgets as QtW6from app import config, data_access7from app.i18n import translate as _t8from . import _dialog_base9from .. import components10class CommandLineDialog(_dialog_base.Dialog):11 """A simple command line interface to interact with the database."""12 def __init__(self, parent: typ.Optional[QtW.QWidget] = None):13 super().__init__(14 parent=parent,15 title=_t('dialog.command_line.title'),16 modal=True,17 mode=_dialog_base.Dialog.CLOSE18 )19 # noinspection PyProtectedMember20 self._connection = data_access.ImageDao(config.CONFIG.database_path)._connection21 self._command_line.setFocus()22 self._disable_closing = False23 self._column_names = None24 self._results = None25 self._results_offset = None26 self._results_total = None27 def _init_body(self) -> QtW.QLayout:28 self.setMinimumSize(500, 300)29 layout = QtW.QVBoxLayout()30 self._command_line = components.CommandLineWidget(parent=self)31 self._command_line.set_input_callback(self._on_input)32 self._command_line.set_input_placeholder(_t('dialog.command_line.query_input.placeholder'))33 layout.addWidget(self._command_line)34 return layout35 def _on_input(self, input_: str):36 if self._results:37 if input_.upper() == 'Y':38 self._print_results()39 elif input_.upper() == 'N':40 self._column_names = None41 self._results = None42 else:43 self._command_line.print(_t('SQL_console.display_more'))44 else:45 cursor = self._connection.cursor()46 try:47 cursor.execute(input_)48 except sqlite3.Error as e:49 self._command_line.print_error(_t('SQL_console.error'))50 self._command_line.print_error(e)51 cursor.close()52 else:53 if input_.lower().startswith('select'):54 results = cursor.fetchall()55 if cursor.description is not None:56 column_names = tuple(desc[0] for desc in cursor.description)57 else:58 column_names = ()59 self._column_names = column_names60 self._results = results61 self._results_offset = 062 self._results_total = len(results)63 self._print_results()64 else:65 self._command_line.print(_t('SQL_console.affected_rows', row_count=cursor.rowcount))66 cursor.close()67 def _print_results(self):68 results = self._results[self._results_offset:]69 if len(results) == 0:70 self._command_line.print(_t('SQL_console.no_results'))71 else:72 limit = 2073 i = 074 rows = []75 for result in results:76 if i % limit == 0:77 if i > 0:78 self._print_rows(rows, self._column_names)79 rows.clear()80 self._command_line.print(_t('SQL_console.display_more'))81 self._results_offset += i82 break83 upper_bound = min(self._results_offset + i + limit, self._results_total)84 self._command_line.print(_t('SQL_console.results', start=self._results_offset + i + 1,85 end=upper_bound, total=self._results_total))86 rows.append(tuple(map(repr, result)))87 i += 188 else:89 self._print_rows(rows, self._column_names)90 self._results = None91 def _print_rows(self, rows: typ.List[typ.Tuple[str, ...]], column_names: typ.Sequence[str]):92 """Prints rows in a table.93 :param rows: List of rows.94 :param column_names: Names of each column.95 """96 columns = list(zip(*([column_names] + rows)))97 column_sizes = [max([len(str(v)) for v in col]) for col in columns]98 self._command_line.print(*[str(v).ljust(column_sizes[i]) for i, v in enumerate(column_names)], sep=' | ')99 self._command_line.print(*['-' * size for size in column_sizes], sep='-+-')100 for i, row in enumerate(rows):101 self._command_line.print(*[str(v).ljust(column_sizes[i]) for i, v in enumerate(row)], sep=' | ')102 def keyPressEvent(self, event: QtG.QKeyEvent):103 if event.key() in [QtC.Qt.Key_Return, QtC.Qt.Key_Enter] and self.focusWidget() != self._ok_btn:104 self._disable_closing = True105 super().keyPressEvent(event)106 def _on_ok_clicked(self):107 if self._disable_closing:108 self._disable_closing = False109 else:...
generic_lsp_completer.py
Source:generic_lsp_completer.py
1# Copyright (C) 2020 ycmd contributors2#3# This file is part of ycmd.4#5# ycmd is free software: you can redistribute it and/or modify6# it under the terms of the GNU General Public License as published by7# the Free Software Foundation, either version 3 of the License, or8# (at your option) any later version.9#10# ycmd is distributed in the hope that it will be useful,11# but WITHOUT ANY WARRANTY; without even the implied warranty of12# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the13# GNU General Public License for more details.14#15# You should have received a copy of the GNU General Public License16# along with ycmd. If not, see <http://www.gnu.org/licenses/>.17import string18from ycmd import responses, utils19from ycmd.completers.language_server import language_server_completer20class GenericLSPCompleter( language_server_completer.LanguageServerCompleter ):21 def __init__( self, user_options, server_settings ):22 utils.LOGGER.info( "Initializing generic LSP completer with: %s",23 server_settings )24 self._name = server_settings[ 'name' ]25 self._supported_filetypes = server_settings[ 'filetypes' ]26 self._project_root_files = server_settings.get( 'project_root_files', [] )27 self._capabilities = server_settings.get( 'capabilities', {} )28 self._command_line = server_settings.get( 'cmdline' )29 self._port = server_settings.get( 'port' )30 if self._port:31 connection_type = 'tcp'32 if self._port == '*':33 self._port = utils.GetUnusedLocalhostPort()34 else:35 connection_type = 'stdio'36 if self._command_line:37 # We modify this, so take a copy38 self._command_line = list( self._command_line )39 cmd = utils.FindExecutable( self._command_line[ 0 ] )40 if cmd is None:41 utils.LOGGER.warn( "Unable to find any executable with the path %s. "42 "Cannot use %s completer.",43 self._command_line[ 0 ],44 self._name )45 raise RuntimeError( f"Invalid cmdline: { str( self._command_line ) }" )46 self._command_line[ 0 ] = cmd47 for idx in range( len( self._command_line ) ):48 self._command_line[ idx ] = string.Template(49 self._command_line[ idx ] ).safe_substitute( {50 'port': self._port51 } )52 super().__init__( user_options, connection_type )53 def GetProjectRootFiles( self ):54 return self._project_root_files55 def Language( self ):56 return self._name57 def GetServerName( self ):58 return self._name + 'Completer'59 def GetCommandLine( self ):60 return self._command_line61 def GetCustomSubcommands( self ):62 return { 'GetHover': lambda self, request_data, args:63 self._GetHover( request_data ) }64 def _GetHover( self, request_data ):65 raw_hover = self.GetHoverResponse( request_data )66 if isinstance( raw_hover, dict ):67 # Both MarkedString and MarkupContent contain 'value' key.68 # MarkupContent is the only one not deprecated.69 return responses.BuildDetailedInfoResponse( raw_hover[ 'value' ] )70 if isinstance( raw_hover, str ):71 # MarkedString might be just a string.72 return responses.BuildDetailedInfoResponse( raw_hover )73 # If we got this far, this is a list of MarkedString objects.74 lines = []75 for marked_string in raw_hover:76 if isinstance( marked_string, str ):77 lines.append( marked_string )78 else:79 lines.append( marked_string[ 'value' ] )80 return responses.BuildDetailedInfoResponse( '\n'.join( lines ) )81 def GetCodepointForCompletionRequest( self, request_data ):82 if request_data[ 'force_semantic' ]:83 return request_data[ 'column_codepoint' ]84 return super().GetCodepointForCompletionRequest( request_data )85 def SupportedFiletypes( self ):86 return self._supported_filetypes87 def ExtraCapabilities( self ):88 return self._capabilities89 def WorkspaceConfigurationResponse( self, request ):90 if self._capabilities.get( 'workspace', {} ).get( 'configuration' ):91 sections_to_config_map = self._settings.get( 'config_sections', {} )92 return [ sections_to_config_map.get( item.get( 'section', '' ) )...
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!!