idx
int64
0
63k
question
stringlengths
61
4.03k
target
stringlengths
6
1.23k
52,700
def generate_aliases ( fieldfile , ** kwargs ) : from easy_thumbnails . files import generate_all_aliases generate_all_aliases ( fieldfile , include_global = False )
A saved_file signal handler which generates thumbnails for all field model and app specific aliases matching the saved file s field .
52,701
def generate_aliases_global ( fieldfile , ** kwargs ) : from easy_thumbnails . files import generate_all_aliases generate_all_aliases ( fieldfile , include_global = True )
A saved_file signal handler which generates thumbnails for all field model and app specific aliases matching the saved file s field also generating thumbnails for each project - wide alias .
52,702
def colorspace ( im , bw = False , replace_alpha = False , ** kwargs ) : if im . mode == 'I' : im = im . point ( list ( _points_table ( ) ) , 'L' ) is_transparent = utils . is_transparent ( im ) is_grayscale = im . mode in ( 'L' , 'LA' ) new_mode = im . mode if is_grayscale or bw : new_mode = 'L' else : new_mode = 'RGB...
Convert images to the correct color space .
52,703
def autocrop ( im , autocrop = False , ** kwargs ) : if autocrop : if utils . is_transparent ( im ) : no_alpha = Image . new ( 'L' , im . size , ( 255 ) ) no_alpha . paste ( im , mask = im . split ( ) [ - 1 ] ) else : no_alpha = im . convert ( 'L' ) bw = no_alpha . convert ( 'L' ) bg = Image . new ( 'L' , im . size , 2...
Remove any unnecessary whitespace from the edges of the source image .
52,704
def filters ( im , detail = False , sharpen = False , ** kwargs ) : if detail : im = im . filter ( ImageFilter . DETAIL ) if sharpen : im = im . filter ( ImageFilter . SHARPEN ) return im
Pass the source image through post - processing filters .
52,705
def background ( im , size , background = None , ** kwargs ) : if not background : return im if not size [ 0 ] or not size [ 1 ] : return im x , y = im . size if x >= size [ 0 ] and y >= size [ 1 ] : return im im = colorspace ( im , replace_alpha = background , ** kwargs ) new_im = Image . new ( 'RGB' , size , backgrou...
Add borders of a certain color to make the resized image fit exactly within the dimensions given .
52,706
def generate_all_aliases ( fieldfile , include_global ) : all_options = aliases . all ( fieldfile , include_global = include_global ) if all_options : thumbnailer = get_thumbnailer ( fieldfile ) for key , options in six . iteritems ( all_options ) : options [ 'ALIAS' ] = key thumbnailer . get_thumbnail ( options )
Generate all of a file s aliases .
52,707
def _get_image ( self ) : if not hasattr ( self , '_image_cache' ) : from easy_thumbnails . source_generators import pil_image self . image = pil_image ( self ) return self . _image_cache
Get a PIL Image instance of this file .
52,708
def _set_image ( self , image ) : if image : self . _image_cache = image self . _dimensions_cache = image . size else : if hasattr ( self , '_image_cache' ) : del self . _cached_image if hasattr ( self , '_dimensions_cache' ) : del self . _dimensions_cache
Set the image for this file .
52,709
def set_image_dimensions ( self , thumbnail ) : try : dimensions = getattr ( thumbnail , 'dimensions' , None ) except models . ThumbnailDimensions . DoesNotExist : dimensions = None if not dimensions : return False self . _dimensions_cache = dimensions . size return self . _dimensions_cache
Set image dimensions from the cached dimensions of a Thumbnail model instance .
52,710
def generate_thumbnail ( self , thumbnail_options , high_resolution = False , silent_template_exception = False ) : thumbnail_options = self . get_options ( thumbnail_options ) orig_size = thumbnail_options [ 'size' ] min_dim , max_dim = 0 , 0 for dim in orig_size : try : dim = int ( dim ) except ( TypeError , ValueErr...
Return an unsaved ThumbnailFile containing a thumbnail image .
52,711
def get_existing_thumbnail ( self , thumbnail_options , high_resolution = False ) : thumbnail_options = self . get_options ( thumbnail_options ) names = [ self . get_thumbnail_name ( thumbnail_options , transparent = False , high_resolution = high_resolution ) ] transparent_name = self . get_thumbnail_name ( thumbnail_...
Return a ThumbnailFile containing an existing thumbnail for a set of thumbnail options or None if not found .
52,712
def get_thumbnail ( self , thumbnail_options , save = True , generate = None , silent_template_exception = False ) : thumbnail_options = self . get_options ( thumbnail_options ) if generate is None : generate = self . generate thumbnail = self . get_existing_thumbnail ( thumbnail_options ) if not thumbnail : if generat...
Return a ThumbnailFile containing a thumbnail .
52,713
def save_thumbnail ( self , thumbnail ) : filename = thumbnail . name try : self . thumbnail_storage . delete ( filename ) except Exception : pass self . thumbnail_storage . save ( filename , thumbnail ) thumb_cache = self . get_thumbnail_cache ( thumbnail . name , create = True , update = True ) if settings . THUMBNAI...
Save a thumbnail to the thumbnail_storage .
52,714
def thumbnail_exists ( self , thumbnail_name ) : if self . remote_source : return False if utils . is_storage_local ( self . source_storage ) : source_modtime = utils . get_modified_time ( self . source_storage , self . name ) else : source = self . get_source_cache ( ) if not source : return False source_modtime = sou...
Calculate whether the thumbnail already exists and that the source is not newer than the thumbnail .
52,715
def save ( self , name , content , * args , ** kwargs ) : super ( ThumbnailerFieldFile , self ) . save ( name , content , * args , ** kwargs ) self . get_source_cache ( create = True , update = True )
Save the file also saving a reference to the thumbnail cache Source model .
52,716
def delete ( self , * args , ** kwargs ) : source_cache = self . get_source_cache ( ) self . delete_thumbnails ( source_cache ) super ( ThumbnailerFieldFile , self ) . delete ( * args , ** kwargs ) if source_cache and source_cache . pk is not None : source_cache . delete ( )
Delete the image along with any generated thumbnails .
52,717
def delete_thumbnails ( self , source_cache = None ) : source_cache = self . get_source_cache ( ) deleted = 0 if source_cache : thumbnail_storage_hash = utils . get_storage_hash ( self . thumbnail_storage ) for thumbnail_cache in source_cache . thumbnails . all ( ) : if thumbnail_cache . storage_hash == thumbnail_stora...
Delete any thumbnails generated from the source image .
52,718
def get_thumbnails ( self , * args , ** kwargs ) : source_cache = self . get_source_cache ( ) if source_cache : thumbnail_storage_hash = utils . get_storage_hash ( self . thumbnail_storage ) for thumbnail_cache in source_cache . thumbnails . all ( ) : if thumbnail_cache . storage_hash == thumbnail_storage_hash : yield ...
Return an iterator which returns ThumbnailFile instances .
52,719
def save ( self , name , content , * args , ** kwargs ) : options = getattr ( self . field , 'resize_source' , None ) if options : if 'quality' not in options : options [ 'quality' ] = self . thumbnail_quality content = Thumbnailer ( content , name ) . generate_thumbnail ( options ) orig_name , ext = os . path . splite...
Save the image .
52,720
def queryset_iterator ( queryset , chunksize = 1000 ) : if queryset . exists ( ) : primary_key = 0 last_pk = queryset . order_by ( '-pk' ) [ 0 ] . pk queryset = queryset . order_by ( 'pk' ) while primary_key < last_pk : for row in queryset . filter ( pk__gt = primary_key ) [ : chunksize ] : primary_key = row . pk yield...
The queryset iterator helps to keep the memory consumption down . And also making it easier to process for weaker computers .
52,721
def print_stats ( self ) : print ( "{0:-<48}" . format ( str ( datetime . now ( ) . strftime ( '%Y-%m-%d %H:%M ' ) ) ) ) print ( "{0:<40} {1:>7}" . format ( "Sources checked:" , self . sources ) ) print ( "{0:<40} {1:>7}" . format ( "Source references deleted from DB:" , self . source_refs_deleted ) ) print ( "{0:<40} ...
Print statistics about the cleanup performed .
52,722
def populate_from_settings ( self ) : settings_aliases = settings . THUMBNAIL_ALIASES if settings_aliases : for target , aliases in settings_aliases . items ( ) : target_aliases = self . _aliases . setdefault ( target , { } ) target_aliases . update ( aliases )
Populate the aliases from the THUMBNAIL_ALIASES setting .
52,723
def set ( self , alias , options , target = None ) : target = self . _coerce_target ( target ) or '' target_aliases = self . _aliases . setdefault ( target , { } ) target_aliases [ alias ] = options
Add an alias .
52,724
def get ( self , alias , target = None ) : for target_part in reversed ( list ( self . _get_targets ( target ) ) ) : options = self . _get ( target_part , alias ) if options : return options
Get a dictionary of aliased options .
52,725
def all ( self , target = None , include_global = True ) : aliases = { } for target_part in self . _get_targets ( target , include_global ) : aliases . update ( self . _aliases . get ( target_part , { } ) ) return aliases
Get a dictionary of all aliases and their options .
52,726
def _get ( self , target , alias ) : if target not in self . _aliases : return return self . _aliases [ target ] . get ( alias )
Internal method to get a specific alias .
52,727
def _get_targets ( self , target , include_global = True ) : target = self . _coerce_target ( target ) if include_global : yield '' if not target : return target_bits = target . split ( '.' ) for i in range ( len ( target_bits ) ) : yield '.' . join ( target_bits [ : i + 1 ] )
Internal iterator to split up a complete target into the possible parts it may match .
52,728
def _coerce_target ( self , target ) : if not target or isinstance ( target , six . string_types ) : return target if not hasattr ( target , 'instance' ) : return None if getattr ( target . instance , '_deferred' , False ) : model = target . instance . _meta . proxy_for_model else : model = target . instance . __class_...
Internal method to coerce a target to a string .
52,729
def image_entropy ( im ) : if not isinstance ( im , Image . Image ) : return 0 hist = im . histogram ( ) hist_size = float ( sum ( hist ) ) hist = [ h / hist_size for h in hist ] return - sum ( [ p * math . log ( p , 2 ) for p in hist if p != 0 ] )
Calculate the entropy of an image . Used for smart cropping .
52,730
def dynamic_import ( import_string ) : lastdot = import_string . rfind ( '.' ) if lastdot == - 1 : return __import__ ( import_string , { } , { } , [ ] ) module_name , attr = import_string [ : lastdot ] , import_string [ lastdot + 1 : ] parent_module = __import__ ( module_name , { } , { } , [ attr ] ) return getattr ( p...
Dynamically import a module or object .
52,731
def is_transparent ( image ) : if not isinstance ( image , Image . Image ) : return False return ( image . mode in ( 'RGBA' , 'LA' ) or ( image . mode == 'P' and 'transparency' in image . info ) )
Check to see if an image is transparent .
52,732
def is_progressive ( image ) : if not isinstance ( image , Image . Image ) : return False return ( 'progressive' in image . info ) or ( 'progression' in image . info )
Check to see if an image is progressive .
52,733
def get_modified_time ( storage , name ) : try : try : modified_time = storage . get_modified_time ( name ) except AttributeError : modified_time = storage . modified_time ( name ) except OSError : return 0 except NotImplementedError : return None if modified_time and timezone . is_naive ( modified_time ) : if getattr ...
Get modified time from storage ensuring the result is a timezone - aware datetime .
52,734
def namedtuple ( typename , field_names , verbose = False , rename = False ) : if isinstance ( field_names , str ) : field_names = field_names . replace ( ',' , ' ' ) . split ( ) field_names = list ( map ( str , field_names ) ) typename = str ( typename ) for name in [ typename ] + field_names : if type ( name ) != str...
Returns a new subclass of tuple with named fields . This is a patched version of collections . namedtuple from the stdlib . Unlike the latter it accepts non - identifier strings as field names . All values are accessible through dict syntax . Fields whose names are identifiers are also accessible via attribute syntax a...
52,735
def write_source ( self , filename ) : with open ( filename , 'w' ) as fp : return json . dump ( self . message . _elem , fp , indent = 4 , sort_keys = True )
Save source to file by calling write on the root element .
52,736
def write_source ( self , filename ) : return self . message . _elem . getroottree ( ) . write ( filename , encoding = 'utf8' )
Save XML source to file by calling write on the root element .
52,737
def group_attrib ( self ) : group_attributes = [ g . attrib for g in self . dataset . groups if self in g ] if group_attributes : return concat_namedtuples ( * group_attributes )
return a namedtuple containing all attributes attached to groups of which the given series is a member for each group of which the series is a member
52,738
def read_instance ( self , cls , sdmxobj , offset = None , first_only = True ) : if offset : try : base = self . _paths [ offset ] ( sdmxobj . _elem ) [ 0 ] except IndexError : return None else : base = sdmxobj . _elem result = self . _paths [ cls ] ( base ) if result : if first_only : return cls ( self , result [ 0 ] ...
If cls in _paths and matches return an instance of cls with the first XML element or if first_only is False a list of cls instances for all elements found If no matches were found return None .
52,739
def load_agency_profile ( cls , source ) : if not isinstance ( source , str_type ) : source = source . read ( ) new_agencies = json . loads ( source ) cls . _agencies . update ( new_agencies )
Classmethod loading metadata on a data provider . source must be a json - formated string or file - like object describing one or more data providers ( URL of the SDMX web API resource types etc . The dict Request . _agencies is updated with the metadata from the source .
52,740
def series_keys ( self , flow_id , cache = True ) : cache_id = 'series_keys_' + flow_id if cache_id in self . cache : return self . cache [ cache_id ] else : resp = self . data ( flow_id , params = { 'detail' : 'serieskeysonly' } ) l = list ( s . key for s in resp . data . series ) df = PD . DataFrame ( l , columns = l...
Get an empty dataset with all possible series keys .
52,741
def preview_data ( self , flow_id , key = None , count = True , total = True ) : all_keys = self . series_keys ( flow_id ) if not key : if count : return all_keys . shape [ 0 ] else : return all_keys key_l = { k : [ v ] if isinstance ( v , str_type ) else v for k , v in key . items ( ) } dim_names = [ k for k in all_ke...
Get keys or number of series for a prospective dataset query allowing for keys with multiple values per dimension . It downloads the complete list of series keys for a dataflow rather than using constraints and DSD . This feature is however not supported by all data providers . ECB and UNSD are known to work .
52,742
def write ( self , source = None , ** kwargs ) : if not source : source = self . msg return self . _writer . write ( source = source , ** kwargs )
Wrappe r to call the writer s write method if present .
52,743
def parse_json ( path ) : with open ( path ) as f : data = json . load ( f ) result = [ ] def assert_type ( value , typ ) : assert isinstance ( value , typ ) , '%s: Unexpected type %r' % ( path , type ( value ) . __name__ ) def assert_dict_item ( dictionary , key , typ ) : assert key in dictionary , '%s: Missing dictio...
Deserialize a JSON file containing runtime collected types .
52,744
def tokenize ( s ) : original = s tokens = [ ] while True : if not s : tokens . append ( End ( ) ) return tokens elif s [ 0 ] == ' ' : s = s [ 1 : ] elif s [ 0 ] in '()[],*' : tokens . append ( Separator ( s [ 0 ] ) ) s = s [ 1 : ] elif s [ : 2 ] == '->' : tokens . append ( Separator ( '->' ) ) s = s [ 2 : ] else : m =...
Translate a type comment into a list of tokens .
52,745
def generate_annotations_json_string ( source_path , only_simple = False ) : items = parse_json ( source_path ) results = [ ] for item in items : signature = unify_type_comments ( item . type_comments ) if is_signature_simple ( signature ) or not only_simple : data = { 'path' : item . path , 'line' : item . line , 'fun...
Produce annotation data JSON file from a JSON file with runtime - collected types .
52,746
def _my_hash ( arg_list ) : res = 0 for arg in arg_list : res = res * 31 + hash ( arg ) return res
Simple helper hash function
52,747
def name_from_type ( type_ ) : if isinstance ( type_ , ( DictType , ListType , TupleType , SetType , IteratorType ) ) : return repr ( type_ ) else : if type_ . __name__ != 'NoneType' : module = type_ . __module__ if module in BUILTIN_MODULES or module == '<unknown>' : return type_ . __name__ else : name = getattr ( typ...
Helper function to get PEP - 484 compatible string representation of our internal types .
52,748
def resolve_type ( arg ) : arg_type = type ( arg ) if arg_type == list : assert isinstance ( arg , list ) sample = arg [ : min ( 4 , len ( arg ) ) ] tentative_type = TentativeType ( ) for sample_item in sample : tentative_type . add ( resolve_type ( sample_item ) ) return ListType ( tentative_type ) elif arg_type == se...
Resolve object to one of our internal collection types or generic built - in type .
52,749
def prep_args ( arg_info ) : filtered_args = [ a for a in arg_info . args if getattr ( arg_info , 'varargs' , None ) != a ] if filtered_args and ( filtered_args [ 0 ] in ( 'self' , 'cls' ) ) : filtered_args = filtered_args [ 1 : ] pos_args = [ ] if filtered_args : for arg in filtered_args : if isinstance ( arg , str ) ...
Resolve types from ArgInfo
52,750
def _flush_signature ( key , return_type ) : signatures = collected_signatures . setdefault ( key , set ( ) ) args_info = collected_args . pop ( key ) if len ( signatures ) < MAX_ITEMS_PER_FUNCTION : signatures . add ( ( args_info , return_type ) ) num_samples [ key ] = num_samples . get ( key , 0 ) + 1
Store signature for a function .
52,751
def type_consumer ( ) : while True : item = _task_queue . get ( ) if isinstance ( item , KeyAndTypes ) : if item . key in collected_args : _flush_signature ( item . key , UnknownType ) collected_args [ item . key ] = ArgTypes ( item . types ) else : assert isinstance ( item , KeyAndReturn ) if item . key in collected_a...
Infinite loop of the type consumer thread . It gets types to process from the task query .
52,752
def _make_sampling_sequence ( n ) : seq = list ( range ( 5 ) ) i = 50 while len ( seq ) < n : seq . append ( i ) i += 50 return seq
Return a list containing the proposed call event sampling sequence .
52,753
def default_filter_filename ( filename ) : if filename is None : return None elif filename . startswith ( TOP_DIR ) : if filename . startswith ( TOP_DIR_DOT ) : return None else : return filename [ TOP_DIR_LEN : ] . lstrip ( os . sep ) elif filename . startswith ( os . sep ) : return None else : return filename
Default filter for filenames .
52,754
def _filter_types ( types_dict ) : def exclude ( k ) : return k . path . startswith ( '<' ) or k . func_name == '<module>' return { k : v for k , v in iteritems ( types_dict ) if not exclude ( k ) }
Filter type info before dumping it to the file .
52,755
def _dump_impl ( ) : filtered_signatures = _filter_types ( collected_signatures ) sorted_by_file = sorted ( iteritems ( filtered_signatures ) , key = ( lambda p : ( p [ 0 ] . path , p [ 0 ] . line , p [ 0 ] . func_name ) ) ) res = [ ] for function_key , signatures in sorted_by_file : comments = [ _make_type_comment ( a...
Internal implementation for dump_stats and dumps_stats
52,756
def dump_stats ( filename ) : res = _dump_impl ( ) f = open ( filename , 'w' ) json . dump ( res , f , indent = 4 ) f . close ( )
Write collected information to file .
52,757
def init_types_collection ( filter_filename = default_filter_filename ) : global _filter_filename _filter_filename = filter_filename sys . setprofile ( _trace_dispatch ) threading . setprofile ( _trace_dispatch )
Setup profiler hooks to enable type collection . Call this one time from the main thread .
52,758
def add ( self , type ) : try : if isinstance ( type , SetType ) : if EMPTY_SET_TYPE in self . types_hashable : self . types_hashable . remove ( EMPTY_SET_TYPE ) elif isinstance ( type , ListType ) : if EMPTY_LIST_TYPE in self . types_hashable : self . types_hashable . remove ( EMPTY_LIST_TYPE ) elif isinstance ( type ...
Add type to the runtime type samples .
52,759
def merge ( self , other ) : for hashables in other . types_hashable : self . add ( hashables ) for non_hashbles in other . types : self . add ( non_hashbles )
Merge two TentativeType instances
52,760
def infer_annotation ( type_comments ) : assert type_comments args = { } returns = set ( ) for comment in type_comments : arg_types , return_type = parse_type_comment ( comment ) for i , arg_type in enumerate ( arg_types ) : args . setdefault ( i , set ( ) ) . add ( arg_type ) returns . add ( return_type ) combined_arg...
Given some type comments return a single inferred signature .
52,761
def argument_kind ( args ) : kinds = set ( arg . kind for arg in args ) if len ( kinds ) != 1 : return None return kinds . pop ( )
Return the kind of an argument based on one or more descriptions of the argument .
52,762
def combine_types ( types ) : items = simplify_types ( types ) if len ( items ) == 1 : return items [ 0 ] else : return UnionType ( items )
Given some types return a combined and simplified type .
52,763
def simplify_types ( types ) : flattened = flatten_types ( types ) items = filter_ignored_items ( flattened ) items = [ simplify_recursive ( item ) for item in items ] items = merge_items ( items ) items = dedupe_types ( items ) items = remove_redundant_items ( items ) if len ( items ) > 3 : return [ AnyType ( ) ] else...
Given some types give simplified types representing the union of types .
52,764
def simplify_recursive ( typ ) : if isinstance ( typ , UnionType ) : return combine_types ( typ . items ) elif isinstance ( typ , ClassType ) : simplified = ClassType ( typ . name , [ simplify_recursive ( arg ) for arg in typ . args ] ) args = simplified . args if ( simplified . name == 'Dict' and len ( args ) == 2 and...
Simplify all components of a type .
52,765
def remove_redundant_items ( items ) : result = [ ] for item in items : for other in items : if item is not other and is_redundant_union_item ( item , other ) : break else : result . append ( item ) return result
Filter out redundant union items .
52,766
def is_redundant_union_item ( first , other ) : if isinstance ( first , ClassType ) and isinstance ( other , ClassType ) : if first . name == 'str' and other . name == 'Text' : return True elif first . name == 'bool' and other . name == 'int' : return True elif first . name == 'int' and other . name == 'float' : return...
If union has both items is the first one redundant?
52,767
def merge_items ( items ) : result = [ ] while items : item = items . pop ( ) merged = None for i , other in enumerate ( items ) : merged = merged_type ( item , other ) if merged : break if merged : del items [ i ] items . append ( merged ) else : result . append ( item ) return list ( reversed ( result ) )
Merge union items that can be merged .
52,768
def merged_type ( t , s ) : if isinstance ( t , TupleType ) and isinstance ( s , TupleType ) : if len ( t . items ) == len ( s . items ) : return TupleType ( [ combine_types ( [ ti , si ] ) for ti , si in zip ( t . items , s . items ) ] ) all_items = t . items + s . items if all_items and all ( item == all_items [ 0 ] ...
Return merged type if two items can be merged in to a different more general type .
52,769
def dump_annotations ( type_info , files ) : with open ( type_info ) as f : data = json . load ( f ) for item in data : path , line , func_name = item [ 'path' ] , item [ 'line' ] , item [ 'func_name' ] if files and path not in files : for f in files : if path . startswith ( os . path . join ( f , '' ) ) : break else :...
Dump annotations out of type_info filtered by files .
52,770
def strip_py ( arg ) : for ext in PY_EXTENSIONS : if arg . endswith ( ext ) : return arg [ : - len ( ext ) ] return None
Strip a trailing . py or . pyi suffix . Return None if no such suffix is found .
52,771
def get_decorators ( self , node ) : if node . parent is None : return [ ] results = { } if not self . decorated . match ( node . parent , results ) : return [ ] decorators = results . get ( 'dd' ) or [ results [ 'd' ] ] decs = [ ] for d in decorators : for child in d . children : if isinstance ( child , Leaf ) and chi...
Return a list of decorators found on a function definition .
52,772
def has_return_exprs ( self , node ) : results = { } if self . return_expr . match ( node , results ) : return True for child in node . children : if child . type not in ( syms . funcdef , syms . classdef ) : if self . has_return_exprs ( child ) : return True return False
Traverse the tree below node looking for return expr .
52,773
def inform_if_paths_invalid ( egrc_path , examples_dir , custom_dir , debug = True ) : if ( not debug ) : return if ( egrc_path ) : _inform_if_path_does_not_exist ( egrc_path ) if ( examples_dir ) : _inform_if_path_does_not_exist ( examples_dir ) if ( custom_dir ) : _inform_if_path_does_not_exist ( custom_dir )
If egrc_path examples_dir or custom_dir is truthy and debug is True informs the user that a path is not set .
52,774
def get_egrc_config ( cli_egrc_path ) : resolved_path = get_priority ( cli_egrc_path , DEFAULT_EGRC_PATH , None ) expanded_path = get_expanded_path ( resolved_path ) egrc_config = get_empty_config ( ) if os . path . isfile ( expanded_path ) : egrc_config = get_config_tuple_from_egrc ( expanded_path ) return egrc_config
Return a Config namedtuple based on the contents of the egrc .
52,775
def get_resolved_config ( egrc_path , examples_dir , custom_dir , use_color , pager_cmd , squeeze , debug = True , ) : inform_if_paths_invalid ( egrc_path , examples_dir , custom_dir ) examples_dir = get_expanded_path ( examples_dir ) custom_dir = get_expanded_path ( custom_dir ) egrc_config = get_egrc_config ( egrc_pa...
Create a Config namedtuple . Passed in values will override defaults .
52,776
def get_config_tuple_from_egrc ( egrc_path ) : with open ( egrc_path , 'r' ) as egrc : try : config = ConfigParser . RawConfigParser ( ) except AttributeError : config = ConfigParser ( ) config . readfp ( egrc ) examples_dir = None custom_dir = None use_color = None pager_cmd = None squeeze = None subs = None editor_cm...
Create a Config named tuple from the values specified in the . egrc . Expands any paths as necessary .
52,777
def get_expanded_path ( path ) : if path : result = path result = os . path . expanduser ( result ) result = os . path . expandvars ( result ) return result else : return None
Expand ~ and variables in a path . If path is not truthy return None .
52,778
def get_editor_cmd_from_environment ( ) : result = os . getenv ( ENV_VISUAL ) if ( not result ) : result = os . getenv ( ENV_EDITOR ) return result
Gets and editor command from environment variables .
52,779
def _inform_if_path_does_not_exist ( path ) : expanded_path = get_expanded_path ( path ) if not os . path . exists ( expanded_path ) : print ( 'Could not find custom path at: {}' . format ( expanded_path ) )
If the path does not exist print a message saying so . This is intended to be helpful to users if they specify a custom path that eg cannot find .
52,780
def get_custom_color_config_from_egrc ( config ) : pound = _get_color_from_config ( config , CONFIG_NAMES . pound ) heading = _get_color_from_config ( config , CONFIG_NAMES . heading ) code = _get_color_from_config ( config , CONFIG_NAMES . code ) backticks = _get_color_from_config ( config , CONFIG_NAMES . backticks )...
Get the ColorConfig from the egrc config object . Any colors not defined will be None .
52,781
def _get_color_from_config ( config , option ) : if not config . has_option ( COLOR_SECTION , option ) : return None else : return ast . literal_eval ( config . get ( COLOR_SECTION , option ) )
Helper method to uet an option from the COLOR_SECTION of the config .
52,782
def parse_substitution_from_list ( list_rep ) : if type ( list_rep ) is not list : raise SyntaxError ( 'Substitution must be a list' ) if len ( list_rep ) < 2 : raise SyntaxError ( 'Substitution must be a list of size 2' ) pattern = list_rep [ 0 ] replacement = list_rep [ 1 ] is_multiline = False if ( len ( list_rep ) ...
Parse a substitution from the list representation in the config file .
52,783
def get_substitutions_from_config ( config ) : result = [ ] pattern_names = config . options ( SUBSTITUTION_SECTION ) pattern_names . sort ( ) for name in pattern_names : pattern_val = config . get ( SUBSTITUTION_SECTION , name ) list_rep = ast . literal_eval ( pattern_val ) substitution = parse_substitution_from_list ...
Return a list of Substitution objects from the config sorted alphabetically by pattern name . Returns an empty list if no Substitutions are specified . If there are problems parsing the values a help message will be printed and an error will be thrown .
52,784
def get_default_color_config ( ) : result = ColorConfig ( pound = DEFAULT_COLOR_POUND , heading = DEFAULT_COLOR_HEADING , code = DEFAULT_COLOR_CODE , backticks = DEFAULT_COLOR_BACKTICKS , prompt = DEFAULT_COLOR_PROMPT , pound_reset = DEFAULT_COLOR_POUND_RESET , heading_reset = DEFAULT_COLOR_HEADING_RESET , code_reset =...
Get a color config object with all the defaults .
52,785
def get_empty_config ( ) : empty_color_config = get_empty_color_config ( ) result = Config ( examples_dir = None , custom_dir = None , color_config = empty_color_config , use_color = None , pager_cmd = None , editor_cmd = None , squeeze = None , subs = None ) return result
Return an empty Config object with no options set .
52,786
def get_empty_color_config ( ) : empty_color_config = ColorConfig ( pound = None , heading = None , code = None , backticks = None , prompt = None , pound_reset = None , heading_reset = None , code_reset = None , backticks_reset = None , prompt_reset = None ) return empty_color_config
Return a color_config with all values set to None .
52,787
def merge_color_configs ( first , second ) : pound = get_priority ( first . pound , second . pound , None ) heading = get_priority ( first . heading , second . heading , None ) code = get_priority ( first . code , second . code , None ) backticks = get_priority ( first . backticks , second . backticks , None ) prompt =...
Merge the color configs .
52,788
def apply_and_get_result ( self , string ) : if self . is_multiline : compiled_pattern = re . compile ( self . pattern , re . MULTILINE ) else : compiled_pattern = re . compile ( self . pattern ) result = re . sub ( compiled_pattern , self . repl , string ) return result
Perform the substitution represented by this object on string and return the result .
52,789
def colorize_text ( self , text ) : result = text result = self . colorize_heading ( result ) result = self . colorize_block_indent ( result ) result = self . colorize_backticks ( result ) return result
Colorize the text .
52,790
def _recursive_get_all_file_names ( dir ) : if not dir : return [ ] result = [ ] for basedir , dirs , files in os . walk ( dir ) : result . extend ( files ) return result
Get all the file names in the directory . Gets all the top level file names only not the full path .
52,791
def edit_custom_examples ( program , config ) : if ( not config . custom_dir ) or ( not os . path . exists ( config . custom_dir ) ) : _inform_cannot_edit_no_custom_dir ( ) return resolved_program = get_resolved_program ( program , config ) custom_file_paths = get_file_paths_for_program ( resolved_program , config . cu...
Edit custom examples for the given program creating the file if it does not exist .
52,792
def get_file_paths_for_program ( program , dir_to_search ) : if dir_to_search is None : return [ ] else : wanted_file_name = program + EXAMPLE_FILE_SUFFIX result = [ ] for basedir , dirs , file_names in os . walk ( dir_to_search ) : for file_name in file_names : if file_name == wanted_file_name : result . append ( os ....
Return an array of full paths matching the given program . If no directory is present returns an empty list .
52,793
def page_string ( str_to_page , pager_cmd ) : use_fallback_page_function = False if pager_cmd is None : use_fallback_page_function = True elif pager_cmd == FLAG_FALLBACK : use_fallback_page_function = True try : if use_fallback_page_function : pydoc . pager ( str_to_page ) else : pydoc . pipepager ( str_to_page , cmd =...
Page str_to_page via the pager .
52,794
def get_list_of_all_supported_commands ( config ) : default_files = _recursive_get_all_file_names ( config . examples_dir ) custom_files = _recursive_get_all_file_names ( config . custom_dir ) default_files = [ path for path in default_files if _is_example_file ( path ) ] custom_files = [ path for path in custom_files ...
Generate a list of all the commands that have examples known to eg . The format of the list is the command names . The fact that there are examples for cp for example would mean that cp was in the list .
52,795
def get_squeezed_contents ( contents ) : line_between_example_code = substitute . Substitution ( '\n\n ' , '\n ' , True ) lines_between_examples = substitute . Substitution ( '\n\n\n' , '\n\n' , True ) lines_between_sections = substitute . Substitution ( '\n\n\n\n' , '\n\n\n' , True ) result = contents result = l...
Squeeze the contents by removing blank lines between definition and example and remove duplicate blank lines except between sections .
52,796
def get_colorized_contents ( contents , color_config ) : colorizer = color . EgColorizer ( color_config ) result = colorizer . colorize_text ( contents ) return result
Colorize the contents based on the color_config .
52,797
def get_substituted_contents ( contents , substitutions ) : result = contents for sub in substitutions : result = sub . apply_and_get_result ( result ) return result
Perform a list of substitutions and return the result .
52,798
def get_resolved_program ( program , config_obj ) : alias_dict = get_alias_dict ( config_obj ) if program in alias_dict : return alias_dict [ program ] else : return program
Take a program that may be an alias for another program and return the resolved program .
52,799
def get_alias_dict ( config_obj ) : if not config_obj . examples_dir : return { } alias_file_path = _get_alias_file_path ( config_obj ) if not os . path . isfile ( alias_file_path ) : return { } alias_file_contents = _get_contents_of_file ( alias_file_path ) result = json . loads ( alias_file_contents ) return result
Return a dictionary consisting of all aliases known to eg .