idx
int64
0
63k
question
stringlengths
61
4.03k
target
stringlengths
6
1.23k
31,800
def activate ( self , title , switchDesktop = False , matchClass = False ) : if switchDesktop : args = [ "-a" , title ] else : args = [ "-R" , title ] if matchClass : args += [ "-x" ] self . _run_wmctrl ( args )
Activate the specified window giving it input focus
31,801
def set_property ( self , title , action , prop , matchClass = False ) : if matchClass : xArgs = [ "-x" ] else : xArgs = [ ] self . _run_wmctrl ( [ "-r" , title , "-b" + action + ',' + prop ] + xArgs )
Set a property on the given window using the specified action
31,802
def run_script_from_macro ( self , args ) : self . __macroArgs = args [ "args" ] . split ( ',' ) try : self . run_script ( args [ "name" ] ) except Exception as e : self . set_return_value ( "{ERROR: %s}" % str ( e ) )
Used internally by AutoKey for phrase macros
31,803
def move_to_pat ( pat : str , offset : ( float , float ) = None , tolerance : int = 0 ) -> None : with tempfile . NamedTemporaryFile ( ) as f : subprocess . call ( + f . name , shell = True ) loc = visgrep ( f . name , pat , tolerance ) pat_size = get_png_dim ( pat ) if offset is None : x , y = [ l + ps // 2 for l , ps...
See help for click_on_pat
31,804
def acknowledge_gnome_notification ( ) : x0 , y0 = mouse_pos ( ) mouse_move ( 10000 , 10000 ) x , y = mouse_pos ( ) mouse_rmove ( - x / 2 , 0 ) mouse_click ( LEFT ) time . sleep ( .2 ) mouse_move ( x0 , y0 )
Moves mouse pointer to the bottom center of the screen and clicks on it .
31,805
def calculate_extra_keys ( self , buffer ) : extraBs = len ( self . inputStack ) - len ( buffer ) if extraBs > 0 : extraKeys = '' . join ( self . inputStack [ len ( buffer ) ] ) else : extraBs = 0 extraKeys = '' return extraBs , extraKeys
Determine extra keys pressed since the given buffer was built
31,806
def __updateStack ( self , key ) : if key == Key . ENTER : key = '\n' if key == Key . TAB : key = '\t' if key == Key . BACKSPACE : if ConfigManager . SETTINGS [ UNDO_USING_BACKSPACE ] and self . phraseRunner . can_undo ( ) : self . phraseRunner . undo_expansion ( ) else : try : self . inputStack . pop ( ) except IndexE...
Update the input stack in non - hotkey mode and determine if anything further is needed .
31,807
def __grabHotkeys ( self ) : c = self . app . configManager hotkeys = c . hotKeys + c . hotKeyFolders for item in c . globalHotkeys : if item . enabled : self . __enqueue ( self . __grabHotkey , item . hotKey , item . modifiers , self . rootWindow ) if self . __needsMutterWorkaround ( item ) : self . __enqueue ( self ....
Run during startup to grab global and specific hotkeys in all open windows
31,808
def __ungrabAllHotkeys ( self ) : c = self . app . configManager hotkeys = c . hotKeys + c . hotKeyFolders for item in c . globalHotkeys : if item . enabled : self . __ungrabHotkey ( item . hotKey , item . modifiers , self . rootWindow ) if self . __needsMutterWorkaround ( item ) : self . __ungrabRecurse ( item , self ...
Ungrab all hotkeys in preparation for keymap change
31,809
def __grabHotkeysForWindow ( self , window ) : c = self . app . configManager hotkeys = c . hotKeys + c . hotKeyFolders window_info = self . get_window_info ( window ) for item in hotkeys : if item . get_applicable_regex ( ) is not None and item . _should_trigger_window_title ( window_info ) : self . __enqueue ( self ....
Grab all hotkeys relevant to the window
31,810
def __grabHotkey ( self , key , modifiers , window ) : logger . debug ( "Grabbing hotkey: %r %r" , modifiers , key ) try : keycode = self . __lookupKeyCode ( key ) mask = 0 for mod in modifiers : mask |= self . modMasks [ mod ] window . grab_key ( keycode , mask , True , X . GrabModeAsync , X . GrabModeAsync ) if Key ....
Grab a specific hotkey in the given window
31,811
def grab_hotkey ( self , item ) : if item . get_applicable_regex ( ) is None : self . __enqueue ( self . __grabHotkey , item . hotKey , item . modifiers , self . rootWindow ) if self . __needsMutterWorkaround ( item ) : self . __enqueue ( self . __grabRecurse , item , self . rootWindow , False ) else : self . __enqueue...
Grab a hotkey .
31,812
def ungrab_hotkey ( self , item ) : import copy newItem = copy . copy ( item ) if item . get_applicable_regex ( ) is None : self . __enqueue ( self . __ungrabHotkey , newItem . hotKey , newItem . modifiers , self . rootWindow ) if self . __needsMutterWorkaround ( item ) : self . __enqueue ( self . __ungrabRecurse , new...
Ungrab a hotkey .
31,813
def __ungrabHotkey ( self , key , modifiers , window ) : logger . debug ( "Ungrabbing hotkey: %r %r" , modifiers , key ) try : keycode = self . __lookupKeyCode ( key ) mask = 0 for mod in modifiers : mask |= self . modMasks [ mod ] window . ungrab_key ( keycode , mask ) if Key . NUMLOCK in self . modMasks : window . un...
Ungrab a specific hotkey in the given window
31,814
def _send_string_clipboard ( self , string : str , paste_command : model . SendMode ) : backup = self . clipboard . text if backup is None : logger . warning ( "Tried to backup the X clipboard content, but got None instead of a string." ) self . clipboard . text = string try : self . mediator . send_string ( paste_comm...
Use the clipboard to send a string .
31,815
def _restore_clipboard_text ( self , backup : str ) : time . sleep ( 0.2 ) self . clipboard . text = backup if backup is not None else ""
Restore the clipboard content .
31,816
def _send_string_selection ( self , string : str ) : backup = self . clipboard . selection if backup is None : logger . warning ( "Tried to backup the X PRIMARY selection content, but got None instead of a string." ) self . clipboard . selection = string self . __enqueue ( self . _paste_using_mouse_button_2 ) self . __...
Use the mouse selection clipboard to send a string .
31,817
def _restore_clipboard_selection ( self , backup : str ) : time . sleep ( 1 ) self . clipboard . selection = backup if backup is not None else ""
Restore the selection clipboard content .
31,818
def save ( self ) : if self . path is None : if self . config_manager . userCodeDir is not None : sys . path . remove ( self . config_manager . userCodeDir ) self . config_manager . userCodeDir = None logger . info ( "Removed custom module search path from configuration and sys.path." ) else : if self . path != self . ...
This function is called by the parent dialog window when the user selects to save the settings .
31,819
def on_browse_button_pressed ( self ) : path = QFileDialog . getExistingDirectory ( self . parentWidget ( ) , "Choose a directory containing Python modules" ) if path : self . path = path self . clear_button . setEnabled ( True ) self . folder_label . setText ( path ) logger . debug ( "User selects a custom module sear...
PyQt slot called when the user hits the Browse button . Display a directory selection dialog and store the returned path .
31,820
def on_clear_button_pressed ( self ) : self . path = None self . clear_button . setEnabled ( False ) self . folder_label . setText ( self . initial_folder_label_text ) logger . debug ( "User selects to clear the custom module search path." )
PyQt slot called when the user hits the Clear button . Removes any set custom module search path .
31,821
def example_ylm ( m = 0 , n = 2 , shape = 128 , limits = [ - 4 , 4 ] , draw = True , show = True , ** kwargs ) : import ipyvolume . pylab as p3 __ , __ , __ , r , theta , phi = xyz ( shape = shape , limits = limits , spherical = True ) radial = np . exp ( - ( r - 2 ) ** 2 ) data = np . abs ( scipy . special . sph_harm ...
Show a spherical harmonic .
31,822
def ball ( rmax = 3 , rmin = 0 , shape = 128 , limits = [ - 4 , 4 ] , draw = True , show = True , ** kwargs ) : import ipyvolume . pylab as p3 __ , __ , __ , r , _theta , _phi = xyz ( shape = shape , limits = limits , spherical = True ) data = r * 0 data [ ( r < rmax ) & ( r >= rmin ) ] = 0.5 if "data_min" not in kwarg...
Show a ball .
31,823
def brain ( draw = True , show = True , fiducial = True , flat = True , inflated = True , subject = 'S1' , interval = 1000 , uv = True , color = None ) : import ipyvolume as ipv try : import cortex except : warnings . warn ( "it seems pycortex is not installed, which is needed for this example" ) raise xlist , ylist , ...
Show a human brain model .
31,824
def head ( draw = True , show = True , max_shape = 256 ) : import ipyvolume as ipv from scipy . interpolate import interp1d colors = [ [ 0.91 , 0.7 , 0.61 , 0.0 ] , [ 0.91 , 0.7 , 0.61 , 80.0 ] , [ 1.0 , 1.0 , 0.85 , 82.0 ] , [ 1.0 , 1.0 , 0.85 , 256 ] ] x = np . array ( [ k [ - 1 ] for k in colors ] ) rgb = np . array...
Show a volumetric rendering of a human male head .
31,825
def gaussian ( N = 1000 , draw = True , show = True , seed = 42 , color = None , marker = 'sphere' ) : import ipyvolume as ipv rng = np . random . RandomState ( seed ) x , y , z = rng . normal ( size = ( 3 , N ) ) if draw : if color : mesh = ipv . scatter ( x , y , z , marker = marker , color = color ) else : mesh = ip...
Show N random gaussian distributed points using a scatter plot .
31,826
def figure ( key = None , width = 400 , height = 500 , lighting = True , controls = True , controls_vr = False , controls_light = False , debug = False , ** kwargs ) : if key is not None and key in current . figures : current . figure = current . figures [ key ] current . container = current . containers [ key ] elif i...
Create a new figure if no key is given or return the figure associated with key .
31,827
def squarelim ( ) : fig = gcf ( ) xmin , xmax = fig . xlim ymin , ymax = fig . ylim zmin , zmax = fig . zlim width = max ( [ abs ( xmax - xmin ) , abs ( ymax - ymin ) , abs ( zmax - zmin ) ] ) xc = ( xmin + xmax ) / 2 yc = ( ymin + ymax ) / 2 zc = ( zmin + zmax ) / 2 xlim ( xc - width / 2 , xc + width / 2 ) ylim ( yc -...
Set all axes with equal aspect ratio such that the space is square .
31,828
def plot_surface ( x , y , z , color = default_color , wrapx = False , wrapy = False ) : return plot_mesh ( x , y , z , color = color , wrapx = wrapx , wrapy = wrapy , wireframe = False )
Draws a 2d surface in 3d defined by the 2d ordered arrays x y z .
31,829
def plot_wireframe ( x , y , z , color = default_color , wrapx = False , wrapy = False ) : return plot_mesh ( x , y , z , color = color , wrapx = wrapx , wrapy = wrapy , wireframe = True , surface = False )
Draws a 2d wireframe in 3d defines by the 2d ordered arrays x y z .
31,830
def plot ( x , y , z , color = default_color , ** kwargs ) : fig = gcf ( ) _grow_limits ( x , y , z ) defaults = dict ( visible_lines = True , color_selected = None , size_selected = 1 , size = 1 , connected = True , visible_markers = False ) kwargs = dict ( defaults , ** kwargs ) s = ipv . Scatter ( x = x , y = y , z ...
Plot a line in 3d .
31,831
def quiver ( x , y , z , u , v , w , size = default_size * 10 , size_selected = default_size_selected * 10 , color = default_color , color_selected = default_color_selected , marker = "arrow" , ** kwargs ) : fig = gcf ( ) _grow_limits ( x , y , z ) if 'vx' in kwargs or 'vy' in kwargs or 'vz' in kwargs : raise KeyError ...
Create a quiver plot which is like a scatter plot but with arrows pointing in the direction given by u v and w .
31,832
def animation_control ( object , sequence_length = None , add = True , interval = 200 ) : if isinstance ( object , ( list , tuple ) ) : objects = object else : objects = [ object ] del object if sequence_length is None : sequence_lengths = [ ] for object in objects : sequence_lengths_previous = list ( sequence_lengths ...
Animate scatter quiver or mesh by adding a slider and play button .
31,833
def transfer_function ( level = [ 0.1 , 0.5 , 0.9 ] , opacity = [ 0.01 , 0.05 , 0.1 ] , level_width = 0.1 , controls = True , max_opacity = 0.2 ) : tf_kwargs = { } try : level [ 0 ] except : level = [ level ] try : opacity [ 0 ] except : opacity = [ opacity ] * 3 try : level_width [ 0 ] except : level_width = [ level_w...
Create a transfer function see volshow .
31,834
def save ( filepath , makedirs = True , title = u'IPyVolume Widget' , all_states = False , offline = False , scripts_path = 'js' , drop_defaults = False , template_options = ( ( "extra_script_head" , "" ) , ( "body_pre" , "" ) , ( "body_post" , "" ) ) , devmode = False , offline_cors = False , ) : ipyvolume . embed . e...
Save the current container to a HTML file .
31,835
def screenshot ( width = None , height = None , format = "png" , fig = None , timeout_seconds = 10 , output_widget = None , headless = False , devmode = False , ) : assert format in [ 'png' , 'jpeg' , 'svg' ] , "image format must be png, jpeg or svg" data = _screenshot_data ( timeout_seconds = timeout_seconds , output_...
Save the figure to a PIL . Image object .
31,836
def savefig ( filename , width = None , height = None , fig = None , timeout_seconds = 10 , output_widget = None , headless = False , devmode = False ) : __ , ext = os . path . splitext ( filename ) format = ext [ 1 : ] assert format in [ 'png' , 'jpeg' , 'svg' ] , "image format must be png, jpeg or svg" with open ( fi...
Save the figure to an image file .
31,837
def xyzlabel ( labelx , labely , labelz ) : xlabel ( labelx ) ylabel ( labely ) zlabel ( labelz )
Set all labels at once .
31,838
def view ( azimuth = None , elevation = None , distance = None ) : fig = gcf ( ) x , y , z = fig . camera . position r = np . sqrt ( x ** 2 + y ** 2 + z ** 2 ) az = np . degrees ( np . arctan2 ( x , z ) ) el = np . degrees ( np . arcsin ( y / r ) ) if azimuth is None : azimuth = az if elevation is None : elevation = el...
Set camera angles and distance and return the current .
31,839
def plot_plane ( where = "back" , texture = None ) : fig = gcf ( ) xmin , xmax = fig . xlim ymin , ymax = fig . ylim zmin , zmax = fig . zlim if where == "back" : x = [ xmin , xmax , xmax , xmin ] y = [ ymin , ymin , ymax , ymax ] z = [ zmin , zmin , zmin , zmin ] if where == "front" : x = [ xmin , xmax , xmax , xmin ]...
Plot a plane at a particular location in the viewbox .
31,840
def _make_triangles_lines ( shape , wrapx = False , wrapy = False ) : nx , ny = shape mx = nx if wrapx else nx - 1 my = ny if wrapy else ny - 1 i , j = np . mgrid [ 0 : mx , 0 : my ] i , j = np . ravel ( i ) , np . ravel ( j ) t1 = ( i * ny + j , ( i + 1 ) % nx * ny + j , ( i + 1 ) % nx * ny + ( j + 1 ) % ny ) t2 = ( i...
Transform rectangular regular grid into triangles .
31,841
def save_ipyvolumejs ( target = "" , devmode = False , version = ipyvolume . _version . __version_js__ , version3js = __version_threejs__ ) : url = "https://unpkg.com/ipyvolume@{version}/dist/index.js" . format ( version = version ) pyv_filename = 'ipyvolume_v{version}.js' . format ( version = version ) pyv_filepath = ...
Output the ipyvolume javascript to a local file .
31,842
def save_requirejs ( target = "" , version = "2.3.4" ) : url = "https://cdnjs.cloudflare.com/ajax/libs/require.js/{version}/require.min.js" . format ( version = version ) filename = "require.min.v{0}.js" . format ( version ) filepath = os . path . join ( target , filename ) download_to_file ( url , filepath ) return fi...
Download and save the require javascript to a local file .
31,843
def save_embed_js ( target = "" , version = wembed . __html_manager_version__ ) : url = u'https://unpkg.com/@jupyter-widgets/html-manager@{0:s}/dist/embed-amd.js' . format ( version ) if version . startswith ( '^' ) : version = version [ 1 : ] filename = "embed-amd_v{0:s}.js" . format ( version ) filepath = os . path ....
Download and save the ipywidgets embedding javascript to a local file .
31,844
def save_font_awesome ( dirpath = '' , version = "4.7.0" ) : directory_name = "font-awesome-{0:s}" . format ( version ) directory_path = os . path . join ( dirpath , directory_name ) if os . path . exists ( directory_path ) : return directory_name url = "https://fontawesome.com/v{0:s}/assets/font-awesome-{0:s}.zip" . f...
Download and save the font - awesome package to a local directory .
31,845
def download_to_bytes ( url , chunk_size = 1024 * 1024 * 10 , loadbar_length = 10 ) : stream = False if chunk_size is None else True print ( "Downloading {0:s}: " . format ( url ) , end = "" ) response = requests . get ( url , stream = stream ) response . raise_for_status ( ) encoding = response . encoding total_length...
Download a url to bytes .
31,846
def download_yield_bytes ( url , chunk_size = 1024 * 1024 * 10 ) : response = requests . get ( url , stream = True ) response . raise_for_status ( ) total_length = response . headers . get ( 'content-length' ) if total_length is not None : total_length = float ( total_length ) length_str = "{0:.2f}Mb " . format ( total...
Yield a downloaded url as byte chunks .
31,847
def download_to_file ( url , filepath , resume = False , overwrite = False , chunk_size = 1024 * 1024 * 10 , loadbar_length = 10 ) : resume_header = None loaded_size = 0 write_mode = 'wb' if os . path . exists ( filepath ) : if overwrite : os . remove ( filepath ) elif resume : loaded_size = os . path . getsize ( filep...
Download a url .
31,848
def _randomSO3 ( ) : u1 = np . random . random ( ) u2 = np . random . random ( ) u3 = np . random . random ( ) R = np . array ( [ [ np . cos ( 2 * np . pi * u1 ) , np . sin ( 2 * np . pi * u1 ) , 0 ] , [ - np . sin ( 2 * np . pi * u1 ) , np . cos ( 2 * np . pi * u1 ) , 0 ] , [ 0 , 0 , 1 ] , ] ) v = np . array ( [ np . ...
Return random rotatation matrix algo by James Arvo .
31,849
def _set_client_id ( self , client_id ) : with self . lock : if self . client_id is None : self . client_id = client_id
Method for tracer to set client ID of throttler .
31,850
def _init_polling ( self ) : with self . lock : if not self . running : return r = random . Random ( ) delay = r . random ( ) * self . refresh_interval self . channel . io_loop . call_later ( delay = delay , callback = self . _delayed_polling ) self . logger . info ( 'Delaying throttling credit polling by %d sec' , del...
Bootstrap polling for throttler .
31,851
def close ( self ) : with self . stop_lock : self . stopped = True return ioloop_util . submit ( self . _flush , io_loop = self . io_loop )
Ensure that all spans from the queue are submitted . Returns Future that will be completed once the queue is empty .
31,852
def finish ( self , finish_time = None ) : if not self . is_sampled ( ) : return self . end_time = finish_time or time . time ( ) self . tracer . report_span ( self )
Indicate that the work represented by this span has been completed or terminated and is ready to be sent to the Reporter .
31,853
def _set_sampling_priority ( self , value ) : if self . is_debug ( ) and value : return False try : value_num = int ( value ) except ValueError : return False if value_num == 0 : self . context . flags &= ~ ( SAMPLED_FLAG | DEBUG_FLAG ) return False if self . tracer . is_debug_allowed ( self . operation_name ) : self ....
N . B . Caller must be holding update_lock .
31,854
def write ( self , buf ) : return self . transport_sock . sendto ( buf , ( self . transport_host , self . transport_port ) )
Raw write to the UDP socket .
31,855
def initialize_tracer ( self , io_loop = None ) : with Config . _initialized_lock : if Config . _initialized : logger . warn ( 'Jaeger tracer already initialized, skipping' ) return Config . _initialized = True tracer = self . new_tracer ( io_loop ) self . _initialize_global_tracer ( tracer = tracer ) return tracer
Initialize Jaeger Tracer based on the passed jaeger_client . Config . Save it to opentracing . tracer global variable . Only the first call to this method has any effect .
31,856
def new_tracer ( self , io_loop = None ) : channel = self . _create_local_agent_channel ( io_loop = io_loop ) sampler = self . sampler if not sampler : sampler = RemoteControlledSampler ( channel = channel , service_name = self . service_name , logger = logger , metrics_factory = self . _metrics_factory , error_reporte...
Create a new Jaeger Tracer based on the passed jaeger_client . Config . Does not set opentracing . tracer global variable .
31,857
def _create_local_agent_channel ( self , io_loop ) : logger . info ( 'Initializing Jaeger Tracer with UDP reporter' ) return LocalAgentSender ( host = self . local_agent_reporting_host , sampling_port = self . local_agent_sampling_port , reporting_port = self . local_agent_reporting_port , throttling_port = self . thro...
Create an out - of - process channel communicating to local jaeger - agent . Spans are submitted as SOCK_DGRAM Thrift sampling strategy is polled via JSON HTTP .
31,858
def span_context_from_string ( value ) : if type ( value ) is list and len ( value ) > 0 : if len ( value ) > 1 : raise SpanContextCorruptedException ( 'trace context must be a string or array of 1: "%s"' % value ) value = value [ 0 ] if not isinstance ( value , six . string_types ) : raise SpanContextCorruptedExceptio...
Decode span ID from a string into a TraceContext . Returns None if the string value is malformed .
31,859
def parse_sampling_strategy ( response ) : s_type = response . strategyType if s_type == sampling_manager . SamplingStrategyType . PROBABILISTIC : if response . probabilisticSampling is None : return None , 'probabilisticSampling field is None' sampling_rate = response . probabilisticSampling . samplingRate if 0 <= sam...
Parse SamplingStrategyResponse and converts to a Sampler .
31,860
def with_debug_id ( debug_id ) : ctx = SpanContext ( trace_id = None , span_id = None , parent_id = None , flags = None ) ctx . _debug_id = debug_id return ctx
Deprecated not used by Jaeger .
31,861
def start_span ( self , operation_name = None , child_of = None , references = None , tags = None , start_time = None , ignore_active_span = False , ) : parent = child_of if self . active_span is not None and not ignore_active_span and not parent : parent = self . active_span if isinstance ( parent , Span ) : parent = ...
Start and return a new Span representing a unit of work .
31,862
def merge_lvm_data ( primary , secondary , name_key ) : pri_data = to_name_key_dict ( primary , name_key ) combined_data = to_name_key_dict ( secondary , name_key ) for name in pri_data : if name not in combined_data : combined_data [ name ] = pri_data [ name ] else : combined_data [ name ] . update ( dict ( ( k , v ) ...
Returns a dictionary containing the set of data from primary and secondary where values in primary will always be returned if present and values in secondary will only be returned if not present in primary or if the value in primary is None .
31,863
def get_output ( self ) : if not os . path . isfile ( self . real_path ) : logger . debug ( 'File %s does not exist' , self . real_path ) return cmd = [ ] cmd . append ( 'sed' ) cmd . append ( '-rf' ) cmd . append ( constants . default_sed_file ) cmd . append ( self . real_path ) sedcmd = Popen ( cmd , stdout = PIPE ) ...
Get file content selecting only lines we are interested in
31,864
def _parse_line ( self , line ) : fields = line . split ( '|' , 4 ) line_info = { 'raw_message' : line } if len ( fields ) == 5 : line_info . update ( dict ( zip ( self . _fieldnames , fields ) ) ) return line_info
Parse line into fields .
31,865
def _import_component ( name ) : for f in ( _get_from_module , _get_from_class ) : try : return f ( name ) except : pass log . debug ( "Couldn't load %s" % name )
Returns a class function or class method specified by the fully qualified name .
31,866
def get_name ( component ) : if six . callable ( component ) : name = getattr ( component , "__qualname__" , component . __name__ ) return '.' . join ( [ component . __module__ , name ] ) return str ( component )
Attempt to get the string name of component including module and class if applicable .
31,867
def walk_dependencies ( root , visitor ) : def visit ( parent , visitor ) : for d in get_dependencies ( parent ) : visitor ( d , parent ) visit ( d , visitor ) visitor ( root , None ) visit ( root , visitor )
Call visitor on root and all dependencies reachable from it in breadth first order .
31,868
def get_subgraphs ( graph = None ) : graph = graph or DEPENDENCIES keys = set ( graph ) frontier = set ( ) seen = set ( ) while keys : frontier . add ( keys . pop ( ) ) while frontier : component = frontier . pop ( ) seen . add ( component ) frontier |= set ( [ d for d in get_dependencies ( component ) if d in graph ] ...
Given a graph of possibly disconnected components generate all graphs of connected components . graph is a dictionary of dependencies . Keys are components and values are sets of components on which they depend .
31,869
def load_components ( * paths , ** kwargs ) : num_loaded = 0 for path in paths : num_loaded += _load_components ( path , ** kwargs ) return num_loaded
Loads all components on the paths . Each path should be a package or module . All components beneath a path are loaded .
31,870
def run ( components = None , broker = None ) : components = components or COMPONENTS [ GROUPS . single ] components = _determine_components ( components ) broker = broker or Broker ( ) for component in run_order ( components ) : start = time . time ( ) try : if component not in broker and component in DELEGATES and is...
Executes components in an order that satisfies their dependency relationships .
31,871
def run_incremental ( components = None , broker = None ) : for graph , _broker in generate_incremental ( components , broker ) : yield run ( graph , broker = _broker )
Executes components in an order that satisfies their dependency relationships . Disjoint subgraphs are executed one at a time and a broker containing the results for each is yielded . If a broker is passed here its instances are used to seed the broker used to hold state for each sub graph .
31,872
def invoke ( self , results ) : args = [ results . get ( d ) for d in self . deps ] return self . component ( * args )
Handles invocation of the component . The default implementation invokes it with positional arguments based on order of dependency declaration .
31,873
def get_missing_dependencies ( self , broker ) : missing_required = [ r for r in self . requires if r not in broker ] missing_at_least_one = [ d for d in self . at_least_one if not set ( d ) . intersection ( broker ) ] if missing_required or missing_at_least_one : return ( missing_required , missing_at_least_one )
Gets required and at - least - one dependencies not provided by the broker .
31,874
def observer ( self , component_type = ComponentType ) : def inner ( func ) : self . add_observer ( func , component_type ) return func return inner
You can use
31,875
def add_observer ( self , o , component_type = ComponentType ) : self . observers [ component_type ] . add ( o )
Add a callback that will get invoked after each component is called .
31,876
def get_tree ( root = None ) : from insights import run return run ( LogRotateConfTree , root = root ) . get ( LogRotateConfTree )
This is a helper function to get a logrotate configuration component for your local machine or an archive . It s for use in interactive sessions .
31,877
def logit ( self , msg , pid , user , cname , priority = None ) : if self . stream : print ( msg , file = self . stream ) elif priority == logging . WARNING : self . logger . warning ( "{0}[pid:{1}] user:{2}: WARNING - {3}" . format ( cname , pid , user , msg ) ) elif priority == logging . ERROR : self . logger . error...
Function for formatting content and logging to syslog
31,878
def log_exceptions ( self , c , broker ) : if c in broker . exceptions : ex = broker . exceptions . get ( c ) ex = "Exception in {0} - {1}" . format ( dr . get_name ( c ) , str ( ex ) ) self . logit ( ex , self . pid , self . user , "insights-run" , logging . ERROR )
Gets exceptions to be logged and sends to logit function to be logged to syslog
31,879
def log_rule_info ( self ) : for c in sorted ( self . broker . get_by_type ( rule ) , key = dr . get_name ) : v = self . broker [ c ] _type = v . get ( "type" ) if _type : if _type != "skip" : msg = "Running {0} " . format ( dr . get_name ( c ) ) self . logit ( msg , self . pid , self . user , "insights-run" , logging ...
Collects rule information and send to logit function to log to syslog
31,880
def _run_pre_command ( self , pre_cmd ) : logger . debug ( 'Executing pre-command: %s' , pre_cmd ) try : pre_proc = Popen ( pre_cmd , stdout = PIPE , stderr = STDOUT , shell = True ) except OSError as err : if err . errno == errno . ENOENT : logger . debug ( 'Command %s not found' , pre_cmd ) return stdout , stderr = p...
Run a pre command to get external args for a command
31,881
def _parse_file_spec ( self , spec ) : if '*' in spec [ 'file' ] : expanded_paths = _expand_paths ( spec [ 'file' ] ) if not expanded_paths : return [ ] expanded_specs = [ ] for p in expanded_paths : _spec = copy . copy ( spec ) _spec [ 'file' ] = p expanded_specs . append ( _spec ) return expanded_specs else : return ...
Separate wildcard specs into more specs
31,882
def _parse_glob_spec ( self , spec ) : some_globs = glob . glob ( spec [ 'glob' ] ) if not some_globs : return [ ] el_globs = [ ] for g in some_globs : _spec = copy . copy ( spec ) _spec [ 'file' ] = g el_globs . append ( _spec ) return el_globs
Grab globs of things
31,883
def run_collection ( self , conf , rm_conf , branch_info ) : if rm_conf is None : rm_conf = { } logger . debug ( 'Beginning to run collection spec...' ) exclude = None if rm_conf : try : exclude = rm_conf [ 'patterns' ] logger . warn ( "WARNING: Skipping patterns found in remove.conf" ) except LookupError : logger . de...
Run specs and collect all the data
31,884
def done ( self , conf , rm_conf ) : if self . config . obfuscate : cleaner = SOSCleaner ( quiet = True ) clean_opts = CleanOptions ( self . config , self . archive . tmp_dir , rm_conf , self . hostname_path ) fresh = cleaner . clean_report ( clean_opts , self . archive . archive_dir ) if clean_opts . keyword_file is n...
Do finalization stuff
31,885
def sap_sid_nr ( broker ) : insts = broker [ DefaultSpecs . saphostctrl_listinstances ] . content hn = broker [ DefaultSpecs . hostname ] . content [ 0 ] . split ( '.' ) [ 0 ] . strip ( ) results = set ( ) for ins in insts : ins_splits = ins . split ( ' - ' ) if ins_splits [ 2 ] . strip ( ) == hn : results . add ( ( in...
Get the SID and Instance Number
31,886
def from_dict ( self , dirent ) : for k in [ 'perms' , 'owner' , 'group' , 'name' , 'dir' ] : if k not in dirent : raise ValueError ( "Need required key '{k}'" . format ( k = k ) ) for k in dirent : setattr ( self , k , dirent [ k ] ) self . perms_owner = self . perms [ 0 : 3 ] self . perms_group = self . perms [ 3 : 6...
Create a new FilePermissions object from the given dictionary . This works with the FileListing parser class which has already done the hard work of pulling many of these fields out . We create an object with all the dictionary keys available as properties and also split the perms string up into owner group
31,887
def owned_by ( self , owner , also_check_group = False ) : if also_check_group : return self . owner == owner and self . group == owner else : return self . owner == owner
Checks if the specified user or user and group own the file .
31,888
def get_tree ( root = None ) : from insights import run return run ( MultipathConfTree , root = root ) . get ( MultipathConfTree )
This is a helper function to get a multipath configuration component for your local machine or an archive . It s for use in interactive sessions .
31,889
def _support_diag_dump ( self ) : cfg_block = [ ] pconn = InsightsConnection ( self . config ) logger . info ( 'Insights version: %s' , get_nvr ( ) ) reg_check = registration_check ( pconn ) cfg_block . append ( 'Registration check:' ) for key in reg_check : cfg_block . append ( key + ': ' + str ( reg_check [ key ] ) )...
Collect log info for debug
31,890
def add_filter ( ds , patterns ) : if not plugins . is_datasource ( ds ) : raise Exception ( "Filters are applicable only to datasources." ) delegate = dr . get_delegate ( ds ) if delegate . raw : raise Exception ( "Filters aren't applicable to raw datasources." ) if not delegate . filterable : raise Exception ( "Filte...
Add a filter or list of filters to a datasource . A filter is a simple string and it matches if it is contained anywhere within a line .
31,891
def get_filters ( component ) : def inner ( c , filters = None ) : filters = filters or set ( ) if not ENABLED : return filters if not plugins . is_datasource ( c ) : return filters if c in FILTERS : filters |= FILTERS [ c ] for d in dr . get_dependents ( c ) : filters |= inner ( d , filters ) return filters if compone...
Get the set of filters for the given datasource .
31,892
def apply_filters ( target , lines ) : filters = get_filters ( target ) if filters : for l in lines : if any ( f in l for f in filters ) : yield l else : for l in lines : yield l
Applys filters to the lines of a datasource . This function is used only in integration tests . Filters are applied in an equivalent but more performant way at run time .
31,893
def loads ( string ) : d = _loads ( string ) for k , v in d . items ( ) : FILTERS [ dr . get_component ( k ) or k ] = set ( v )
Loads the filters dictionary given a string .
31,894
def load ( stream = None ) : if stream : loads ( stream . read ( ) ) else : data = pkgutil . get_data ( insights . __name__ , _filename ) return loads ( data ) if data else None
Loads filters from a stream normally an open file . If one is not passed filters are loaded from a default location within the project .
31,895
def dumps ( ) : d = { } for k , v in FILTERS . items ( ) : d [ dr . get_name ( k ) ] = list ( v ) return _dumps ( d )
Returns a string representation of the FILTERS dictionary .
31,896
def dump ( stream = None ) : if stream : stream . write ( dumps ( ) ) else : path = os . path . join ( os . path . dirname ( insights . __file__ ) , _filename ) with open ( path , "wu" ) as f : f . write ( dumps ( ) )
Dumps a string representation of FILTERS to a stream normally an open file . If none is passed FILTERS is dumped to a default location within the project .
31,897
def _parse_script ( list , line , line_iter ) : ifIdx = 0 while ( True ) : line = next ( line_iter ) if line . startswith ( "fi" ) : if ifIdx == 0 : return ifIdx -= 1 elif line . startswith ( "if" ) : ifIdx += 1
Eliminate any bash script contained in the grub v2 configuration
31,898
def _parse_title ( line_iter , cur_line , conf ) : title = [ ] conf [ 'title' ] . append ( title ) title . append ( ( 'title_name' , cur_line . split ( 'title' , 1 ) [ 1 ] . strip ( ) ) ) while ( True ) : line = next ( line_iter ) if line . startswith ( "title " ) : return line cmd , opt = _parse_cmd ( line ) title . a...
Parse title in grub v1 config
31,899
def is_kdump_iommu_enabled ( self ) : for line in self . _boot_entries : if line . cmdline and IOMMU in line . cmdline : return True return False
Does any kernel have intel_iommu = on set?