idx
int64
0
63k
question
stringlengths
61
4.03k
target
stringlengths
6
1.23k
31,700
def makedirs ( self , path , mode = 0o700 ) : os . makedirs ( os . path . join ( self . _archive_root , path ) , mode = mode ) self . log_debug ( "created directory at '%s' in FileCacheArchive '%s'" % ( path , self . _archive_root ) )
Create path including leading components .
31,701
def _encrypt ( self , archive ) : arc_name = archive . replace ( "sosreport-" , "secured-sosreport-" ) arc_name += ".gpg" enc_cmd = "gpg --batch -o %s " % arc_name env = None if self . enc_opts [ "key" ] : enc_cmd += "--trust-model always -e -r %s " % self . enc_opts [ "key" ] enc_cmd += archive if self . enc_opts [ "p...
Encrypts the compressed archive using GPG .
31,702
def tail ( filename , number_of_bytes ) : with open ( filename , "rb" ) as f : if os . stat ( filename ) . st_size > number_of_bytes : f . seek ( - number_of_bytes , 2 ) return f . read ( )
Returns the last number_of_bytes of filename
31,703
def fileobj ( path_or_file , mode = 'r' ) : if isinstance ( path_or_file , six . string_types ) : try : return open ( path_or_file , mode ) except IOError : log = logging . getLogger ( 'sos' ) log . debug ( "fileobj: %s could not be opened" % path_or_file ) return closing ( six . StringIO ( ) ) else : return closing ( ...
Returns a file - like object that can be used as a context manager
31,704
def convert_bytes ( bytes_ , K = 1 << 10 , M = 1 << 20 , G = 1 << 30 , T = 1 << 40 ) : fn = float ( bytes_ ) if bytes_ >= T : return '%.1fT' % ( fn / T ) elif bytes_ >= G : return '%.1fG' % ( fn / G ) elif bytes_ >= M : return '%.1fM' % ( fn / M ) elif bytes_ >= K : return '%.1fK' % ( fn / K ) else : return '%d' % byte...
Converts a number of bytes to a shorter more human friendly format
31,705
def grep ( pattern , * files_or_paths ) : matches = [ ] for fop in files_or_paths : with fileobj ( fop ) as fo : matches . extend ( ( line for line in fo if re . match ( pattern , line ) ) ) return matches
Returns lines matched in fnames where fnames can either be pathnames to files to grep through or open file objects to grep through line by line
31,706
def is_executable ( command ) : paths = os . environ . get ( "PATH" , "" ) . split ( os . path . pathsep ) candidates = [ command ] + [ os . path . join ( p , command ) for p in paths ] return any ( os . access ( path , os . X_OK ) for path in candidates )
Returns if a command matches an executable on the PATH
31,707
def sos_get_command_output ( command , timeout = 300 , stderr = False , chroot = None , chdir = None , env = None , binary = False , sizelimit = None , poller = None ) : def _child_prep_fn ( ) : if ( chroot ) : os . chroot ( chroot ) if ( chdir ) : os . chdir ( chdir ) cmd_env = os . environ . copy ( ) cmd_env [ 'LC_AL...
Execute a command and return a dictionary of status and output optionally changing root or current working directory before executing command .
31,708
def import_module ( module_fqname , superclasses = None ) : module_name = module_fqname . rpartition ( "." ) [ - 1 ] module = __import__ ( module_fqname , globals ( ) , locals ( ) , [ module_name ] ) modules = [ class_ for cname , class_ in inspect . getmembers ( module , inspect . isclass ) if class_ . __module__ == m...
Imports the module module_fqname and returns a list of defined classes from that module . If superclasses is defined then the classes returned will be subclasses of the specified superclass or superclasses . If superclasses is plural it must be a tuple of classes .
31,709
def shell_out ( cmd , timeout = 30 , chroot = None , runat = None ) : return sos_get_command_output ( cmd , timeout = timeout , chroot = chroot , chdir = runat ) [ 'output' ]
Shell out to an external command and return the output or the empty string in case of error .
31,710
def get_contents ( self ) : while self . running : pass if not self . binary : return '' . join ( ln . decode ( 'utf-8' , 'ignore' ) for ln in self . deque ) else : return b'' . join ( ln for ln in self . deque )
Returns the contents of the deque as a string
31,711
def _plugin_name ( self , path ) : "Returns the plugin module name given the path" base = os . path . basename ( path ) name , ext = os . path . splitext ( base ) return name
Returns the plugin module name given the path
31,712
def get_modules ( self ) : plugins = [ ] for path in self . package . __path__ : if os . path . isdir ( path ) : plugins . extend ( self . _find_plugins_in_dir ( path ) ) return plugins
Returns the list of importable modules in the configured python package .
31,713
def check_usrmove ( self , pkgs ) : if 'filesystem' not in pkgs : return os . path . islink ( '/bin' ) and os . path . islink ( '/sbin' ) else : filesys_version = pkgs [ 'filesystem' ] [ 'version' ] return True if filesys_version [ 0 ] == '3' else False
Test whether the running system implements UsrMove .
31,714
def mangle_package_path ( self , files ) : paths = [ ] def transform_path ( path ) : skip_paths = [ "/bin/rpm" , "/bin/mailx" ] if path in skip_paths : return ( path , os . path . join ( "/usr" , path [ 1 : ] ) ) return ( re . sub ( r'(^)(/s?bin)' , r'\1/usr\2' , path ) , ) if self . usrmove : for f in files : paths . ...
Mangle paths for post - UsrMove systems .
31,715
def _container_init ( self ) : if ENV_CONTAINER in os . environ : if os . environ [ ENV_CONTAINER ] in [ 'docker' , 'oci' ] : self . _in_container = True if ENV_HOST_SYSROOT in os . environ : self . _host_sysroot = os . environ [ ENV_HOST_SYSROOT ] use_sysroot = self . _in_container and self . _host_sysroot != '/' if u...
Check if sos is running in a container and perform container specific initialisation based on ENV_HOST_SYSROOT .
31,716
def check ( cls ) : if not os . path . exists ( OS_RELEASE ) : return False with open ( OS_RELEASE , "r" ) as f : for line in f : if line . startswith ( "NAME" ) : ( name , value ) = line . split ( "=" ) value = value . strip ( "\"'" ) if value . startswith ( cls . distro ) : return True return False
Test to see if the running host is a RHEL installation .
31,717
def get_params ( self , name , param_list ) : self . add_cmd_output ( "lctl get_param %s" % " " . join ( param_list ) , suggest_filename = "params-%s" % name , stderr = False )
Use lctl get_param to collect a selection of parameters into a file .
31,718
def setup ( self ) : options = "" if self . get_option ( "port" ) : options = ( options + " -b " + gethostname ( ) + ":%s" % ( self . get_option ( "port" ) ) ) for option in [ "ssl-certificate" , "ssl-key" , "ssl-trustfile" ] : if self . get_option ( option ) : options = ( options + " --%s=" % ( option ) + self . get_o...
performs data collection for qpid dispatch router
31,719
def __str ( self , quote = False , prefix = "" , suffix = "" ) : quotes = '"%s"' pstr = "dry_run=%s, " % self . _dry_run kmods = self . _kmods kmods = [ quotes % k for k in kmods ] if quote else kmods pstr += "kmods=[%s], " % ( "," . join ( kmods ) ) services = self . _services services = [ quotes % s for s in services...
Return a string representation of this SoSPredicate with optional prefix suffix and value quoting .
31,720
def do_file_sub ( self , srcpath , regexp , subst ) : try : path = self . _get_dest_for_srcpath ( srcpath ) self . _log_debug ( "substituting scrpath '%s'" % srcpath ) self . _log_debug ( "substituting '%s' for '%s' in '%s'" % ( subst , regexp , path ) ) if not path : return 0 readable = self . archive . open_file ( pa...
Apply a regexp substitution to a file archived by sosreport . srcpath is the path in the archive where the file can be found . regexp can be a regexp string or a compiled re object . subst is a string to replace each occurance of regexp in the content of srcpath .
31,721
def do_path_regex_sub ( self , pathexp , regexp , subst ) : if not hasattr ( pathexp , "match" ) : pathexp = re . compile ( pathexp ) match = pathexp . match file_list = [ f for f in self . copied_files if match ( f [ 'srcpath' ] ) ] for file in file_list : self . do_file_sub ( file [ 'srcpath' ] , regexp , subst )
Apply a regexp substituation to a set of files archived by sos . The set of files to be substituted is generated by matching collected file pathnames against pathexp which may be a regular expression string or compiled re object . The portion of the file to be replaced is specified via regexp and the replacement string...
31,722
def _do_copy_path ( self , srcpath , dest = None ) : if self . _is_forbidden_path ( srcpath ) : self . _log_debug ( "skipping forbidden path '%s'" % srcpath ) return '' if not dest : dest = srcpath if self . use_sysroot ( ) : dest = self . strip_sysroot ( dest ) try : st = os . lstat ( srcpath ) except ( OSError , IOEr...
Copy file or directory to the destination tree . If a directory then everything below it is recursively copied . A list of copied files are saved for use later in preparing a report .
31,723
def set_option ( self , optionname , value ) : for name , parms in zip ( self . opt_names , self . opt_parms ) : if name == optionname : defaulttype = type ( parms [ 'enabled' ] ) if defaulttype != type ( value ) and defaulttype != type ( None ) : value = ( defaulttype ) ( value ) parms [ 'enabled' ] = value return Tru...
Set the named option to value . Ensure the original type of the option value is preserved .
31,724
def get_option ( self , optionname , default = 0 ) : global_options = ( 'verify' , 'all_logs' , 'log_size' , 'plugin_timeout' ) if optionname in global_options : return getattr ( self . commons [ 'cmdlineopts' ] , optionname ) for name , parms in zip ( self . opt_names , self . opt_parms ) : if name == optionname : val...
Returns the first value that matches optionname in parameters passed in via the command line or set via set_option or via the global_plugin_options dictionary in that order .
31,725
def get_option_as_list ( self , optionname , delimiter = "," , default = None ) : option = self . get_option ( optionname ) try : opt_list = [ opt . strip ( ) for opt in option . split ( delimiter ) ] return list ( filter ( None , opt_list ) ) except Exception : return default
Will try to return the option as a list separated by the delimiter .
31,726
def add_copy_spec ( self , copyspecs , sizelimit = None , tailit = True , pred = None ) : if not self . test_predicate ( pred = pred ) : self . _log_info ( "skipped copy spec '%s' due to predicate (%s)" % ( copyspecs , self . get_predicate ( pred = pred ) ) ) return if sizelimit is None : sizelimit = self . get_option ...
Add a file or glob but limit it to sizelimit megabytes . If fname is a single file the file will be tailed to meet sizelimit . If the first file in a glob is too large it will be tailed to meet the sizelimit .
31,727
def call_ext_prog ( self , prog , timeout = 300 , stderr = True , chroot = True , runat = None ) : return self . get_command_output ( prog , timeout = timeout , stderr = stderr , chroot = chroot , runat = runat )
Execute a command independantly of the output gathering part of sosreport .
31,728
def _add_cmd_output ( self , cmd , suggest_filename = None , root_symlink = None , timeout = 300 , stderr = True , chroot = True , runat = None , env = None , binary = False , sizelimit = None , pred = None ) : cmdt = ( cmd , suggest_filename , root_symlink , timeout , stderr , chroot , runat , env , binary , sizelimit...
Internal helper to add a single command to the collection list .
31,729
def add_cmd_output ( self , cmds , suggest_filename = None , root_symlink = None , timeout = 300 , stderr = True , chroot = True , runat = None , env = None , binary = False , sizelimit = None , pred = None ) : if isinstance ( cmds , six . string_types ) : cmds = [ cmds ] if len ( cmds ) > 1 and ( suggest_filename or r...
Run a program or a list of programs and collect the output
31,730
def get_cmd_output_path ( self , name = None , make = True ) : cmd_output_path = os . path . join ( self . archive . get_tmp_dir ( ) , 'sos_commands' , self . name ( ) ) if name : cmd_output_path = os . path . join ( cmd_output_path , name ) if make : os . makedirs ( cmd_output_path ) return cmd_output_path
Return a path into which this module should store collected command output
31,731
def _make_command_filename ( self , exe ) : outfn = os . path . join ( self . commons [ 'cmddir' ] , self . name ( ) , self . _mangle_command ( exe ) ) if os . path . exists ( outfn ) : inc = 2 while True : newfn = "%s_%d" % ( outfn , inc ) if not os . path . exists ( newfn ) : outfn = newfn break inc += 1 return outfn
The internal function to build up a filename based on a command .
31,732
def add_string_as_file ( self , content , filename , pred = None ) : summary = content . splitlines ( ) [ 0 ] if content else '' if not isinstance ( summary , six . string_types ) : summary = content . decode ( 'utf8' , 'ignore' ) if not self . test_predicate ( cmd = False , pred = pred ) : self . _log_info ( "skipped ...
Add a string to the archive as a file named filename
31,733
def add_journal ( self , units = None , boot = None , since = None , until = None , lines = None , allfields = False , output = None , timeout = None , identifier = None , catalog = None , sizelimit = None , pred = None ) : journal_cmd = "journalctl --no-pager " unit_opt = " --unit %s" boot_opt = " --boot %s" since_opt...
Collect journald logs from one of more units .
31,734
def add_udev_info ( self , device , attrs = False ) : udev_cmd = 'udevadm info' if attrs : udev_cmd += ' -a' if isinstance ( device , six . string_types ) : device = [ device ] for dev in device : self . _log_debug ( "collecting udev info for: %s" % dev ) self . _add_cmd_output ( '%s %s' % ( udev_cmd , dev ) )
Collect udevadm info output for a given device
31,735
def collect ( self ) : start = time ( ) self . _collect_copy_specs ( ) self . _collect_cmd_output ( ) self . _collect_strings ( ) fields = ( self . name ( ) , time ( ) - start ) self . _log_debug ( "collected plugin '%s' in %s" % fields )
Collect the data for a plugin .
31,736
def get_description ( self ) : try : if hasattr ( self , '__doc__' ) and self . __doc__ : return self . __doc__ . strip ( ) return super ( self . __class__ , self ) . __doc__ . strip ( ) except Exception : return "<no description available>"
This function will return the description for the plugin
31,737
def check_enabled ( self ) : if any ( [ self . files , self . packages , self . commands , self . kernel_mods , self . services ] ) : if isinstance ( self . files , six . string_types ) : self . files = [ self . files ] if isinstance ( self . packages , six . string_types ) : self . packages = [ self . packages ] if is...
This method will be used to verify that a plugin should execute given the condition of the underlying environment .
31,738
def report ( self ) : html = u'<hr/><a name="%s"></a>\n' % self . name ( ) html = html + "<h2> Plugin <em>" + self . name ( ) + "</em></h2>\n" if len ( self . copied_files ) : html = html + "<p>Files copied:<br><ul>\n" for afile in self . copied_files : html = html + '<li><a href="%s">%s</a>' % ( u'..' + _to_u ( afile ...
Present all information that was gathered in an html file that allows browsing the results .
31,739
def get_process_pids ( self , process ) : pids = [ ] cmd_line_glob = "/proc/[0-9]*/cmdline" cmd_line_paths = glob . glob ( cmd_line_glob ) for path in cmd_line_paths : try : with open ( path , 'r' ) as f : cmd_line = f . read ( ) . strip ( ) if process in cmd_line : pids . append ( path . split ( "/" ) [ 2 ] ) except I...
Returns PIDs of all processes with process name . If the process doesn t exist returns an empty list
31,740
def convert_cmd_scl ( self , scl , cmd ) : prefix = self . policy . get_default_scl_prefix ( ) try : prefix = open ( '/etc/scl/prefixes/%s' % scl , 'r' ) . read ( ) . rstrip ( '\n' ) except Exception as e : self . _log_error ( "Failed to find prefix for SCL %s, using %s" % ( scl , prefix ) ) path = os . environ [ "PATH...
wrapping command in scl enable call and adds proper PATH
31,741
def add_cmd_output_scl ( self , scl , cmds , ** kwargs ) : if isinstance ( cmds , six . string_types ) : cmds = [ cmds ] scl_cmds = [ ] for cmd in cmds : scl_cmds . append ( self . convert_cmd_scl ( scl , cmd ) ) self . add_cmd_output ( scl_cmds , ** kwargs )
Same as add_cmd_output except that it wraps command in scl enable call and sets proper PATH .
31,742
def add_copy_spec_scl ( self , scl , copyspecs ) : if isinstance ( copyspecs , six . string_types ) : copyspecs = [ copyspecs ] scl_copyspecs = [ ] for copyspec in copyspecs : scl_copyspecs . append ( self . convert_copyspec_scl ( scl , copyspec ) ) self . add_copy_spec ( scl_copyspecs )
Same as add_copy_spec except that it prepends path to SCL root to copyspecs .
31,743
def add_copy_spec_limit_scl ( self , scl , copyspec , ** kwargs ) : self . add_copy_spec_limit ( self . convert_copyspec_scl ( scl , copyspec ) , ** kwargs )
Same as add_copy_spec_limit except that it prepends path to SCL root to copyspec .
31,744
def setup ( self ) : r = self . call_ext_prog ( self . get_option ( "script" ) ) if r [ 'status' ] == 0 : tarfile = "" for line in r [ 'output' ] : line = line . strip ( ) tarfile = self . do_regex_find_all ( r"ftp (.*tar.gz)" , line ) if len ( tarfile ) == 1 : self . add_copy_spec ( tarfile [ 0 ] )
interface with vrtsexplorer to capture veritas related data
31,745
def postproc ( self ) : secrets_files = [ "/etc/openstack_deploy/user_secrets.yml" , "/etc/rpc_deploy/user_secrets.yml" ] regexp = r"(?m)^\s*#*([\w_]*:\s*).*" for secrets_file in secrets_files : self . do_path_regex_sub ( secrets_file , regexp , r"\1*********" )
Remove sensitive keys and passwords from YAML files .
31,746
def finalize_options ( self ) -> None : "Get options from config files." self . arguments = { } computed_settings = from_path ( os . getcwd ( ) ) for key , value in computed_settings . items ( ) : self . arguments [ key ] = value
Get options from config files .
31,747
def distribution_files ( self ) -> Iterator [ str ] : if self . distribution . packages : package_dirs = self . distribution . package_dir or { } for package in self . distribution . packages : pkg_dir = package if package in package_dirs : pkg_dir = package_dirs [ package ] elif '' in package_dirs : pkg_dir = package_...
Find distribution packages .
31,748
def chdir ( path : str ) -> Iterator [ None ] : curdir = os . getcwd ( ) os . chdir ( path ) try : yield finally : os . chdir ( curdir )
Context manager for changing dir and restoring previous workdir after exit .
31,749
def union ( a : Iterable [ Any ] , b : Iterable [ Any ] ) -> List [ Any ] : u = [ ] for item in a : if item not in u : u . append ( item ) for item in b : if item not in u : u . append ( item ) return u
Return a list of items that are in a or b
31,750
def difference ( a : Iterable [ Any ] , b : Container [ Any ] ) -> List [ Any ] : d = [ ] for item in a : if item not in b : d . append ( item ) return d
Return a list of items from a that are not in b .
31,751
def sort_kate_imports ( add_imports = ( ) , remove_imports = ( ) ) : document = kate . activeDocument ( ) view = document . activeView ( ) position = view . cursorPosition ( ) selection = view . selectionRange ( ) sorter = SortImports ( file_contents = document . text ( ) , add_imports = add_imports , remove_imports = ...
Sorts imports within Kate while maintaining cursor position and selection even if length of file changes .
31,752
def _get_line ( self ) -> str : line = self . in_lines [ self . index ] self . index += 1 return line
Returns the current line from the file while incrementing the index .
31,753
def _add_comments ( self , comments : Optional [ Sequence [ str ] ] , original_string : str = "" ) -> str : if self . config [ 'ignore_comments' ] : return self . _strip_comments ( original_string ) [ 0 ] if not comments : return original_string else : return "{0}{1} {2}" . format ( self . _strip_comments ( original_st...
Returns a string with comments added if ignore_comments is not set .
31,754
def _wrap ( self , line : str ) -> str : wrap_mode = self . config [ 'multi_line_output' ] if len ( line ) > self . config [ 'line_length' ] and wrap_mode != WrapModes . NOQA : line_without_comment = line comment = None if '#' in line : line_without_comment , comment = line . split ( '#' , 1 ) for splitter in ( "import...
Returns an import wrapped to the specified line - length if possible .
31,755
def _parse_known_pattern ( self , pattern : str ) -> List [ str ] : if pattern . endswith ( os . path . sep ) : patterns = [ filename for filename in os . listdir ( pattern ) if os . path . isdir ( os . path . join ( pattern , filename ) ) ] else : patterns = [ pattern ] return patterns
Expand pattern if identified as a directory and return found sub packages
31,756
def _load_mapping ( ) -> Optional [ Dict [ str , str ] ] : if not pipreqs : return None path = os . path . dirname ( inspect . getfile ( pipreqs ) ) path = os . path . join ( path , 'mapping' ) with open ( path ) as f : mappings = { } for line in f : import_name , _ , pypi_name = line . strip ( ) . partition ( ":" ) ma...
Return list of mappings package_name - > module_name
31,757
def _load_names ( self ) -> List [ str ] : names = [ ] for path in self . _get_files ( ) : for name in self . _get_names ( path ) : names . append ( self . _normalize_name ( name ) ) return names
Return list of thirdparty modules from requirements
31,758
def _get_files ( self ) -> Iterator [ str ] : path = os . path . abspath ( self . path ) if os . path . isfile ( path ) : path = os . path . dirname ( path ) for path in self . _get_parents ( path ) : for file_path in self . _get_files_from_dir ( path ) : yield file_path
Return paths to all requirements files
31,759
def _normalize_name ( self , name : str ) -> str : if self . mapping : name = self . mapping . get ( name , name ) return name . lower ( ) . replace ( '-' , '_' )
Convert package name to module name
31,760
def _get_names ( self , path : str ) -> Iterator [ str ] : for i in RequirementsFinder . _get_names_cached ( path ) : yield i
Load required packages from path to requirements file
31,761
def receive ( self , content , ** kwargs ) : self . connection_context = DjangoChannelConnectionContext ( self . message ) self . subscription_server = DjangoChannelSubscriptionServer ( graphene_settings . SCHEMA ) self . subscription_server . on_open ( self . connection_context ) self . subscription_server . handle ( ...
Called when a message is received with either text or bytes filled out .
31,762
def save ( self ) : logger . debug ( "User requested to save settings. New settings: " + self . _settings_str ( ) ) cm . ConfigManager . SETTINGS [ cm . PROMPT_TO_SAVE ] = not self . autosave_checkbox . isChecked ( ) cm . ConfigManager . SETTINGS [ cm . SHOW_TRAY_ICON ] = self . show_tray_checkbox . isChecked ( ) cm . ...
Called by the parent settings dialog when the user clicks on the Save button . Stores the current settings in the ConfigManager .
31,763
def _settings_str ( self ) : settings = "Automatically save changes: {}, " "Show tray icon: {}, " "Allow keyboard navigation: {}, " "Sort by usage count: {}, " "Enable undo using backspace: {}, " "Tray icon theme: {}" . format ( self . autosave_checkbox . isChecked ( ) , self . show_tray_checkbox . isChecked ( ) , self...
Returns a human readable settings representation for logging purposes .
31,764
def _should_trigger_abbreviation ( self , buffer ) : return any ( self . __checkInput ( buffer , abbr ) for abbr in self . abbreviations )
Checks whether based on the settings for the abbreviation and the given input the abbreviation should trigger .
31,765
def get_filter_regex ( self ) : if self . windowInfoRegex is not None : if self . isRecursive : return self . windowInfoRegex . pattern else : return self . windowInfoRegex . pattern elif self . parent is not None : return self . parent . get_child_filter ( ) else : return ""
Used by the GUI to obtain human - readable version of the filter
31,766
def add_item ( self , item ) : item . parent = self self . items . append ( item )
Add a new script or phrase to the folder .
31,767
def get_backspace_count ( self , buffer ) : if TriggerMode . ABBREVIATION in self . modes and self . backspace : if self . _should_trigger_abbreviation ( buffer ) : abbr = self . _get_trigger_abbreviation ( buffer ) stringBefore , typedAbbr , stringAfter = self . _partition_input ( buffer , abbr ) return len ( abbr ) +...
Given the input buffer calculate how many backspaces are needed to erase the text that triggered this folder .
31,768
def calculate_input ( self , buffer ) : if TriggerMode . ABBREVIATION in self . modes : if self . _should_trigger_abbreviation ( buffer ) : if self . immediate : return len ( self . _get_trigger_abbreviation ( buffer ) ) else : return len ( self . _get_trigger_abbreviation ( buffer ) ) + 1 if TriggerMode . HOTKEY in se...
Calculate how many keystrokes were used in triggering this phrase .
31,769
def _persist_metadata ( self ) : serializable_data = self . get_serializable ( ) try : self . _try_persist_metadata ( serializable_data ) except TypeError : cleaned_data = Script . _remove_non_serializable_store_entries ( serializable_data [ "store" ] ) self . _try_persist_metadata ( cleaned_data )
Write all script meta - data including the persistent script Store . The Store instance might contain arbitrary user data like function objects OpenCL contexts or whatever other non - serializable objects both as keys or values . Try to serialize the data and if it fails fall back to checking the store and removing all...
31,770
def _remove_non_serializable_store_entries ( store : Store ) -> dict : cleaned_store_data = { } for key , value in store . items ( ) : if Script . _is_serializable ( key ) and Script . _is_serializable ( value ) : cleaned_store_data [ key ] = value else : _logger . info ( "Skip non-serializable item in the local script...
Copy all serializable data into a new dict and skip the rest . This makes sure to keep the items during runtime even if the user edits and saves the script .
31,771
def _configure_root_logger ( self ) : root_logger = logging . getLogger ( ) root_logger . setLevel ( logging . DEBUG ) if self . args . verbose : handler = logging . StreamHandler ( sys . stdout ) else : handler = logging . handlers . RotatingFileHandler ( common . LOG_FILE , maxBytes = common . MAX_LOG_SIZE , backupCo...
Initialise logging system
31,772
def _create_storage_directories ( ) : if not os . path . exists ( common . CONFIG_DIR ) : os . makedirs ( common . CONFIG_DIR ) if not os . path . exists ( common . DATA_DIR ) : os . makedirs ( common . DATA_DIR ) if not os . path . exists ( common . RUN_DIR ) : os . makedirs ( common . RUN_DIR )
Create various storage directories if those do not exist .
31,773
def toggle_service ( self ) : self . monitoring_disabled . emit ( not self . service . is_running ( ) ) if self . service . is_running ( ) : self . pause_service ( ) else : self . unpause_service ( )
Convenience method for toggling the expansion service on or off . This is called by the global hotkey .
31,774
def create_assign_context_menu ( self ) : menu = QMenu ( "AutoKey" ) self . _build_menu ( menu ) self . setContextMenu ( menu )
Create a context menu then set the created QMenu as the context menu . This builds the menu with all required actions and signal - slot connections .
31,775
def update_tool_tip ( self , service_running : bool ) : if service_running : self . setToolTip ( TOOLTIP_RUNNING ) else : self . setToolTip ( TOOLTIP_PAUSED )
Slot function that updates the tooltip when the user activates or deactivates the expansion service .
31,776
def _create_action ( self , icon_name : Optional [ str ] , title : str , slot_function : Callable [ [ None ] , None ] , tool_tip : Optional [ str ] = None ) -> QAction : action = QAction ( title , self ) if icon_name : action . setIcon ( QIcon . fromTheme ( icon_name ) ) action . triggered . connect ( slot_function ) i...
QAction factory . All items created belong to the calling instance i . e . created QAction parent is self .
31,777
def _create_static_actions ( self ) : logger . info ( "Creating static context menu actions." ) self . action_view_script_error = self . _create_action ( None , "&View script error" , self . reset_tray_icon , "View the last script error." ) self . action_view_script_error . triggered . connect ( self . app . show_scrip...
Create all static menu actions . The created actions will be placed in the tray icon context menu .
31,778
def _fill_context_menu_with_model_item_actions ( self , context_menu : QMenu ) : logger . info ( "Rebuilding model item actions, adding all items marked for access through the tray icon." ) folders = [ folder for folder in self . config_manager . allFolders if folder . show_in_tray_menu ] items = [ item for item in sel...
Find all model items that should be available in the context menu and create QActions for each by using the available logic in popupmenu . PopupMenu .
31,779
def _build_menu ( self , context_menu : QMenu ) : logger . debug ( "Show tray icon enabled in settings: {}" . format ( cm . ConfigManager . SETTINGS [ cm . SHOW_TRAY_ICON ] ) ) self . _fill_context_menu_with_model_item_actions ( context_menu ) context_menu . addAction ( self . action_view_script_error ) context_menu . ...
Build the context menu .
31,780
def _persist_settings ( config_manager ) : serializable_data = config_manager . get_serializable ( ) try : _try_persist_settings ( serializable_data ) except ( TypeError , ValueError ) : _remove_non_serializable_store_entries ( serializable_data [ "settings" ] [ SCRIPT_GLOBALS ] ) _try_persist_settings ( serializable_d...
Write the settings including the persistent global script Store . The Store instance might contain arbitrary user data like function objects OpenCL contexts or whatever other non - serializable objects both as keys or values . Try to serialize the data and if it fails fall back to checking the store and removing all no...
31,781
def _remove_non_serializable_store_entries ( store : dict ) : removed_key_list = [ ] for key , value in store . items ( ) : if not ( _is_serializable ( key ) and _is_serializable ( value ) ) : _logger . info ( "Remove non-serializable item from the global script store. Key: '{}', Value: '{}'. " "This item cannot be sav...
This function is called if there are non - serializable items in the global script storage . This function removes all such items .
31,782
def get_autostart ( ) -> AutostartSettings : autostart_file = Path ( common . AUTOSTART_DIR ) / "autokey.desktop" if not autostart_file . exists ( ) : return AutostartSettings ( None , False ) else : return _extract_data_from_desktop_file ( autostart_file )
Returns the autostart settings as read from the system .
31,783
def _create_autostart_entry ( autostart_data : AutostartSettings , autostart_file : Path ) : try : source_desktop_file = get_source_desktop_file ( autostart_data . desktop_file_name ) except FileNotFoundError : _logger . exception ( "Failed to find a usable .desktop file! Unable to find: {}" . format ( autostart_data ....
Create an autostart . desktop file in the autostart directory if possible .
31,784
def delete_autostart_entry ( ) : autostart_file = Path ( common . AUTOSTART_DIR ) / "autokey.desktop" if autostart_file . exists ( ) : autostart_file . unlink ( ) _logger . info ( "Deleted old autostart entry: {}" . format ( autostart_file ) )
Remove a present autostart entry . If none is found nothing happens .
31,785
def apply_settings ( settings ) : for key , value in settings . items ( ) : ConfigManager . SETTINGS [ key ] = value
Allows new settings to be added without users having to lose all their configuration
31,786
def check_abbreviation_unique ( self , abbreviation , newFilterPattern , targetItem ) : for item in self . allFolders : if model . TriggerMode . ABBREVIATION in item . modes : if abbreviation in item . abbreviations and item . filter_matches ( newFilterPattern ) : return item is targetItem , item for item in self . all...
Checks that the given abbreviation is not already in use .
31,787
def check_hotkey_unique ( self , modifiers , hotKey , newFilterPattern , targetItem ) : for item in self . allFolders : if model . TriggerMode . HOTKEY in item . modes : if item . modifiers == modifiers and item . hotKey == hotKey and item . filter_matches ( newFilterPattern ) : return item is targetItem , item for ite...
Checks that the given hotkey is not already in use . Also checks the special hotkeys configured from the advanced settings dialog .
31,788
def on_setButton_pressed ( self ) : self . keyLabel . setText ( "Press a key or combination..." ) logger . debug ( "User starts to record a key combination." ) self . grabber = iomediator . KeyGrabber ( self ) self . grabber . start ( )
Start recording a key combination when the user clicks on the setButton . The button itself is automatically disabled during the recording process .
31,789
def set_key ( self , key , modifiers : typing . List [ Key ] = None ) : if modifiers is None : modifiers = [ ] if key in self . KEY_MAP : key = self . KEY_MAP [ key ] self . _setKeyLabel ( key ) self . key = key self . controlButton . setChecked ( Key . CONTROL in modifiers ) self . altButton . setChecked ( Key . ALT i...
This is called when the user successfully finishes recording a key combination .
31,790
def cancel_grab ( self ) : logger . debug ( "User canceled hotkey recording." ) self . recording_finished . emit ( True ) self . _setKeyLabel ( self . key if self . key is not None else "(None)" )
This is called when the user cancels a recording . Canceling is done by clicking with the left mouse button .
31,791
def handle_modifier_down ( self , modifier ) : _logger . debug ( "%s pressed" , modifier ) if modifier in ( Key . CAPSLOCK , Key . NUMLOCK ) : if self . modifiers [ modifier ] : self . modifiers [ modifier ] = False else : self . modifiers [ modifier ] = True else : self . modifiers [ modifier ] = True
Updates the state of the given modifier key to pressed
31,792
def handle_modifier_up ( self , modifier ) : _logger . debug ( "%s released" , modifier ) if modifier not in ( Key . CAPSLOCK , Key . NUMLOCK ) : self . modifiers [ modifier ] = False
Updates the state of the given modifier key to released .
31,793
def send_string ( self , string : str ) : if not string : return string = string . replace ( '\n' , "<enter>" ) string = string . replace ( '\t' , "<tab>" ) _logger . debug ( "Send via event interface" ) self . __clearModifiers ( ) modifiers = [ ] for section in KEY_SPLIT_RE . split ( string ) : if len ( section ) > 0 ...
Sends the given string for output .
31,794
def send_left ( self , count ) : for i in range ( count ) : self . interface . send_key ( Key . LEFT )
Sends the given number of left key presses .
31,795
def send_up ( self , count ) : for i in range ( count ) : self . interface . send_key ( Key . UP )
Sends the given number of up key presses .
31,796
def send_backspace ( self , count ) : for i in range ( count ) : self . interface . send_key ( Key . BACKSPACE )
Sends the given number of backspace key presses .
31,797
def fake_keypress ( self , key , repeat = 1 ) : for _ in range ( repeat ) : self . mediator . fake_keypress ( key )
Fake a keypress
31,798
def info_dialog ( self , title = "Information" , message = "" , ** kwargs ) : return self . _run_kdialog ( title , [ "--msgbox" , message ] , kwargs )
Show an information dialog
31,799
def calendar ( self , title = "Choose a date" , format_str = "%Y-%m-%d" , date = "today" , ** kwargs ) : return self . _run_kdialog ( title , [ "--calendar" , title ] , kwargs )
Show a calendar dialog