idx int64 0 63k | question stringlengths 53 5.28k | target stringlengths 5 805 |
|---|---|---|
44,500 | def diff_write_only ( resource ) : if resource . present and not resource . existing : return ADD elif not resource . present and resource . existing : return DEL elif resource . present and resource . existing : return OVERWRITE return NOOP | A different implementation of diff that is used for those Vault resources that are write - only such as AWS root configs |
44,501 | def read ( self , client ) : val = None if self . no_resource : return val LOG . debug ( "Reading from %s" , self ) try : val = client . read ( self . path ) except hvac . exceptions . InvalidRequest as vault_exception : if str ( vault_exception ) . startswith ( 'no handler for route' ) : val = None return val | Read from Vault while handling non surprising errors . |
44,502 | def write ( self , client ) : val = None if not self . no_resource : val = client . write ( self . path , ** self . obj ( ) ) return val | Write to Vault while handling non - surprising errors . |
44,503 | def find_file ( name , directory ) : path_bits = directory . split ( os . sep ) for i in range ( 0 , len ( path_bits ) - 1 ) : check_path = path_bits [ 0 : len ( path_bits ) - i ] check_file = "%s%s%s" % ( os . sep . join ( check_path ) , os . sep , name ) if os . path . exists ( check_file ) : return abspath ( check_file ) return None | Searches up from a directory looking for a file |
44,504 | def in_file ( string , search_file ) : handle = open ( search_file , 'r' ) for line in handle . readlines ( ) : if string in line : return True return False | Looks in a file for a string . |
44,505 | def gitignore ( opt ) : directory = os . path . dirname ( abspath ( opt . secretfile ) ) gitignore_file = find_file ( '.gitignore' , directory ) if gitignore_file : secrets_path = subdir_path ( abspath ( opt . secrets ) , gitignore_file ) if secrets_path : if not in_file ( secrets_path , gitignore_file ) : e_msg = "The path %s was not found in %s" % ( secrets_path , gitignore_file ) raise aomi . exceptions . AomiFile ( e_msg ) else : LOG . debug ( "Using a non-relative secret directory" ) else : raise aomi . exceptions . AomiFile ( "You should really have a .gitignore" ) | Will check directories upwards from the Secretfile in order to ensure the gitignore file is set properly |
44,506 | def secret_file ( filename ) : filestat = os . stat ( abspath ( filename ) ) if stat . S_ISREG ( filestat . st_mode ) == 0 and stat . S_ISLNK ( filestat . st_mode ) == 0 : e_msg = "Secret file %s must be a real file or symlink" % filename raise aomi . exceptions . AomiFile ( e_msg ) if platform . system ( ) != "Windows" : if filestat . st_mode & stat . S_IROTH or filestat . st_mode & stat . S_IWOTH or filestat . st_mode & stat . S_IWGRP : e_msg = "Secret file %s has too loose permissions" % filename raise aomi . exceptions . AomiFile ( e_msg ) | Will check the permissions of things which really should be secret files |
44,507 | def validate_obj ( keys , obj ) : msg = '' for k in keys : if isinstance ( k , str ) : if k not in obj or ( not isinstance ( obj [ k ] , list ) and not obj [ k ] ) : if msg : msg = "%s," % msg msg = "%s%s" % ( msg , k ) elif isinstance ( k , list ) : found = False for k_a in k : if k_a in obj : found = True if not found : if msg : msg = "%s," % msg msg = "%s(%s" % ( msg , ',' . join ( k ) ) if msg : msg = "%s missing" % msg return msg | Super simple object validation . |
44,508 | def check_obj ( keys , name , obj ) : msg = validate_obj ( keys , obj ) if msg : raise aomi . exceptions . AomiData ( "object check : %s in %s" % ( msg , name ) ) | Do basic validation on an object |
44,509 | def sanitize_mount ( mount ) : sanitized_mount = mount if sanitized_mount . startswith ( '/' ) : sanitized_mount = sanitized_mount [ 1 : ] if sanitized_mount . endswith ( '/' ) : sanitized_mount = sanitized_mount [ : - 1 ] sanitized_mount = sanitized_mount . replace ( '//' , '/' ) return sanitized_mount | Returns a quote - unquote sanitized mount path |
44,510 | def gpg_fingerprint ( key ) : if ( len ( key ) == 8 and re . match ( r'^[0-9A-F]{8}$' , key ) ) or ( len ( key ) == 40 and re . match ( r'^[0-9A-F]{40}$' , key ) ) : return raise aomi . exceptions . Validation ( 'Invalid GPG Fingerprint' ) | Validates a GPG key fingerprint |
44,511 | def is_unicode_string ( string ) : try : if sys . version_info >= ( 3 , 0 ) : if not isinstance ( string , str ) : string . decode ( 'utf-8' ) else : string . decode ( 'utf-8' ) except UnicodeError : raise aomi . exceptions . Validation ( 'Not a unicode string' ) | Validates that we are some kinda unicode string |
44,512 | def is_unicode ( string ) : str_type = str ( type ( string ) ) if str_type . find ( 'str' ) > 0 or str_type . find ( 'unicode' ) > 0 : return True return False | Validates that the object itself is some kinda string |
44,513 | def get_sectionsf ( self , * args , ** kwargs ) : def func ( f ) : doc = f . __doc__ self . get_sections ( doc or '' , * args , ** kwargs ) return f return func | Decorator method to extract sections from a function docstring |
44,514 | def delete_params_s ( s , params ) : patt = '(?s)' + '|' . join ( '(?<=\n)' + s + '\s*:.+?\n(?=\S+|$)' for s in params ) return re . sub ( patt , '' , '\n' + s . strip ( ) + '\n' ) . strip ( ) | Delete the given parameters from a string |
44,515 | def delete_types_s ( s , types ) : patt = '(?s)' + '|' . join ( '(?<=\n)' + s + '\n.+?\n(?=\S+|$)' for s in types ) return re . sub ( patt , '' , '\n' + s . strip ( ) + '\n' , ) . strip ( ) | Delete the given types from a string |
44,516 | def keep_params_s ( s , params ) : patt = '(?s)' + '|' . join ( '(?<=\n)' + s + '\s*:.+?\n(?=\S+|$)' for s in params ) return '' . join ( re . findall ( patt , '\n' + s . strip ( ) + '\n' ) ) . rstrip ( ) | Keep the given parameters from a string |
44,517 | def keep_types_s ( s , types ) : patt = '|' . join ( '(?<=\n)' + s + '\n(?s).+?\n(?=\S+|$)' for s in types ) return '' . join ( re . findall ( patt , '\n' + s . strip ( ) + '\n' ) ) . rstrip ( ) | Keep the given types from a string |
44,518 | def save_docstring ( self , key ) : def func ( f ) : self . params [ key ] = f . __doc__ or '' return f return func | Descriptor method to save a docstring from a function |
44,519 | def get_summary ( self , s , base = None ) : summary = summary_patt . search ( s ) . group ( ) if base is not None : self . params [ base + '.summary' ] = summary return summary | Get the summary of the given docstring |
44,520 | def get_summaryf ( self , * args , ** kwargs ) : def func ( f ) : doc = f . __doc__ self . get_summary ( doc or '' , * args , ** kwargs ) return f return func | Extract the summary from a function docstring |
44,521 | def get_extended_summary ( self , s , base = None ) : s = self . _remove_summary ( s ) ret = '' if not self . _all_sections_patt . match ( s ) : m = self . _extended_summary_patt . match ( s ) if m is not None : ret = m . group ( ) . strip ( ) if base is not None : self . params [ base + '.summary_ext' ] = ret return ret | Get the extended summary from a docstring |
44,522 | def get_extended_summaryf ( self , * args , ** kwargs ) : def func ( f ) : doc = f . __doc__ self . get_extended_summary ( doc or '' , * args , ** kwargs ) return f return func | Extract the extended summary from a function docstring |
44,523 | def get_full_description ( self , s , base = None ) : summary = self . get_summary ( s ) extended_summary = self . get_extended_summary ( s ) ret = ( summary + '\n\n' + extended_summary ) . strip ( ) if base is not None : self . params [ base + '.full_desc' ] = ret return ret | Get the full description from a docstring |
44,524 | def get_full_descriptionf ( self , * args , ** kwargs ) : def func ( f ) : doc = f . __doc__ self . get_full_description ( doc or '' , * args , ** kwargs ) return f return func | Extract the full description from a function docstring |
44,525 | def make_mergable_if_possible ( cls , data , context ) : if isinstance ( data , dict ) : return MergableDict ( data = data , context = context ) elif isiterable ( data ) : return MergableList ( data = [ cls . make_mergable_if_possible ( i , context ) for i in data ] , context = context ) else : return data | Makes an object mergable if possible . Returns the virgin object if cannot convert it to a mergable instance . |
44,526 | def merge ( self , * args ) : for data in args : if isinstance ( data , str ) : to_merge = load_string ( data , self . context ) if not to_merge : continue else : to_merge = data if not self . can_merge ( to_merge ) : raise TypeError ( 'Cannot merge myself:%s with %s. data: %s' % ( type ( self ) , type ( data ) , data ) ) self . _merge ( to_merge ) | Merges this instance with new instances in - place . |
44,527 | def load_file ( self , filename ) : if not path . exists ( filename ) : raise FileNotFoundError ( filename ) loaded_yaml = load_yaml ( filename , self . context ) if loaded_yaml : self . merge ( loaded_yaml ) | load file which contains yaml configuration entries . and merge it by current instance |
44,528 | def initialize ( self , init_value , context = None , force = False ) : if not force and self . _instance is not None : raise ConfigurationAlreadyInitializedError ( 'Configuration manager object is already initialized.' ) self . __class__ . _instance = Root ( init_value , context = context ) | Initialize the configuration manager |
44,529 | def grok_filter_name ( element ) : e_name = None if element . name == 'default' : if isinstance ( element . node , jinja2 . nodes . Getattr ) : e_name = element . node . node . name else : e_name = element . node . name return e_name | Extracts the name which may be embedded for a Jinja2 filter node |
44,530 | def grok_for_node ( element , default_vars ) : if isinstance ( element . iter , jinja2 . nodes . Filter ) : if element . iter . name == 'default' and element . iter . node . name not in default_vars : default_vars . append ( element . iter . node . name ) default_vars = default_vars + grok_vars ( element ) return default_vars | Properly parses a For loop element |
44,531 | def grok_if_node ( element , default_vars ) : if isinstance ( element . test , jinja2 . nodes . Filter ) and element . test . name == 'default' : default_vars . append ( element . test . node . name ) return default_vars + grok_vars ( element ) | Properly parses a If element |
44,532 | def grok_vars ( elements ) : default_vars = [ ] iterbody = None if hasattr ( elements , 'body' ) : iterbody = elements . body elif hasattr ( elements , 'nodes' ) : iterbody = elements . nodes for element in iterbody : if isinstance ( element , jinja2 . nodes . Output ) : default_vars = default_vars + grok_vars ( element ) elif isinstance ( element , jinja2 . nodes . Filter ) : e_name = grok_filter_name ( element ) if e_name not in default_vars : default_vars . append ( e_name ) elif isinstance ( element , jinja2 . nodes . For ) : default_vars = grok_for_node ( element , default_vars ) elif isinstance ( element , jinja2 . nodes . If ) : default_vars = grok_if_node ( element , default_vars ) elif isinstance ( element , jinja2 . nodes . Assign ) : default_vars . append ( element . target . name ) elif isinstance ( element , jinja2 . nodes . FromImport ) : for from_var in element . names : default_vars . append ( from_var ) return default_vars | Returns a list of vars for which the value is being appropriately set This currently includes the default filter for - based iterators and the explicit use of set |
44,533 | def jinja_env ( template_path ) : fs_loader = FileSystemLoader ( os . path . dirname ( template_path ) ) env = Environment ( loader = fs_loader , autoescape = True , trim_blocks = True , lstrip_blocks = True ) env . filters [ 'b64encode' ] = portable_b64encode env . filters [ 'b64decode' ] = f_b64decode return env | Sets up our Jinja environment loading the few filters we have |
44,534 | def missing_vars ( template_vars , parsed_content , obj ) : missing = [ ] default_vars = grok_vars ( parsed_content ) for var in template_vars : if var not in default_vars and var not in obj : missing . append ( var ) if missing : e_msg = "Missing required variables %s" % ',' . join ( missing ) raise aomi_excep . AomiData ( e_msg ) | If we find missing variables when rendering a template we want to give the user a friendly error |
44,535 | def render ( filename , obj ) : template_path = abspath ( filename ) env = jinja_env ( template_path ) template_base = os . path . basename ( template_path ) try : parsed_content = env . parse ( env . loader . get_source ( env , template_base ) ) template_vars = meta . find_undeclared_variables ( parsed_content ) if template_vars : missing_vars ( template_vars , parsed_content , obj ) LOG . debug ( "rendering %s with %s vars" , template_path , len ( template_vars ) ) return env . get_template ( template_base ) . render ( ** obj ) except jinja2 . exceptions . TemplateSyntaxError as exception : template_trace = traceback . format_tb ( sys . exc_info ( ) [ 2 ] ) if exception . filename : template_line = template_trace [ len ( template_trace ) - 1 ] raise aomi_excep . Validation ( "Bad template %s %s" % ( template_line , str ( exception ) ) ) template_str = '' if isinstance ( exception . source , tuple ) : template_str = "Embedded Template\n%s" % exception . source [ 0 ] raise aomi_excep . Validation ( "Bad template %s" % str ( exception ) , source = template_str ) except jinja2 . exceptions . UndefinedError as exception : template_traces = [ x . strip ( ) for x in traceback . format_tb ( sys . exc_info ( ) [ 2 ] ) if 'template code' in x ] raise aomi_excep . Validation ( "Missing template variable %s" % ' ' . join ( template_traces ) ) | Render a template maybe mixing in extra variables |
44,536 | def load_var_files ( opt , p_obj = None ) : obj = { } if p_obj : obj = p_obj for var_file in opt . extra_vars_file : LOG . debug ( "loading vars from %s" , var_file ) obj = merge_dicts ( obj . copy ( ) , load_var_file ( var_file , obj ) ) return obj | Load variable files merge return contents |
44,537 | def load_var_file ( filename , obj ) : rendered = render ( filename , obj ) ext = os . path . splitext ( filename ) [ 1 ] [ 1 : ] v_obj = dict ( ) if ext == 'json' : v_obj = json . loads ( rendered ) elif ext == 'yaml' or ext == 'yml' : v_obj = yaml . safe_load ( rendered ) else : LOG . warning ( "assuming yaml for unrecognized extension %s" , ext ) v_obj = yaml . safe_load ( rendered ) return v_obj | Loads a varible file processing it as a template |
44,538 | def load_template_help ( builtin ) : help_file = "templates/%s-help.yml" % builtin help_file = resource_filename ( __name__ , help_file ) help_obj = { } if os . path . exists ( help_file ) : help_data = yaml . safe_load ( open ( help_file ) ) if 'name' in help_data : help_obj [ 'name' ] = help_data [ 'name' ] if 'help' in help_data : help_obj [ 'help' ] = help_data [ 'help' ] if 'args' in help_data : help_obj [ 'args' ] = help_data [ 'args' ] return help_obj | Loads the help for a given template |
44,539 | def builtin_list ( ) : for template in resource_listdir ( __name__ , "templates" ) : builtin , ext = os . path . splitext ( os . path . basename ( abspath ( template ) ) ) if ext == '.yml' : continue help_obj = load_template_help ( builtin ) if 'name' in help_obj : print ( "%-*s %s" % ( 20 , builtin , help_obj [ 'name' ] ) ) else : print ( "%s" % builtin ) | Show a listing of all our builtin templates |
44,540 | def builtin_info ( builtin ) : help_obj = load_template_help ( builtin ) if help_obj . get ( 'name' ) and help_obj . get ( 'help' ) : print ( "The %s template" % ( help_obj [ 'name' ] ) ) print ( help_obj [ 'help' ] ) else : print ( "No help for %s" % builtin ) if help_obj . get ( 'args' ) : for arg , arg_help in iteritems ( help_obj [ 'args' ] ) : print ( " %-*s %s" % ( 20 , arg , arg_help ) ) | Show information on a particular builtin template |
44,541 | def render_secretfile ( opt ) : LOG . debug ( "Using Secretfile %s" , opt . secretfile ) secretfile_path = abspath ( opt . secretfile ) obj = load_vars ( opt ) return render ( secretfile_path , obj ) | Renders and returns the Secretfile construct |
44,542 | def update_user_password ( client , userpass ) : vault_path = '' user = '' user_path_bits = userpass . split ( '/' ) if len ( user_path_bits ) == 1 : user = user_path_bits [ 0 ] vault_path = "auth/userpass/users/%s/password" % user LOG . debug ( "Updating password for user %s at the default path" , user ) elif len ( user_path_bits ) == 2 : mount = user_path_bits [ 0 ] user = user_path_bits [ 1 ] vault_path = "auth/%s/users/%s/password" % ( mount , user ) LOG . debug ( "Updating password for user %s at path %s" , user , mount ) else : client . revoke_self_token ( ) raise aomi . exceptions . AomiCommand ( "invalid user path" ) new_password = get_password ( ) obj = { 'user' : user , 'password' : new_password } client . write ( vault_path , ** obj ) | Will update the password for a userpass user |
44,543 | def update_generic_password ( client , path ) : vault_path , key = path_pieces ( path ) mount = mount_for_path ( vault_path , client ) if not mount : client . revoke_self_token ( ) raise aomi . exceptions . VaultConstraint ( 'invalid path' ) if backend_type ( mount , client ) != 'generic' : client . revoke_self_token ( ) raise aomi . exceptions . AomiData ( "Unsupported backend type" ) LOG . debug ( "Updating generic password at %s" , path ) existing = client . read ( vault_path ) if not existing or 'data' not in existing : LOG . debug ( "Nothing exists yet at %s!" , vault_path ) existing = { } else : LOG . debug ( "Updating %s at %s" , key , vault_path ) existing = existing [ 'data' ] new_password = get_password ( ) if key in existing and existing [ key ] == new_password : client . revoke_self_token ( ) raise aomi . exceptions . AomiData ( "Password is same as existing" ) existing [ key ] = new_password client . write ( vault_path , ** existing ) | Will update a single key in a generic secret backend as thought it were a password |
44,544 | def password ( client , path ) : if path . startswith ( 'user:' ) : update_user_password ( client , path [ 5 : ] ) else : update_generic_password ( client , path ) | Will attempt to contextually update a password in Vault |
44,545 | def vault_file ( env , default ) : home = os . environ [ 'HOME' ] if 'HOME' in os . environ else os . environ [ 'USERPROFILE' ] filename = os . environ . get ( env , os . path . join ( home , default ) ) filename = abspath ( filename ) if os . path . exists ( filename ) : return filename return None | The path to a misc Vault file This function will check for the env override on a file path compute a fully qualified OS appropriate path to the desired file and return it if it exists . Otherwise returns None |
44,546 | def vault_time_to_s ( time_string ) : if not time_string or len ( time_string ) < 2 : raise aomi . exceptions . AomiData ( "Invalid timestring %s" % time_string ) last_char = time_string [ len ( time_string ) - 1 ] if last_char == 's' : return int ( time_string [ 0 : len ( time_string ) - 1 ] ) elif last_char == 'm' : cur = int ( time_string [ 0 : len ( time_string ) - 1 ] ) return cur * 60 elif last_char == 'h' : cur = int ( time_string [ 0 : len ( time_string ) - 1 ] ) return cur * 3600 elif last_char == 'd' : cur = int ( time_string [ 0 : len ( time_string ) - 1 ] ) return cur * 86400 else : raise aomi . exceptions . AomiData ( "Invalid time scale %s" % last_char ) | Will convert a time string as recognized by other Vault tooling into an integer representation of seconds |
44,547 | def set_executing ( on : bool ) : my_thread = threading . current_thread ( ) if isinstance ( my_thread , threads . CauldronThread ) : my_thread . is_executing = on | Toggle whether or not the current thread is executing a step file . This will only apply when the current thread is a CauldronThread . This function has no effect when run on a Main thread . |
44,548 | def get_file_contents ( source_path : str ) -> str : open_funcs = [ functools . partial ( codecs . open , source_path , encoding = 'utf-8' ) , functools . partial ( open , source_path , 'r' ) ] for open_func in open_funcs : try : with open_func ( ) as f : return f . read ( ) except Exception : pass return ( 'raise IOError("Unable to load step file at: {}")' . format ( source_path ) ) | Loads the contents of the source into a string for execution using multiple loading methods to handle cross - platform encoding edge cases . If none of the load methods work a string is returned that contains an error function response that will be displayed when the step is run alert the user to the error . |
44,549 | def load_step_file ( source_path : str ) -> str : return templating . render_template ( template_name = 'embedded-step.py.txt' , source_contents = get_file_contents ( source_path ) ) | Loads the source for a step file at the given path location and then renders it in a template to add additional footer data . |
44,550 | def run ( project : 'projects.Project' , step : 'projects.ProjectStep' , ) -> dict : target_module = create_module ( project , step ) source_code = load_step_file ( step . source_path ) try : code = InspectLoader . source_to_code ( source_code , step . source_path ) except SyntaxError as error : return render_syntax_error ( project , error ) def exec_test ( ) : step . test_locals = dict ( ) step . test_locals . update ( target_module . __dict__ ) exec ( code , step . test_locals ) try : set_executing ( True ) threads . abort_thread ( ) if environ . modes . has ( environ . modes . TESTING ) : exec_test ( ) else : exec ( code , target_module . __dict__ ) out = { 'success' : True , 'stop_condition' : projects . StopCondition ( False , False ) } except threads . ThreadAbortError : out = { 'success' : False , 'stop_condition' : projects . StopCondition ( True , True ) } except UserAbortError as error : out = { 'success' : True , 'stop_condition' : projects . StopCondition ( True , error . halt ) } except Exception as error : out = render_error ( project , error ) set_executing ( False ) return out | Carries out the execution of the step python source file by loading it into an artificially created module and then executing that module and returning the result . |
44,551 | def render_syntax_error ( project : 'projects.Project' , error : SyntaxError ) -> dict : return render_error ( project = project , error = error , stack = [ dict ( filename = getattr ( error , 'filename' ) , location = None , line_number = error . lineno , line = error . text . rstrip ( ) ) ] ) | Renders a SyntaxError which has a shallow custom stack trace derived from the data included in the error instead of the standard stack trace pulled from the exception frames . |
44,552 | def render_error ( project : 'projects.Project' , error : Exception , stack : typing . List [ dict ] = None ) -> dict : data = dict ( type = error . __class__ . __name__ , message = '{}' . format ( error ) , stack = ( stack if stack is not None else render_stack . get_formatted_stack_frame ( project ) ) ) return dict ( success = False , error = error , message = templating . render_template ( 'user-code-error.txt' , ** data ) , html_message = templating . render_template ( 'user-code-error.html' , ** data ) ) | Renders an Exception to an error response that includes rendered text and html error messages for display . |
44,553 | def save ( self ) -> 'Configuration' : data = self . load ( ) . persistent if data is None : return self directory = os . path . dirname ( self . _source_path ) if not os . path . exists ( directory ) : os . makedirs ( directory ) path = self . _source_path with open ( path , 'w+' ) as f : json . dump ( data , f ) return self | Saves the configuration settings object to the current user s home directory |
44,554 | def _get_userinfo ( self ) : if not hasattr ( self , "_userinfo" ) : userinfo = { "name" : self . user_name , "email" : self . user_email , "url" : self . user_url } if self . user_id : u = self . user if u . email : userinfo [ "email" ] = u . email if u . get_full_name ( ) : userinfo [ "name" ] = self . user . get_full_name ( ) elif not self . user_name : userinfo [ "name" ] = u . get_username ( ) self . _userinfo = userinfo return self . _userinfo | Get a dictionary that pulls together information about the poster safely for both authenticated and non - authenticated comments . |
44,555 | def deploy ( files_list : typing . List [ tuple ] ) : def deploy_entry ( entry ) : if not entry : return if hasattr ( entry , 'source' ) and hasattr ( entry , 'destination' ) : return copy ( entry ) if hasattr ( entry , 'path' ) and hasattr ( entry , 'contents' ) : return write ( entry ) raise ValueError ( 'Unrecognized deployment entry {}' . format ( entry ) ) return [ deploy_entry ( f ) for f in files_list ] | Iterates through the specified files_list and copies or writes each entry depending on whether its a file copy entry or a file write entry . |
44,556 | def copy ( copy_entry : FILE_COPY_ENTRY ) : source_path = environ . paths . clean ( copy_entry . source ) output_path = environ . paths . clean ( copy_entry . destination ) copier = shutil . copy2 if os . path . isfile ( source_path ) else shutil . copytree make_output_directory ( output_path ) for i in range ( 3 ) : try : copier ( source_path , output_path ) return except Exception : time . sleep ( 0.5 ) raise IOError ( 'Unable to copy "{source}" to "{destination}"' . format ( source = source_path , destination = output_path ) ) | Copies the specified file from its source location to its destination location . |
44,557 | def write ( write_entry : FILE_WRITE_ENTRY ) : output_path = environ . paths . clean ( write_entry . path ) make_output_directory ( output_path ) writer . write_file ( output_path , write_entry . contents ) | Writes the contents of the specified file entry to its destination path . |
44,558 | def enable ( step : 'projects.ProjectStep' ) : restore_default_configuration ( ) stdout_interceptor = RedirectBuffer ( sys . stdout ) sys . stdout = stdout_interceptor step . report . stdout_interceptor = stdout_interceptor stderr_interceptor = RedirectBuffer ( sys . stderr ) sys . stderr = stderr_interceptor step . report . stderr_interceptor = stderr_interceptor stdout_interceptor . active = True stderr_interceptor . active = True | Create a print equivalent function that also writes the output to the project page . The write_through is enabled so that the TextIOWrapper immediately writes all of its input data directly to the underlying BytesIO buffer . This is needed so that we can safely access the buffer data in a multi - threaded environment to display updates while the buffer is being written to . |
44,559 | def restore_default_configuration ( ) : def restore ( target , default_value ) : if target == default_value : return default_value if not isinstance ( target , RedirectBuffer ) : return target try : target . active = False target . close ( ) except Exception : pass return default_value sys . stdout = restore ( sys . stdout , sys . __stdout__ ) sys . stderr = restore ( sys . stderr , sys . __stderr__ ) | Restores the sys . stdout and the sys . stderr buffer streams to their default values without regard to what step has currently overridden their values . This is useful during cleanup outside of the running execution block |
44,560 | def create ( project : 'projects.Project' , destination_directory , destination_filename : str = None ) -> file_io . FILE_WRITE_ENTRY : template_path = environ . paths . resources ( 'web' , 'project.html' ) with open ( template_path , 'r' ) as f : dom = f . read ( ) dom = dom . replace ( '<!-- CAULDRON:EXPORT , templating . render_template ( 'notebook-script-header.html' , uuid = project . uuid , version = environ . version ) ) filename = ( destination_filename if destination_filename else '{}.html' . format ( project . uuid ) ) html_out_path = os . path . join ( destination_directory , filename ) return file_io . FILE_WRITE_ENTRY ( path = html_out_path , contents = dom ) | Creates a FILE_WRITE_ENTRY for the rendered HTML file for the given project that will be saved in the destination directory with the given filename . |
44,561 | def run_container ( ) : os . chdir ( my_directory ) cmd = [ 'docker' , 'run' , '-it' , '--rm' , '-v' , '{}:/cauldron' . format ( my_directory ) , '-p' , '5010:5010' , 'cauldron_app' , '/bin/bash' ] return os . system ( ' ' . join ( cmd ) ) | Runs an interactive container |
44,562 | def run ( ) : command = sys . argv [ 1 ] . strip ( ) . lower ( ) print ( '[COMMAND]:' , command ) if command == 'test' : return run_test ( ) elif command == 'build' : return run_build ( ) elif command == 'up' : return run_container ( ) elif command == 'serve' : import cauldron cauldron . run_server ( port = 5010 , public = True ) | Execute the Cauldron container command |
44,563 | def gatekeeper ( func ) : @ wraps ( func ) def check_identity ( * args , ** kwargs ) : code = server_runner . authorization [ 'code' ] comparison = request . headers . get ( 'Cauldron-Authentication-Code' ) return ( abort ( 401 ) if code and code != comparison else func ( * args , ** kwargs ) ) return check_identity | This function is used to handle authorization code authentication of protected endpoints . This form of authentication is not recommended because it s not very secure but can be used in places where SSH tunneling or similar strong connection security is not possible . The function looks for a special Cauldron - Authentication - Code header in the request and confirms that the specified value matches the code that was provided by arguments to the Cauldron kernel server . This function acts as a pass - through if no code is specified when the server starts . |
44,564 | def inspect ( source : dict ) : r = _get_report ( ) r . append_body ( render . inspect ( source ) ) | Inspects the data and structure of the source dictionary object and adds the results to the display for viewing . |
44,565 | def header ( header_text : str , level : int = 1 , expand_full : bool = False ) : r = _get_report ( ) r . append_body ( render . header ( header_text , level = level , expand_full = expand_full ) ) | Adds a text header to the display with the specified level . |
44,566 | def text ( value : str , preformatted : bool = False ) : if preformatted : result = render_texts . preformatted_text ( value ) else : result = render_texts . text ( value ) r = _get_report ( ) r . append_body ( result ) r . stdout_interceptor . write_source ( '{}\n' . format ( textwrap . dedent ( value ) ) ) | Adds text to the display . If the text is not preformatted it will be displayed in paragraph format . Preformatted text will be displayed inside a pre tag with a monospace font . |
44,567 | def markdown ( source : str = None , source_path : str = None , preserve_lines : bool = False , font_size : float = None , ** kwargs ) : r = _get_report ( ) result = render_texts . markdown ( source = source , source_path = source_path , preserve_lines = preserve_lines , font_size = font_size , ** kwargs ) r . library_includes += result [ 'library_includes' ] r . append_body ( result [ 'body' ] ) r . stdout_interceptor . write_source ( '{}\n' . format ( textwrap . dedent ( result [ 'rendered' ] ) ) ) | Renders the specified source string or source file using markdown and adds the resulting HTML to the notebook display . |
44,568 | def json ( ** kwargs ) : r = _get_report ( ) r . append_body ( render . json ( ** kwargs ) ) r . stdout_interceptor . write_source ( '{}\n' . format ( _json_io . dumps ( kwargs , indent = 2 ) ) ) | Adds the specified data to the the output display window with the specified key . This allows the user to make available arbitrary JSON - compatible data to the display for runtime use . |
44,569 | def plotly ( data : typing . Union [ dict , list ] = None , layout : dict = None , scale : float = 0.5 , figure : dict = None , static : bool = False ) : r = _get_report ( ) if not figure and not isinstance ( data , ( list , tuple ) ) : data = [ data ] if 'plotly' not in r . library_includes : r . library_includes . append ( 'plotly' ) r . append_body ( render . plotly ( data = data , layout = layout , scale = scale , figure = figure , static = static ) ) r . stdout_interceptor . write_source ( '[ADDED] Plotly plot\n' ) | Creates a Plotly plot in the display with the specified data and layout . |
44,570 | def table ( data_frame , scale : float = 0.7 , include_index : bool = False , max_rows : int = 500 ) : r = _get_report ( ) r . append_body ( render . table ( data_frame = data_frame , scale = scale , include_index = include_index , max_rows = max_rows ) ) r . stdout_interceptor . write_source ( '[ADDED] Table\n' ) | Adds the specified data frame to the display in a nicely formatted scrolling table . |
44,571 | def svg ( svg_dom : str , filename : str = None ) : r = _get_report ( ) r . append_body ( render . svg ( svg_dom ) ) r . stdout_interceptor . write_source ( '[ADDED] SVG\n' ) if not filename : return if not filename . endswith ( '.svg' ) : filename += '.svg' r . files [ filename ] = svg_dom | Adds the specified SVG string to the display . If a filename is included the SVG data will also be saved to that filename within the project results folder . |
44,572 | def jinja ( path : str , ** kwargs ) : r = _get_report ( ) r . append_body ( render . jinja ( path , ** kwargs ) ) r . stdout_interceptor . write_source ( '[ADDED] Jinja2 rendered HTML\n' ) | Renders the specified Jinja2 template to HTML and adds the output to the display . |
44,573 | def whitespace ( lines : float = 1.0 ) : r = _get_report ( ) r . append_body ( render . whitespace ( lines ) ) r . stdout_interceptor . write_source ( '\n' ) | Adds the specified number of lines of whitespace . |
44,574 | def image ( filename : str , width : int = None , height : int = None , justify : str = 'left' ) : r = _get_report ( ) path = '/' . join ( [ 'reports' , r . project . uuid , 'latest' , 'assets' , filename ] ) r . append_body ( render . image ( path , width , height , justify ) ) r . stdout_interceptor . write_source ( '[ADDED] Image\n' ) | Adds an image to the display . The image must be located within the assets directory of the Cauldron notebook s folder . |
44,575 | def html ( dom : str ) : r = _get_report ( ) r . append_body ( render . html ( dom ) ) r . stdout_interceptor . write_source ( '[ADDED] HTML\n' ) | A string containing a valid HTML snippet . |
44,576 | def workspace ( show_values : bool = True , show_types : bool = True ) : r = _get_report ( ) data = { } for key , value in r . project . shared . fetch ( None ) . items ( ) : if key . startswith ( '__cauldron_' ) : continue data [ key ] = value r . append_body ( render . status ( data , values = show_values , types = show_types ) ) | Adds a list of the shared variables currently stored in the project workspace . |
44,577 | def pyplot ( figure = None , scale : float = 0.8 , clear : bool = True , aspect_ratio : typing . Union [ list , tuple ] = None ) : r = _get_report ( ) r . append_body ( render_plots . pyplot ( figure , scale = scale , clear = clear , aspect_ratio = aspect_ratio ) ) r . stdout_interceptor . write_source ( '[ADDED] PyPlot plot\n' ) | Creates a matplotlib plot in the display for the specified figure . The size of the plot is determined automatically to best fit the notebook . |
44,578 | def bokeh ( model , scale : float = 0.7 , responsive : bool = True ) : r = _get_report ( ) if 'bokeh' not in r . library_includes : r . library_includes . append ( 'bokeh' ) r . append_body ( render_plots . bokeh_plot ( model = model , scale = scale , responsive = responsive ) ) r . stdout_interceptor . write_source ( '[ADDED] Bokeh plot\n' ) | Adds a Bokeh plot object to the notebook display . |
44,579 | def head ( source , count : int = 5 ) : r = _get_report ( ) r . append_body ( render_texts . head ( source , count = count ) ) r . stdout_interceptor . write_source ( '[ADDED] Head\n' ) | Displays a specified number of elements in a source object of many different possible types . |
44,580 | def status ( message : str = None , progress : float = None , section_message : str = None , section_progress : float = None , ) : environ . abort_thread ( ) step = _cd . project . get_internal_project ( ) . current_step if message is not None : step . progress_message = message if progress is not None : step . progress = max ( 0.0 , min ( 1.0 , progress ) ) if section_message is not None : step . sub_progress_message = section_message if section_progress is not None : step . sub_progress = section_progress | Updates the status display which is only visible while a step is running . This is useful for providing feedback and information during long - running steps . |
44,581 | def code_block ( code : str = None , path : str = None , language_id : str = None , title : str = None , caption : str = None ) : environ . abort_thread ( ) r = _get_report ( ) r . append_body ( render . code_block ( block = code , path = path , language = language_id , title = title , caption = caption ) ) r . stdout_interceptor . write_source ( '{}\n' . format ( code ) ) | Adds a block of syntax highlighted code to the display from either the supplied code argument or from the code file specified by the path argument . |
44,582 | def elapsed ( ) : environ . abort_thread ( ) step = _cd . project . get_internal_project ( ) . current_step r = _get_report ( ) r . append_body ( render . elapsed_time ( step . elapsed_time ) ) result = '[ELAPSED]: {}\n' . format ( timedelta ( seconds = step . elapsed_time ) ) r . stdout_interceptor . write_source ( result ) | Displays the elapsed time since the step started running . |
44,583 | def get_module ( name : str ) -> typing . Union [ types . ModuleType , None ] : return sys . modules . get ( name ) | Retrieves the loaded module for the given module name or returns None if no such module has been loaded . |
44,584 | def get_module_name ( module : types . ModuleType ) -> str : try : return module . __spec__ . name except AttributeError : return module . __name__ | Returns the name of the specified module by looking up its name in multiple ways to prevent incompatibility issues . |
44,585 | def do_reload ( module : types . ModuleType , newer_than : int ) -> bool : path = getattr ( module , '__file__' ) directory = getattr ( module , '__path__' , [ None ] ) [ 0 ] if path is None and directory : path = os . path . join ( directory , '__init__.py' ) last_modified = os . path . getmtime ( path ) if last_modified < newer_than : return False try : importlib . reload ( module ) return True except ImportError : return False | Executes the reload of the specified module if the source file that it was loaded from was updated more recently than the specified time |
44,586 | def reload_children ( parent_module : types . ModuleType , newer_than : int ) -> bool : if not hasattr ( parent_module , '__path__' ) : return False parent_name = get_module_name ( parent_module ) children = filter ( lambda item : item [ 0 ] . startswith ( parent_name ) , sys . modules . items ( ) ) return any ( [ do_reload ( item [ 1 ] , newer_than ) for item in children ] ) | Reloads all imported children of the specified parent module object |
44,587 | def reload_module ( module : typing . Union [ str , types . ModuleType ] , recursive : bool , force : bool ) -> bool : if isinstance ( module , str ) : module = get_module ( module ) if module is None or not isinstance ( module , types . ModuleType ) : return False try : step = session . project . get_internal_project ( ) . current_step modified = step . last_modified if step else None except AttributeError : modified = 0 if modified is None : return False newer_than = modified if not force and modified else 0 if recursive : children_reloaded = reload_children ( module , newer_than ) else : children_reloaded = False reloaded = do_reload ( module , newer_than ) return reloaded or children_reloaded | Reloads the specified module which can either be a module object or a string name of a module . Will not reload a module that has not been imported |
44,588 | def refresh ( * modules : typing . Union [ str , types . ModuleType ] , recursive : bool = False , force : bool = False ) -> bool : out = [ ] for module in modules : out . append ( reload_module ( module , recursive , force ) ) return any ( out ) | Checks the specified module or modules for changes and reloads them if they have been changed since the module was first imported or last refreshed . |
44,589 | def get_arg_names ( target ) -> typing . List [ str ] : code = getattr ( target , '__code__' ) if code is None : return [ ] arg_count = code . co_argcount kwarg_count = code . co_kwonlyargcount args_index = get_args_index ( target ) kwargs_index = get_kwargs_index ( target ) arg_names = list ( code . co_varnames [ : arg_count ] ) if args_index != - 1 : arg_names . append ( code . co_varnames [ args_index ] ) arg_names += list ( code . co_varnames [ arg_count : ( arg_count + kwarg_count ) ] ) if kwargs_index != - 1 : arg_names . append ( code . co_varnames [ kwargs_index ] ) if len ( arg_names ) > 0 and arg_names [ 0 ] in [ 'self' , 'cls' ] : arg_count -= 1 arg_names . pop ( 0 ) return arg_names | Gets the list of named arguments for the target function |
44,590 | def create_argument ( target , name , description : str = '' ) -> dict : arg_names = get_arg_names ( target ) annotations = getattr ( target , '__annotations__' , { } ) out = dict ( name = name , index = arg_names . index ( name ) , description = description , type = conversions . arg_type_to_string ( annotations . get ( name , 'Any' ) ) ) out . update ( get_optional_data ( target , name , arg_names ) ) return out | Creates a dictionary representation of the parameter |
44,591 | def explode_line ( argument_line : str ) -> typing . Tuple [ str , str ] : parts = tuple ( argument_line . split ( ' ' , 1 ) [ - 1 ] . split ( ':' , 1 ) ) return parts if len ( parts ) > 1 else ( parts [ 0 ] , '' ) | Returns a tuple containing the parameter name and the description parsed from the given argument line |
44,592 | def update_base_image ( path : str ) : with open ( path , 'r' ) as file_handle : contents = file_handle . read ( ) regex = re . compile ( 'from\s+(?P<source>[^\s]+)' , re . IGNORECASE ) matches = regex . findall ( contents ) if not matches : return None match = matches [ 0 ] os . system ( 'docker pull {}' . format ( match ) ) return match | Pulls the latest version of the base image |
44,593 | def build ( path : str ) -> dict : update_base_image ( path ) match = file_pattern . search ( os . path . basename ( path ) ) build_id = match . group ( 'id' ) tags = [ '{}:{}-{}' . format ( HUB_PREFIX , version , build_id ) , '{}:latest-{}' . format ( HUB_PREFIX , build_id ) , '{}:current-{}' . format ( HUB_PREFIX , build_id ) ] if build_id == 'standard' : tags . append ( '{}:latest' . format ( HUB_PREFIX ) ) command = 'docker build --file "{}" {} .' . format ( path , ' ' . join ( [ '-t {}' . format ( t ) for t in tags ] ) ) print ( '[BUILDING]:' , build_id ) os . system ( command ) return dict ( id = build_id , path = path , command = command , tags = tags ) | Builds the container from the specified docker file path |
44,594 | def publish ( build_entry : dict ) : for tag in build_entry [ 'tags' ] : print ( '[PUSHING]:' , tag ) os . system ( 'docker push {}' . format ( tag ) ) | Publishes the specified build entry to docker hub |
44,595 | def run ( ) : args = parse ( ) build_results = [ build ( p ) for p in glob . iglob ( glob_path ) ] if not args [ 'publish' ] : return for entry in build_results : publish ( entry ) | Execute the build process |
44,596 | def elapsed_time ( seconds : float ) -> str : environ . abort_thread ( ) parts = ( '{}' . format ( timedelta ( seconds = seconds ) ) . rsplit ( '.' , 1 ) ) hours , minutes , seconds = parts [ 0 ] . split ( ':' ) return templating . render_template ( 'elapsed_time.html' , hours = hours . zfill ( 2 ) , minutes = minutes . zfill ( 2 ) , seconds = seconds . zfill ( 2 ) , microseconds = parts [ - 1 ] if len ( parts ) > 1 else '' ) | Displays the elapsed time since the current step started running . |
44,597 | def image ( rendered_path : str , width : int = None , height : int = None , justify : str = None ) -> str : environ . abort_thread ( ) return templating . render_template ( 'image.html' , path = rendered_path , width = width , height = height , justification = ( justify or 'left' ) . lower ( ) ) | Renders an image block |
44,598 | def get_environment_info ( ) -> dict : data = _environ . systems . get_system_data ( ) data [ 'cauldron' ] = _environ . package_settings . copy ( ) return data | Information about Cauldron and its Python interpreter . |
44,599 | def run_server ( port = 5010 , debug = False , ** kwargs ) : from cauldron . cli . server import run run . execute ( port = port , debug = debug , ** kwargs ) | Run the cauldron http server used to interact with cauldron from a remote host . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.