idx
int64
0
252k
question
stringlengths
48
5.28k
target
stringlengths
5
1.23k
246,500
def register_graphql_handlers ( app : "Application" , engine_sdl : str = None , engine_schema_name : str = "default" , executor_context : dict = None , executor_http_endpoint : str = "/graphql" , executor_http_methods : List [ str ] = None , engine : Engine = None , subscription_ws_endpoint : Optional [ str ] = None , ...
Register a Tartiflette Engine to an app
246,501
async def on_shutdown ( app ) : for method in app . get ( "close_methods" , [ ] ) : logger . debug ( "Calling < %s >" , method ) if asyncio . iscoroutinefunction ( method ) : await method ( ) else : method ( )
app SHUTDOWN event handler
246,502
def _load_from_file ( path ) : config = [ ] try : with open ( path , 'r' ) as config_file : config = yaml . load ( config_file ) [ 'normalizations' ] except EnvironmentError as e : raise ConfigError ( 'Problem while loading file: %s' % e . args [ 1 ] if len ( e . args ) > 1 else e ) except ( TypeError , KeyError ) as e...
Load a config file from the given path .
246,503
def _parse_normalization ( normalization ) : parsed_normalization = None if isinstance ( normalization , dict ) : if len ( normalization . keys ( ) ) == 1 : items = list ( normalization . items ( ) ) [ 0 ] if len ( items ) == 2 : if items [ 1 ] and isinstance ( items [ 1 ] , dict ) : parsed_normalization = items else :...
Parse a normalization item .
246,504
def _parse_normalizations ( self , normalizations ) : parsed_normalizations = [ ] if isinstance ( normalizations , list ) : for item in normalizations : normalization = self . _parse_normalization ( item ) if normalization : parsed_normalizations . append ( normalization ) else : raise ConfigError ( 'List expected. Fou...
Returns a list of parsed normalizations .
246,505
def initialize_logger ( debug ) : level = logging . DEBUG if debug else logging . INFO logger = logging . getLogger ( 'cucco' ) logger . setLevel ( level ) formatter = logging . Formatter ( '%(asctime)s %(levelname).1s %(message)s' ) console_handler = logging . StreamHandler ( ) console_handler . setLevel ( level ) con...
Set up logger to be used by the library .
246,506
def batch ( ctx , path , recursive , watch ) : batch = Batch ( ctx . obj [ 'config' ] , ctx . obj [ 'cucco' ] ) if os . path . exists ( path ) : if watch : batch . watch ( path , recursive ) elif os . path . isfile ( path ) : batch . process_file ( path ) else : batch . process_files ( path , recursive ) else : click ....
Normalize files in a path .
246,507
def normalize ( ctx , text ) : if text : click . echo ( ctx . obj [ 'cucco' ] . normalize ( text ) ) else : for line in sys . stdin : click . echo ( ctx . obj [ 'cucco' ] . normalize ( line ) )
Normalize text or piped input .
246,508
def cli ( ctx , config , debug , language , verbose ) : ctx . obj = { } try : ctx . obj [ 'config' ] = Config ( normalizations = config , language = language , debug = debug , verbose = verbose ) except ConfigError as e : click . echo ( e . message ) sys . exit ( - 1 ) ctx . obj [ 'cucco' ] = Cucco ( ctx . obj [ 'confi...
Cucco allows to apply normalizations to a given text or file . This normalizations include among others removal of accent marks stop words an extra white spaces replacement of punctuation symbols emails emojis etc .
246,509
def files_generator ( path , recursive ) : if recursive : for ( path , _ , files ) in os . walk ( path ) : for file in files : if not file . endswith ( BATCH_EXTENSION ) : yield ( path , file ) else : for file in os . listdir ( path ) : if ( os . path . isfile ( os . path . join ( path , file ) ) and not file . endswit...
Yield files found in a given path .
246,510
def process_file ( self , path ) : if self . _config . verbose : self . _logger . info ( 'Processing file "%s"' , path ) output_path = '%s%s' % ( path , BATCH_EXTENSION ) with open ( output_path , 'w' ) as file : for line in lines_generator ( path ) : file . write ( '%s\n' % self . _cucco . normalize ( line . encode ( ...
Process a file applying normalizations .
246,511
def process_files ( self , path , recursive = False ) : self . _logger . info ( 'Processing files in "%s"' , path ) for ( path , file ) in files_generator ( path , recursive ) : if not file . endswith ( BATCH_EXTENSION ) : self . process_file ( os . path . join ( path , file ) )
Apply normalizations over all files in the given directory .
246,512
def stop_watching ( self ) : self . _watch = False if self . _observer : self . _logger . info ( 'Stopping watcher' ) self . _observer . stop ( ) self . _logger . info ( 'Watcher stopped' )
Stop watching for files .
246,513
def watch ( self , path , recursive = False ) : self . _logger . info ( 'Initializing watcher for path "%s"' , path ) handler = FileHandler ( self ) self . _observer = Observer ( ) self . _observer . schedule ( handler , path , recursive ) self . _logger . info ( 'Starting watcher' ) self . _observer . start ( ) self ....
Watch for files in a directory and apply normalizations .
246,514
def _process_event ( self , event ) : if ( not event . is_directory and not event . src_path . endswith ( BATCH_EXTENSION ) ) : self . _logger . info ( 'Detected file change: %s' , event . src_path ) self . _batch . process_file ( event . src_path )
Process received events .
246,515
def on_created ( self , event ) : self . _logger . debug ( 'Detected create event on watched path: %s' , event . src_path ) self . _process_event ( event )
Function called everytime a new file is created .
246,516
def on_modified ( self , event ) : self . _logger . debug ( 'Detected modify event on watched path: %s' , event . src_path ) self . _process_event ( event )
Function called everytime a new file is modified .
246,517
def _parse_normalizations ( normalizations ) : str_type = str if sys . version_info [ 0 ] > 2 else ( str , unicode ) for normalization in normalizations : yield ( normalization , { } ) if isinstance ( normalization , str_type ) else normalization
Parse and yield normalizations .
246,518
def _parse_stop_words_file ( self , path ) : language = None loaded = False if os . path . isfile ( path ) : self . _logger . debug ( 'Loading stop words in %s' , path ) language = path . split ( '-' ) [ - 1 ] if not language in self . __stop_words : self . __stop_words [ language ] = set ( ) with codecs . open ( path ...
Load stop words from the given path .
246,519
def normalize ( self , text , normalizations = None ) : for normalization , kwargs in self . _parse_normalizations ( normalizations or self . _config . normalizations ) : try : text = getattr ( self , normalization ) ( text , ** kwargs ) except AttributeError as e : self . _logger . debug ( 'Invalid normalization: %s' ...
Normalize a given text applying all normalizations .
246,520
def remove_accent_marks ( text , excluded = None ) : if excluded is None : excluded = set ( ) return unicodedata . normalize ( 'NFKC' , '' . join ( c for c in unicodedata . normalize ( 'NFKD' , text ) if unicodedata . category ( c ) != 'Mn' or c in excluded ) )
Remove accent marks from input text .
246,521
def replace_characters ( self , text , characters , replacement = '' ) : if not characters : return text characters = '' . join ( sorted ( characters ) ) if characters in self . _characters_regexes : characters_regex = self . _characters_regexes [ characters ] else : characters_regex = re . compile ( "[%s]" % re . esca...
Remove characters from text .
246,522
def replace_punctuation ( self , text , excluded = None , replacement = '' ) : if excluded is None : excluded = set ( ) elif not isinstance ( excluded , set ) : excluded = set ( excluded ) punct = '' . join ( self . __punctuation . difference ( excluded ) ) return self . replace_characters ( text , characters = punct ,...
Replace punctuation symbols in text .
246,523
def replace_symbols ( text , form = 'NFKD' , excluded = None , replacement = '' ) : if excluded is None : excluded = set ( ) categories = set ( [ 'Mn' , 'Sc' , 'Sk' , 'Sm' , 'So' ] ) return '' . join ( c if unicodedata . category ( c ) not in categories or c in excluded else replacement for c in unicodedata . normalize...
Replace symbols in text .
246,524
def get_idb_graph ( ) : digraph = nx . DiGraph ( ) for function in functions ( ) : for xref in itertools . chain ( function . xrefs_from , function . xrefs_to ) : frm = _try_get_function_start ( xref . frm ) to = _try_get_function_start ( xref . to ) digraph . add_edge ( frm , to ) return digraph
Export IDB to a NetworkX graph .
246,525
def name ( self ) : return self . TYPES . get ( self . _type , self . TYPES [ idaapi . o_idpspec0 ] )
Name of the xref type .
246,526
def reg ( self ) : if self . type . is_displ or self . type . is_phrase : size = core . get_native_size ( ) return base . get_register_name ( self . reg_id , size ) if self . type . is_reg : return base . get_register_name ( self . reg_id , self . size ) else : raise exceptions . SarkOperandWithoutReg ( "Operand does n...
Name of the register used in the operand .
246,527
def has_reg ( self , reg_name ) : return any ( operand . has_reg ( reg_name ) for operand in self . operands )
Check if a register is used in the instruction .
246,528
def regs ( self ) : regs = set ( ) for operand in self . operands : if not operand . type . has_reg : continue regs . update ( operand . regs ) return regs
Names of all registers used by the instruction .
246,529
def _pad ( self , text ) : top_bottom = ( "\n" * self . _padding ) + " " right_left = " " * self . _padding * self . PAD_WIDTH return top_bottom + right_left + text + right_left + top_bottom
Pad the text .
246,530
def _make_unique_title ( self , title ) : unique_title = title for counter in itertools . count ( ) : unique_title = "{}-{}" . format ( title , counter ) if not idaapi . find_tform ( unique_title ) : break return unique_title
Make the title unique .
246,531
def _get_handler ( self , node_id ) : handler = self . _get_attrs ( node_id ) . get ( self . HANDLER , self . _default_handler ) if not isinstance ( handler , BasicNodeHandler ) : idaapi . msg ( ( "Invalid handler for node {}: {}. All handlers must inherit from" "`BasicNodeHandler`." ) . format ( node_id , handler ) ) ...
Get the handler of a given node .
246,532
def _OnNodeInfo ( self , node_id ) : handler , value , attrs = self . _get_handling_triplet ( node_id ) frame_color = handler . on_frame_color ( value , attrs ) node_info = idaapi . node_info_t ( ) if frame_color is not None : node_info . frame_color = frame_color flags = node_info . get_flags_for_valid ( ) self . SetN...
Sets the node info based on its attributes .
246,533
def get_string ( ea ) : string_type = idc . GetStringType ( idaapi . get_item_head ( ea ) ) if string_type is None : raise exceptions . SarkNoString ( "No string at 0x{:08X}" . format ( ea ) ) string = idc . GetString ( ea , strtype = string_type ) if not string : raise exceptions . SarkNoString ( "No string at 0x{:08X...
Read the string at the given ea .
246,534
def copy_current_file_offset ( ) : start , end = sark . get_selection ( ) try : file_offset = sark . core . get_fileregion_offset ( start ) clipboard . copy ( "0x{:08X}" . format ( file_offset ) ) except sark . exceptions . NoFileOffset : message ( "The current address cannot be mapped to a valid offset of the input fi...
Get the file - offset mapped to the current address .
246,535
def fix_addresses ( start = None , end = None ) : if start in ( None , idaapi . BADADDR ) : start = idaapi . cvar . inf . minEA if end in ( None , idaapi . BADADDR ) : end = idaapi . cvar . inf . maxEA return start , end
Set missing addresses to start and end of IDB .
246,536
def set_name ( address , name , anyway = False ) : success = idaapi . set_name ( address , name , idaapi . SN_NOWARN | idaapi . SN_NOCHECK ) if success : return if anyway : success = idaapi . do_name_anyway ( address , name ) if success : return raise exceptions . SarkSetNameFailed ( "Failed renaming 0x{:08X} to {!r}."...
Set the name of an address .
246,537
def is_same_function ( ea1 , ea2 ) : func1 = idaapi . get_func ( ea1 ) func2 = idaapi . get_func ( ea2 ) if any ( func is None for func in ( func1 , func2 ) ) : return False return func1 . startEA == func2 . startEA
Are both addresses in the same function?
246,538
def get_nx_graph ( ea ) : nx_graph = networkx . DiGraph ( ) func = idaapi . get_func ( ea ) flowchart = FlowChart ( func ) for block in flowchart : nx_graph . add_node ( block . startEA ) for pred in block . preds ( ) : nx_graph . add_edge ( pred . startEA , block . startEA ) for succ in block . succs ( ) : nx_graph . ...
Convert an IDA flowchart to a NetworkX graph .
246,539
def codeblocks ( start = None , end = None , full = True ) : if full : for function in functions ( start , end ) : fc = FlowChart ( f = function . func_t ) for block in fc : yield block else : start , end = fix_addresses ( start , end ) for code_block in FlowChart ( bounds = ( start , end ) ) : yield code_block
Get all CodeBlock s in a given range .
246,540
def struct_member_error ( err , sid , name , offset , size ) : exception , msg = STRUCT_ERROR_MAP [ err ] struct_name = idc . GetStrucName ( sid ) return exception ( ( 'AddStructMember(struct="{}", member="{}", offset={}, size={}) ' 'failed: {}' ) . format ( struct_name , name , offset , size , msg ) )
Create and format a struct member exception .
246,541
def create_struct ( name ) : sid = idc . GetStrucIdByName ( name ) if sid != idaapi . BADADDR : raise exceptions . SarkStructAlreadyExists ( "A struct names {!r} already exists." . format ( name ) ) sid = idc . AddStrucEx ( - 1 , name , 0 ) if sid == idaapi . BADADDR : raise exceptions . SarkStructCreationFailed ( "Str...
Create a structure .
246,542
def get_struct ( name ) : sid = idc . GetStrucIdByName ( name ) if sid == idaapi . BADADDR : raise exceptions . SarkStructNotFound ( ) return sid
Get a struct by it s name .
246,543
def get_common_register ( start , end ) : registers = defaultdict ( int ) for line in lines ( start , end ) : insn = line . insn for operand in insn . operands : if not operand . type . has_phrase : continue if not operand . base : continue register_name = operand . base registers [ register_name ] += 1 return max ( re...
Get the register most commonly used in accessing structs .
246,544
def _enum_member_error ( err , eid , name , value , bitmask ) : exception , msg = ENUM_ERROR_MAP [ err ] enum_name = idaapi . get_enum_name ( eid ) return exception ( ( 'add_enum_member(enum="{}", member="{}", value={}, bitmask=0x{:08X}) ' 'failed: {}' ) . format ( enum_name , name , value , bitmask , msg ) )
Format enum member error .
246,545
def _get_enum ( name ) : eid = idaapi . get_enum ( name ) if eid == idaapi . BADADDR : raise exceptions . EnumNotFound ( 'Enum "{}" does not exist.' . format ( name ) ) return eid
Get an existing enum ID
246,546
def add_enum ( name = None , index = None , flags = idaapi . hexflag ( ) , bitfield = False ) : if name is not None : with ignored ( exceptions . EnumNotFound ) : _get_enum ( name ) raise exceptions . EnumAlreadyExists ( ) if index is None or index < 0 : index = idaapi . get_enum_qty ( ) eid = idaapi . add_enum ( index...
Create a new enum .
246,547
def _add_enum_member ( enum , name , value , bitmask = DEFMASK ) : error = idaapi . add_enum_member ( enum , name , value , bitmask ) if error : raise _enum_member_error ( error , enum , name , value , bitmask )
Add an enum member .
246,548
def _iter_bitmasks ( eid ) : bitmask = idaapi . get_first_bmask ( eid ) yield bitmask while bitmask != DEFMASK : bitmask = idaapi . get_next_bmask ( eid , bitmask ) yield bitmask
Iterate all bitmasks in a given enum .
246,549
def _iter_enum_member_values ( eid , bitmask ) : value = idaapi . get_first_enum_member ( eid , bitmask ) yield value while value != DEFMASK : value = idaapi . get_next_enum_member ( eid , value , bitmask ) yield value
Iterate member values with given bitmask inside the enum
246,550
def _iter_serial_enum_member ( eid , value , bitmask ) : cid , serial = idaapi . get_first_serial_enum_member ( eid , value , bitmask ) while cid != idaapi . BADNODE : yield cid , serial cid , serial = idaapi . get_next_serial_enum_member ( cid , serial )
Iterate serial and CID of enum members with given value and bitmask .
246,551
def _iter_enum_constant_ids ( eid ) : for bitmask in _iter_bitmasks ( eid ) : for value in _iter_enum_member_values ( eid , bitmask ) : for cid , serial in _iter_serial_enum_member ( eid , value , bitmask ) : yield cid
Iterate the constant IDs of all members in the given enum
246,552
def add ( self , name , value , bitmask = DEFMASK ) : _add_enum_member ( self . _eid , name , value , bitmask )
Add an enum member
246,553
def remove ( self , name ) : member = self [ name ] serial = member . serial value = member . value bmask = member . bmask success = idaapi . del_enum_member ( self . _eid , value , serial , bmask ) if not success : raise exceptions . CantDeleteEnumMember ( "Can't delete enum member {!r}." . format ( name ) )
Remove an enum member by name
246,554
def name ( self , name ) : success = idaapi . set_enum_name ( self . eid , name ) if not success : raise exceptions . CantRenameEnum ( "Cant rename enum {!r} to {!r}." . format ( self . name , name ) )
Set the enum name .
246,555
def name ( self , name ) : success = idaapi . set_enum_member_name ( self . cid , name ) if not success : raise exceptions . CantRenameEnumMember ( "Failed renaming {!r} to {!r}. Does the name exist somewhere else?" . format ( self . name , name ) )
Set the member name .
246,556
def functions ( start = None , end = None ) : start , end = fix_addresses ( start , end ) for func_t in idautils . Functions ( start , end ) : yield Function ( func_t )
Get all functions in range .
246,557
def xrefs_from ( self ) : for line in self . lines : for xref in line . xrefs_from : if xref . type . is_flow : continue if xref . to in self and xref . iscode : continue yield xref
Xrefs from the function .
246,558
def set_name ( self , name , anyway = False ) : set_name ( self . startEA , name , anyway = anyway )
Set Function Name .
246,559
def color ( self ) : color = idc . GetColor ( self . ea , idc . CIC_FUNC ) if color == 0xFFFFFFFF : return None return color
Function color in IDA View
246,560
def color ( self , color ) : if color is None : color = 0xFFFFFFFF idc . SetColor ( self . ea , idc . CIC_FUNC , color )
Function Color in IDA View .
246,561
def lines ( start = None , end = None , reverse = False , selection = False ) : if selection : start , end = get_selection ( ) else : start , end = fix_addresses ( start , end ) if not reverse : item = idaapi . get_item_head ( start ) while item < end : yield Line ( item ) item += idaapi . get_item_size ( item ) else :...
Iterate lines in range .
246,562
def type ( self ) : properties = { self . is_code : "code" , self . is_data : "data" , self . is_string : "string" , self . is_tail : "tail" , self . is_unknown : "unknown" } for k , v in properties . items ( ) : if k : return v
return the type of the Line
246,563
def color ( self ) : color = idc . GetColor ( self . ea , idc . CIC_ITEM ) if color == 0xFFFFFFFF : return None return color
Line color in IDA View
246,564
def color ( self , color ) : if color is None : color = 0xFFFFFFFF idc . SetColor ( self . ea , idc . CIC_ITEM , color )
Line Color in IDA View .
246,565
def capture_widget ( widget , path = None ) : if use_qt5 : pixmap = widget . grab ( ) else : pixmap = QtGui . QPixmap . grabWidget ( widget ) if path : pixmap . save ( path ) else : image_buffer = QtCore . QBuffer ( ) image_buffer . open ( QtCore . QIODevice . ReadWrite ) pixmap . save ( image_buffer , "PNG" ) return i...
Grab an image of a Qt widget
246,566
def get_widget ( title ) : tform = idaapi . find_tform ( title ) if not tform : raise exceptions . FormNotFound ( "No form titled {!r} found." . format ( title ) ) return form_to_widget ( tform )
Get the Qt widget of the IDA window with the given title .
246,567
def get_window ( ) : tform = idaapi . get_current_tform ( ) if not tform : tform = idaapi . find_tform ( "Output window" ) widget = form_to_widget ( tform ) window = widget . window ( ) return window
Get IDA s top level window .
246,568
def add_menu ( self , name ) : if name in self . _menus : raise exceptions . MenuAlreadyExists ( "Menu name {!r} already exists." . format ( name ) ) menu = self . _menu . addMenu ( name ) self . _menus [ name ] = menu
Add a top - level menu .
246,569
def remove_menu ( self , name ) : if name not in self . _menus : raise exceptions . MenuNotFound ( "Menu {!r} was not found. It might be deleted, or belong to another menu manager." . format ( name ) ) self . _menu . removeAction ( self . _menus [ name ] . menuAction ( ) ) del self . _menus [ name ]
Remove a top - level menu .
246,570
def clear ( self ) : for menu in self . _menus . itervalues ( ) : self . _menu . removeAction ( menu . menuAction ( ) ) self . _menus = { }
Clear all menus created by this manager .
246,571
def get_by_flags ( self , flags ) : for reg in self . _reg_infos : if reg . flags & flags == flags : yield reg
Iterate all register infos matching the given flags .
246,572
def get_single_by_flags ( self , flags ) : regs = list ( self . get_by_flags ( flags ) ) if len ( regs ) != 1 : raise ValueError ( "Flags do not return unique resigter. {!r}" , regs ) return regs [ 0 ]
Get the register info matching the flag . Raises ValueError if more than one are found .
246,573
def segments ( seg_type = None ) : for index in xrange ( idaapi . get_segm_qty ( ) ) : seg = Segment ( index = index ) if ( seg_type is None ) or ( seg . type == seg_type ) : yield Segment ( index = index )
Iterate segments based on type
246,574
def next ( self ) : seg = Segment ( segment_t = idaapi . get_next_seg ( self . ea ) ) if seg . ea <= self . ea : raise exceptions . NoMoreSegments ( "This is the last segment. No segments exist after it." ) return seg
Get the next segment .
246,575
def prev ( self ) : seg = Segment ( segment_t = idaapi . get_prev_seg ( self . ea ) ) if seg . ea >= self . ea : raise exceptions . NoMoreSegments ( "This is the first segment. no segments exist before it." ) return seg
Get the previous segment .
246,576
def get_ecosystem_solver ( ecosystem_name , parser_kwargs = None , fetcher_kwargs = None ) : from . python import PythonSolver if ecosystem_name . lower ( ) == "pypi" : source = Source ( url = "https://pypi.org/simple" , warehouse_api_url = "https://pypi.org/pypi" , warehouse = True ) return PythonSolver ( parser_kwarg...
Get Solver subclass instance for particular ecosystem .
246,577
def check ( self , version ) : def _compare_spec ( spec ) : if len ( spec ) == 1 : spec = ( "=" , spec [ 0 ] ) token = Tokens . operators . index ( spec [ 0 ] ) comparison = compare_version ( version , spec [ 1 ] ) if token in [ Tokens . EQ1 , Tokens . EQ2 ] : return comparison == 0 elif token == Tokens . GT : return c...
Check if version fits into our dependency specification .
246,578
def solve ( self , dependencies , graceful = True , all_versions = False ) : def _compare_version_index_url ( v1 , v2 ) : return compare_version ( v1 [ 0 ] , v2 [ 0 ] ) solved = { } for dep in self . dependency_parser . parse ( dependencies ) : _LOGGER . debug ( "Fetching releases for: {}" . format ( dep ) ) name , rel...
Solve dependencies against upstream repository .
246,579
def pip_compile ( * packages : str ) : result = None packages = "\n" . join ( packages ) with tempfile . TemporaryDirectory ( ) as tmp_dirname , cwd ( tmp_dirname ) : with open ( "requirements.in" , "w" ) as requirements_file : requirements_file . write ( packages ) runner = CliRunner ( ) try : result = runner . invoke...
Run pip - compile to pin down packages also resolve their transitive dependencies .
246,580
def _print_version ( ctx , _ , value ) : if not value or ctx . resilient_parsing : return click . echo ( analyzer_version ) ctx . exit ( )
Print solver version and exit .
246,581
def cli ( ctx = None , verbose = 0 ) : if ctx : ctx . auto_envvar_prefix = "THOTH_SOLVER" if verbose : _LOG . setLevel ( logging . DEBUG ) _LOG . debug ( "Debug mode is on" )
Thoth solver command line interface .
246,582
def pypi ( click_ctx , requirements , index = None , python_version = 3 , exclude_packages = None , output = None , subgraph_check_api = None , no_transitive = True , no_pretty = False , ) : requirements = [ requirement . strip ( ) for requirement in requirements . split ( "\\n" ) if requirement ] if not requirements :...
Manipulate with dependency requirements using PyPI .
246,583
def _create_entry ( entry : dict , source : Source = None ) -> dict : entry [ "package_name" ] = entry [ "package" ] . pop ( "package_name" ) entry [ "package_version" ] = entry [ "package" ] . pop ( "installed_version" ) if source : entry [ "index_url" ] = source . url entry [ "sha256" ] = [ ] for item in source . get...
Filter and normalize the output of pipdeptree entry .
246,584
def _get_environment_details ( python_bin : str ) -> list : cmd = "{} -m pipdeptree --json" . format ( python_bin ) output = run_command ( cmd , is_json = True ) . stdout return [ _create_entry ( entry ) for entry in output ]
Get information about packages in environment where packages get installed .
246,585
def _should_resolve_subgraph ( subgraph_check_api : str , package_name : str , package_version : str , index_url : str ) -> bool : _LOGGER . info ( "Checking if the given dependency subgraph for package %r in version %r from index %r should be resolved" , package_name , package_version , index_url , ) response = reques...
Ask the given subgraph check API if the given package in the given version should be included in the resolution .
246,586
def _install_requirement ( python_bin : str , package : str , version : str = None , index_url : str = None , clean : bool = True ) -> None : previous_version = _pipdeptree ( python_bin , package ) try : cmd = "{} -m pip install --force-reinstall --no-cache-dir --no-deps {}" . format ( python_bin , quote ( package ) ) ...
Install requirements specified using suggested pip binary .
246,587
def _pipdeptree ( python_bin , package_name : str = None , warn : bool = False ) -> typing . Optional [ dict ] : cmd = "{} -m pipdeptree --json" . format ( python_bin ) _LOGGER . debug ( "Obtaining pip dependency tree using: %r" , cmd ) output = run_command ( cmd , is_json = True ) . stdout if not package_name : return...
Get pip dependency tree by executing pipdeptree tool .
246,588
def _get_dependency_specification ( dep_spec : typing . List [ tuple ] ) -> str : return "," . join ( dep_range [ 0 ] + dep_range [ 1 ] for dep_range in dep_spec )
Get string representation of dependency specification as provided by PythonDependencyParser .
246,589
def resolve ( requirements : typing . List [ str ] , index_urls : list = None , python_version : int = 3 , exclude_packages : set = None , transitive : bool = True , subgraph_check_api : str = None , ) -> dict : assert python_version in ( 2 , 3 ) , "Unknown Python version" if subgraph_check_api and not transitive : _LO...
Resolve given requirements for the given Python version .
246,590
def fetch_releases ( self , package_name ) : package_name = self . source . normalize_package_name ( package_name ) releases = self . source . get_package_versions ( package_name ) releases_with_index_url = [ ( item , self . index_url ) for item in releases ] return package_name , releases_with_index_url
Fetch package and index_url for a package_name .
246,591
def parse_python ( spec ) : def _extract_op_version ( spec ) : if spec . operator == "~=" : version = spec . version . split ( "." ) if len ( version ) in { 2 , 3 , 4 } : if len ( version ) in { 3 , 4 } : del version [ - 1 ] version [ - 1 ] = str ( int ( version [ - 1 ] ) + 1 ) else : raise ValueError ( "%r must not be...
Parse PyPI specification of a single dependency .
246,592
def get ( obj ) : if not isinstance ( obj , bytes ) : raise TypeError ( "object type must be bytes" ) info = { "type" : dict ( ) , "extension" : dict ( ) , "mime" : dict ( ) } stream = " " . join ( [ '{:02X}' . format ( byte ) for byte in obj ] ) for element in data : for signature in element [ "signature" ] : offset =...
Determines file format and picks suitable file types extensions and MIME types
246,593
def bottleneck_matching ( I1 , I2 , matchidx , D , labels = [ "dgm1" , "dgm2" ] , ax = None ) : plot_diagrams ( [ I1 , I2 ] , labels = labels , ax = ax ) cp = np . cos ( np . pi / 4 ) sp = np . sin ( np . pi / 4 ) R = np . array ( [ [ cp , - sp ] , [ sp , cp ] ] ) if I1 . size == 0 : I1 = np . array ( [ [ 0 , 0 ] ] ) i...
Visualize bottleneck matching between two diagrams
246,594
def transform ( self , diagrams ) : if len ( diagrams ) == 0 : return np . zeros ( ( self . nx , self . ny ) ) try : singular = not isinstance ( diagrams [ 0 ] [ 0 ] , collections . Iterable ) except IndexError : singular = False if singular : diagrams = [ diagrams ] dgs = [ np . copy ( diagram , np . float64 ) for dia...
Convert diagram or list of diagrams to a persistence image .
246,595
def weighting ( self , landscape = None ) : if landscape is not None : if len ( landscape ) > 0 : maxy = np . max ( landscape [ : , 1 ] ) else : maxy = 1 def linear ( interval ) : d = interval [ 1 ] return ( 1 / maxy ) * d if landscape is not None else d def pw_linear ( interval ) : t = interval [ 1 ] b = maxy / self ....
Define a weighting function for stability results to hold the function must be 0 at y = 0 .
246,596
def show ( self , imgs , ax = None ) : ax = ax or plt . gca ( ) if type ( imgs ) is not list : imgs = [ imgs ] for i , img in enumerate ( imgs ) : ax . imshow ( img , cmap = plt . get_cmap ( "plasma" ) ) ax . axis ( "off" )
Visualize the persistence image
246,597
def resolve_orm_path ( model , orm_path ) : bits = orm_path . split ( '__' ) endpoint_model = reduce ( get_model_at_related_field , [ model ] + bits [ : - 1 ] ) if bits [ - 1 ] == 'pk' : field = endpoint_model . _meta . pk else : field = endpoint_model . _meta . get_field ( bits [ - 1 ] ) return field
Follows the queryset - style query path of orm_path starting from model class . If the path ends up referring to a bad field name django . db . models . fields . FieldDoesNotExist will be raised .
246,598
def get_model_at_related_field ( model , attr ) : field = model . _meta . get_field ( attr ) if hasattr ( field , 'related_model' ) : return field . related_model raise ValueError ( "{model}.{attr} ({klass}) is not a relationship field." . format ( ** { 'model' : model . __name__ , 'attr' : attr , 'klass' : field . __c...
Looks up attr as a field of model and returns the related model class . If attr is not a relationship field ValueError is raised .
246,599
def contains_plural_field ( model , fields ) : source_model = model for orm_path in fields : model = source_model bits = orm_path . lstrip ( '+-' ) . split ( '__' ) for bit in bits [ : - 1 ] : field = model . _meta . get_field ( bit ) if field . many_to_many or field . one_to_many : return True model = get_model_at_rel...
Returns a boolean indicating if fields contains a relationship to multiple items .