idx
int64
0
252k
question
stringlengths
48
5.28k
target
stringlengths
5
1.23k
238,500
def clean_form_template ( self ) : form_template = self . cleaned_data . get ( 'form_template' , '' ) if form_template : try : get_template ( form_template ) except TemplateDoesNotExist : msg = _ ( 'Selected Form Template does not exist.' ) raise forms . ValidationError ( msg ) return form_template
Check if template exists
238,501
def _embed ( x , order = 3 , delay = 1 ) : N = len ( x ) Y = np . empty ( ( order , N - ( order - 1 ) * delay ) ) for i in range ( order ) : Y [ i ] = x [ i * delay : i * delay + Y . shape [ 1 ] ] return Y . T
Time - delay embedding .
238,502
def util_pattern_space ( time_series , lag , dim ) : n = len ( time_series ) if lag * dim > n : raise Exception ( 'Result matrix exceeded size limit, try to change lag or dim.' ) elif lag < 1 : raise Exception ( 'Lag should be greater or equal to 1.' ) pattern_space = np . empty ( ( n - lag * ( dim - 1 ) , dim ) ) for ...
Create a set of sequences with given lag and dimension
238,503
def util_granulate_time_series ( time_series , scale ) : n = len ( time_series ) b = int ( np . fix ( n / scale ) ) temp = np . reshape ( time_series [ 0 : b * scale ] , ( b , scale ) ) cts = np . mean ( temp , axis = 1 ) return cts
Extract coarse - grained time series
238,504
def shannon_entropy ( time_series ) : if not isinstance ( time_series , str ) : time_series = list ( time_series ) data_set = list ( set ( time_series ) ) freq_list = [ ] for entry in data_set : counter = 0. for i in time_series : if i == entry : counter += 1 freq_list . append ( float ( counter ) / len ( time_series )...
Return the Shannon Entropy of the sample data .
238,505
def sample_entropy ( time_series , sample_length , tolerance = None ) : M = sample_length - 1 time_series = np . array ( time_series ) if tolerance is None : tolerance = 0.1 * np . std ( time_series ) n = len ( time_series ) Ntemp = np . zeros ( M + 2 ) Ntemp [ 0 ] = n * ( n - 1 ) / 2 for i in range ( n - M - 1 ) : tem...
Calculates the sample entropy of degree m of a time_series .
238,506
def multiscale_entropy ( time_series , sample_length , tolerance = None , maxscale = None ) : if tolerance is None : tolerance = 0.1 * np . std ( time_series ) if maxscale is None : maxscale = len ( time_series ) mse = np . zeros ( maxscale ) for i in range ( maxscale ) : temp = util_granulate_time_series ( time_series...
Calculate the Multiscale Entropy of the given time series considering different time - scales of the time series .
238,507
def permutation_entropy ( time_series , order = 3 , delay = 1 , normalize = False ) : x = np . array ( time_series ) hashmult = np . power ( order , np . arange ( order ) ) sorted_idx = _embed ( x , order = order , delay = delay ) . argsort ( kind = 'quicksort' ) hashval = ( np . multiply ( sorted_idx , hashmult ) ) . ...
Permutation Entropy .
238,508
def multiscale_permutation_entropy ( time_series , m , delay , scale ) : mspe = [ ] for i in range ( scale ) : coarse_time_series = util_granulate_time_series ( time_series , i + 1 ) pe = permutation_entropy ( coarse_time_series , order = m , delay = delay ) mspe . append ( pe ) return mspe
Calculate the Multiscale Permutation Entropy
238,509
def composite_multiscale_entropy ( time_series , sample_length , scale , tolerance = None ) : cmse = np . zeros ( ( 1 , scale ) ) for i in range ( scale ) : for j in range ( i ) : tmp = util_granulate_time_series ( time_series [ j : ] , i + 1 ) cmse [ i ] += sample_entropy ( tmp , sample_length , tolerance ) / ( i + 1 ...
Calculate the Composite Multiscale Entropy of the given time series .
238,510
def ones_comp_sum16 ( num1 : int , num2 : int ) -> int : carry = 1 << 16 result = num1 + num2 return result if result < carry else result + 1 - carry
Calculates the 1 s complement sum for 16 - bit numbers .
238,511
def checksum ( source : bytes ) -> int : if len ( source ) % 2 : source += b'\x00' sum = 0 for i in range ( 0 , len ( source ) , 2 ) : sum = ones_comp_sum16 ( sum , ( source [ i + 1 ] << 8 ) + source [ i ] ) return ~ sum & 0xffff
Calculates the checksum of the input bytes .
238,512
def send_one_ping ( sock : socket , dest_addr : str , icmp_id : int , seq : int , size : int ) : try : dest_addr = socket . gethostbyname ( dest_addr ) except socket . gaierror as e : print ( "Cannot resolve {}: Unknown host" . format ( dest_addr ) ) raise errors . HostUnknown ( dest_addr ) from e pseudo_checksum = 0 i...
Sends one ping to the given destination .
238,513
def receive_one_ping ( sock : socket , icmp_id : int , seq : int , timeout : int ) -> float or None : ip_header_slice = slice ( 0 , struct . calcsize ( IP_HEADER_FORMAT ) ) icmp_header_slice = slice ( ip_header_slice . stop , ip_header_slice . stop + struct . calcsize ( ICMP_HEADER_FORMAT ) ) ip_header_keys = ( 'versio...
Receives the ping from the socket .
238,514
def ping ( dest_addr : str , timeout : int = 4 , unit : str = "s" , src_addr : str = None , ttl : int = 64 , seq : int = 0 , size : int = 56 ) -> float or None : with socket . socket ( socket . AF_INET , socket . SOCK_RAW , socket . IPPROTO_ICMP ) as sock : sock . setsockopt ( socket . SOL_IP , socket . IP_TTL , ttl ) ...
Send one ping to destination address with the given timeout .
238,515
def verbose_ping ( dest_addr : str , count : int = 4 , * args , ** kwargs ) : timeout = kwargs . get ( "timeout" ) src = kwargs . get ( "src" ) unit = kwargs . setdefault ( "unit" , "ms" ) for i in range ( count ) : output_text = "ping '{}'" . format ( dest_addr ) output_text += " from '{}'" . format ( src ) if src els...
Send pings to destination address with the given timeout and display the result .
238,516
def distance ( self , val ) : tmp = 2 try : int ( val ) if val > 0 and val <= 2 : tmp = val except ( ValueError , TypeError ) : pass self . _distance = tmp
set the distance parameter
238,517
def export ( self , filepath , encoding = "utf-8" , gzipped = True ) : data = json . dumps ( self . word_frequency . dictionary , sort_keys = True ) write_file ( filepath , encoding , gzipped , data )
Export the word frequency list for import in the future
238,518
def word_probability ( self , word , total_words = None ) : if total_words is None : total_words = self . _word_frequency . total_words return self . _word_frequency . dictionary [ word ] / total_words
Calculate the probability of the word being the desired correct word
238,519
def correction ( self , word ) : return max ( self . candidates ( word ) , key = self . word_probability )
The most probable correct spelling for the word
238,520
def candidates ( self , word ) : if self . known ( [ word ] ) : return { word } res = [ x for x in self . edit_distance_1 ( word ) ] tmp = self . known ( res ) if tmp : return tmp if self . _distance == 2 : tmp = self . known ( [ x for x in self . __edit_distance_alt ( res ) ] ) if tmp : return tmp return { word }
Generate possible spelling corrections for the provided word up to an edit distance of two if and only when needed
238,521
def known ( self , words ) : tmp = [ w . lower ( ) for w in words ] return set ( w for w in tmp if w in self . _word_frequency . dictionary or not self . _check_if_should_check ( w ) )
The subset of words that appear in the dictionary of words
238,522
def edit_distance_1 ( self , word ) : word = word . lower ( ) if self . _check_if_should_check ( word ) is False : return { word } letters = self . _word_frequency . letters splits = [ ( word [ : i ] , word [ i : ] ) for i in range ( len ( word ) + 1 ) ] deletes = [ L + R [ 1 : ] for L , R in splits if R ] transposes =...
Compute all strings that are one edit away from word using only the letters in the corpus
238,523
def edit_distance_2 ( self , word ) : word = word . lower ( ) return [ e2 for e1 in self . edit_distance_1 ( word ) for e2 in self . edit_distance_1 ( e1 ) ]
Compute all strings that are two edits away from word using only the letters in the corpus
238,524
def __edit_distance_alt ( self , words ) : words = [ x . lower ( ) for x in words ] return [ e2 for e1 in words for e2 in self . edit_distance_1 ( e1 ) ]
Compute all strings that are 1 edits away from all the words using only the letters in the corpus
238,525
def pop ( self , key , default = None ) : return self . _dictionary . pop ( key . lower ( ) , default )
Remove the key and return the associated value or default if not found
238,526
def items ( self ) : for word in self . _dictionary . keys ( ) : yield word , self . _dictionary [ word ]
Iterator over the words in the dictionary
238,527
def load_dictionary ( self , filename , encoding = "utf-8" ) : with load_file ( filename , encoding ) as data : self . _dictionary . update ( json . loads ( data . lower ( ) , encoding = encoding ) ) self . _update_dictionary ( )
Load in a pre - built word frequency list
238,528
def load_text_file ( self , filename , encoding = "utf-8" , tokenizer = None ) : with load_file ( filename , encoding = encoding ) as data : self . load_text ( data , tokenizer )
Load in a text file from which to generate a word frequency list
238,529
def load_text ( self , text , tokenizer = None ) : if tokenizer : words = [ x . lower ( ) for x in tokenizer ( text ) ] else : words = self . tokenize ( text ) self . _dictionary . update ( words ) self . _update_dictionary ( )
Load text from which to generate a word frequency list
238,530
def load_words ( self , words ) : self . _dictionary . update ( [ word . lower ( ) for word in words ] ) self . _update_dictionary ( )
Load a list of words from which to generate a word frequency list
238,531
def remove_words ( self , words ) : for word in words : self . _dictionary . pop ( word . lower ( ) ) self . _update_dictionary ( )
Remove a list of words from the word frequency list
238,532
def remove ( self , word ) : self . _dictionary . pop ( word . lower ( ) ) self . _update_dictionary ( )
Remove a word from the word frequency list
238,533
def remove_by_threshold ( self , threshold = 5 ) : keys = [ x for x in self . _dictionary . keys ( ) ] for key in keys : if self . _dictionary [ key ] <= threshold : self . _dictionary . pop ( key ) self . _update_dictionary ( )
Remove all words at or below the provided threshold
238,534
def _update_dictionary ( self ) : self . _total_words = sum ( self . _dictionary . values ( ) ) self . _unique_words = len ( self . _dictionary . keys ( ) ) self . _letters = set ( ) for key in self . _dictionary : self . _letters . update ( key )
Update the word frequency object
238,535
def load_file ( filename , encoding ) : try : with gzip . open ( filename , mode = "rt" ) as fobj : yield fobj . read ( ) except ( OSError , IOError ) : with OPEN ( filename , mode = "r" , encoding = encoding ) as fobj : yield fobj . read ( )
Context manager to handle opening a gzip or text file correctly and reading all the data
238,536
def write_file ( filepath , encoding , gzipped , data ) : if gzipped : with gzip . open ( filepath , "wt" ) as fobj : fobj . write ( data ) else : with OPEN ( filepath , "w" , encoding = encoding ) as fobj : if sys . version_info < ( 3 , 0 ) : data = data . decode ( encoding ) fobj . write ( data )
Write the data to file either as a gzip file or text based on the gzipped parameter
238,537
def preprocess ( self , raw_inputs ) : image_arrays = [ ] for raw_im in raw_inputs : im = raw_im . convert ( 'L' ) im = im . resize ( MNIST_DIM , Image . ANTIALIAS ) arr = np . array ( im ) image_arrays . append ( arr ) inputs = np . array ( image_arrays ) return inputs . reshape ( len ( inputs ) , MNIST_DIM [ 0 ] , MN...
Convert images into the format required by our model .
238,538
def initialize_new_session ( ) : if 'image_uid_counter' in session and 'image_list' in session : logger . debug ( 'images are already being tracked' ) else : session [ 'image_uid_counter' ] = 0 session [ 'image_list' ] = [ ] if 'img_input_dir' in session and 'img_output_dir' in session : logger . debug ( 'temporary ima...
Check session and initialize if necessary
238,539
def images ( ) : if request . method == 'POST' : file_upload = request . files [ 'file' ] if file_upload : image = dict ( ) image [ 'filename' ] = secure_filename ( file_upload . filename ) full_path = os . path . join ( session [ 'img_input_dir' ] , image [ 'filename' ] ) file_upload . save ( full_path ) image [ 'uid'...
Upload images via REST interface
238,540
def visualizers ( ) : list_of_visualizers = [ ] for visualizer in get_visualizations ( ) : list_of_visualizers . append ( { 'name' : visualizer } ) return jsonify ( visualizers = list_of_visualizers )
Get a list of available visualizers
238,541
def visualize ( ) : session [ 'settings' ] = { } image_uid = request . args . get ( 'image' ) vis_name = request . args . get ( 'visualizer' ) vis = get_visualizations ( ) [ vis_name ] if vis . ALLOWED_SETTINGS : for key in vis . ALLOWED_SETTINGS . keys ( ) : if request . args . get ( key ) is not None : session [ 'set...
Trigger a visualization via the REST API
238,542
def reset ( ) : shutil . rmtree ( session [ 'img_input_dir' ] ) shutil . rmtree ( session [ 'img_output_dir' ] ) session . clear ( ) return jsonify ( ok = 'true' )
Delete the session and clear temporary directories
238,543
def update_settings ( self , settings ) : def error_string ( setting , setting_val ) : return ( '{val} is not an acceptable value for ' 'parameter {param} for visualization' '{vis}.' ) . format ( val = setting_val , param = setting , vis = self . __class__ . __name__ ) for setting in settings : if settings [ setting ] ...
Update the settings
238,544
def load_model ( model_cls_path , model_cls_name , model_load_args ) : spec = importlib . util . spec_from_file_location ( 'active_model' , model_cls_path ) model_module = importlib . util . module_from_spec ( spec ) spec . loader . exec_module ( model_module ) model_cls = getattr ( model_module , model_cls_name ) mode...
Get an instance of the described model .
238,545
def decode_prob ( self , class_probabilities ) : results = [ ] for row in class_probabilities : entries = [ ] for i , prob in enumerate ( row ) : entries . append ( { 'index' : i , 'name' : str ( i ) , 'prob' : prob } ) entries = sorted ( entries , key = itemgetter ( 'prob' ) , reverse = True ) [ : self . top_probs ] f...
Given predicted class probabilites for a set of examples annotate each logit with a class name .
238,546
def _get_visualization_classes ( ) : visualization_attr = vars ( import_module ( 'picasso.visualizations' ) ) visualization_submodules = [ visualization_attr [ x ] for x in visualization_attr if isinstance ( visualization_attr [ x ] , ModuleType ) ] visualization_classes = [ ] for submodule in visualization_submodules ...
Import visualizations classes dynamically
238,547
def get_model ( ) : if not hasattr ( g , 'model' ) : g . model = load_model ( current_app . config [ 'MODEL_CLS_PATH' ] , current_app . config [ 'MODEL_CLS_NAME' ] , current_app . config [ 'MODEL_LOAD_ARGS' ] ) return g . model
Get the NN model that s being analyzed from the request context . Put the model in the request context if it is not yet there .
238,548
def get_visualizations ( ) : if not hasattr ( g , 'visualizations' ) : g . visualizations = { } for VisClass in _get_visualization_classes ( ) : vis = VisClass ( get_model ( ) ) g . visualizations [ vis . __class__ . __name__ ] = vis return g . visualizations
Get the available visualizations from the request context . Put the visualizations in the request context if they are not yet there .
238,549
def get_app_state ( ) : if not hasattr ( g , 'app_state' ) : model = get_model ( ) g . app_state = { 'app_title' : APP_TITLE , 'model_name' : type ( model ) . __name__ , 'latest_ckpt_name' : model . latest_ckpt_name , 'latest_ckpt_time' : model . latest_ckpt_time } return g . app_state
Get current status of application in context
238,550
async def login ( username : str , password : str , brand : str , websession : ClientSession = None ) -> API : api = API ( brand , websession ) await api . authenticate ( username , password ) return api
Log in to the API .
238,551
def _create_websession ( self ) : from socket import AF_INET from aiohttp import ClientTimeout , TCPConnector _LOGGER . debug ( 'Creating web session' ) conn = TCPConnector ( family = AF_INET , limit_per_host = 5 , enable_cleanup_closed = True , ) session_timeout = ClientTimeout ( connect = 10 ) self . _websession = Cl...
Create a web session .
238,552
async def close_websession ( self ) : if self . _supplied_websession or self . _websession is None : return _LOGGER . debug ( 'Closing connections' ) temp_websession = self . _websession self . _websession = None await temp_websession . close ( ) await asyncio . sleep ( 0 ) _LOGGER . debug ( 'Connections closed' )
Close web session if not already closed and created by us .
238,553
async def authenticate ( self , username : str , password : str ) -> None : self . _credentials = { 'username' : username , 'password' : password , } await self . _get_security_token ( )
Authenticate against the API .
238,554
async def _get_security_token ( self ) -> None : _LOGGER . debug ( 'Requesting security token.' ) if self . _credentials is None : return async with self . _security_token_lock : if self . _security_token is None : login_resp = await self . _request ( 'post' , LOGIN_ENDPOINT , json = self . _credentials , login_request...
Request a security token .
238,555
async def get_devices ( self , covers_only : bool = True ) -> list : from . device import MyQDevice _LOGGER . debug ( 'Retrieving list of devices' ) devices_resp = await self . _request ( 'get' , DEVICE_LIST_ENDPOINT ) device_list = [ ] if devices_resp is None : return device_list for device in devices_resp [ 'Devices'...
Get a list of all devices associated with the account .
238,556
def name ( self ) -> str : return next ( attr [ 'Value' ] for attr in self . _device_json . get ( 'Attributes' , [ ] ) if attr . get ( 'AttributeDisplayName' ) == 'desc' )
Return the device name .
238,557
def available ( self ) -> bool : is_available = self . api . online and next ( attr [ 'Value' ] for attr in self . _device_json . get ( 'Attributes' , [ ] ) if attr . get ( 'AttributeDisplayName' ) == 'online' ) == "True" return is_available
Return if device is online or not .
238,558
def open_allowed ( self ) -> bool : return next ( attr [ 'Value' ] for attr in self . _device_json . get ( 'Attributes' , [ ] ) if attr . get ( 'AttributeDisplayName' ) == 'isunattendedopenallowed' ) == "1"
Door can be opened unattended .
238,559
def close_allowed ( self ) -> bool : return next ( attr [ 'Value' ] for attr in self . _device_json . get ( 'Attributes' , [ ] ) if attr . get ( 'AttributeDisplayName' ) == 'isunattendedcloseallowed' ) == "1"
Door can be closed unattended .
238,560
def _update_state ( self , value : str ) -> None : attribute = next ( attr for attr in self . _device [ 'device_info' ] . get ( 'Attributes' , [ ] ) if attr . get ( 'AttributeDisplayName' ) == 'doorstate' ) if attribute is not None : attribute [ 'Value' ] = value
Update state temporary during open or close .
238,561
def _coerce_state_from_string ( value : Union [ int , str ] ) -> str : try : return STATE_MAP [ int ( value ) ] except KeyError : _LOGGER . error ( 'Unknown state: %s' , value ) return STATE_UNKNOWN
Return a proper state from a string input .
238,562
async def _set_state ( self , state : int ) -> bool : try : set_state_resp = await self . api . _request ( 'put' , DEVICE_SET_ENDPOINT , json = { 'attributeName' : 'desireddoorstate' , 'myQDeviceId' : self . device_id , 'AttributeValue' : state , } ) except RequestError as err : _LOGGER . error ( '%s: Setting state fai...
Set the state of the device .
238,563
async def close ( self ) -> bool : _LOGGER . debug ( '%s: Sending close command' , self . name ) if not await self . _set_state ( 0 ) : return False self . next_allowed_update = datetime . utcnow ( ) + timedelta ( seconds = 10 ) if self . state not in ( STATE_CLOSED , STATE_CLOSING ) : self . _update_state ( '5' ) self...
Close the device .
238,564
async def update ( self ) -> None : if self . next_allowed_update is not None and datetime . utcnow ( ) < self . next_allowed_update : return self . next_allowed_update = None await self . api . _update_device_state ( ) self . _device_json = self . _device [ 'device_info' ]
Retrieve updated device state .
238,565
def get_transaction ( cls , txid ) : for api_call in cls . GET_TX_MAIN : try : return api_call ( txid ) except cls . IGNORED_ERRORS : pass raise ConnectionError ( 'All APIs are unreachable.' )
Gets the full transaction details .
238,566
def get_tx_amount ( cls , txid , txindex ) : for api_call in cls . GET_TX_AMOUNT_MAIN : try : return api_call ( txid , txindex ) except cls . IGNORED_ERRORS : pass raise ConnectionError ( 'All APIs are unreachable.' )
Gets the amount of a given transaction output .
238,567
def get_fee ( speed = FEE_SPEED_MEDIUM ) : if speed == FEE_SPEED_FAST : return DEFAULT_FEE_FAST elif speed == FEE_SPEED_MEDIUM : return DEFAULT_FEE_MEDIUM elif speed == FEE_SPEED_SLOW : return DEFAULT_FEE_SLOW else : raise ValueError ( 'Invalid speed argument.' )
Gets the recommended satoshi per byte fee .
238,568
def find_binutils_libs ( self , libdir , lib_ext ) : bfd_expr = re . compile ( "(lib(?:bfd)|(?:opcodes))(.*?)\%s" % lib_ext ) libs = { } for root , dirs , files in os . walk ( libdir ) : for f in files : m = bfd_expr . search ( f ) if m : lib , version = m . groups ( ) fp = os . path . join ( root , f ) if version in l...
Find Binutils libraries .
238,569
def generate_source_files ( self ) : from pybfd . gen_supported_disasm import get_supported_architectures , get_supported_machines , generate_supported_architectures_source , generate_supported_disassembler_header , gen_supported_archs libs_dirs = [ os . path . dirname ( lib ) for lib in self . libs ] libopcodes = [ li...
Genertate source files to be used during the compile process of the extension module . This is better than just hardcoding the values on python files because header definitions might change along differente Binutils versions and we ll be able to catch the changes and keep the correct values .
238,570
def _darwin_current_arch ( self ) : if sys . platform == "darwin" : if sys . maxsize > 2 ** 32 : return platform . mac_ver ( ) [ 2 ] else : return platform . processor ( )
Add Mac OS X support .
238,571
def init_parser ( ) : usage = "Usage: %(prog)s <option(s)> <file(s)>" description = " Display information from object <file(s)>.\n" description += " At least one of the following switches must be given:" parser = ArgumentParser ( usage = usage , description = description , add_help = False ) group = parser . add_mutual...
Initialize option parser .
238,572
def dump ( self , src , length = 16 , start = 0 , preffix = "" ) : FILTER = "" . join ( [ ( len ( repr ( chr ( x ) ) ) == 3 ) and chr ( x ) or '.' for x in xrange ( 256 ) ] ) result = list ( ) for i in xrange ( 0 , len ( src ) , length ) : s = src [ i : i + length ] hexa = " " . join ( [ "%02X" % ord ( x ) for x in s ]...
Dump the specified buffer in hex + ASCII format .
238,573
def content ( self ) : return _bfd . section_get_content ( self . bfd , self . _ptr , 0 , self . size )
Return the entire section content .
238,574
def get_content ( self , offset , size ) : return _bfd . section_get_content ( self . bfd , self . _ptr , offset , size )
Return the specified number of bytes from the current section .
238,575
def main ( ) : test_targets = ( [ ARCH_I386 , MACH_I386_I386_INTEL_SYNTAX , ENDIAN_MONO , "\x55\x89\xe5\xE8\xB8\xFF\xFF\xFF" , 0x1000 ] , [ ARCH_I386 , MACH_X86_64_INTEL_SYNTAX , ENDIAN_MONO , "\x55\x48\x89\xe5\xE8\xA3\xFF\xFF\xFF" , 0x1000 ] , [ ARCH_ARM , MACH_ARM_2 , ENDIAN_LITTLE , "\x04\xe0\x2d\xe5\xED\xFF\xFF\xEB...
Test case for simple opcode disassembly .
238,576
def initialize_bfd ( self , abfd ) : self . _ptr = _opcodes . initialize_bfd ( abfd . _ptr ) if self . architecture == ARCH_I386 : if abfd . arch_size == 32 : self . machine = MACH_I386_I386_INTEL_SYNTAX elif abfd . arch_size == 64 : self . machine = MACH_X86_64_INTEL_SYNTAX
Initialize underlying libOpcodes library using BFD .
238,577
def initialize_non_bfd ( self , architecture = None , machine = None , endian = ENDIAN_UNKNOWN ) : if None in [ architecture , machine , endian ] : return self . architecture = architecture self . machine = machine self . endian = endian
Initialize underlying libOpcodes library not using BFD .
238,578
def initialize_smart_disassemble ( self , data , start_address = 0 ) : _opcodes . initialize_smart_disassemble ( self . _ptr , data , start_address )
Set the binary buffer to disassemble with other related information ready for an instruction by instruction disassembly session .
238,579
def print_single_instruction_callback ( self , address , size , branch_delay_insn , insn_type , target , target2 , disassembly ) : print "0x%X SZ=%d BD=%d IT=%d\t%s" % ( address , size , branch_delay_insn , insn_type , disassembly ) return PYBFD_DISASM_CONTINUE
Callack on each disassembled instruction to print its information .
238,580
def disassemble ( self , data , start_address = 0 ) : return _opcodes . disassemble ( self . _ptr , data , start_address )
Return a list containing the virtual memory address instruction length and disassembly code for the given binary buffer .
238,581
def open ( self , _file , target = DEFAULT_TARGET ) : self . close ( ) if type ( _file ) is FileType : filename = _file . name if islink ( filename ) : raise BfdException ( "Symlinks file-descriptors are not valid" ) try : self . _ptr = _bfd . fdopenr ( filename , target , dup ( _file . fileno ( ) ) ) except Exception ...
Open the existing file for reading .
238,582
def __populate_archive_files ( self ) : self . archive_files = [ ] for _ptr in _bfd . archive_list_files ( self . _ptr ) : try : self . archive_files . append ( Bfd ( _ptr ) ) except BfdException , err : pass
Store the list of files inside an archive file .
238,583
def archive_filenames ( self ) : try : return _bfd . archive_list_filenames ( self . _ptr ) except TypeError , err : raise BfdException ( err )
Return the list of files inside an archive file .
238,584
def file_format_name ( self ) : try : return BfdFormatNamesLong [ self . file_format ] except IndexError , err : raise BfdException ( "Invalid format specified (%d)" % self . file_format )
Return the current format name of the open bdf .
238,585
def __populate_sections ( self ) : if not self . _ptr : raise BfdException ( "BFD not initialized" ) for section in _bfd . get_sections_list ( self . _ptr ) : try : bfd_section = BfdSection ( self . _ptr , section ) self . _sections [ bfd_section . name ] = bfd_section except BfdSectionException , err : pass
Get a list of the section present in the bfd to populate our internal list .
238,586
def __populate_symbols ( self ) : if not self . _ptr : raise BfdException ( "BFD not initialized" ) try : symbols = _bfd . get_symbols ( self . _ptr ) sections = { } for section in self . sections : sections [ self . sections [ section ] . index ] = self . sections [ section ] for symbol in symbols : symbol_section_ind...
Get a list of the symbols present in the bfd to populate our internal list .
238,587
def close ( self ) : if self . _ptr : try : _bfd . close ( self . _ptr ) except TypeError , err : raise BfdException ( "Unable to close bfd (%s)" % err ) finally : self . _ptr = None
Close any existing BFD structure before open a new one .
238,588
def filename ( self ) : if not self . _ptr : raise BfdException ( "BFD not initialized" ) return _bfd . get_bfd_attribute ( self . _ptr , BfdAttributes . FILENAME )
Return the filename of the BFD file being processed .
238,589
def cacheable ( self ) : if not self . _ptr : raise BfdException ( "BFD not initialized" ) return _bfd . get_bfd_attribute ( self . _ptr , BfdAttributes . CACHEABLE )
Return the cacheable attribute of the BFD file being processed .
238,590
def format ( self ) : if not self . _ptr : raise BfdException ( "BFD not initialized" ) return _bfd . get_bfd_attribute ( self . _ptr , BfdAttributes . FORMAT )
Return the format attribute of the BFD file being processed .
238,591
def target ( self ) : if not self . _ptr : raise BfdException ( "BFD not initialized" ) return _bfd . get_bfd_attribute ( self . _ptr , BfdAttributes . TARGET )
Return the target of the BFD file being processed .
238,592
def machine ( self ) : if not self . _ptr : raise BfdException ( "BFD not initialized" ) return _bfd . get_bfd_attribute ( self . _ptr , BfdAttributes . FLAVOUR )
Return the flavour attribute of the BFD file being processed .
238,593
def family_coff ( self ) : if not self . _ptr : raise BfdException ( "BFD not initialized" ) return _bfd . get_bfd_attribute ( self . _ptr , BfdAttributes . FAMILY_COFF )
Return the family_coff attribute of the BFD file being processed .
238,594
def big_endian ( self ) : if not self . _ptr : raise BfdException ( "BFD not initialized" ) return _bfd . get_bfd_attribute ( self . _ptr , BfdAttributes . IS_BIG_ENDIAN )
Return the big endian attribute of the BFD file being processed .
238,595
def little_endian ( self ) : if not self . _ptr : raise BfdException ( "BFD not initialized" ) return _bfd . get_bfd_attribute ( self . _ptr , BfdAttributes . IS_LITTLE_ENDIAN )
Return the little_endian attribute of the BFD file being processed .
238,596
def header_big_endian ( self ) : if not self . _ptr : raise BfdException ( "BFD not initialized" ) return _bfd . get_bfd_attribute ( self . _ptr , BfdAttributes . HEADER_BIG_ENDIAN )
Return the header_big_endian attribute of the BFD file being processed .
238,597
def header_little_endian ( self ) : if not self . _ptr : raise BfdException ( "BFD not initialized" ) return _bfd . get_bfd_attribute ( self . _ptr , BfdAttributes . HEADER_LITTLE_ENDIAN )
Return the header_little_endian attribute of the BFD file being processed .
238,598
def file_flags ( self ) : if not self . _ptr : raise BfdException ( "BFD not initialized" ) return _bfd . get_bfd_attribute ( self . _ptr , BfdAttributes . FILE_FLAGS )
Return the file flags attribute of the BFD file being processed .
238,599
def file_flags ( self , _file_flags ) : if not self . _ptr : raise BfdException ( "BFD not initialized" ) return _bfd . set_file_flags ( self . _ptr , _file_flags )
Set the new file flags attribute of the BFD file being processed .