idx int64 0 63k | question stringlengths 53 5.28k | target stringlengths 5 805 |
|---|---|---|
34,900 | def dump ( self ) : report_as_json_string = utils . dict_to_json ( self . report ) if self . out_file : utils . string_to_file ( self . out_file , report_as_json_string ) else : print report_as_json_string | Dump the output to json . |
34,901 | def fast_float ( x , key = lambda x : x , nan = None , _uni = unicodedata . numeric , _nan_inf = NAN_INF , _first_char = POTENTIAL_FIRST_CHAR , ) : if x [ 0 ] in _first_char or x . lstrip ( ) [ : 3 ] in _nan_inf : try : x = float ( x ) return nan if nan is not None and x != x else x except ValueError : try : return _un... | Convert a string to a float quickly return input as - is if not possible . |
34,902 | def fast_int ( x , key = lambda x : x , _uni = unicodedata . digit , _first_char = POTENTIAL_FIRST_CHAR , ) : if x [ 0 ] in _first_char : try : return long ( x ) except ValueError : try : return _uni ( x , key ( x ) ) if len ( x ) == 1 else key ( x ) except TypeError : return key ( x ) else : try : return _uni ( x , ke... | Convert a string to a int quickly return input as - is if not possible . |
34,903 | def check_filters ( filters ) : if not filters : return None try : return [ range_check ( f [ 0 ] , f [ 1 ] ) for f in filters ] except ValueError as err : raise ValueError ( "Error in --filter: " + py23_str ( err ) ) | Execute range_check for every element of an iterable . |
34,904 | def keep_entry_range ( entry , lows , highs , converter , regex ) : return any ( low <= converter ( num ) <= high for num in regex . findall ( entry ) for low , high in zip ( lows , highs ) ) | Check if an entry falls into a desired range . |
34,905 | def keep_entry_value ( entry , values , converter , regex ) : return not any ( converter ( num ) in values for num in regex . findall ( entry ) ) | Check if an entry does not match a given value . |
34,906 | def sort_and_print_entries ( entries , args ) : is_float = args . number_type in ( "float" , "real" , "f" , "r" ) signed = args . signed or args . number_type in ( "real" , "r" ) alg = ( natsort . ns . FLOAT * is_float | natsort . ns . SIGNED * signed | natsort . ns . NOEXP * ( not args . exp ) | natsort . ns . PATH * ... | Sort the entries applying the filters first if necessary . |
34,907 | def regex_chooser ( alg ) : if alg & ns . FLOAT : alg &= ns . FLOAT | ns . SIGNED | ns . NOEXP else : alg &= ns . INT | ns . SIGNED return { ns . INT : NumericalRegularExpressions . int_nosign ( ) , ns . FLOAT : NumericalRegularExpressions . float_nosign_exp ( ) , ns . INT | ns . SIGNED : NumericalRegularExpressions . ... | Select an appropriate regex for the type of number of interest . |
34,908 | def _normalize_input_factory ( alg ) : normalization_form = "NFKD" if alg & ns . COMPATIBILITYNORMALIZE else "NFD" wrapped = partial ( normalize , normalization_form ) if NEWPY : return wrapped else : return lambda x , _f = wrapped : _f ( x ) if isinstance ( x , py23_str ) else x | Create a function that will normalize unicode input data . |
34,909 | def natsort_key ( val , key , string_func , bytes_func , num_func ) : if key is not None : val = key ( val ) try : return string_func ( val ) except ( TypeError , AttributeError ) : if type ( val ) in ( bytes , ) : return bytes_func ( val ) try : return tuple ( natsort_key ( x , None , string_func , bytes_func , num_fu... | Key to sort strings and numbers naturally . |
34,910 | def parse_number_factory ( alg , sep , pre_sep ) : nan_replace = float ( "+inf" ) if alg & ns . NANLAST else float ( "-inf" ) def func ( val , _nan_replace = nan_replace , _sep = sep ) : return _sep , _nan_replace if val != val else val if alg & ns . PATH and alg & ns . UNGROUPLETTERS and alg & ns . LOCALEALPHA : retur... | Create a function that will format a number into a tuple . |
34,911 | def sep_inserter ( iterable , sep ) : try : types = ( int , float , long ) first = next ( iterable ) if type ( first ) in types : yield sep yield first second = next ( iterable ) if type ( first ) in types and type ( second ) in types : yield sep yield second for x in iterable : first , second = second , x if type ( fi... | Insert between numbers in an iterable . |
34,912 | def input_string_transform_factory ( alg ) : lowfirst = alg & ns . LOWERCASEFIRST dumb = alg & NS_DUMB function_chain = [ ] if ( dumb and not lowfirst ) or ( lowfirst and not dumb ) : function_chain . append ( methodcaller ( "swapcase" ) ) if alg & ns . IGNORECASE : if NEWPY : function_chain . append ( methodcaller ( "... | Create a function to transform a string . |
34,913 | def string_component_transform_factory ( alg ) : use_locale = alg & ns . LOCALEALPHA dumb = alg & NS_DUMB group_letters = ( alg & ns . GROUPLETTERS ) or ( use_locale and dumb ) nan_val = float ( "+inf" ) if alg & ns . NANLAST else float ( "-inf" ) func_chain = [ ] if group_letters : func_chain . append ( groupletters )... | Create a function to either transform a string or convert to a number . |
34,914 | def final_data_transform_factory ( alg , sep , pre_sep ) : if alg & ns . UNGROUPLETTERS and alg & ns . LOCALEALPHA : swap = alg & NS_DUMB and alg & ns . LOWERCASEFIRST transform = methodcaller ( "swapcase" ) if swap else _no_op def func ( split_val , val , _transform = transform , _sep = sep , _pre_sep = pre_sep ) : sp... | Create a function to transform a tuple . |
34,915 | def groupletters ( x , _low = lower_function ) : return "" . join ( ichain . from_iterable ( ( _low ( y ) , y ) for y in x ) ) | Double all characters making doubled letters lowercase . |
34,916 | def chain_functions ( functions ) : functions = list ( functions ) if not functions : return _no_op elif len ( functions ) == 1 : return functions [ 0 ] else : return partial ( reduce , lambda res , f : f ( res ) , functions ) | Chain a list of single - argument functions together and return . |
34,917 | def path_splitter ( s , _d_match = re . compile ( r"\.\d" ) . match ) : if has_pathlib and isinstance ( s , PurePath ) : s = py23_str ( s ) path_parts = deque ( ) p_appendleft = path_parts . appendleft path_location = s while path_location != os_curdir and path_location != os_pardir : parent_path = path_location path_l... | Split a string into its path components . |
34,918 | def _construct_regex ( cls , fmt ) : return re . compile ( fmt . format ( ** vars ( cls ) ) , flags = re . U ) | Given a format string construct the regex with class attributes . |
34,919 | def natsort_keygen ( key = None , alg = ns . DEFAULT ) : try : ns . DEFAULT | alg except TypeError : msg = "natsort_keygen: 'alg' argument must be from the enum 'ns'" raise ValueError ( msg + ", got {}" . format ( py23_str ( alg ) ) ) if alg & ns . LOCALEALPHA and natsort . compat . locale . dumb_sort ( ) : alg |= NS_D... | Generate a key to sort strings and numbers naturally . |
34,920 | def natsorted ( seq , key = None , reverse = False , alg = ns . DEFAULT ) : key = natsort_keygen ( key , alg ) return sorted ( seq , reverse = reverse , key = key ) | Sorts an iterable naturally . |
34,921 | def humansorted ( seq , key = None , reverse = False , alg = ns . DEFAULT ) : return natsorted ( seq , key , reverse , alg | ns . LOCALE ) | Convenience function to properly sort non - numeric characters . |
34,922 | def realsorted ( seq , key = None , reverse = False , alg = ns . DEFAULT ) : return natsorted ( seq , key , reverse , alg | ns . REAL ) | Convenience function to properly sort signed floats . |
34,923 | def index_natsorted ( seq , key = None , reverse = False , alg = ns . DEFAULT ) : if key is None : newkey = itemgetter ( 1 ) else : def newkey ( x ) : return key ( itemgetter ( 1 ) ( x ) ) index_seq_pair = [ [ x , y ] for x , y in enumerate ( seq ) ] index_seq_pair . sort ( reverse = reverse , key = natsort_keygen ( ne... | Determine the list of the indexes used to sort the input sequence . |
34,924 | def order_by_index ( seq , index , iter = False ) : return ( seq [ i ] for i in index ) if iter else [ seq [ i ] for i in index ] | Order a given sequence by an index sequence . |
34,925 | def _iterOutFiles ( self ) : out = StringIO ( ) self . callgrind ( out , relative_path = True ) yield ( 'cachegrind.out.pprofile' , out . getvalue ( ) , 'application/x-kcachegrind' , ) for name , lines in self . iterSource ( ) : lines = '' . join ( lines ) if lines : if isinstance ( lines , unicode ) : lines = lines . ... | Yields path data mimetype for each file involved on or produced by profiling . |
34,926 | def run ( cmd , filename = None , threads = True , verbose = False ) : _run ( threads , verbose , 'run' , filename , cmd ) | Similar to profile . run . |
34,927 | def runctx ( cmd , globals , locals , filename = None , threads = True , verbose = False ) : _run ( threads , verbose , 'runctx' , filename , cmd , globals , locals ) | Similar to profile . runctx . |
34,928 | def runfile ( fd , argv , fd_name = '<unknown>' , compile_flags = 0 , dont_inherit = 1 , filename = None , threads = True , verbose = False ) : _run ( threads , verbose , 'runfile' , filename , fd , argv , fd_name , compile_flags , dont_inherit ) | Run code from given file descriptor with profiling enabled . Closes fd before executing contained code . |
34,929 | def runpath ( path , argv , filename = None , threads = True , verbose = False ) : _run ( threads , verbose , 'runpath' , filename , path , argv ) | Run code from open - accessible file path with profiling enabled . |
34,930 | def pprofile ( line , cell = None ) : if cell is None : return run ( line ) return _main ( [ '%%pprofile' , '-m' , '-' ] + shlex . split ( line ) , io . StringIO ( cell ) , ) | Profile line execution . |
34,931 | def hit ( self , code , line , duration ) : entry = self . line_dict [ line ] [ code ] entry [ 0 ] += 1 entry [ 1 ] += duration | A line has finished executing . |
34,932 | def call ( self , code , line , callee_file_timing , callee , duration , frame ) : try : entry = self . call_dict [ ( code , line , callee ) ] except KeyError : self . call_dict [ ( code , line , callee ) ] = [ callee_file_timing , 1 , duration ] else : entry [ 1 ] += 1 entry [ 2 ] += duration | A call originating from this file returned . |
34,933 | def dump_stats ( self , filename ) : if _isCallgrindName ( filename ) : with open ( filename , 'w' ) as out : self . callgrind ( out ) else : with io . open ( filename , 'w' , errors = 'replace' ) as out : self . annotate ( out ) | Similar to profile . Profile . dump_stats - but different output format ! |
34,934 | def runctx ( self , cmd , globals , locals ) : with self ( ) : exec ( cmd , globals , locals ) return self | Similar to profile . Profile . runctx . |
34,935 | def enable ( self ) : if self . enabled_start : warn ( 'Duplicate "enable" call' ) else : self . _enable ( ) sys . settrace ( self . _global_trace ) | Enable profiling . |
34,936 | def _disable ( self ) : self . total_time += time ( ) - self . enabled_start self . enabled_start = None del self . stack | Overload this method when subclassing . Called after actually disabling trace . |
34,937 | def _make_expanded_field_serializer ( self , name , nested_expand , nested_fields , nested_omit ) : field_options = self . expandable_fields [ name ] serializer_class = field_options [ 0 ] serializer_settings = copy . deepcopy ( field_options [ 1 ] ) if name in nested_expand : serializer_settings [ "expand" ] = nested_... | Returns an instance of the dynamically created nested serializer . |
34,938 | def _clean_fields ( self , omit_fields , sparse_fields , next_level_omits ) : sparse = len ( sparse_fields ) > 0 to_remove = [ ] if not sparse and len ( omit_fields ) == 0 : return for field_name in self . fields : is_present = self . _should_field_exist ( field_name , omit_fields , sparse_fields , next_level_omits ) i... | Remove fields that are found in omit list and if sparse names are passed remove any fields not found in that list . |
34,939 | def _can_access_request ( self ) : if self . parent : return False if not hasattr ( self , "context" ) or not self . context . get ( "request" , None ) : return False return self . context [ "request" ] . method == "GET" | Can access current request object if all are true - The serializer is the root . - A request context was passed in . - The request method is GET . |
34,940 | def _get_expand_input ( self , passed_settings ) : value = passed_settings . get ( "expand" ) if len ( value ) > 0 : return value if not self . _can_access_request : return [ ] expand = self . _parse_request_list_value ( "expand" ) if "permitted_expands" in self . context : permitted_expands = self . context [ "permitt... | If expand value is explicitliy passed just return it . If parsing from request ensure that the value complies with the permitted_expands list passed into the context from the FlexFieldsMixin . |
34,941 | def is_expanded ( request , key ) : expand = request . query_params . get ( "expand" , "" ) expand_fields = [ ] for e in expand . split ( "," ) : expand_fields . extend ( [ e for e in e . split ( "." ) ] ) return "~all" in expand_fields or key in expand_fields | Examines request object to return boolean of whether passed field is expanded . |
34,942 | def color_replace ( image , color ) : pixels = image . load ( ) size = image . size [ 0 ] for width in range ( size ) : for height in range ( size ) : r , g , b , a = pixels [ width , height ] if ( r , g , b , a ) == ( 0 , 0 , 0 , 255 ) : pixels [ width , height ] = color else : pixels [ width , height ] = ( r , g , b ... | Replace black with other color |
34,943 | def wrap_in_ndarray ( value ) : if hasattr ( value , "__len__" ) : return np . array ( value ) else : return np . array ( [ value ] ) | Wraps the argument in a numpy . ndarray . |
34,944 | def coefficients_non_uni ( deriv , acc , coords , idx ) : if acc % 2 == 1 : acc += 1 num_central = 2 * math . floor ( ( deriv + 1 ) / 2 ) - 1 + acc num_side = num_central // 2 if deriv % 2 == 0 : num_coef = num_central + 1 else : num_coef = num_central if idx < num_side : matrix = _build_matrix_non_uniform ( 0 , num_co... | Calculates the finite difference coefficients for given derivative order and accuracy order . Assumes that the underlying grid is non - uniform . |
34,945 | def _build_matrix ( p , q , deriv ) : A = [ ( [ 1 for _ in range ( - p , q + 1 ) ] ) ] for i in range ( 1 , p + q + 1 ) : A . append ( [ j ** i for j in range ( - p , q + 1 ) ] ) return np . array ( A ) | Constructs the equation system matrix for the finite difference coefficients |
34,946 | def _build_rhs ( p , q , deriv ) : b = [ 0 for _ in range ( p + q + 1 ) ] b [ deriv ] = math . factorial ( deriv ) return np . array ( b ) | The right hand side of the equation system matrix |
34,947 | def _build_matrix_non_uniform ( p , q , coords , k ) : A = [ [ 1 ] * ( p + q + 1 ) ] for i in range ( 1 , p + q + 1 ) : line = [ ( coords [ k + j ] - coords [ k ] ) ** i for j in range ( - p , q + 1 ) ] A . append ( line ) return np . array ( A ) | Constructs the equation matrix for the finite difference coefficients of non - uniform grids at location k |
34,948 | def set_accuracy ( self , acc ) : self . acc = acc if self . child : self . child . set_accuracy ( acc ) | Sets the accuracy order of the finite difference scheme . If the FinDiff object is not a raw partial derivative but a composition of derivatives the accuracy order will be propagated to the child operators . |
34,949 | def diff ( self , y , h , deriv , dim , coefs ) : try : npts = y . shape [ dim ] except AttributeError as err : raise ValueError ( "FinDiff objects can only be applied to arrays or evaluated(!) functions returning arrays" ) from err scheme = "center" weights = coefs [ scheme ] [ "coefficients" ] offsets = coefs [ schem... | The core function to take a partial derivative on a uniform grid . |
34,950 | def diff_non_uni ( self , y , coords , dim , coefs ) : yd = np . zeros_like ( y ) ndims = len ( y . shape ) multi_slice = [ slice ( None , None ) ] * ndims ref_multi_slice = [ slice ( None , None ) ] * ndims for i , x in enumerate ( coords ) : weights = coefs [ i ] [ "coefficients" ] offsets = coefs [ i ] [ "offsets" ]... | The core function to take a partial derivative on a non - uniform grid |
34,951 | def _apply_to_array ( self , yd , y , weights , off_slices , ref_slice , dim ) : ndims = len ( y . shape ) all = slice ( None , None , 1 ) ref_multi_slice = [ all ] * ndims ref_multi_slice [ dim ] = ref_slice for w , s in zip ( weights , off_slices ) : off_multi_slice = [ all ] * ndims off_multi_slice [ dim ] = s if ab... | Applies the finite differences only to slices along a given axis |
34,952 | def get_current_user_info ( anchore_auth ) : user_url = anchore_auth [ 'client_info_url' ] + '/' + anchore_auth [ 'username' ] user_timeout = 60 retries = 3 result = requests . get ( user_url , headers = { 'x-anchore-password' : anchore_auth [ 'password' ] } ) if result . status_code == 200 : user_data = json . loads (... | Return the metadata about the current user as supplied by the anchore . io service . Includes permissions and tier access . |
34,953 | def show ( details ) : ecode = 0 try : policymeta = anchore_policy . load_policymeta ( ) if details : anchore_print ( policymeta , do_formatting = True ) else : output = { } name = policymeta [ 'name' ] output [ name ] = { } output [ name ] [ 'id' ] = policymeta [ 'id' ] output [ name ] [ 'policies' ] = policymeta [ 'p... | Show list of Anchore data policies . |
34,954 | def extended_help_option ( extended_help = None , * param_decls , ** attrs ) : def decorator ( f ) : def callback ( ctx , param , value ) : if value and not ctx . resilient_parsing : if not extended_help : ctx . command . help = ctx . command . callback . __doc__ click . echo ( ctx . get_help ( ) , color = ctx . color ... | Based on the click . help_option code . |
34,955 | def anchore_print ( msg , do_formatting = False ) : if do_formatting : click . echo ( formatter ( msg ) ) else : click . echo ( msg ) | Print to stdout using the proper formatting for the command . |
34,956 | def build_image_list ( config , image , imagefile , all_local , include_allanchore , dockerfile = None , exclude_file = None ) : if not image and not ( imagefile or all_local ) : raise click . BadOptionUsage ( 'No input found for image source. One of <image>, <imagefile>, or <all> must be specified' ) if image and imag... | Given option inputs from the cli construct a list of image ids . Includes all found with no exclusion logic |
34,957 | def init_output_formatters ( output_verbosity = 'normal' , stderr = sys . stderr , logfile = None , debug_logfile = None ) : if output_verbosity not in console_verbosity_options : raise ValueError ( 'output_verbosity must be one of: %s' % console_verbosity_options . keys ( ) ) stderr_handler = logging . StreamHandler (... | Initialize the CLI logging scheme . |
34,958 | def main_entry ( ctx , verbose , debug , quiet , json , plain , html , config_override ) : logfile = None debug_logfile = None try : try : config_overrides = { } if config_override : for el in config_override : try : ( key , val ) = el . split ( '=' ) if not key or not val : raise Exception ( "could not split by '='" )... | Anchore is a tool to analyze query and curate container images . The options at this top level control stdout and stderr verbosity and format . |
34,959 | def get_user_agent ( ) : global user_agent_string if user_agent_string is None : try : sysinfo = subprocess . check_output ( 'lsb_release -i -r -s' . split ( ' ' ) ) dockerinfo = subprocess . check_output ( 'docker --version' . split ( ' ' ) ) user_agent_string = ' ' . join ( [ sysinfo . replace ( '\t' , '/' ) , docker... | Construct and informative user - agent string . Includes OS version and docker version info |
34,960 | def normalize_headers ( headers ) : for ( k , v ) in headers . items ( ) : headers . pop ( k ) headers [ k . lower ( ) ] = v result = { } if 'content-length' in headers : result [ 'content-length' ] = headers [ 'content-length' ] elif 'contentlength' in headers : result [ 'content-length' ] = headers [ 'contentlength' ... | Convert useful headers to a normalized type and return in a new dict |
34,961 | def get_resource_retriever ( url ) : if url . startswith ( 'http://' ) or url . startswith ( 'https://' ) : return HttpResourceRetriever ( url ) else : raise ValueError ( 'Unsupported scheme in url: %s' % url ) | Get the appropriate retriever object for the specified url based on url scheme . Makes assumption that HTTP urls do not require any special authorization . |
34,962 | def get ( self , url ) : self . _load ( url ) self . _flush ( ) return self . metadata [ url ] | Lookup the given url and return an entry if found . Else return None . The returned entry is a dict with metadata about the content and a content key with a file path value |
34,963 | def _load ( self , url ) : self . _logger . debug ( 'Loading url %s into resource cache' % url ) retriever = get_resource_retriever ( url ) content_path = os . path . join ( self . path , self . _hash_path ( url ) ) try : if url in self . metadata : headers = retriever . fetch ( content_path , last_etag = self . metada... | Load from remote but check local file content to identify duplicate content . If local file is found with same hash then it is used with metadata from remote object to avoid fetching full content . |
34,964 | def calc_file_md5 ( filepath , chunk_size = None ) : if chunk_size is None : chunk_size = 256 * 1024 md5sum = hashlib . md5 ( ) with io . open ( filepath , 'r+b' ) as f : datachunk = f . read ( chunk_size ) while datachunk is not None and len ( datachunk ) > 0 : md5sum . update ( datachunk ) datachunk = f . read ( chun... | Calculate a file s md5 checksum . Use the specified chunk_size for IO or the default 256KB |
34,965 | def toolbox ( anchore_config , ctx , image , imageid ) : global config , imagelist , nav config = anchore_config ecode = 0 try : if image : imagelist = [ image ] try : result = anchore_utils . discover_imageIds ( imagelist ) except ValueError as err : raise err else : imagelist = result elif imageid : if len ( imageid ... | A collection of tools for operating on images and containers and building anchore modules . |
34,966 | def unpack ( destdir ) : if not nav : sys . exit ( 1 ) ecode = 0 try : anchore_print ( "Unpacking images: " + ' ' . join ( nav . get_images ( ) ) ) result = nav . unpack ( destdir = destdir ) if not result : anchore_print_err ( "no images unpacked" ) ecode = 1 else : for imageId in result : anchore_print ( "Unpacked im... | Unpack and Squash image to local filesystem |
34,967 | def show_analyzer_status ( ) : ecode = 0 try : image = contexts [ 'anchore_allimages' ] [ imagelist [ 0 ] ] analyzer_status = contexts [ 'anchore_db' ] . load_analyzer_manifest ( image . meta [ 'imageId' ] ) result = { image . meta [ 'imageId' ] : { 'result' : { 'header' : [ 'Analyzer' , 'Status' , '*Type' , 'LastExec'... | Show analyzer status for specified image |
34,968 | def export ( outfile ) : if not nav : sys . exit ( 1 ) ecode = 0 savelist = list ( ) for imageId in imagelist : try : record = { } record [ 'image' ] = { } record [ 'image' ] [ 'imageId' ] = imageId record [ 'image' ] [ 'imagedata' ] = contexts [ 'anchore_db' ] . load_image_new ( imageId ) savelist . append ( record ) ... | Export image anchore data to a JSON file . |
34,969 | def image_import ( infile , force ) : ecode = 0 try : with open ( infile , 'r' ) as FH : savelist = json . loads ( FH . read ( ) ) except Exception as err : anchore_print_err ( "could not load input file: " + str ( err ) ) ecode = 1 if ecode == 0 : for record in savelist : try : imageId = record [ 'image' ] [ 'imageId'... | Import image anchore data from a JSON file . |
34,970 | def status ( conf ) : ecode = 0 try : if conf : if config . cliargs [ 'json' ] : anchore_print ( config . data , do_formatting = True ) else : anchore_print ( yaml . safe_dump ( config . data , indent = True , default_flow_style = False ) ) else : result = { } if contexts [ 'anchore_db' ] . check ( ) : result [ "anchor... | Show anchore system status . |
34,971 | def show_schemas ( schemaname ) : ecode = 0 try : schemas = { } schema_dir = os . path . join ( contexts [ 'anchore_config' ] [ 'pkg_dir' ] , 'schemas' ) for f in os . listdir ( schema_dir ) : sdata = { } try : with open ( os . path . join ( schema_dir , f ) , 'r' ) as FH : sdata = json . loads ( FH . read ( ) ) except... | Show anchore document schemas . |
34,972 | def backup ( outputdir ) : ecode = 0 try : anchore_print ( 'Backing up anchore system to directory ' + str ( outputdir ) + ' ...' ) backupfile = config . backup ( outputdir ) anchore_print ( { "anchore_backup_tarball" : str ( backupfile ) } , do_formatting = True ) except Exception as err : anchore_print_err ( 'operati... | Backup an anchore installation to a tarfile . |
34,973 | def restore ( inputfile , destination_root ) : ecode = 0 try : anchore_print ( 'Restoring anchore system from backup file %s ...' % ( str ( inputfile . name ) ) ) restoredir = config . restore ( destination_root , inputfile ) anchore_print ( "Anchore restored." ) except Exception as err : anchore_print_err ( 'operation... | Restore an anchore installation from a previously backed up tar file . |
34,974 | def exportdb ( outdir ) : ecode = 0 try : imgdir = os . path . join ( outdir , "images" ) feeddir = os . path . join ( outdir , "feeds" ) storedir = os . path . join ( outdir , "storedfiles" ) for d in [ outdir , imgdir , feeddir , storedir ] : if not os . path . exists ( d ) : os . makedirs ( d ) anchore_print ( "expo... | Export all anchore images to JSON files |
34,975 | def next_token ( expected_type , data ) : next_data = copy . copy ( data ) next_type = TokenType . INVALID if len ( next_data ) == 0 or next_data [ 0 ] == None : next_type = TokenType . END elif ( expected_type == TokenType . DIGIT or expected_type == TokenType . DIGIT_OR_ZERO ) and next_data [ 0 ] . isalpha ( ) : next... | Based on the expected next type consume the next token returning the type found and an updated buffer with the found token removed |
34,976 | def show ( feed ) : ecode = 0 try : feedmeta = anchore_feeds . load_anchore_feedmeta ( ) if feed in feedmeta : result = { } groups = feedmeta [ feed ] . get ( 'groups' , { } ) . values ( ) result [ 'name' ] = feed result [ 'access_tier' ] = int ( feedmeta [ feed ] . get ( 'access_tier' ) ) result [ 'description' ] = fe... | Show detailed feed information |
34,977 | def list ( showgroups ) : ecode = 0 try : result = { } subscribed = { } available = { } unavailable = { } current_user_data = contexts [ 'anchore_auth' ] [ 'user_info' ] feedmeta = anchore_feeds . load_anchore_feedmeta ( ) for feed in feedmeta . keys ( ) : if feedmeta [ feed ] [ 'subscribed' ] : subscribed [ feed ] = {... | Show list of Anchore data feeds . |
34,978 | def evaluate_familytree ( self , family_tree , image_set ) : if family_tree is None or image_set is None : raise ValueError ( 'Cannot execute analysis strategy on None image or image with no familytree data' ) toanalyze = OrderedDict ( ) tree_len = len ( family_tree ) for i in family_tree : image = image_set [ i ] if s... | Evaluate strategy for the given family tree and return a dict of images to analyze that match the strategy |
34,979 | def logout ( anchore_config ) : ecode = 0 try : aa = contexts [ 'anchore_auth' ] if aa : anchore_auth . anchore_auth_invalidate ( aa ) if 'auth_file' in aa : os . remove ( aa [ 'auth_file' ] ) print "Logout successful." except Exception as err : anchore_print_err ( 'operation failed' ) ecode = 1 sys . exit ( ecode ) | Log out of Anchore service |
34,980 | async def connect ( self ) : if isinstance ( self . connection , dict ) : kwargs = self . connection . copy ( ) address = ( kwargs . pop ( 'host' , 'localhost' ) , kwargs . pop ( 'port' , 6379 ) ) redis_kwargs = kwargs elif isinstance ( self . connection , aioredis . Redis ) : self . _pool = self . connection else : ad... | Get an connection for the self instance |
34,981 | async def close ( self ) : if self . _pool is not None and not isinstance ( self . connection , aioredis . Redis ) : self . _pool . close ( ) await self . _pool . wait_closed ( ) self . _pool = None | Closes connection and resets pool |
34,982 | async def set_lock ( self , resource , lock_identifier ) : start_time = time . time ( ) lock_timeout = self . lock_timeout successes = await asyncio . gather ( * [ i . set_lock ( resource , lock_identifier , lock_timeout ) for i in self . instances ] , return_exceptions = True ) successful_sets = sum ( s is None for s ... | Tries to set the lock to all the redis instances |
34,983 | async def unset_lock ( self , resource , lock_identifier ) : start_time = time . time ( ) successes = await asyncio . gather ( * [ i . unset_lock ( resource , lock_identifier ) for i in self . instances ] , return_exceptions = True ) successful_remvoes = sum ( s is None for s in successes ) elapsed_time = time . time (... | Tries to unset the lock to all the redis instances |
34,984 | def _clean ( value ) : if isinstance ( value , np . ndarray ) : if value . dtype . kind == 'S' : return np . char . decode ( value ) . tolist ( ) else : return value . tolist ( ) elif type ( value ) . __module__ == np . __name__ : conversion = np . asscalar ( value ) if sys . version_info . major == 3 and isinstance ( ... | Convert numpy numeric types to their python equivalents . |
34,985 | def get_prior_alignment ( self ) : data_group = '{}/HairpinAlign' . format ( self . group_name ) data = self . handle . get_analysis_dataset ( data_group , 'Alignment' ) return data | Return the prior alignment that was used for 2D basecalling . |
34,986 | def get_2d_call_alignment ( self ) : data_group = '{}/BaseCalled_2D' . format ( self . group_name ) data = self . handle . get_analysis_dataset ( data_group , 'Alignment' ) return data | Return the alignment and model_states from the 2D basecall . |
34,987 | def get_results ( self ) : summary = self . handle . get_summary_data ( self . group_name ) results = { 'template' : { 'status' : 'no data' } , 'complement' : { 'status' : 'no data' } , '2d' : { 'status' : 'no data' } } if 'genome_mapping_template' in summary : results [ 'template' ] = self . _get_results ( summary [ '... | Get details about the alignments that have been performed . |
34,988 | def calculate_speed ( self , section , alignment_results = None ) : speed = 0.0 if alignment_results : results = self . _get_results ( alignment_results ) else : results = self . get_results ( ) [ section ] if results [ 'status' ] != 'match found' : return 0.0 ref_span = results [ 'ref_span' ] ref_len = ref_span [ 1 ] ... | Calculate speed using alignment information . |
34,989 | def add_raw_data ( self , data , attrs ) : self . assert_writeable ( ) if "Raw" not in self . handle : self . handle . create_group ( "Raw" ) if "Signal" in self . handle [ 'Raw' ] : msg = "Fast5 file already has raw data for read '{}' in: {}" raise KeyError ( msg . format ( self . read_id , self . filename ) ) self . ... | Add raw data for a read . |
34,990 | def add_channel_info ( self , attrs , clear = False ) : self . assert_writeable ( ) if 'channel_id' not in self . handle : self . handle . create_group ( 'channel_id' ) self . _add_attributes ( 'channel_id' , attrs , clear ) | Add channel info data to the channel_id group . |
34,991 | def add_analysis ( self , component , group_name , attrs , config = None ) : if "Analyses" not in self . handle : self . handle . create_group ( "Analyses" ) super ( Fast5Read , self ) . add_analysis ( component , group_name , attrs , config ) | Add a new analysis group to the file . |
34,992 | def write_strand ( self , strand ) : if strand [ 'channel' ] != self . _current_channel or self . _strand_counter == self . _reads_per_file : self . _start_new_file ( strand ) fname = self . _write_strand ( strand ) self . _index . write ( '{}\t{}\t{}\t{}\n' . format ( strand [ 'channel' ] , strand [ 'read_attrs' ] [ '... | Writes a Strand object to the stream . |
34,993 | def close ( self ) : if self . _is_open : self . mode = None if self . handle : self . handle . close ( ) self . handle = None self . filename = None self . _is_open = False self . status = None | Closes the object . |
34,994 | def add_chain ( self , group_name , component_map ) : self . assert_writeable ( ) for component , path in component_map . items ( ) : if not path . startswith ( 'Analyses/' ) : path = 'Analyses/{}' . format ( path ) component_map [ component ] = path self . add_analysis_attributes ( group_name , component_map ) | Adds the component chain to group_name in the fast5 . These are added as attributes to the group . |
34,995 | def add_read ( self , read_number , read_id , start_time , duration , mux , median_before ) : self . assert_writeable ( ) read_info = ReadInfo ( read_number , read_id , start_time , duration , mux = mux , median_before = median_before ) self . status . read_info . append ( read_info ) n = len ( self . status . read_inf... | Add a new read to the file . |
34,996 | def set_summary_data ( self , group_name , section_name , data ) : self . assert_writeable ( ) group = 'Analyses/{}/Summary/{}' . format ( group_name , section_name ) self . _add_group ( group , data ) | Set the summary data for an analysis group . |
34,997 | def get_analysis_config ( self , group_name ) : self . assert_open ( ) group = 'Analyses/{}/Configuration' . format ( group_name ) config = None if group in self . handle : config = self . _parse_attribute_tree ( group ) return config | Gets any config data saved for the analysis . |
34,998 | def read_summary_data ( fname , component ) : summary = { } with Fast5File ( fname , mode = 'r' ) as fh : summary [ 'tracking_id' ] = fh . get_tracking_id ( ) summary [ 'channel_id' ] = fh . get_channel_info ( ) read_info = fh . status . read_info read_summary = [ ] for read in read_info : read_summary . append ( { 're... | Read summary data suitable to encode as a json packet . |
34,999 | def get_conn_info ( self ) : return session . ConnectionInfo ( self . request . remote_ip , self . request . cookies , self . request . arguments , self . request . headers , self . request . path ) | Return ConnectionInfo object from current transport |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.