idx
int64
0
63k
question
stringlengths
61
4.03k
target
stringlengths
6
1.23k
30,400
def set_win_wallpaper ( img ) : if "x86" in os . environ [ "PROGRAMFILES" ] : ctypes . windll . user32 . SystemParametersInfoW ( 20 , 0 , img , 3 ) else : ctypes . windll . user32 . SystemParametersInfoA ( 20 , 0 , img , 3 )
Set the wallpaper on Windows .
30,401
def change ( img ) : if not os . path . isfile ( img ) : return desktop = get_desktop_env ( ) if OS == "Darwin" : set_mac_wallpaper ( img ) elif OS == "Windows" : set_win_wallpaper ( img ) else : set_desktop_wallpaper ( desktop , img ) logging . info ( "Set the new wallpaper." )
Set the wallpaper .
30,402
def get ( cache_dir = CACHE_DIR ) : current_wall = os . path . join ( cache_dir , "wal" ) if os . path . isfile ( current_wall ) : return util . read_file ( current_wall ) [ 0 ] return "None"
Get the current wallpaper .
30,403
def save_file_json ( data , export_file ) : create_dir ( os . path . dirname ( export_file ) ) with open ( export_file , "w" ) as file : json . dump ( data , file , indent = 4 )
Write data to a json file .
30,404
def setup_logging ( ) : logging . basicConfig ( format = ( "[%(levelname)s\033[0m] " "\033[1;31m%(module)s\033[0m: " "%(message)s" ) , level = logging . INFO , stream = sys . stdout ) logging . addLevelName ( logging . ERROR , '\033[1;31mE' ) logging . addLevelName ( logging . INFO , '\033[1;32mI' ) logging . addLevelN...
Logging config .
30,405
def darken_color ( color , amount ) : color = [ int ( col * ( 1 - amount ) ) for col in hex_to_rgb ( color ) ] return rgb_to_hex ( color )
Darken a hex color .
30,406
def lighten_color ( color , amount ) : color = [ int ( col + ( 255 - col ) * amount ) for col in hex_to_rgb ( color ) ] return rgb_to_hex ( color )
Lighten a hex color .
30,407
def blend_color ( color , color2 ) : r1 , g1 , b1 = hex_to_rgb ( color ) r2 , g2 , b2 = hex_to_rgb ( color2 ) r3 = int ( 0.5 * r1 + 0.5 * r2 ) g3 = int ( 0.5 * g1 + 0.5 * g2 ) b3 = int ( 0.5 * b1 + 0.5 * b2 ) return rgb_to_hex ( ( r3 , g3 , b3 ) )
Blend two colors together .
30,408
def saturate_color ( color , amount ) : r , g , b = hex_to_rgb ( color ) r , g , b = [ x / 255.0 for x in ( r , g , b ) ] h , l , s = colorsys . rgb_to_hls ( r , g , b ) s = amount r , g , b = colorsys . hls_to_rgb ( h , l , s ) r , g , b = [ x * 255.0 for x in ( r , g , b ) ] return rgb_to_hex ( ( int ( r ) , int ( g ...
Saturate a hex color .
30,409
def disown ( cmd ) : subprocess . Popen ( cmd , stdout = subprocess . DEVNULL , stderr = subprocess . DEVNULL )
Call a system command in the background disown it and hide it s output .
30,410
def get_pid ( name ) : if not shutil . which ( "pidof" ) : return False try : subprocess . check_output ( [ "pidof" , "-s" , name ] ) except subprocess . CalledProcessError : return False return True
Check if process is running by name .
30,411
def get_image_dir ( img_dir ) : current_wall = wallpaper . get ( ) current_wall = os . path . basename ( current_wall ) file_types = ( ".png" , ".jpg" , ".jpeg" , ".jpe" , ".gif" ) return [ img . name for img in os . scandir ( img_dir ) if img . name . lower ( ) . endswith ( file_types ) ] , current_wall
Get all images in a directory .
30,412
def get_random_image ( img_dir ) : images , current_wall = get_image_dir ( img_dir ) if len ( images ) > 2 and current_wall in images : images . remove ( current_wall ) elif not images : logging . error ( "No images found in directory." ) sys . exit ( 1 ) random . shuffle ( images ) return os . path . join ( img_dir , ...
Pick a random image file from a directory .
30,413
def get_next_image ( img_dir ) : images , current_wall = get_image_dir ( img_dir ) images . sort ( key = lambda img : [ int ( x ) if x . isdigit ( ) else x for x in re . split ( '([0-9]+)' , img ) ] ) try : next_index = images . index ( current_wall ) + 1 except ValueError : next_index = 0 try : image = images [ next_i...
Get the next image in a dir .
30,414
def get ( img , cache_dir = CACHE_DIR , iterative = False ) : if os . path . isfile ( img ) : wal_img = img elif os . path . isdir ( img ) : if iterative : wal_img = get_next_image ( img ) else : wal_img = get_random_image ( img ) else : logging . error ( "No valid image file found." ) sys . exit ( 1 ) wal_img = os . p...
Validate image input .
30,415
def gtk_reload ( ) : events = gtk . gdk . Event ( gtk . gdk . CLIENT_EVENT ) data = gtk . gdk . atom_intern ( "_GTK_READ_RCFILES" , False ) events . data_format = 8 events . send_event = True events . message_type = data events . send_clientmessage_toall ( )
Reload GTK2 themes .
30,416
def list_backends ( ) : return [ b . name . replace ( ".py" , "" ) for b in os . scandir ( os . path . join ( MODULE_DIR , "backends" ) ) if "__" not in b . name ]
List color backends .
30,417
def colors_to_dict ( colors , img ) : return { "wallpaper" : img , "alpha" : util . Color . alpha_num , "special" : { "background" : colors [ 0 ] , "foreground" : colors [ 15 ] , "cursor" : colors [ 15 ] } , "colors" : { "color0" : colors [ 0 ] , "color1" : colors [ 1 ] , "color2" : colors [ 2 ] , "color3" : colors [ 3...
Convert list of colors to pywal format .
30,418
def generic_adjust ( colors , light ) : if light : for color in colors : color = util . saturate_color ( color , 0.60 ) color = util . darken_color ( color , 0.5 ) colors [ 0 ] = util . lighten_color ( colors [ 0 ] , 0.95 ) colors [ 7 ] = util . darken_color ( colors [ 0 ] , 0.75 ) colors [ 8 ] = util . darken_color ( ...
Generic color adjustment for themers .
30,419
def saturate_colors ( colors , amount ) : if amount and float ( amount ) <= 1.0 : for i , _ in enumerate ( colors ) : if i not in [ 0 , 7 , 8 , 15 ] : colors [ i ] = util . saturate_color ( colors [ i ] , float ( amount ) ) return colors
Saturate all colors .
30,420
def get_backend ( backend ) : if backend == "random" : backends = list_backends ( ) random . shuffle ( backends ) return backends [ 0 ] return backend
Figure out which backend to use .
30,421
def palette ( ) : for i in range ( 0 , 16 ) : if i % 8 == 0 : print ( ) if i > 7 : i = "8;5;%s" % i print ( "\033[4%sm%s\033[0m" % ( i , " " * ( 80 // 20 ) ) , end = "" ) print ( "\n" )
Generate a palette from the colors .
30,422
def gen_colors ( img ) : color_cmd = ColorThief ( img ) . get_palette for i in range ( 0 , 10 , 1 ) : raw_colors = color_cmd ( color_count = 8 + i ) if len ( raw_colors ) >= 8 : break elif i == 10 : logging . error ( "ColorThief couldn't generate a suitable palette." ) sys . exit ( 1 ) else : logging . warning ( "Color...
Loop until 16 colors are generated .
30,423
def list_out ( ) : dark_themes = [ theme . name . replace ( ".json" , "" ) for theme in list_themes ( ) ] ligh_themes = [ theme . name . replace ( ".json" , "" ) for theme in list_themes ( dark = False ) ] user_themes = [ theme . name . replace ( ".json" , "" ) for theme in list_themes_user ( ) ] if user_themes : print...
List all themes in a pretty format .
30,424
def list_themes ( dark = True ) : dark = "dark" if dark else "light" themes = os . scandir ( os . path . join ( MODULE_DIR , "colorschemes" , dark ) ) return [ t for t in themes if os . path . isfile ( t . path ) ]
List all installed theme files .
30,425
def list_themes_user ( ) : themes = [ * os . scandir ( os . path . join ( CONF_DIR , "colorschemes/dark/" ) ) , * os . scandir ( os . path . join ( CONF_DIR , "colorschemes/light/" ) ) ] return [ t for t in themes if os . path . isfile ( t . path ) ]
List user theme files .
30,426
def terminal_sexy_to_wal ( data ) : data [ "colors" ] = { } data [ "special" ] = { "foreground" : data [ "foreground" ] , "background" : data [ "background" ] , "cursor" : data [ "color" ] [ 9 ] } for i , color in enumerate ( data [ "color" ] ) : data [ "colors" ] [ "color%s" % i ] = color return data
Convert terminal . sexy json schema to wal .
30,427
def parse ( theme_file ) : data = util . read_file_json ( theme_file ) if "wallpaper" not in data : data [ "wallpaper" ] = "None" if "alpha" not in data : data [ "alpha" ] = util . Color . alpha_num if "color" in data : data = terminal_sexy_to_wal ( data ) return data
Parse the theme file .
30,428
def get_random_theme ( dark = True ) : themes = [ theme . path for theme in list_themes ( dark ) ] random . shuffle ( themes ) return themes [ 0 ]
Get a random theme file .
30,429
def file ( input_file , light = False ) : util . create_dir ( os . path . join ( CONF_DIR , "colorschemes/light/" ) ) util . create_dir ( os . path . join ( CONF_DIR , "colorschemes/dark/" ) ) theme_name = "." . join ( ( input_file , "json" ) ) bri = "light" if light else "dark" user_theme_file = os . path . join ( CON...
Import colorscheme from json file .
30,430
def imagemagick ( color_count , img , magick_command ) : flags = [ "-resize" , "25%" , "-colors" , str ( color_count ) , "-unique-colors" , "txt:-" ] img += "[0]" return subprocess . check_output ( [ * magick_command , img , * flags ] ) . splitlines ( )
Call Imagemagick to generate a scheme .
30,431
def has_im ( ) : if shutil . which ( "magick" ) : return [ "magick" , "convert" ] if shutil . which ( "convert" ) : return [ "convert" ] logging . error ( "Imagemagick wasn't found on your system." ) logging . error ( "Try another backend. (wal --backend)" ) sys . exit ( 1 )
Check to see if the user has im installed .
30,432
def gen_colors ( img ) : magick_command = has_im ( ) for i in range ( 0 , 20 , 1 ) : raw_colors = imagemagick ( 16 + i , img , magick_command ) if len ( raw_colors ) > 16 : break elif i == 19 : logging . error ( "Imagemagick couldn't generate a suitable palette." ) sys . exit ( 1 ) else : logging . warning ( "Imagemagi...
Format the output from imagemagick into a list of hex colors .
30,433
def adjust ( colors , light ) : raw_colors = colors [ : 1 ] + colors [ 8 : 16 ] + colors [ 8 : - 1 ] if light : for color in raw_colors : color = util . saturate_color ( color , 0.5 ) raw_colors [ 0 ] = util . lighten_color ( colors [ - 1 ] , 0.85 ) raw_colors [ 7 ] = colors [ 0 ] raw_colors [ 8 ] = util . darken_color...
Adjust the generated colors and store them in a dict that we will later save in json format .
30,434
def parse_args_exit ( parser ) : args = parser . parse_args ( ) if len ( sys . argv ) <= 1 : parser . print_help ( ) sys . exit ( 1 ) if args . v : parser . exit ( 0 , "wal %s\n" % __version__ ) if args . preview : print ( "Current colorscheme:" , sep = '' ) colors . palette ( ) sys . exit ( 0 ) if args . i and args . ...
Process args that exit .
30,435
def parse_args ( parser ) : args = parser . parse_args ( ) if args . q : logging . getLogger ( ) . disabled = True sys . stdout = sys . stderr = open ( os . devnull , "w" ) if args . a : util . Color . alpha_num = args . a if args . i : image_file = image . get ( args . i , iterative = args . iterative ) colors_plain =...
Process args .
30,436
def set_special ( index , color , iterm_name = "h" , alpha = 100 ) : if OS == "Darwin" and iterm_name : return "\033]P%s%s\033\\" % ( iterm_name , color . strip ( "#" ) ) if index in [ 11 , 708 ] and alpha != "100" : return "\033]%s;[%s]%s\033\\" % ( index , alpha , color ) return "\033]%s;%s\033\\" % ( index , color )
Convert a hex color to a special sequence .
30,437
def set_color ( index , color ) : if OS == "Darwin" and index < 20 : return "\033]P%1x%s\033\\" % ( index , color . strip ( "#" ) ) return "\033]4;%s;%s\033\\" % ( index , color )
Convert a hex color to a text color sequence .
30,438
def create_sequences ( colors , vte_fix = False ) : alpha = colors [ "alpha" ] sequences = [ set_color ( index , colors [ "colors" ] [ "color%s" % index ] ) for index in range ( 16 ) ] sequences . extend ( [ set_special ( 10 , colors [ "special" ] [ "foreground" ] , "g" ) , set_special ( 11 , colors [ "special" ] [ "ba...
Create the escape sequences .
30,439
def send ( colors , cache_dir = CACHE_DIR , to_send = True , vte_fix = False ) : if OS == "Darwin" : tty_pattern = "/dev/ttys00[0-9]*" else : tty_pattern = "/dev/pts/[0-9]*" sequences = create_sequences ( colors , vte_fix ) if to_send : for term in glob . glob ( tty_pattern ) : util . save_file ( sequences , term ) uti...
Send colors to all open terminals .
30,440
def template ( colors , input_file , output_file = None ) : template_data = util . read_file_raw ( input_file ) try : template_data = "" . join ( template_data ) . format ( ** colors ) except ValueError : logging . error ( "Syntax error in template file '%s'." , input_file ) return util . save_file ( template_data , ou...
Read template file substitute markers and save the file elsewhere .
30,441
def every ( colors , output_dir = CACHE_DIR ) : colors = flatten_colors ( colors ) template_dir = os . path . join ( MODULE_DIR , "templates" ) template_dir_user = os . path . join ( CONF_DIR , "templates" ) util . create_dir ( template_dir_user ) join = os . path . join for file in [ * os . scandir ( template_dir ) , ...
Export all template files .
30,442
def color ( colors , export_type , output_file = None ) : all_colors = flatten_colors ( colors ) template_name = get_export_type ( export_type ) template_file = os . path . join ( MODULE_DIR , "templates" , template_name ) output_file = output_file or os . path . join ( CACHE_DIR , template_name ) if os . path . isfile...
Export a single template file .
30,443
def tty ( tty_reload ) : tty_script = os . path . join ( CACHE_DIR , "colors-tty.sh" ) term = os . environ . get ( "TERM" ) if tty_reload and term == "linux" : subprocess . Popen ( [ "sh" , tty_script ] )
Load colors in tty .
30,444
def xrdb ( xrdb_files = None ) : xrdb_files = xrdb_files or [ os . path . join ( CACHE_DIR , "colors.Xresources" ) ] if shutil . which ( "xrdb" ) and OS != "Darwin" : for file in xrdb_files : subprocess . run ( [ "xrdb" , "-merge" , "-quiet" , file ] )
Merge the colors into the X db so new terminals use them .
30,445
def gtk ( ) : if shutil . which ( "python2" ) : gtk_reload = os . path . join ( MODULE_DIR , "scripts" , "gtk_reload.py" ) util . disown ( [ "python2" , gtk_reload ] ) else : logging . warning ( "GTK2 reload support requires Python 2." )
Reload GTK theme on the fly .
30,446
def env ( xrdb_file = None , tty_reload = True ) : xrdb ( xrdb_file ) i3 ( ) bspwm ( ) kitty ( ) sway ( ) polybar ( ) logging . info ( "Reloaded environment." ) tty ( tty_reload )
Reload environment .
30,447
def add_resource ( self , filename ) : filename = os . path . abspath ( filename ) self . _emit_resource_added ( filename )
Add a file as a resource .
30,448
def find_best_match ( path , prefixes ) : path_parts = path . split ( '.' ) for p in prefixes : if len ( p ) <= len ( path_parts ) and p == path_parts [ : len ( p ) ] : return '.' . join ( p ) , '.' . join ( path_parts [ len ( p ) : ] ) return '' , path
Find the Ingredient that shares the longest prefix with path .
30,449
def _non_unicode_repr ( objekt , context , maxlevels , level ) : repr_string , isreadable , isrecursive = pprint . _safe_repr ( objekt , context , maxlevels , level ) if repr_string . startswith ( 'u"' ) or repr_string . startswith ( "u'" ) : repr_string = repr_string [ 1 : ] return repr_string , isreadable , isrecursi...
Used to override the pprint format method to get rid of unicode prefixes .
30,450
def print_config ( _run ) : final_config = _run . config config_mods = _run . config_modifications print ( _format_config ( final_config , config_mods ) )
Print the updated configuration and exit .
30,451
def print_named_configs ( ingredient ) : def print_named_configs ( ) : named_configs = OrderedDict ( ingredient . gather_named_configs ( ) ) print ( _format_named_configs ( named_configs , 2 ) ) return print_named_configs
Returns a command function that prints the available named configs for the ingredient and all sub - ingredients and exits .
30,452
def print_dependencies ( _run ) : print ( 'Dependencies:' ) for dep in _run . experiment_info [ 'dependencies' ] : pack , _ , version = dep . partition ( '==' ) print ( ' {:<20} == {}' . format ( pack , version ) ) print ( '\nSources:' ) for source , digest in _run . experiment_info [ 'sources' ] : print ( ' {:<43} ...
Print the detected source - files and dependencies .
30,453
def save_config ( _config , _log , config_filename = 'config.json' ) : if 'config_filename' in _config : del _config [ 'config_filename' ] _log . info ( 'Saving config to "{}"' . format ( config_filename ) ) save_config_file ( flatten ( _config ) , config_filename )
Store the updated configuration in a file .
30,454
def log_metrics ( self , metrics_by_name , info ) : try : metrics_path = os . path . join ( self . dir , "metrics.json" ) with open ( metrics_path , 'r' ) as f : saved_metrics = json . load ( f ) except IOError : saved_metrics = { } for metric_name , metric_ptr in metrics_by_name . items ( ) : if metric_name not in sav...
Store new measurements into metrics . json .
30,455
def is_different ( old_value , new_value ) : if opt . has_numpy : return not opt . np . array_equal ( old_value , new_value ) else : return old_value != new_value
Numpy aware comparison between two values .
30,456
def main ( self , function ) : captured = self . command ( function ) self . default_command = captured . __name__ return captured
Decorator to define the main function of the experiment .
30,457
def option_hook ( self , function ) : sig = Signature ( function ) if "options" not in sig . arguments : raise KeyError ( "option_hook functions must have an argument called" " 'options', but got {}" . format ( sig . arguments ) ) self . option_hooks . append ( function ) return function
Decorator for adding an option hook function .
30,458
def get_usage ( self , program_name = None ) : program_name = os . path . relpath ( program_name or sys . argv [ 0 ] or 'Dummy' , self . base_dir ) commands = OrderedDict ( self . gather_commands ( ) ) options = gather_command_line_options ( ) long_usage = format_usage ( program_name , self . doc , commands , options )...
Get the commandline usage string for this experiment .
30,459
def run ( self , command_name = None , config_updates = None , named_configs = ( ) , meta_info = None , options = None ) : run = self . _create_run ( command_name , config_updates , named_configs , meta_info , options ) run ( ) return run
Run the main function of the experiment or a given command .
30,460
def run_command ( self , command_name , config_updates = None , named_configs = ( ) , args = ( ) , meta_info = None ) : import warnings warnings . warn ( "run_command is deprecated. Use run instead" , DeprecationWarning ) return self . run ( command_name , config_updates , named_configs , meta_info , args )
Run the command with the given name .
30,461
def run_commandline ( self , argv = None ) : argv = ensure_wellformed_argv ( argv ) short_usage , usage , internal_usage = self . get_usage ( ) args = docopt ( internal_usage , [ str ( a ) for a in argv [ 1 : ] ] , help = False ) cmd_name = args . get ( 'COMMAND' ) or self . default_command config_updates , named_confi...
Run the command - line interface of this experiment .
30,462
def get_default_options ( self ) : _ , _ , internal_usage = self . get_usage ( ) args = docopt ( internal_usage , [ ] ) return { k : v for k , v in args . items ( ) if k . startswith ( '--' ) }
Get a dictionary of default options as used with run .
30,463
def construct_arguments ( self , args , kwargs , options , bound = False ) : expected_args = self . _get_expected_args ( bound ) self . _assert_no_unexpected_args ( expected_args , args ) self . _assert_no_unexpected_kwargs ( expected_args , kwargs ) self . _assert_no_duplicate_args ( expected_args , args , kwargs ) ar...
Construct args list and kwargs dictionary for this signature .
30,464
def flush ( ) : try : sys . stdout . flush ( ) sys . stderr . flush ( ) except ( AttributeError , ValueError , IOError ) : pass try : libc . fflush ( None ) except ( AttributeError , ValueError , IOError ) : pass
Try to flush all stdio buffers both from python and from C .
30,465
def tee_output_python ( ) : buffer = StringIO ( ) out = CapturedStdout ( buffer ) orig_stdout , orig_stderr = sys . stdout , sys . stderr flush ( ) sys . stdout = TeeingStreamProxy ( sys . stdout , buffer ) sys . stderr = TeeingStreamProxy ( sys . stderr , buffer ) try : yield out finally : flush ( ) out . finalize ( )...
Duplicate sys . stdout and sys . stderr to new StringIO .
30,466
def tee_output_fd ( ) : with NamedTemporaryFile ( mode = 'w+' ) as target : original_stdout_fd = 1 original_stderr_fd = 2 target_fd = target . fileno ( ) saved_stdout_fd = os . dup ( original_stdout_fd ) saved_stderr_fd = os . dup ( original_stderr_fd ) try : tee_stdout = subprocess . Popen ( [ 'tee' , '-a' , target . ...
Duplicate stdout and stderr to a file on the file descriptor level .
30,467
def get_config_updates ( updates ) : config_updates = { } named_configs = [ ] if not updates : return config_updates , named_configs for upd in updates : if upd == '' : continue path , sep , value = upd . partition ( '=' ) if sep == '=' : path = path . strip ( ) value = value . strip ( ) set_by_dotted_path ( config_upd...
Parse the UPDATES given on the commandline .
30,468
def _format_options_usage ( options ) : options_usage = "" for op in options : short , long = op . get_flags ( ) if op . arg : flag = "{short} {arg} {long}={arg}" . format ( short = short , long = long , arg = op . arg ) else : flag = "{short} {long}" . format ( short = short , long = long ) wrapped_description = textw...
Format the Options - part of the usage text .
30,469
def _format_arguments_usage ( options ) : argument_usage = "" for op in options : if op . arg and op . arg_description : wrapped_description = textwrap . wrap ( op . arg_description , width = 79 , initial_indent = ' ' * 12 , subsequent_indent = ' ' * 12 ) wrapped_description = "\n" . join ( wrapped_description ) . stri...
Construct the Arguments - part of the usage text .
30,470
def _format_command_usage ( commands ) : if not commands : return "" command_usage = "\nCommands:\n" cmd_len = max ( [ len ( c ) for c in commands ] + [ 8 ] ) command_doc = OrderedDict ( [ ( cmd_name , _get_first_line_of_docstring ( cmd_doc ) ) for cmd_name , cmd_doc in commands . items ( ) ] ) for cmd_name , cmd_doc i...
Construct the Commands - part of the usage text .
30,471
def format_usage ( program_name , description , commands = None , options = ( ) ) : usage = USAGE_TEMPLATE . format ( program_name = cmd_quote ( program_name ) , description = description . strip ( ) if description else '' , options = _format_options_usage ( options ) , arguments = _format_arguments_usage ( options ) ,...
Construct the usage text .
30,472
def _convert_value ( value ) : try : return restore ( ast . literal_eval ( value ) ) except ( ValueError , SyntaxError ) : if SETTINGS . COMMAND_LINE . STRICT_PARSING : raise return value
Parse string as python literal if possible and fallback to string .
30,473
def iterate_flattened_separately ( dictionary , manually_sorted_keys = None ) : if manually_sorted_keys is None : manually_sorted_keys = [ ] for key in manually_sorted_keys : if key in dictionary : yield key , dictionary [ key ] single_line_keys = [ key for key in dictionary . keys ( ) if key not in manually_sorted_key...
Recursively iterate over the items of a dictionary in a special order .
30,474
def iterate_flattened ( d ) : for key in sorted ( d . keys ( ) ) : value = d [ key ] if isinstance ( value , dict ) and value : for k , v in iterate_flattened ( d [ key ] ) : yield join_paths ( key , k ) , v else : yield key , value
Recursively iterate over the items of a dictionary .
30,475
def set_by_dotted_path ( d , path , value ) : split_path = path . split ( '.' ) current_option = d for p in split_path [ : - 1 ] : if p not in current_option : current_option [ p ] = dict ( ) current_option = current_option [ p ] current_option [ split_path [ - 1 ] ] = value
Set an entry in a nested dict using a dotted path .
30,476
def get_by_dotted_path ( d , path , default = None ) : if not path : return d split_path = path . split ( '.' ) current_option = d for p in split_path : if p not in current_option : return default current_option = current_option [ p ] return current_option
Get an entry from nested dictionaries using a dotted path .
30,477
def iter_path_splits ( path ) : split_path = path . split ( '.' ) for i in range ( len ( split_path ) ) : p1 = join_paths ( * split_path [ : i ] ) p2 = join_paths ( * split_path [ i : ] ) yield p1 , p2
Iterate over possible splits of a dotted path .
30,478
def is_prefix ( pre_path , path ) : pre_path = pre_path . strip ( '.' ) path = path . strip ( '.' ) return not pre_path or path . startswith ( pre_path + '.' )
Return True if pre_path is a path - prefix of path .
30,479
def rel_path ( base , path ) : if base == path : return '' assert is_prefix ( base , path ) , "{} not a prefix of {}" . format ( base , path ) return path [ len ( base ) : ] . strip ( '.' )
Return path relative to base .
30,480
def convert_to_nested_dict ( dotted_dict ) : nested_dict = { } for k , v in iterate_flattened ( dotted_dict ) : set_by_dotted_path ( nested_dict , k , v ) return nested_dict
Convert a dict with dotted path keys to corresponding nested dict .
30,481
def format_filtered_stacktrace ( filter_traceback = 'default' ) : exc_type , exc_value , exc_traceback = sys . exc_info ( ) current_tb = exc_traceback while current_tb . tb_next is not None : current_tb = current_tb . tb_next if filter_traceback == 'default' and _is_sacred_frame ( current_tb . tb_frame ) : header = [ "...
Returns the traceback as string .
30,482
def get_inheritors ( cls ) : subclasses = set ( ) work = [ cls ] while work : parent = work . pop ( ) for child in parent . __subclasses__ ( ) : if child not in subclasses : subclasses . add ( child ) work . append ( child ) return subclasses
Get a set of all classes that inherit from the given class .
30,483
def apply_backspaces_and_linefeeds ( text ) : orig_lines = text . split ( '\n' ) orig_lines_len = len ( orig_lines ) new_lines = [ ] for orig_line_idx , orig_line in enumerate ( orig_lines ) : chars , cursor = [ ] , 0 orig_line_len = len ( orig_line ) for orig_char_idx , orig_char in enumerate ( orig_line ) : if orig_c...
Interpret backspaces and linefeeds in text like a terminal would .
30,484
def module_is_imported ( modname , scope = None ) : if not module_is_in_cache ( modname ) : return False if scope is None : scope = inspect . stack ( ) [ 1 ] [ 0 ] . f_globals for m in scope . values ( ) : if isinstance ( m , type ( sys ) ) and m . __name__ == modname : return True return False
Checks if a module is imported within the current namespace .
30,485
def from_config ( cls , filename ) : import telegram d = load_config_file ( filename ) request = cls . get_proxy_request ( d ) if 'proxy_url' in d else None if 'token' in d and 'chat_id' in d : bot = telegram . Bot ( d [ 'token' ] , request = request ) obs = cls ( bot , ** d ) else : raise ValueError ( "Telegram config...
Create a TelegramObserver from a given configuration file .
30,486
def log_metrics ( self , metrics_by_name , info ) : if self . metrics is None : return for key in metrics_by_name : query = { "run_id" : self . run_entry [ '_id' ] , "name" : key } push = { "steps" : { "$each" : metrics_by_name [ key ] [ "steps" ] } , "values" : { "$each" : metrics_by_name [ key ] [ "values" ] } , "tim...
Store new measurements to the database .
30,487
def get_digest ( filename ) : h = hashlib . md5 ( ) with open ( filename , 'rb' ) as f : data = f . read ( 1 * MB ) while data : h . update ( data ) data = f . read ( 1 * MB ) return h . hexdigest ( )
Compute the MD5 hash for a given file .
30,488
def get_commit_if_possible ( filename ) : if opt . has_gitpython : from git import Repo , InvalidGitRepositoryError try : directory = os . path . dirname ( filename ) repo = Repo ( directory , search_parent_directories = True ) try : path = repo . remote ( ) . url except ValueError : path = 'git:/' + repo . working_dir...
Try to retrieve VCS information for a given file .
30,489
def convert_path_to_module_parts ( path ) : module_parts = splitall ( path ) if module_parts [ - 1 ] in [ '__init__.py' , '__init__.pyc' ] : module_parts = module_parts [ : - 1 ] else : module_parts [ - 1 ] , _ = os . path . splitext ( module_parts [ - 1 ] ) return module_parts
Convert path to a python file into list of module names .
30,490
def is_local_source ( filename , modname , experiment_path ) : if not is_subdir ( filename , experiment_path ) : return False rel_path = os . path . relpath ( filename , experiment_path ) path_parts = convert_path_to_module_parts ( rel_path ) mod_parts = modname . split ( '.' ) if path_parts == mod_parts : return True ...
Check if a module comes from the given experiment path .
30,491
def gather_sources_and_dependencies ( globs , base_dir = None ) : experiment_path , main = get_main_file ( globs ) base_dir = base_dir or experiment_path gather_sources = source_discovery_strategies [ SETTINGS [ 'DISCOVER_SOURCES' ] ] sources = gather_sources ( globs , base_dir ) if main is not None : sources . add ( m...
Scan the given globals for modules and return them as dependencies .
30,492
def assert_is_valid_key ( key ) : if SETTINGS . CONFIG . ENFORCE_KEYS_MONGO_COMPATIBLE and ( isinstance ( key , basestring ) and ( '.' in key or key [ 0 ] == '$' ) ) : raise KeyError ( 'Invalid key "{}". Config-keys cannot ' 'contain "." or start with "$"' . format ( key ) ) if SETTINGS . CONFIG . ENFORCE_KEYS_JSONPICK...
Raise KeyError if a given config key violates any requirements .
30,493
def from_config ( cls , filename ) : d = load_config_file ( filename ) obs = None if 'webhook_url' in d : obs = cls ( d [ 'webhook_url' ] ) else : raise ValueError ( "Slack configuration file must contain " "an entry for 'webhook_url'!" ) for k in [ 'completed_text' , 'interrupted_text' , 'failed_text' , 'bot_name' , '...
Create a SlackObserver from a given configuration file .
30,494
def get_host_info ( ) : host_info = { } for k , v in host_info_gatherers . items ( ) : try : host_info [ k ] = v ( ) except IgnoreHostInfo : pass return host_info
Collect some information about the machine this experiment runs on .
30,495
def host_info_getter ( func , name = None ) : name = name or func . __name__ host_info_gatherers [ name ] = func return func
The decorated function is added to the process of collecting the host_info .
30,496
def linearize_metrics ( logged_metrics ) : metrics_by_name = { } for metric_entry in logged_metrics : if metric_entry . name not in metrics_by_name : metrics_by_name [ metric_entry . name ] = { "steps" : [ ] , "values" : [ ] , "timestamps" : [ ] , "name" : metric_entry . name } metrics_by_name [ metric_entry . name ] [...
Group metrics by name .
30,497
def get_last_metrics ( self ) : read_up_to = self . _logged_metrics . qsize ( ) messages = [ ] for i in range ( read_up_to ) : try : messages . append ( self . _logged_metrics . get_nowait ( ) ) except Empty : pass return messages
Read all measurement events since last call of the method .
30,498
def gather_command_line_options ( filter_disabled = None ) : if filter_disabled is None : filter_disabled = not SETTINGS . COMMAND_LINE . SHOW_DISABLED_OPTIONS options = [ opt for opt in get_inheritors ( CommandLineOption ) if not filter_disabled or opt . _enabled ] return sorted ( options , key = lambda opt : opt . __...
Get a sorted list of all CommandLineOption subclasses .
30,499
def apply ( cls , args , run ) : try : lvl = int ( args ) except ValueError : lvl = args run . root_logger . setLevel ( lvl )
Adjust the loglevel of the root - logger of this run .