idx
int64
0
63k
question
stringlengths
53
5.28k
target
stringlengths
5
805
55,100
def get_subclass_from_module ( module , parent_class ) : try : r = __recursive_import ( module ) member_dict = dict ( inspect . getmembers ( r ) ) sprinter_class = parent_class for v in member_dict . values ( ) : if inspect . isclass ( v ) and issubclass ( v , parent_class ) and v != parent_class : if sprinter_class is...
Get a subclass of parent_class from the module at module
55,101
def __recursive_import ( module_name ) : names = module_name . split ( "." ) path = None module = None while len ( names ) > 0 : if module : path = module . __path__ name = names . pop ( 0 ) ( module_file , pathname , description ) = imp . find_module ( name , path ) module = imp . load_module ( name , module_file , pa...
Recursively looks for and imports the names returning the module desired
55,102
def err_exit ( msg , rc = 1 ) : print ( msg , file = sys . stderr ) sys . exit ( rc )
Print msg to stderr and exit with rc .
55,103
def read_file ( self , infile ) : try : with open ( infile , 'rt' ) as file : return file . read ( ) except UnicodeDecodeError as e : err_exit ( 'Error reading %s: %s' % ( infile , e ) ) except ( IOError , OSError ) as e : err_exit ( 'Error reading %s: %s' % ( infile , e . strerror or e ) )
Read a reST file into a string .
55,104
def write_file ( self , html , outfile ) : try : with open ( outfile , 'wt' ) as file : file . write ( html ) except ( IOError , OSError ) as e : err_exit ( 'Error writing %s: %s' % ( outfile , e . strerror or e ) )
Write an HTML string to a file .
55,105
def convert_string ( self , rest ) : try : html = publish_string ( rest , writer_name = 'html' ) except SystemExit as e : err_exit ( 'HTML conversion failed with error: %s' % e . code ) else : if sys . version_info [ 0 ] >= 3 : return html . decode ( 'utf-8' ) return html
Convert a reST string to an HTML string .
55,106
def apply_styles ( self , html , styles ) : index = html . find ( '</head>' ) if index >= 0 : return '' . join ( ( html [ : index ] , styles , html [ index : ] ) ) return html
Insert style information into the HTML string .
55,107
def publish_string ( self , rest , outfile , styles = '' ) : html = self . convert_string ( rest ) html = self . strip_xml_header ( html ) html = self . apply_styles ( html , styles ) self . write_file ( html , outfile ) return outfile
Render a reST string as HTML .
55,108
def publish_file ( self , infile , outfile , styles = '' ) : rest = self . read_file ( infile ) return self . publish_string ( rest , outfile , styles )
Render a reST file as HTML .
55,109
def upgrade ( self ) : warn ( 'Upgrading ' + self . filename ) if self . backup_config ( self . filename ) : return self . write_default_config ( self . filename ) return False
Upgrade the config file .
55,110
def backup_config ( self , filename ) : backup_name = filename + '-' + self . version warn ( 'Moving current configuration to ' + backup_name ) try : shutil . copy2 ( filename , backup_name ) return True except ( IOError , OSError ) as e : print ( 'Error copying %s: %s' % ( filename , e . strerror or e ) , file = sys ....
Backup the current config file .
55,111
def write_default_config ( self , filename ) : try : with open ( filename , 'wt' ) as file : file . write ( DEFAULT_CONFIG ) return True except ( IOError , OSError ) as e : print ( 'Error writing %s: %s' % ( filename , e . strerror or e ) , file = sys . stderr ) return False
Write the default config file .
55,112
def reset_defaults ( self , config_file ) : if not exists ( config_file ) : err_exit ( 'No such file: %(config_file)s' % locals ( ) ) if not isfile ( config_file ) : err_exit ( 'Not a file: %(config_file)s' % locals ( ) ) if not os . access ( config_file , os . R_OK ) : err_exit ( 'File cannot be read: %(config_file)s'...
Reset defaults .
55,113
def write_defaults ( self ) : self . defaults . write ( ) self . reset_defaults ( self . defaults . filename )
Create default config file and reload .
55,114
def upgrade_defaults ( self ) : self . defaults . upgrade ( ) self . reset_defaults ( self . defaults . filename )
Upgrade config file and reload .
55,115
def list_styles ( self ) : known = sorted ( self . defaults . known_styles ) if not known : err_exit ( 'No styles' , 0 ) for style in known : if style == self . defaults . default_style : print ( style , '(default)' ) else : print ( style ) sys . exit ( 0 )
Print available styles and exit .
55,116
def render_file ( self , filename ) : dirname , basename = split ( filename ) with changedir ( dirname ) : infile = abspath ( basename ) outfile = abspath ( '.%s.html' % basename ) self . docutils . publish_file ( infile , outfile , self . styles ) return outfile
Convert a reST file to HTML .
55,117
def render_long_description ( self , dirname ) : with changedir ( dirname ) : self . setuptools . check_valid_package ( ) long_description = self . setuptools . get_long_description ( ) outfile = abspath ( '.long-description.html' ) self . docutils . publish_string ( long_description , outfile , self . styles ) return ...
Convert a package s long description to HTML .
55,118
def open_in_browser ( self , outfile ) : if self . browser == 'default' : webbrowser . open ( 'file://%s' % outfile ) else : browser = webbrowser . get ( self . browser ) browser . open ( 'file://%s' % outfile )
Open the given HTML file in a browser .
55,119
def run ( self ) : os . environ [ 'JARN_RUN' ] = '1' self . python . check_valid_python ( ) args = self . parse_options ( self . args ) if args : arg = args [ 0 ] else : arg = os . curdir if arg : arg = expanduser ( arg ) if isfile ( arg ) : outfile = self . render_file ( arg ) elif isdir ( arg ) : outfile = self . ren...
Render and display Python package documentation .
55,120
def preprocess_cell ( self , cell : "NotebookNode" , resources : dict , cell_index : int ) -> Tuple [ "NotebookNode" , dict ] : output_files_dir = resources . get ( "output_files_dir" , None ) if not isinstance ( resources [ "outputs" ] , dict ) : resources [ "outputs" ] = { } for name , attach in cell . get ( "attachm...
Apply a transformation on each cell .
55,121
def combine_pdf_as_bytes ( pdfs : List [ BytesIO ] ) -> bytes : writer = PdfWriter ( ) for pdf in pdfs : writer . addpages ( PdfReader ( pdf ) . pages ) bio = BytesIO ( ) writer . write ( bio ) bio . seek ( 0 ) output = bio . read ( ) bio . close ( ) return output
Combine PDFs and return a byte - string with the result .
55,122
def split ( self , granularity_after_split , exclude_partial = True ) : if granularity_after_split == Granularity . DAY : return self . get_days ( ) elif granularity_after_split == Granularity . WEEK : return self . get_weeks ( exclude_partial ) elif granularity_after_split == Granularity . MONTH : return self . get_mo...
Split a period into a given granularity . Optionally include partial periods at the start and end of the period .
55,123
def apply_calibration ( df , calibration_df , calibration ) : from dmf_control_board_firmware import FeedbackResults for i , ( fb_resistor , R_fb , C_fb ) in calibration_df [ [ 'fb_resistor' , 'R_fb' , 'C_fb' ] ] . iterrows ( ) : calibration . R_fb [ int ( fb_resistor ) ] = R_fb calibration . C_fb [ int ( fb_resistor )...
Apply calibration values from fit_fb_calibration result to calibration object .
55,124
def config_dict ( config ) : return dict ( ( key , getattr ( config , key ) ) for key in config . values )
Given a Sphinx config object return a dictionary of config values .
55,125
def from_defn ( cls , defn ) : "Return the first Repl subclass that works with this" instances = ( subcl ( defn ) for subcl in cls . __subclasses__ ( ) ) return next ( filter ( None , instances ) )
Return the first Repl subclass that works with this
55,126
def show_colormap ( cls , names = [ ] , N = 10 , show = True , * args , ** kwargs ) : names = safe_list ( names ) obj = cls ( names , N , * args , ** kwargs ) vbox = obj . layout ( ) buttons = QDialogButtonBox ( QDialogButtonBox . Close , parent = obj ) buttons . rejected . connect ( obj . close ) vbox . addWidget ( bu...
Show a colormap dialog
55,127
def cmd_list ( args ) : for penlist in penStore . data : puts ( penlist + " (" + str ( len ( penStore . data [ penlist ] ) ) + ")" )
List all element in pen
55,128
def cmd_all ( args ) : for penlist in penStore . data : puts ( penlist ) with indent ( 4 , ' -' ) : for penfile in penStore . data [ penlist ] : puts ( penfile )
List everything recursively
55,129
def cmd_create ( args ) : name = args . get ( 0 ) if name : penStore . createList ( name ) else : puts ( "not valid" )
Creates a list
55,130
def cmd_touch_note ( args ) : major = args . get ( 0 ) minor = args . get ( 1 ) if major in penStore . data : if minor is None : for note in penStore . data [ major ] : puts ( note ) elif minor in penStore . data [ major ] : penStore . openNote ( major , minor ) else : penStore . createNote ( major , minor ) penStore ....
Create a note
55,131
def cmd_delete ( args ) : major = args . get ( 0 ) minor = args . get ( 1 ) if major is not None : if major in penStore . data : if minor is None : if len ( penStore . data [ major ] ) > 0 : if raw_input ( "are you sure (y/n)? " ) not in [ 'y' , 'Y' , 'yes' , 'Yes' ] : return ExitStatus . ABORT penStore . deleteList ( ...
Deletes a node
55,132
def restclient_admin_required ( view_func ) : def wrapper ( request , * args , ** kwargs ) : template = 'access_denied.html' if hasattr ( settings , 'RESTCLIENTS_ADMIN_AUTH_MODULE' ) : auth_func = import_string ( settings . RESTCLIENTS_ADMIN_AUTH_MODULE ) else : context = { 'error_msg' : ( "Your application must define...
View decorator that checks whether the user is permitted to view proxy restclients . Calls login_required in case the user is not authenticated .
55,133
def destination_heuristic ( data ) : counter = collections . Counter ( ) for entry in data : file_field = entry [ 'fields' ] . get ( 'file' ) if not file_field : continue path = os . path . dirname ( file_field ) counter [ path ] += 1 if not counter : raise click . ClickException ( 'Path finding heuristics failed: no p...
A heuristic to get the folder with all other files from bib using majority vote .
55,134
def remove_entry ( data , entry ) : file_field = entry [ 'fields' ] . get ( 'file' ) if file_field : try : os . remove ( file_field ) except IOError : click . echo ( 'This entry\'s file was missing' ) data . remove ( entry )
Remove an entry in place .
55,135
def string_to_basename ( s ) : s = s . strip ( ) . lower ( ) s = re . sub ( r'[^\w\s-]' , '' , s ) return re . sub ( r'[\s-]+' , '-' , s )
Converts to lowercase removes non - alpha characters and converts spaces to hyphens .
55,136
def editor ( * args , ** kwargs ) : result = click . edit ( * args , ** kwargs ) if result is None : msg = 'Editor exited without saving, command aborted' raise click . ClickException ( msg ) return result
Wrapper for click . edit that raises an error when None is returned .
55,137
def terms ( self , facet_name , field , size = 10 , order = None , all_terms = False , exclude = [ ] , regex = '' , regex_flags = '' ) : self [ facet_name ] = dict ( terms = dict ( field = field , size = size ) ) if order : self [ facet_name ] [ terms ] [ 'order' ] = order if all_terms : self [ facet_name ] [ terms ] [...
Allow to specify field facets that return the N most frequent terms .
55,138
def backup_file ( filename ) : if not os . path . exists ( filename ) : return BACKUP_SUFFIX = ".sprinter.bak" backup_filename = filename + BACKUP_SUFFIX shutil . copyfile ( filename , backup_filename )
create a backup of the file desired
55,139
def inject ( self , filename , content ) : content = _unicode ( content ) . rstrip ( ) + "\n" if filename not in self . inject_dict : self . inject_dict [ filename ] = "" self . inject_dict [ filename ] += content
add the injection content to the dictionary
55,140
def commit ( self ) : self . logger . debug ( "Starting injections..." ) self . logger . debug ( "Injections dict is:" ) self . logger . debug ( self . inject_dict ) self . logger . debug ( "Clear list is:" ) self . logger . debug ( self . clear_set ) for filename , content in self . inject_dict . items ( ) : content =...
commit the injections desired overwriting any previous injections in the file .
55,141
def injected ( self , filename ) : full_path = os . path . expanduser ( filename ) if not os . path . exists ( full_path ) : return False with codecs . open ( full_path , 'r+' , encoding = "utf-8" ) as fh : contents = fh . read ( ) return self . wrapper_match . search ( contents ) is not None
Return true if the file has already been injected before .
55,142
def destructive_inject ( self , filename , content ) : content = _unicode ( content ) backup_file ( filename ) full_path = self . __generate_file ( filename ) with codecs . open ( full_path , 'r' , encoding = "utf-8" ) as f : new_content = self . inject_content ( f . read ( ) , content ) with codecs . open ( full_path ...
Injects the injections desired immediately . This should generally be run only during the commit phase when no future injections will be done .
55,143
def __generate_file ( self , file_path ) : file_path = os . path . expanduser ( file_path ) if not os . path . exists ( os . path . dirname ( file_path ) ) : self . logger . debug ( "Directories missing! Creating directories for %s..." % file_path ) os . makedirs ( os . path . dirname ( file_path ) ) if not os . path ....
Generate the file at the file_path desired . Creates any needed directories on the way . returns the absolute path of the file .
55,144
def in_noninjected_file ( self , file_path , content ) : if os . path . exists ( file_path ) : file_content = codecs . open ( file_path , encoding = "utf-8" ) . read ( ) file_content = self . wrapper_match . sub ( u"" , file_content ) else : file_content = "" return file_content . find ( content ) != - 1
Checks if a string exists in the file sans the injected
55,145
def clear_content ( self , content ) : content = _unicode ( content ) return self . wrapper_match . sub ( "" , content )
Clear the injected content from the content buffer and return the results
55,146
def add_order ( self , order ) : key = '%s_%s' % ( order . region_id , order . type_id ) if not self . _orders . has_key ( key ) : self . set_empty_region ( order . region_id , order . type_id , order . generated_at ) self . _orders [ key ] . add_order ( order )
Adds a MarketOrder instance to the list of market orders contained within this order list . Does some behind - the - scenes magic to get it all ready for serialization .
55,147
def add_entry ( self , entry ) : key = '%s_%s' % ( entry . region_id , entry . type_id ) if not self . _history . has_key ( key ) : self . set_empty_region ( entry . region_id , entry . type_id , entry . generated_at ) self . _history [ key ] . add_entry ( entry )
Adds a MarketHistoryEntry instance to the list of market history entries contained within this instance . Does some behind - the - scenes magic to get it all ready for serialization .
55,148
def _find_file ( self , file_name : str , lookup_dir : Path ) -> Path or None : self . logger . debug ( 'Trying to find the file {file_name} inside the directory {lookup_dir}' ) result = None for item in lookup_dir . rglob ( '*' ) : if item . name == file_name : result = item break else : raise FileNotFoundError ( file...
Find a file in a directory by name . Check subdirectories recursively .
55,149
def _sync_repo ( self , repo_url : str , revision : str or None = None ) -> Path : repo_name = repo_url . split ( '/' ) [ - 1 ] . rsplit ( '.' , maxsplit = 1 ) [ 0 ] repo_path = ( self . _cache_path / repo_name ) . resolve ( ) self . logger . debug ( f'Synchronizing with repo; URL: {repo_url}, revision: {revision}' ) t...
Clone a Git repository to the cache dir . If it has been cloned before update it .
55,150
def _shift_headings ( self , content : str , shift : int ) -> str : def _sub ( heading ) : new_heading_level = len ( heading . group ( 'hashes' ) ) + shift self . logger . debug ( f'Shift heading level to {new_heading_level}, heading title: {heading.group("title")}' ) if new_heading_level <= 6 : return f'{"#" * new_hea...
Shift Markdown headings in a string by a given value . The shift can be positive or negative .
55,151
def _cut_from_heading_to_heading ( self , content : str , from_heading : str , to_heading : str or None = None , options = { } ) -> str : self . logger . debug ( f'Cutting from heading: {from_heading}, to heading: {to_heading}, options: {options}' ) from_heading_pattern = re . compile ( r'^\#{1,6}\s+' + rf'{from_headin...
Cut part of Markdown string between two headings set internal heading level and remove top heading .
55,152
def _cut_to_heading ( self , content : str , to_heading : str or None = None , options = { } ) -> str : self . logger . debug ( f'Cutting to heading: {to_heading}, options: {options}' ) content_buffer = StringIO ( content ) first_line = content_buffer . readline ( ) if self . _heading_pattern . fullmatch ( first_line )...
Cut part of Markdown string from the start to a certain heading set internal heading level and remove top heading .
55,153
def _adjust_image_paths ( self , content : str , md_file_path : Path ) -> str : def _sub ( image ) : image_caption = image . group ( 'caption' ) image_path = md_file_path . parent / Path ( image . group ( 'path' ) ) self . logger . debug ( f'Updating image reference; user specified path: {image.group("path")}, ' + f'ab...
Locate images referenced in a Markdown string and replace their paths with the absolute ones .
55,154
def _get_src_file_path ( self , markdown_file_path : Path ) -> Path : path_relative_to_working_dir = markdown_file_path . relative_to ( self . working_dir . resolve ( ) ) self . logger . debug ( 'Currently processed Markdown file path relative to working dir: ' + f'{path_relative_to_working_dir}' ) path_mapped_to_src_d...
Translate the path of Markdown file that is located inside the temporary working directory into the path of the corresponding Markdown file that is located inside the source directory of Foliant project .
55,155
def _get_included_file_path ( self , user_specified_path : str , current_processed_file_path : Path ) -> Path : self . logger . debug ( f'Currently processed Markdown file: {current_processed_file_path}' ) included_file_path = ( current_processed_file_path . parent / user_specified_path ) . resolve ( ) self . logger . ...
Resolve user specified path to the local included file .
55,156
def process_includes ( self , markdown_file_path : Path , content : str ) -> str : markdown_file_path = markdown_file_path . resolve ( ) self . logger . debug ( f'Processing Markdown file: {markdown_file_path}' ) processed_content = '' include_statement_pattern = re . compile ( rf'((?<!\<)\<{"|".join(self.tags)}(?:\s[^...
Replace all include statements with the respective file contents .
55,157
def get_logger ( name , CFG = None ) : logger = logging . getLogger ( name ) if CFG : for handler in CFG . get ( 'handlers' , { } ) . itervalues ( ) : if 'filename' in handler : log_dir = os . path . dirname ( handler [ 'filename' ] ) if not os . path . exists ( log_dir ) : os . makedirs ( log_dir ) try : logging . con...
set up logging for a service using the py 2 . 7 dictConfig
55,158
def t_trailingwhitespace ( self , token ) : ur'.+? \n' print "Error: trailing whitespace at line %s in text '%s'" % ( token . lexer . lineno + 1 , token . value [ : - 1 ] ) token . lexer . lexerror = True token . lexer . skip ( 1 )
ur . + ? \ n
55,159
def exec_before_request_actions ( actions , ** kwargs ) : groups = ( "before" , "before_" + flask . request . method . lower ( ) ) return execute_actions ( actions , limit_groups = groups , ** kwargs )
Execute actions in the before and before_METHOD groups
55,160
def exec_after_request_actions ( actions , response , ** kwargs ) : current_context [ "response" ] = response groups = ( "after_" + flask . request . method . lower ( ) , "after" ) try : rv = execute_actions ( actions , limit_groups = groups , ** kwargs ) except ReturnValueException as e : rv = e . value if rv : return...
Executes actions of the after and after_METHOD groups . A response var will be injected in the current context .
55,161
def as_view ( url = None , methods = None , view_class = ActionsView , name = None , url_rules = None , ** kwargs ) : def decorator ( f ) : if url is not None : f = expose ( url , methods = methods ) ( f ) clsdict = { "name" : name or f . __name__ , "actions" : getattr ( f , "actions" , None ) , "url_rules" : url_rules...
Decorator to transform a function into a view class . Be warned that this will replace the function with the view class .
55,162
def register ( self , target ) : for rule , options in self . url_rules : target . add_url_rule ( rule , self . name , self . dispatch_request , ** options )
Registers url_rules on the blueprint
55,163
def view ( self , * args , ** kwargs ) : def decorator ( f ) : kwargs . setdefault ( "view_class" , self . view_class ) return self . add_view ( as_view ( * args , ** kwargs ) ( f ) ) return decorator
Decorator to automatically apply as_view decorator and register it .
55,164
def add_action_view ( self , name , url , actions , ** kwargs ) : view = ActionsView ( name , url = url , self_var = self , ** kwargs ) if isinstance ( actions , dict ) : for group , actions in actions . iteritems ( ) : view . actions . extend ( load_actions ( actions , group = group or None ) ) else : view . actions ....
Creates an ActionsView instance and registers it .
55,165
def process ( exam_num : int , time : str , date : str ) -> None : prefix = Path ( f"exams/exam-{exam_num}" ) problems = list ( prefix . glob ( f"exam-{exam_num}-{time}-[0-9].ipynb" ) ) problems = sorted ( problems , key = lambda k : k . stem [ - 1 ] ) output_directory = ( prefix / "output" ) . resolve ( ) fw = FilesWr...
Process the exams in the exam_num folder for the time .
55,166
def main ( argv : Optional [ Sequence [ str ] ] = None ) -> None : parser = ArgumentParser ( description = "Convert Jupyter Notebook exams to PDFs" ) parser . add_argument ( "--exam" , type = int , required = True , help = "Exam number to convert" , dest = "exam_num" , ) parser . add_argument ( "--time" , type = str , ...
Parse arguments and process the exam assignment .
55,167
def extract_meta ( self , text ) : first_line = True metadata = [ ] content = [ ] metadata_parsed = False for line in text . split ( '\n' ) : if first_line : first_line = False if line . strip ( ) != '---' : raise MetaParseException ( 'Invalid metadata' ) else : continue if line . strip ( ) == '' and not metadata_parse...
Takes input as the entire file . Reads the first yaml document as metadata . and the rest of the document as text
55,168
def set_defaults ( self ) : for key , value in self . spec . items ( ) : setattr ( self , key . upper ( ) , value . get ( "default" , None ) )
Add each model entry with it s default
55,169
def load_env ( self ) : for key , value in self . spec . items ( ) : if value [ 'type' ] in ( dict , list ) : envar = ( self . env_prefix + "_" + key ) . upper ( ) try : envvar = env . json ( envar , default = getattr ( self , key . upper ( ) , value . get ( 'default' ) ) ) except ConfigurationError as _err : print ( _...
Load the model fron environment variables
55,170
def parse_args ( self ) : parser = ArgumentParser ( description = '' , formatter_class = RawTextHelpFormatter ) parser . add_argument ( "--generate" , action = "store" , dest = 'generate' , choices = [ 'command' , 'docker-run' , 'docker-compose' , 'ini' , 'env' , 'kubernetes' , 'readme' , 'drone-plugin' ] , help = "Gen...
Parse the cli args
55,171
def add_args ( self , args ) : for key , value in vars ( args ) . items ( ) : if value is not None : setattr ( self , key . upper ( ) , value )
Add the args
55,172
def load_ini ( self , ini_file ) : if ini_file and not os . path . exists ( ini_file ) : self . log . critical ( f"Settings file specified but not found. {ini_file}" ) sys . exit ( 1 ) if not ini_file : ini_file = f"{self.cwd}/settings.ini" if os . path . exists ( ini_file ) : config = configparser . RawConfigParser ( ...
Load the contents from the ini file
55,173
def check_required ( self ) : die = False for key , value in self . spec . items ( ) : if not getattr ( self , key . upper ( ) ) and value [ 'required' ] : print ( f"{key} is a required setting. " "Set via command-line params, env or file. " "For examples, try '--generate' or '--help'." ) die = True if die : sys . exit...
Check all required settings have been provided
55,174
def generate ( self ) : otype = getattr ( self , 'GENERATE' ) if otype : if otype == 'env' : self . generate_env ( ) elif otype == "command" : self . generate_command ( ) elif otype == "docker-run" : self . generate_docker_run ( ) elif otype == "docker-compose" : self . generate_docker_compose ( ) elif otype == "kubern...
Generate sample settings
55,175
def generate_env ( self ) : for key in sorted ( list ( self . spec . keys ( ) ) ) : if self . spec [ key ] [ 'type' ] in ( dict , list ) : value = f"\'{json.dumps(self.spec[key].get('example', ''))}\'" else : value = f"{self.spec[key].get('example', '')}" print ( f"export {self.env_prefix}_{key.upper()}={value}" )
Generate sample environment variables
55,176
def generate_command ( self ) : example = [ ] example . append ( f"{sys.argv[0]}" ) for key in sorted ( list ( self . spec . keys ( ) ) ) : if self . spec [ key ] [ 'type' ] == list : value = " " . join ( self . spec [ key ] . get ( 'example' , '' ) ) elif self . spec [ key ] [ 'type' ] == dict : value = f"\'{json.dump...
Generate a sample command
55,177
def generate_docker_run ( self ) : example = [ ] example . append ( "docker run -it" ) for key in sorted ( list ( self . spec . keys ( ) ) ) : if self . spec [ key ] [ 'type' ] in ( dict , list ) : value = f"\'{json.dumps(self.spec[key].get('example', ''))}\'" else : value = f"{self.spec[key].get('example', '')}" strin...
Generate a sample docker run
55,178
def generate_docker_compose ( self ) : example = { } example [ 'app' ] = { } example [ 'app' ] [ 'environment' ] = [ ] for key in sorted ( list ( self . spec . keys ( ) ) ) : if self . spec [ key ] [ 'type' ] in ( dict , list ) : value = f"\'{json.dumps(self.spec[key].get('example', ''))}\'" else : value = f"{self.spec...
Generate a sample docker compose
55,179
def generate_ini ( self ) : example = [ ] example . append ( "[settings]" ) for key in sorted ( list ( self . spec . keys ( ) ) ) : if self . spec [ key ] [ 'type' ] in [ list , dict ] : value = json . dumps ( self . spec [ key ] . get ( 'example' , '' ) ) else : value = self . spec [ key ] . get ( 'example' , '' ) str...
Generate a sample ini
55,180
def generate_kubernetes ( self ) : example = { } example [ 'spec' ] = { } example [ 'spec' ] [ 'containers' ] = [ ] example [ 'spec' ] [ 'containers' ] . append ( { "name" : '' , "image" : '' , "env" : [ ] } ) for key , value in self . spec . items ( ) : if value [ 'type' ] in ( dict , list ) : kvalue = f"\'{json.dumps...
Generate a sample kubernetes
55,181
def generate_drone_plugin ( self ) : example = { } example [ 'pipeline' ] = { } example [ 'pipeline' ] [ 'appname' ] = { } example [ 'pipeline' ] [ 'appname' ] [ 'image' ] = "" example [ 'pipeline' ] [ 'appname' ] [ 'secrets' ] = "" for key , value in self . spec . items ( ) : if value [ 'type' ] in ( dict , list ) : k...
Generate a sample drone plugin configuration
55,182
def generate_readme ( self ) : print ( "## Examples of settings runtime params" ) print ( "### Command-line parameters" ) print ( "```" ) self . generate_command ( ) print ( "```" ) print ( "### Environment variables" ) print ( "```" ) self . generate_env ( ) print ( "```" ) print ( "### ini file" ) print ( "```" ) s...
Generate a readme with all the generators
55,183
def file_exists ( self , subdir , prefix , suffix ) : real_path = os . path . join ( self . STATIC_DIR , self . DIR , subdir , prefix + suffix ) return os . path . exists ( real_path )
Returns true if the resource file exists else False .
55,184
def add_css ( self , subdir , file_name_prefix ) : suffix_maxify = '.css' suffix_minify = '.min.css' if self . minify and self . file_exists ( subdir , file_name_prefix , suffix_minify ) : self . resources_css . append ( posixpath . join ( self . DIR , subdir , file_name_prefix + suffix_minify ) ) elif self . file_exis...
Add a css file for this resource .
55,185
def read_dataframe_from_xls ( desired_type : Type [ T ] , file_path : str , encoding : str , logger : Logger , ** kwargs ) -> pd . DataFrame : return pd . read_excel ( file_path , ** kwargs )
We register this method rather than the other because pandas guesses the encoding by itself .
55,186
def read_df_or_series_from_csv ( desired_type : Type [ pd . DataFrame ] , file_path : str , encoding : str , logger : Logger , ** kwargs ) -> pd . DataFrame : if desired_type is pd . Series : if 'index_col' not in kwargs . keys ( ) : one_col_df = pd . read_csv ( file_path , encoding = encoding , index_col = 0 , ** kwar...
Helper method to read a dataframe from a csv file . By default this is well suited for a dataframe with headers in the first row for example a parameter dataframe .
55,187
def dict_to_df ( desired_type : Type [ T ] , dict_obj : Dict , logger : Logger , orient : str = None , ** kwargs ) -> pd . DataFrame : if len ( dict_obj ) > 0 : first_val = dict_obj [ next ( iter ( dict_obj ) ) ] if isinstance ( first_val , dict ) or isinstance ( first_val , list ) : orient = orient or 'index' return p...
Helper method to convert a dictionary into a dataframe . It supports both simple key - value dicts as well as true table dicts . For this it uses pd . DataFrame constructor or pd . DataFrame . from_dict intelligently depending on the case .
55,188
def single_row_or_col_df_to_series ( desired_type : Type [ T ] , single_rowcol_df : pd . DataFrame , logger : Logger , ** kwargs ) -> pd . Series : if single_rowcol_df . shape [ 0 ] == 1 : return single_rowcol_df . transpose ( ) [ 0 ] elif single_rowcol_df . shape [ 1 ] == 2 and isinstance ( single_rowcol_df . index , ...
Helper method to convert a dataframe with one row or one or two columns into a Series
55,189
def single_row_or_col_df_to_dict ( desired_type : Type [ T ] , single_rowcol_df : pd . DataFrame , logger : Logger , ** kwargs ) -> Dict [ str , str ] : if single_rowcol_df . shape [ 0 ] == 1 : return single_rowcol_df . transpose ( ) [ 0 ] . to_dict ( ) elif single_rowcol_df . shape [ 1 ] == 2 and isinstance ( single_r...
Helper method to convert a dataframe with one row or one or two columns into a dictionary
55,190
def full_subgraph ( self , vertices ) : subgraph_vertices = { v for v in vertices } subgraph_edges = { edge for v in subgraph_vertices for edge in self . _out_edges [ v ] if self . _heads [ edge ] in subgraph_vertices } subgraph_heads = { edge : self . _heads [ edge ] for edge in subgraph_edges } subgraph_tails = { edg...
Return the subgraph of this graph whose vertices are the given ones and whose edges are all the edges of the original graph between those vertices .
55,191
def _raw ( cls , vertices , edges , heads , tails ) : self = object . __new__ ( cls ) self . _vertices = vertices self . _edges = edges self . _heads = heads self . _tails = tails self . _out_edges = collections . defaultdict ( set ) self . _in_edges = collections . defaultdict ( set ) for edge in self . _edges : self ...
Private constructor for direct construction of a DirectedGraph from its consituents .
55,192
def from_out_edges ( cls , vertices , edge_mapper ) : vertices = set ( vertices ) edges = set ( ) heads = { } tails = { } edge_identifier = itertools . count ( ) for tail in vertices : for head in edge_mapper [ tail ] : edge = next ( edge_identifier ) edges . add ( edge ) heads [ edge ] = head tails [ edge ] = tail ret...
Create a DirectedGraph from a collection of vertices and a mapping giving the vertices that each vertex is connected to .
55,193
def from_edge_pairs ( cls , vertices , edge_pairs ) : vertices = set ( vertices ) edges = set ( ) heads = { } tails = { } edge_identifier = itertools . count ( ) for tail , head in edge_pairs : edge = next ( edge_identifier ) edges . add ( edge ) heads [ edge ] = head tails [ edge ] = tail return cls . _raw ( vertices ...
Create a DirectedGraph from a collection of vertices and a collection of pairs giving links between the vertices .
55,194
def annotated ( self ) : annotated_vertices = { vertex : AnnotatedVertex ( id = vertex_id , annotation = six . text_type ( vertex ) , ) for vertex_id , vertex in zip ( itertools . count ( ) , self . vertices ) } annotated_edges = [ AnnotatedEdge ( id = edge_id , annotation = six . text_type ( edge ) , head = annotated_...
Return an AnnotatedGraph with the same structure as this graph .
55,195
def load ( self ) : if self . exists ( ) : with open ( self . dot_file , 'r' ) as handle : self . update ( json . load ( handle ) ) if self . options [ 'context' ] is not None : self [ 'context' ] = self . options [ 'context' ] else : self . options [ 'context' ] = self [ 'context' ] if self . options [ 'defaults' ] is...
read dotfile and populate self opts will override the dotfile settings make sure everything is synced in both opts and this object
55,196
def env_dictionary ( self ) : none_to_str = lambda x : str ( x ) if x else "" return { "DOCKERSTACHE_{}" . format ( k . upper ( ) ) : none_to_str ( v ) for k , v in six . iteritems ( self ) }
convert the options to this script into an env var dictionary for pre and post scripts
55,197
def pre_script ( self ) : if self [ 'pre_script' ] is None : return LOGGER . info ( "Executing pre script: {}" . format ( self [ 'pre_script' ] ) ) cmd = self [ 'pre_script' ] execute_command ( self . abs_input_dir ( ) , cmd , self . env_dictionary ( ) ) LOGGER . info ( "Pre Script completed" )
execute the pre script if it is defined
55,198
def say_tmp_filepath ( text = None , preference_program = "festival" ) : filepath = shijian . tmp_filepath ( ) + ".wav" say ( text = text , preference_program = preference_program , filepath = filepath ) return filepath
Say specified text to a temporary file and return the filepath .
55,199
def clacks_overhead ( fn ) : @ wraps ( fn ) def _wrapped ( * args , ** kw ) : response = fn ( * args , ** kw ) response [ 'X-Clacks-Overhead' ] = 'GNU Terry Pratchett' return response return _wrapped
A Django view decorator that will add the X - Clacks - Overhead header .