idx int64 0 252k | question stringlengths 48 5.28k | target stringlengths 5 1.23k |
|---|---|---|
231,000 | def main ( args = None ) : if args is None : args = sys . argv [ 1 : ] parser = create_parser ( ) args = parser . parse_args ( args ) if args . verbose >= 2 : level = logging . DEBUG elif args . verbose >= 1 : level = logging . INFO else : level = logging . WARNING logging . basicConfig ( level = level ) try : args . c... | Main command - line interface entrypoint . |
231,001 | def create_jlink ( self , args ) : jlink = pylink . JLink ( ) jlink . open ( args . serial_no , args . ip_addr ) if hasattr ( args , 'tif' ) and args . tif is not None : if args . tif . lower ( ) == 'swd' : jlink . set_tif ( pylink . JLinkInterfaces . SWD ) else : jlink . set_tif ( pylink . JLinkInterfaces . JTAG ) if ... | Creates an instance of a J - Link from the given arguments . |
231,002 | def add_common_arguments ( self , parser , has_device = False ) : if has_device : parser . add_argument ( '-t' , '--tif' , required = True , type = str . lower , choices = [ 'jtag' , 'swd' ] , help = 'target interface (JTAG | SWD)' ) parser . add_argument ( '-d' , '--device' , required = True , help = 'specify the targ... | Adds common arguments to the given parser . |
231,003 | def run ( self , args ) : jlink = self . create_jlink ( args ) erased = jlink . erase ( ) print ( 'Bytes Erased: %d' % erased ) | Erases the device connected to the J - Link . |
231,004 | def run ( self , args ) : kwargs = { } kwargs [ 'path' ] = args . file [ 0 ] kwargs [ 'addr' ] = args . addr kwargs [ 'on_progress' ] = pylink . util . flash_progress_callback jlink = self . create_jlink ( args ) _ = jlink . flash_file ( ** kwargs ) print ( 'Flashed device successfully.' ) | Flashes the device connected to the J - Link . |
231,005 | def add_arguments ( self , parser ) : parser . add_argument ( 'name' , nargs = 1 , choices = [ 'kinetis' ] , help = 'name of MCU to unlock' ) return self . add_common_arguments ( parser , True ) | Adds the unlock command arguments to the parser . |
231,006 | def run ( self , args ) : jlink = self . create_jlink ( args ) mcu = args . name [ 0 ] . lower ( ) if pylink . unlock ( jlink , mcu ) : print ( 'Successfully unlocked device!' ) else : print ( 'Failed to unlock device!' ) | Unlocks the target device . |
231,007 | def run ( self , args ) : jlink = self . create_jlink ( args ) if args . list : print ( 'Built-in Licenses: %s' % ', ' . join ( jlink . licenses . split ( ',' ) ) ) print ( 'Custom Licenses: %s' % ', ' . join ( jlink . custom_licenses . split ( ',' ) ) ) elif args . add is not None : if jlink . add_license ( args . add... | Runs the license command . |
231,008 | def add_arguments ( self , parser ) : parser . add_argument ( '-p' , '--product' , action = 'store_true' , help = 'print the production information' ) parser . add_argument ( '-j' , '--jtag' , action = 'store_true' , help = 'print the JTAG pin status' ) return self . add_common_arguments ( parser , False ) | Adds the information commands to the parser . |
231,009 | def run ( self , args ) : jlink = self . create_jlink ( args ) if args . product : print ( 'Product: %s' % jlink . product_name ) manufacturer = 'SEGGER' if jlink . oem is None else jlink . oem print ( 'Manufacturer: %s' % manufacturer ) print ( 'Hardware Version: %s' % jlink . hardware_version ) print ( 'Firmware: %s'... | Runs the information command . |
231,010 | def add_arguments ( self , parser ) : group = parser . add_mutually_exclusive_group ( required = True ) group . add_argument ( '-l' , '--list' , nargs = '?' , type = str . lower , default = '_' , choices = [ 'usb' , 'ip' ] , help = 'list all the connected emulators' ) group . add_argument ( '-s' , '--supported' , nargs... | Adds the arguments for the emulator command . |
231,011 | def run ( self , args ) : jlink = pylink . JLink ( ) if args . test : if jlink . test ( ) : print ( 'Self-test succeeded.' ) else : print ( 'Self-test failed.' ) elif args . list is None or args . list in [ 'usb' , 'ip' ] : host = pylink . JLinkHost . USB_OR_IP if args . list == 'usb' : host = pylink . JLinkHost . USB ... | Runs the emulator command . |
231,012 | def add_arguments ( self , parser ) : group = parser . add_mutually_exclusive_group ( required = True ) group . add_argument ( '-d' , '--downgrade' , action = 'store_true' , help = 'downgrade the J-Link firmware' ) group . add_argument ( '-u' , '--upgrade' , action = 'store_true' , help = 'upgrade the J-Link firmware' ... | Adds the arguments for the firmware command . |
231,013 | def run ( self , args ) : jlink = self . create_jlink ( args ) if args . downgrade : if not jlink . firmware_newer ( ) : print ( 'DLL firmware is not older than J-Link firmware.' ) else : jlink . invalidate_firmware ( ) try : jlink . update_firmware ( ) except pylink . JLinkException as e : jlink = self . create_jlink ... | Runs the firmware command . |
231,014 | def name ( self ) : return ctypes . cast ( self . sName , ctypes . c_char_p ) . value . decode ( ) | Returns the name of the device . |
231,015 | def manufacturer ( self ) : buf = ctypes . cast ( self . sManu , ctypes . c_char_p ) . value return buf . decode ( ) if buf else None | Returns the name of the manufacturer of the device . |
231,016 | def software_breakpoint ( self ) : software_types = [ enums . JLinkBreakpoint . SW_RAM , enums . JLinkBreakpoint . SW_FLASH , enums . JLinkBreakpoint . SW ] return any ( self . Type & stype for stype in software_types ) | Returns whether this is a software breakpoint . |
231,017 | def find_library_windows ( cls ) : dll = cls . get_appropriate_windows_sdk_name ( ) + '.dll' root = 'C:\\' for d in os . listdir ( root ) : dir_path = os . path . join ( root , d ) if d . startswith ( 'Program Files' ) and os . path . isdir ( dir_path ) : dir_path = os . path . join ( dir_path , 'SEGGER' ) if not os . ... | Loads the SEGGER DLL from the windows installation directory . |
231,018 | def find_library_linux ( cls ) : dll = Library . JLINK_SDK_NAME root = os . path . join ( '/' , 'opt' , 'SEGGER' ) for ( directory_name , subdirs , files ) in os . walk ( root ) : fnames = [ ] x86_found = False for f in files : path = os . path . join ( directory_name , f ) if os . path . isfile ( path ) and f . starts... | Loads the SEGGER DLL from the root directory . |
231,019 | def find_library_darwin ( cls ) : dll = Library . JLINK_SDK_NAME root = os . path . join ( '/' , 'Applications' , 'SEGGER' ) if not os . path . isdir ( root ) : return for d in os . listdir ( root ) : dir_path = os . path . join ( root , d ) if os . path . isdir ( dir_path ) and d . startswith ( 'JLink' ) : files = lis... | Loads the SEGGER DLL from the installed applications . |
231,020 | def load_default ( self ) : path = ctypes_util . find_library ( self . _sdk ) if path is None : if self . _windows or self . _cygwin : path = next ( self . find_library_windows ( ) , None ) elif sys . platform . startswith ( 'linux' ) : path = next ( self . find_library_linux ( ) , None ) elif sys . platform . startswi... | Loads the default J - Link SDK DLL . |
231,021 | def load ( self , path = None ) : self . unload ( ) self . _path = path or self . _path if self . _windows or self . _cygwin : suffix = '.dll' elif sys . platform . startswith ( 'darwin' ) : suffix = '.dylib' else : suffix = '.so' tf = tempfile . NamedTemporaryFile ( delete = False , suffix = suffix ) with open ( tf . ... | Loads the specified DLL if any otherwise re - loads the current DLL . |
231,022 | def unload ( self ) : unloaded = False if self . _lib is not None : if self . _winlib is not None : ctypes . windll . kernel32 . FreeLibrary . argtypes = ( ctypes . c_void_p , ) ctypes . windll . kernel32 . FreeLibrary ( self . _lib . _handle ) ctypes . windll . kernel32 . FreeLibrary ( self . _winlib . _handle ) self ... | Unloads the library s DLL if it has been loaded . |
231,023 | def _open ( filename = None , mode = 'r' ) : if not filename or filename == '-' : if not mode or 'r' in mode : file = sys . stdin elif 'w' in mode : file = sys . stdout else : raise ValueError ( 'Invalid mode for file: {}' . format ( mode ) ) else : file = open ( filename , mode ) try : yield file finally : if file not... | Open a file or sys . stdout depending on the provided filename . |
231,024 | def get_pkg_names ( pkgs ) : result = set ( ) with open ( join ( "mapping" ) , "r" ) as f : data = dict ( x . strip ( ) . split ( ":" ) for x in f ) for pkg in pkgs : result . add ( data . get ( pkg , pkg ) ) return sorted ( result , key = lambda s : s . lower ( ) ) | Get PyPI package names from a list of imports . |
231,025 | def charmap ( prefixed_name ) : prefix , name = prefixed_name . split ( '.' ) return _instance ( ) . charmap [ prefix ] [ name ] | Return the character map used for a given font . |
231,026 | def set_global_defaults ( ** kwargs ) : valid_options = [ 'active' , 'selected' , 'disabled' , 'on' , 'off' , 'on_active' , 'on_selected' , 'on_disabled' , 'off_active' , 'off_selected' , 'off_disabled' , 'color' , 'color_on' , 'color_off' , 'color_active' , 'color_selected' , 'color_disabled' , 'color_on_selected' , '... | Set global defaults for the options passed to the icon painter . |
231,027 | def paint ( self , iconic , painter , rect , mode , state , options ) : for opt in options : self . _paint_icon ( iconic , painter , rect , mode , state , opt ) | Main paint method . |
231,028 | def _paint_icon ( self , iconic , painter , rect , mode , state , options ) : painter . save ( ) color = options [ 'color' ] char = options [ 'char' ] color_options = { QIcon . On : { QIcon . Normal : ( options [ 'color_on' ] , options [ 'on' ] ) , QIcon . Disabled : ( options [ 'color_on_disabled' ] , options [ 'on_di... | Paint a single icon . |
231,029 | def icon ( self , * names , ** kwargs ) : cache_key = '{}{}' . format ( names , kwargs ) if cache_key not in self . icon_cache : options_list = kwargs . pop ( 'options' , [ { } ] * len ( names ) ) general_options = kwargs if len ( options_list ) != len ( names ) : error = '"options" must be a list of size {0}' . format... | Return a QIcon object corresponding to the provided icon name . |
231,030 | def font ( self , prefix , size ) : font = QFont ( self . fontname [ prefix ] ) font . setPixelSize ( size ) if prefix [ - 1 ] == 's' : font . setStyleName ( 'Solid' ) return font | Return a QFont corresponding to the given prefix and size . |
231,031 | def _custom_icon ( self , name , ** kwargs ) : options = dict ( _default_options , ** kwargs ) if name in self . painters : painter = self . painters [ name ] return self . _icon_by_painter ( painter , options ) else : return QIcon ( ) | Return the custom icon corresponding to the given name . |
231,032 | def _icon_by_painter ( self , painter , options ) : engine = CharIconEngine ( self , painter , options ) return QIcon ( engine ) | Return the icon corresponding to the given painter . |
231,033 | def finalize_options ( self ) : assert bool ( self . fa_version ) , 'FA version is mandatory for this command.' if self . zip_path : assert os . path . exists ( self . zip_path ) , ( 'Local zipfile does not exist: %s' % self . zip_path ) | Validate the command options . |
231,034 | def __print ( self , msg ) : self . announce ( msg , level = distutils . log . INFO ) | Shortcut for printing with the distutils logger . |
231,035 | def __zip_file ( self ) : if self . zip_path : self . __print ( 'Opening local zipfile: %s' % self . zip_path ) return open ( self . zip_path , 'rb' ) url = self . __release_url self . __print ( 'Downloading from URL: %s' % url ) response = urlopen ( url ) return io . BytesIO ( response . read ( ) ) | Get a file object of the FA zip file . |
231,036 | def __zipped_files_data ( self ) : files = { } with zipfile . ZipFile ( self . __zip_file ) as thezip : for zipinfo in thezip . infolist ( ) : if zipinfo . filename . endswith ( 'metadata/icons.json' ) : with thezip . open ( zipinfo ) as compressed_file : files [ 'icons.json' ] = compressed_file . read ( ) elif zipinfo... | Get a dict of all files of interest from the FA release zipfile . |
231,037 | def from_string ( proto_str ) : _ , proto_file = tempfile . mkstemp ( suffix = '.proto' ) with open ( proto_file , 'w+' ) as proto_f : proto_f . write ( proto_str ) return from_file ( proto_file ) | Produce a Protobuf module from a string description . Return the module if successfully compiled otherwise raise a BadProtobuf exception . |
231,038 | def _load_module ( path ) : 'Helper to load a Python file at path and return as a module' module_name = os . path . splitext ( os . path . basename ( path ) ) [ 0 ] module = None if sys . version_info . minor < 5 : loader = importlib . machinery . SourceFileLoader ( module_name , path ) module = loader . load_module ( ... | Helper to load a Python file at path and return as a module |
231,039 | def _compile_proto ( full_path , dest ) : 'Helper to compile protobuf files' proto_path = os . path . dirname ( full_path ) protoc_args = [ find_protoc ( ) , '--python_out={}' . format ( dest ) , '--proto_path={}' . format ( proto_path ) , full_path ] proc = subprocess . Popen ( protoc_args , stdout = subprocess . PIPE... | Helper to compile protobuf files |
231,040 | def from_file ( proto_file ) : if not proto_file . endswith ( '.proto' ) : raise BadProtobuf ( ) dest = tempfile . mkdtemp ( ) full_path = os . path . abspath ( proto_file ) _compile_proto ( full_path , dest ) filename = os . path . split ( full_path ) [ - 1 ] name = re . search ( r'^(.*)\.proto$' , filename ) . group ... | Take a filename |protoc_file| compile it via the Protobuf compiler and import the module . Return the module if successfully compiled otherwise raise either a ProtocNotFound or BadProtobuf exception . |
231,041 | def types_from_module ( pb_module ) : types = pb_module . DESCRIPTOR . message_types_by_name return [ getattr ( pb_module , name ) for name in types ] | Return protobuf class types from an imported generated module . |
231,042 | def _resolve_child ( self , path ) : 'Return a member generator by a dot-delimited path' obj = self for component in path . split ( '.' ) : ptr = obj if not isinstance ( ptr , Permuter ) : raise self . MessageNotFound ( "Bad element path [wrong type]" ) found_gen = ( _ for _ in ptr . _generators if _ . name ( ) == comp... | Return a member generator by a dot - delimited path |
231,043 | def make_dependent ( self , source , target , action ) : if not self . _generators : return src_permuter , src = self . _resolve_child ( source ) dest = self . _resolve_child ( target ) [ 1 ] container = src_permuter . _generators idx = container . index ( src ) container [ idx ] = DependentValueGenerator ( src . name ... | Create a dependency between path source and path target via the callable action . |
231,044 | def get ( self ) : 'Retrieve the most recent value generated' return tuple ( [ ( x . name ( ) , x . get ( ) ) for x in self . _generators ] ) | Retrieve the most recent value generated |
231,045 | def _fuzzdb_integers ( limit = 0 ) : 'Helper to grab some integers from fuzzdb' path = os . path . join ( BASE_PATH , 'integer-overflow/integer-overflows.txt' ) stream = _open_fuzzdb_file ( path ) for line in _limit_helper ( stream , limit ) : yield int ( line . decode ( 'utf-8' ) , 0 ) | Helper to grab some integers from fuzzdb |
231,046 | def _fuzzdb_get_strings ( max_len = 0 ) : 'Helper to get all the strings from fuzzdb' ignored = [ 'integer-overflow' ] for subdir in pkg_resources . resource_listdir ( 'protofuzz' , BASE_PATH ) : if subdir in ignored : continue path = '{}/{}' . format ( BASE_PATH , subdir ) listing = pkg_resources . resource_listdir ( ... | Helper to get all the strings from fuzzdb |
231,047 | def get_integers ( bitwidth , unsigned , limit = 0 ) : if unsigned : start , stop = 0 , ( ( 1 << bitwidth ) - 1 ) else : start , stop = ( - ( 1 << bitwidth - 1 ) ) , ( 1 << ( bitwidth - 1 ) - 1 ) for num in _fuzzdb_integers ( limit ) : if num >= start and num <= stop : yield num | Get integers from fuzzdb database |
231,048 | def get_floats ( bitwidth , limit = 0 ) : assert bitwidth in ( 32 , 64 , 80 ) values = [ 0.0 , - 1.0 , 1.0 , - 1231231231231.0123 , 123123123123123.123 ] for val in _limit_helper ( values , limit ) : yield val | Return a number of interesting floating point values |
231,049 | def _int_generator ( descriptor , bitwidth , unsigned ) : 'Helper to create a basic integer value generator' vals = list ( values . get_integers ( bitwidth , unsigned ) ) return gen . IterValueGenerator ( descriptor . name , vals ) | Helper to create a basic integer value generator |
231,050 | def _string_generator ( descriptor , max_length = 0 , limit = 0 ) : 'Helper to create a string generator' vals = list ( values . get_strings ( max_length , limit ) ) return gen . IterValueGenerator ( descriptor . name , vals ) | Helper to create a string generator |
231,051 | def _float_generator ( descriptor , bitwidth ) : 'Helper to create floating point values' return gen . IterValueGenerator ( descriptor . name , values . get_floats ( bitwidth ) ) | Helper to create floating point values |
231,052 | def _enum_generator ( descriptor ) : 'Helper to create protobuf enums' vals = descriptor . enum_type . values_by_number . keys ( ) return gen . IterValueGenerator ( descriptor . name , vals ) | Helper to create protobuf enums |
231,053 | def _prototype_to_generator ( descriptor , cls ) : 'Helper to map a descriptor to a protofuzz generator' _fd = D . FieldDescriptor generator = None ints32 = [ _fd . TYPE_INT32 , _fd . TYPE_UINT32 , _fd . TYPE_FIXED32 , _fd . TYPE_SFIXED32 , _fd . TYPE_SINT32 ] ints64 = [ _fd . TYPE_INT64 , _fd . TYPE_UINT64 , _fd . TYP... | Helper to map a descriptor to a protofuzz generator |
231,054 | def descriptor_to_generator ( cls_descriptor , cls , limit = 0 ) : 'Convert a protobuf descriptor to a protofuzz generator for same type' generators = [ ] for descriptor in cls_descriptor . fields_by_name . values ( ) : generator = _prototype_to_generator ( descriptor , cls ) if limit != 0 : generator . set_limit ( lim... | Convert a protobuf descriptor to a protofuzz generator for same type |
231,055 | def _assign_to_field ( obj , name , val ) : 'Helper to assign an arbitrary value to a protobuf field' target = getattr ( obj , name ) if isinstance ( target , containers . RepeatedScalarFieldContainer ) : target . append ( val ) elif isinstance ( target , containers . RepeatedCompositeFieldContainer ) : target = target... | Helper to assign an arbitrary value to a protobuf field |
231,056 | def _fields_to_object ( descriptor , fields ) : 'Helper to convert a descriptor and a set of fields to a Protobuf instance' obj = descriptor . _concrete_class ( ) for name , value in fields : if isinstance ( value , tuple ) : subtype = descriptor . fields_by_name [ name ] . message_type value = _fields_to_object ( subt... | Helper to convert a descriptor and a set of fields to a Protobuf instance |
231,057 | def _module_to_generators ( pb_module ) : if not pb_module : return None message_types = pb_module . DESCRIPTOR . message_types_by_name return { k : ProtobufGenerator ( v ) for k , v in message_types . items ( ) } | Convert a protobuf module to a dict of generators . |
231,058 | def add_dependency ( self , source , target , action ) : self . _dependencies . append ( ( source , target , action ) ) | Create a dependency between fields source and target via callable action . |
231,059 | def print_report ( self ) : report = compare_report_print ( self . sorted , self . scores , self . best_name ) print ( report ) | Print Compare report . |
231,060 | def F_calc ( TP , FP , FN , beta ) : try : result = ( ( 1 + ( beta ) ** 2 ) * TP ) / ( ( 1 + ( beta ) ** 2 ) * TP + FP + ( beta ** 2 ) * FN ) return result except ZeroDivisionError : return "None" | Calculate F - score . |
231,061 | def G_calc ( item1 , item2 ) : try : result = math . sqrt ( item1 * item2 ) return result except Exception : return "None" | Calculate G - measure & G - mean . |
231,062 | def RACC_calc ( TOP , P , POP ) : try : result = ( TOP * P ) / ( ( POP ) ** 2 ) return result except Exception : return "None" | Calculate random accuracy . |
231,063 | def CEN_misclassification_calc ( table , TOP , P , i , j , subject_class , modified = False ) : try : result = TOP + P if modified : result -= table [ subject_class ] [ subject_class ] result = table [ i ] [ j ] / result return result except Exception : return "None" | Calculate misclassification probability of classifying . |
231,064 | def html_init ( name ) : result = "" result += "<html>\n" result += "<head>\n" result += "<title>" + str ( name ) + "</title>\n" result += "</head>\n" result += "<body>\n" result += '<h1 style="border-bottom:1px solid ' 'black;text-align:center;">PyCM Report</h1>' return result | Return HTML report file first lines . |
231,065 | def html_dataset_type ( is_binary , is_imbalanced ) : result = "<h2>Dataset Type : </h2>\n" balance_type = "Balanced" class_type = "Binary Classification" if is_imbalanced : balance_type = "Imbalanced" if not is_binary : class_type = "Multi-Class Classification" result += "<ul>\n\n<li>{0}</li>\n\n<li>{1}</li>\n</ul>\n"... | Return HTML report file dataset type . |
231,066 | def color_check ( color ) : if isinstance ( color , ( tuple , list ) ) : if all ( map ( lambda x : isinstance ( x , int ) , color ) ) : if all ( map ( lambda x : x < 256 , color ) ) : return list ( color ) if isinstance ( color , str ) : color_lower = color . lower ( ) if color_lower in TABLE_COLOR . keys ( ) : return ... | Check input color format . |
231,067 | def html_table_color ( row , item , color = ( 0 , 0 , 0 ) ) : result = [ 0 , 0 , 0 ] color_list = color_check ( color ) max_color = max ( color_list ) back_color_index = 255 - int ( ( item / ( sum ( list ( row . values ( ) ) ) + 1 ) ) * 255 ) for i in range ( 3 ) : result [ i ] = back_color_index - ( max_color - color_... | Return background color of each cell of table . |
231,068 | def html_table ( classes , table , rgb_color , normalize = False ) : result = "" result += "<h2>Confusion Matrix " if normalize : result += "(Normalized)" result += ": </h2>\n" result += '<table>\n' result += '<tr align="center">' + "\n" result += '<td>Actual</td>\n' result += '<td>Predict\n' table_size = str ( ( len ... | Return HTML report file confusion matrix . |
231,069 | def html_overall_stat ( overall_stat , digit = 5 , overall_param = None , recommended_list = ( ) ) : result = "" result += "<h2>Overall Statistics : </h2>\n" result += '<table style="border:1px solid black;border-collapse: collapse;">\n' overall_stat_keys = sorted ( overall_stat . keys ( ) ) if isinstance ( overall_par... | Return HTML report file overall stat . |
231,070 | def html_class_stat ( classes , class_stat , digit = 5 , class_param = None , recommended_list = ( ) ) : result = "" result += "<h2>Class Statistics : </h2>\n" result += '<table style="border:1px solid black;border-collapse: collapse;">\n' result += '<tr align="center">\n<td>Class</td>\n' for i in classes : result += '... | Return HTML report file class_stat . |
231,071 | def table_print ( classes , table ) : classes_len = len ( classes ) table_list = [ ] for key in classes : table_list . extend ( list ( table [ key ] . values ( ) ) ) table_list . extend ( classes ) table_max_length = max ( map ( len , map ( str , table_list ) ) ) shift = "%-" + str ( 7 + table_max_length ) + "s" result... | Return printable confusion matrix . |
231,072 | def csv_matrix_print ( classes , table ) : result = "" classes . sort ( ) for i in classes : for j in classes : result += str ( table [ i ] [ j ] ) + "," result = result [ : - 1 ] + "\n" return result [ : - 1 ] | Return matrix as csv data . |
231,073 | def csv_print ( classes , class_stat , digit = 5 , class_param = None ) : result = "Class" classes . sort ( ) for item in classes : result += ',"' + str ( item ) + '"' result += "\n" class_stat_keys = sorted ( class_stat . keys ( ) ) if isinstance ( class_param , list ) : if set ( class_param ) <= set ( class_stat_keys... | Return csv file data . |
231,074 | def stat_print ( classes , class_stat , overall_stat , digit = 5 , overall_param = None , class_param = None ) : shift = max ( map ( len , PARAMS_DESCRIPTION . values ( ) ) ) + 5 classes_len = len ( classes ) overall_stat_keys = sorted ( overall_stat . keys ( ) ) result = "" if isinstance ( overall_param , list ) : if ... | Return printable statistics table . |
231,075 | def compare_report_print ( sorted_list , scores , best_name ) : title_items = [ "Rank" , "Name" , "Class-Score" , "Overall-Score" ] class_scores_len = map ( lambda x : len ( str ( x [ "class" ] ) ) , list ( scores . values ( ) ) ) shifts = [ "%-" + str ( len ( sorted_list ) + 4 ) + "s" , "%-" + str ( max ( map ( lambda... | Return compare report . |
231,076 | def online_help ( param = None ) : try : PARAMS_LINK_KEYS = sorted ( PARAMS_LINK . keys ( ) ) if param in PARAMS_LINK_KEYS : webbrowser . open_new_tab ( DOCUMENT_ADR + PARAMS_LINK [ param ] ) elif param in range ( 1 , len ( PARAMS_LINK_KEYS ) + 1 ) : webbrowser . open_new_tab ( DOCUMENT_ADR + PARAMS_LINK [ PARAMS_LINK_... | Open online document in web browser . |
231,077 | def rounder ( input_number , digit = 5 ) : if isinstance ( input_number , tuple ) : tuple_list = list ( input_number ) tuple_str = [ ] for i in tuple_list : if isfloat ( i ) : tuple_str . append ( str ( numpy . around ( i , digit ) ) ) else : tuple_str . append ( str ( i ) ) return "(" + "," . join ( tuple_str ) + ")" ... | Round input number and convert to str . |
231,078 | def class_filter ( classes , class_name ) : result_classes = classes if isinstance ( class_name , list ) : if set ( class_name ) <= set ( classes ) : result_classes = class_name return result_classes | Filter classes by comparing two lists . |
231,079 | def vector_check ( vector ) : for i in vector : if isinstance ( i , int ) is False : return False if i < 0 : return False return True | Check input vector items type . |
231,080 | def matrix_check ( table ) : try : if len ( table . keys ( ) ) == 0 : return False for i in table . keys ( ) : if table . keys ( ) != table [ i ] . keys ( ) or vector_check ( list ( table [ i ] . values ( ) ) ) is False : return False return True except Exception : return False | Check input matrix format . |
231,081 | def vector_filter ( actual_vector , predict_vector ) : temp = [ ] temp . extend ( actual_vector ) temp . extend ( predict_vector ) types = set ( map ( type , temp ) ) if len ( types ) > 1 : return [ list ( map ( str , actual_vector ) ) , list ( map ( str , predict_vector ) ) ] return [ actual_vector , predict_vector ] | Convert different type of items in vectors to str . |
231,082 | def class_check ( vector ) : for i in vector : if not isinstance ( i , type ( vector [ 0 ] ) ) : return False return True | Check different items in matrix classes . |
231,083 | def one_vs_all_func ( classes , table , TP , TN , FP , FN , class_name ) : try : report_classes = [ str ( class_name ) , "~" ] report_table = { str ( class_name ) : { str ( class_name ) : TP [ class_name ] , "~" : FN [ class_name ] } , "~" : { str ( class_name ) : FP [ class_name ] , "~" : TN [ class_name ] } } return ... | One - Vs - All mode handler . |
231,084 | def normalized_table_calc ( classes , table ) : map_dict = { k : 0 for k in classes } new_table = { k : map_dict . copy ( ) for k in classes } for key in classes : div = sum ( table [ key ] . values ( ) ) if div == 0 : div = 1 for item in classes : new_table [ key ] [ item ] = numpy . around ( table [ key ] [ item ] / ... | Return normalized confusion matrix . |
231,085 | def transpose_func ( classes , table ) : transposed_table = table for i , item1 in enumerate ( classes ) : for j , item2 in enumerate ( classes ) : if i > j : temp = transposed_table [ item1 ] [ item2 ] transposed_table [ item1 ] [ item2 ] = transposed_table [ item2 ] [ item1 ] transposed_table [ item2 ] [ item1 ] = te... | Transpose table . |
231,086 | def matrix_params_from_table ( table , transpose = False ) : classes = sorted ( table . keys ( ) ) map_dict = { k : 0 for k in classes } TP_dict = map_dict . copy ( ) TN_dict = map_dict . copy ( ) FP_dict = map_dict . copy ( ) FN_dict = map_dict . copy ( ) for i in classes : TP_dict [ i ] = table [ i ] [ i ] sum_row = ... | Calculate TP TN FP FN from confusion matrix . |
231,087 | def matrix_params_calc ( actual_vector , predict_vector , sample_weight ) : if isinstance ( actual_vector , numpy . ndarray ) : actual_vector = actual_vector . tolist ( ) if isinstance ( predict_vector , numpy . ndarray ) : predict_vector = predict_vector . tolist ( ) classes = set ( actual_vector ) . union ( set ( pre... | Calculate TP TN FP FN for each class . |
231,088 | def imbalance_check ( P ) : p_list = list ( P . values ( ) ) max_value = max ( p_list ) min_value = min ( p_list ) if min_value > 0 : balance_ratio = max_value / min_value else : balance_ratio = max_value is_imbalanced = False if balance_ratio > BALANCE_RATIO_THRESHOLD : is_imbalanced = True return is_imbalanced | Check if the dataset is imbalanced . |
231,089 | def binary_check ( classes ) : num_classes = len ( classes ) is_binary = False if num_classes == 2 : is_binary = True return is_binary | Check if the problem is a binary classification . |
231,090 | def statistic_recommend ( classes , P ) : if imbalance_check ( P ) : return IMBALANCED_RECOMMEND if binary_check ( classes ) : return BINARY_RECOMMEND return MULTICLASS_RECOMMEND | Return recommend parameters which are more suitable due to the input dataset characteristics . |
231,091 | def print_result ( failed = False ) : message = "Version tag tests " if not failed : print ( "\n" + message + "passed!" ) else : print ( "\n" + message + "failed!" ) print ( "Passed : " + str ( TEST_NUMBER - Failed ) + "/" + str ( TEST_NUMBER ) ) | Print final result . |
231,092 | def AUNP_calc ( classes , P , POP , AUC_dict ) : try : result = 0 for i in classes : result += ( P [ i ] / POP [ i ] ) * AUC_dict [ i ] return result except Exception : return "None" | Calculate AUNP . |
231,093 | def overall_MCC_calc ( classes , table , TOP , P ) : try : cov_x_y = 0 cov_x_x = 0 cov_y_y = 0 matrix_sum = sum ( list ( TOP . values ( ) ) ) for i in classes : cov_x_x += TOP [ i ] * ( matrix_sum - TOP [ i ] ) cov_y_y += P [ i ] * ( matrix_sum - P [ i ] ) cov_x_y += ( table [ i ] [ i ] * matrix_sum - P [ i ] * TOP [ i... | Calculate Overall_MCC . |
231,094 | def convex_combination ( classes , TP , TOP , P , class_name , modified = False ) : try : class_number = len ( classes ) alpha = 1 if class_number == 2 : alpha = 0 matrix_sum = sum ( list ( TOP . values ( ) ) ) TP_sum = sum ( list ( TP . values ( ) ) ) up = TOP [ class_name ] + P [ class_name ] down = 2 * matrix_sum if... | Calculate Overall_CEN coefficient . |
231,095 | def ncr ( n , r ) : r = min ( r , n - r ) numer = reduce ( op . mul , range ( n , n - r , - 1 ) , 1 ) denom = reduce ( op . mul , range ( 1 , r + 1 ) , 1 ) return numer // denom | Calculate n choose r . |
231,096 | def p_value_calc ( TP , POP , NIR ) : try : n = POP x = sum ( list ( TP . values ( ) ) ) p = NIR result = 0 for j in range ( x ) : result += ncr ( n , j ) * ( p ** j ) * ( ( 1 - p ) ** ( n - j ) ) return 1 - result except Exception : return "None" | Calculate p_value . |
231,097 | def hamming_calc ( TP , POP ) : try : length = POP return ( 1 / length ) * ( length - sum ( TP . values ( ) ) ) except Exception : return "None" | Calculate hamming loss . |
231,098 | def zero_one_loss_calc ( TP , POP ) : try : length = POP return ( length - sum ( TP . values ( ) ) ) except Exception : return "None" | Calculate zero - one loss . |
231,099 | def entropy_calc ( item , POP ) : try : result = 0 for i in item . keys ( ) : likelihood = item [ i ] / POP [ i ] if likelihood != 0 : result += likelihood * math . log ( likelihood , 2 ) return - result except Exception : return "None" | Calculate reference and response likelihood . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.