idx
int64
0
63k
question
stringlengths
61
4.03k
target
stringlengths
6
1.23k
27,400
def _rdsignal ( fp , file_size , header_size , n_sig , bit_width , is_signed , cut_end ) : fp . seek ( header_size ) signal_size = file_size - header_size byte_width = int ( bit_width / 8 ) dtype = str ( byte_width ) if is_signed : dtype = 'i' + dtype else : dtype = 'u' + dtype dtype = '>' + dtype max_samples = int ( s...
Read the signal
27,401
def xqrs_detect ( sig , fs , sampfrom = 0 , sampto = 'end' , conf = None , learn = True , verbose = True ) : xqrs = XQRS ( sig = sig , fs = fs , conf = conf ) xqrs . detect ( sampfrom = sampfrom , sampto = sampto , verbose = verbose ) return xqrs . qrs_inds
Run the xqrs qrs detection algorithm on a signal . See the docstring of the XQRS class for algorithm details .
27,402
def gqrs_detect ( sig = None , fs = None , d_sig = None , adc_gain = None , adc_zero = None , threshold = 1.0 , hr = 75 , RRdelta = 0.2 , RRmin = 0.28 , RRmax = 2.4 , QS = 0.07 , QT = 0.35 , RTmin = 0.25 , RTmax = 0.33 , QRSa = 750 , QRSamin = 130 ) : if sig is not None : record = Record ( p_signal = sig . reshape ( [ ...
Detect qrs locations in a single channel ecg . Functionally a direct port of the gqrs algorithm from the original wfdb package . Accepts either a physical signal or a digital signal with known adc_gain and adc_zero .
27,403
def _set_conf ( self ) : self . rr_init = 60 * self . fs / self . conf . hr_init self . rr_max = 60 * self . fs / self . conf . hr_min self . rr_min = 60 * self . fs / self . conf . hr_max self . qrs_width = int ( self . conf . qrs_width * self . fs ) self . qrs_radius = int ( self . conf . qrs_radius * self . fs ) sel...
Set configuration parameters from the Conf object into the detector object .
27,404
def _bandpass ( self , fc_low = 5 , fc_high = 20 ) : self . fc_low = fc_low self . fc_high = fc_high b , a = signal . butter ( 2 , [ float ( fc_low ) * 2 / self . fs , float ( fc_high ) * 2 / self . fs ] , 'pass' ) self . sig_f = signal . filtfilt ( b , a , self . sig [ self . sampfrom : self . sampto ] , axis = 0 ) se...
Apply a bandpass filter onto the signal and save the filtered signal .
27,405
def _set_init_params ( self , qrs_amp_recent , noise_amp_recent , rr_recent , last_qrs_ind ) : self . qrs_amp_recent = qrs_amp_recent self . noise_amp_recent = noise_amp_recent self . qrs_thr = max ( 0.25 * self . qrs_amp_recent + 0.75 * self . noise_amp_recent , self . qrs_thr_min * self . transform_gain ) self . rr_r...
Set initial online parameters
27,406
def _set_default_init_params ( self ) : if self . verbose : print ( 'Initializing using default parameters' ) qrs_thr_init = self . qrs_thr_init * self . transform_gain qrs_thr_min = self . qrs_thr_min * self . transform_gain qrs_amp = 27 / 40 * qrs_thr_init noise_amp = qrs_amp / 10 rr_recent = self . rr_init last_qrs_...
Set initial running parameters using default values .
27,407
def _update_qrs ( self , peak_num , backsearch = False ) : i = self . peak_inds_i [ peak_num ] rr_new = i - self . last_qrs_ind if rr_new < self . rr_max : self . rr_recent = 0.875 * self . rr_recent + 0.125 * rr_new self . qrs_inds . append ( i ) self . last_qrs_ind = i self . last_qrs_peak_num = self . peak_num if ba...
Update live qrs parameters . Adjust the recent rr - intervals and qrs amplitudes and the qrs threshold .
27,408
def _is_twave ( self , peak_num ) : i = self . peak_inds_i [ peak_num ] if self . last_qrs_ind - self . qrs_radius < 0 : return False sig_segment = normalize ( ( self . sig_f [ i - self . qrs_radius : i ] ) . reshape ( - 1 , 1 ) , axis = 0 ) last_qrs_segment = self . sig_f [ self . last_qrs_ind - self . qrs_radius : se...
Check whether a segment is a t - wave . Compare the maximum gradient of the filtered signal segment with that of the previous qrs segment .
27,409
def _update_noise ( self , peak_num ) : i = self . peak_inds_i [ peak_num ] self . noise_amp_recent = ( 0.875 * self . noise_amp_recent + 0.125 * self . sig_i [ i ] ) return
Update live noise parameters
27,410
def _require_backsearch ( self ) : if self . peak_num == self . n_peaks_i - 1 : return False next_peak_ind = self . peak_inds_i [ self . peak_num + 1 ] if next_peak_ind - self . last_qrs_ind > self . rr_recent * 1.66 : return True else : return False
Determine whether a backsearch should be performed on prior peaks
27,411
def _run_detection ( self ) : if self . verbose : print ( 'Running QRS detection...' ) self . qrs_inds = [ ] self . backsearch_qrs_inds = [ ] for self . peak_num in range ( self . n_peaks_i ) : if self . _is_qrs ( self . peak_num ) : self . _update_qrs ( self . peak_num ) else : self . _update_noise ( self . peak_num )...
Run the qrs detection after all signals and parameters have been configured and set .
27,412
def detect ( self , sampfrom = 0 , sampto = 'end' , learn = True , verbose = True ) : if sampfrom < 0 : raise ValueError ( "'sampfrom' cannot be negative" ) self . sampfrom = sampfrom if sampto == 'end' : sampto = self . sig_len elif sampto > self . sig_len : raise ValueError ( "'sampto' cannot exceed the signal length...
Detect qrs locations between two samples .
27,413
def detect ( self , x , conf , adc_zero ) : self . c = conf self . annotations = [ ] self . sample_valid = False if len ( x ) < 1 : return [ ] self . x = x self . adc_zero = adc_zero self . qfv = np . zeros ( ( self . c . _BUFLN ) , dtype = "int64" ) self . smv = np . zeros ( ( self . c . _BUFLN ) , dtype = "int64" ) s...
Run detection . x is digital signal
27,414
def compute_hr ( sig_len , qrs_inds , fs ) : heart_rate = np . full ( sig_len , np . nan , dtype = 'float32' ) if len ( qrs_inds ) < 2 : return heart_rate for i in range ( 0 , len ( qrs_inds ) - 2 ) : a = qrs_inds [ i ] b = qrs_inds [ i + 1 ] c = qrs_inds [ i + 2 ] rr = ( b - a ) * ( 1.0 / fs ) * 1000 hr = 60000.0 / rr...
Compute instantaneous heart rate from peak indices .
27,415
def calc_rr ( qrs_locs , fs = None , min_rr = None , max_rr = None , qrs_units = 'samples' , rr_units = 'samples' ) : rr = np . diff ( qrs_locs ) if not len ( rr ) : return rr if qrs_units == 'samples' and rr_units == 'seconds' : rr = rr / fs elif qrs_units == 'seconds' and rr_units == 'samples' : rr = rr * fs if min_r...
Compute rr intervals from qrs indices by extracting the time differences .
27,416
def calc_mean_hr ( rr , fs = None , min_rr = None , max_rr = None , rr_units = 'samples' ) : if not len ( rr ) : return 0 if min_rr is not None : rr = rr [ rr > min_rr ] if max_rr is not None : rr = rr [ rr < max_rr ] mean_rr = np . mean ( rr ) mean_hr = 60 / mean_rr if rr_units == 'samples' : mean_hr = mean_hr * fs re...
Compute mean heart rate in beats per minute from a set of rr intervals . Returns 0 if rr is empty .
27,417
def compare_annotations ( ref_sample , test_sample , window_width , signal = None ) : comparitor = Comparitor ( ref_sample = ref_sample , test_sample = test_sample , window_width = window_width , signal = signal ) comparitor . compare ( ) return comparitor
Compare a set of reference annotation locations against a set of test annotation locations .
27,418
def benchmark_mitdb ( detector , verbose = False , print_results = False ) : record_list = get_record_list ( 'mitdb' ) n_records = len ( record_list ) args = zip ( record_list , n_records * [ detector ] , n_records * [ verbose ] ) with Pool ( cpu_count ( ) - 1 ) as p : comparitors = p . starmap ( benchmark_mitdb_record...
Benchmark a qrs detector against mitdb s records .
27,419
def benchmark_mitdb_record ( rec , detector , verbose ) : sig , fields = rdsamp ( rec , pb_dir = 'mitdb' , channels = [ 0 ] ) ann_ref = rdann ( rec , pb_dir = 'mitdb' , extension = 'atr' ) qrs_inds = detector ( sig = sig [ : , 0 ] , fs = fields [ 'fs' ] , verbose = verbose ) comparitor = compare_annotations ( ref_sampl...
Benchmark a single mitdb record
27,420
def _calc_stats ( self ) : self . matched_ref_inds = np . where ( self . matching_sample_nums != - 1 ) [ 0 ] self . unmatched_ref_inds = np . where ( self . matching_sample_nums == - 1 ) [ 0 ] self . matched_test_inds = self . matching_sample_nums [ self . matching_sample_nums != - 1 ] self . unmatched_test_inds = np ....
Calculate performance statistics after the two sets of annotations are compared .
27,421
def compare ( self ) : test_samp_num = 0 ref_samp_num = 0 while ref_samp_num < self . n_ref and test_samp_num < self . n_test : closest_samp_num , smallest_samp_diff = ( self . _get_closest_samp_num ( ref_samp_num , test_samp_num ) ) if ref_samp_num < self . n_ref - 1 : closest_samp_num_next , smallest_samp_diff_next =...
Main comparison function
27,422
def _get_closest_samp_num ( self , ref_samp_num , start_test_samp_num ) : if start_test_samp_num >= self . n_test : raise ValueError ( 'Invalid starting test sample number.' ) ref_samp = self . ref_sample [ ref_samp_num ] test_samp = self . test_sample [ start_test_samp_num ] samp_diff = ref_samp - test_samp closest_sa...
Return the closest testing sample number for the given reference sample number . Limit the search from start_test_samp_num .
27,423
def print_summary ( self ) : self . tp = len ( self . matched_ref_inds ) self . fp = self . n_test - self . tp self . fn = self . n_ref - self . tp self . specificity = self . tp / self . n_ref self . positive_predictivity = self . tp / self . n_test self . false_positive_rate = self . fp / self . n_test print ( '%d re...
Print summary metrics of the annotation comparisons .
27,424
def plot ( self , sig_style = '' , title = None , figsize = None , return_fig = False ) : fig = plt . figure ( figsize = figsize ) ax = fig . add_subplot ( 1 , 1 , 1 ) legend = [ 'Signal' , 'Matched Reference Annotations (%d/%d)' % ( self . tp , self . n_ref ) , 'Unmatched Reference Annotations (%d/%d)' % ( self . fn ,...
Plot the comparison of two sets of annotations possibly overlaid on their original signal .
27,425
def add_module ( self , module ) : if module in self . _modules : raise KeyError ( "module already added to this engine" ) ffi . lib . LLVMPY_AddModule ( self , module ) module . _owned = True self . _modules . add ( module )
Ownership of module is transferred to the execution engine
27,426
def remove_module ( self , module ) : with ffi . OutputString ( ) as outerr : if ffi . lib . LLVMPY_RemoveModule ( self , module , outerr ) : raise RuntimeError ( str ( outerr ) ) self . _modules . remove ( module ) module . _owned = False
Ownership of module is returned
27,427
def target_data ( self ) : if self . _td is not None : return self . _td ptr = ffi . lib . LLVMPY_GetExecutionEngineTargetData ( self ) self . _td = targets . TargetData ( ptr ) self . _td . _owned = True return self . _td
The TargetData for this execution engine .
27,428
def _find_module_ptr ( self , module_ptr ) : ptr = cast ( module_ptr , c_void_p ) . value for module in self . _modules : if cast ( module . _ptr , c_void_p ) . value == ptr : return module return None
Find the ModuleRef corresponding to the given pointer .
27,429
def set_object_cache ( self , notify_func = None , getbuffer_func = None ) : self . _object_cache_notify = notify_func self . _object_cache_getbuffer = getbuffer_func self . _object_cache = _ObjectCacheRef ( self ) ffi . lib . LLVMPY_SetObjectCache ( self , self . _object_cache )
Set the object cache notifyObjectCompiled and getBuffer callbacks to the given Python functions .
27,430
def _raw_object_cache_notify ( self , data ) : if self . _object_cache_notify is None : return module_ptr = data . contents . module_ptr buf_ptr = data . contents . buf_ptr buf_len = data . contents . buf_len buf = string_at ( buf_ptr , buf_len ) module = self . _find_module_ptr ( module_ptr ) if module is None : raise...
Low - level notify hook .
27,431
def _raw_object_cache_getbuffer ( self , data ) : if self . _object_cache_getbuffer is None : return module_ptr = data . contents . module_ptr module = self . _find_module_ptr ( module_ptr ) if module is None : raise RuntimeError ( "object compilation notification " "for unknown module %s" % ( module_ptr , ) ) buf = se...
Low - level getbuffer hook .
27,432
def position_before ( self , instr ) : self . _block = instr . parent self . _anchor = self . _block . instructions . index ( instr )
Position immediately before the given instruction . The current block is also changed to the instruction s basic block .
27,433
def position_after ( self , instr ) : self . _block = instr . parent self . _anchor = self . _block . instructions . index ( instr ) + 1
Position immediately after the given instruction . The current block is also changed to the instruction s basic block .
27,434
def resume ( self , landingpad ) : br = instructions . Branch ( self . block , "resume" , [ landingpad ] ) self . _set_terminator ( br ) return br
Resume an in - flight exception .
27,435
def asm ( self , ftype , asm , constraint , args , side_effect , name = '' ) : asm = instructions . InlineAsm ( ftype , asm , constraint , side_effect ) return self . call ( asm , args , name )
Inline assembler .
27,436
def extract_element ( self , vector , idx , name = '' ) : instr = instructions . ExtractElement ( self . block , vector , idx , name = name ) self . _insert ( instr ) return instr
Returns the value at position idx .
27,437
def functions ( self ) : return [ v for v in self . globals . values ( ) if isinstance ( v , values . Function ) ]
A list of functions declared or defined in this module .
27,438
def add_global ( self , globalvalue ) : assert globalvalue . name not in self . globals self . globals [ globalvalue . name ] = globalvalue
Add a new global value .
27,439
def sh2 ( cmd ) : p = Popen ( cmd , stdout = PIPE , shell = True , env = sub_environment ( ) ) out = p . communicate ( ) [ 0 ] retcode = p . returncode if retcode : raise CalledProcessError ( retcode , cmd ) else : return out . rstrip ( )
Execute command in a subshell return stdout .
27,440
def sh3 ( cmd ) : p = Popen ( cmd , stdout = PIPE , stderr = PIPE , shell = True , env = sub_environment ( ) ) out , err = p . communicate ( ) retcode = p . returncode if retcode : raise CalledProcessError ( retcode , cmd ) else : return out . rstrip ( ) , err . rstrip ( )
Execute command in a subshell return stdout stderr
27,441
def init_repo ( path ) : sh ( "git clone %s %s" % ( pages_repo , path ) ) here = os . getcwd ( ) cd ( path ) sh ( 'git checkout gh-pages' ) cd ( here )
clone the gh - pages repo if we haven t already .
27,442
def create_execution_engine ( ) : target = llvm . Target . from_default_triple ( ) target_machine = target . create_target_machine ( ) backing_mod = llvm . parse_assembly ( "" ) engine = llvm . create_mcjit_compiler ( backing_mod , target_machine ) return engine
Create an ExecutionEngine suitable for JIT code generation on the host CPU . The engine is reusable for an arbitrary number of modules .
27,443
def compile_ir ( engine , llvm_ir ) : mod = llvm . parse_assembly ( llvm_ir ) mod . verify ( ) engine . add_module ( mod ) engine . finalize_object ( ) engine . run_static_constructors ( ) return mod
Compile the LLVM IR string with the given engine . The compiled module object is returned .
27,444
def get_default_triple ( ) : with ffi . OutputString ( ) as out : ffi . lib . LLVMPY_GetDefaultTargetTriple ( out ) return str ( out )
Return the default target triple LLVM is configured to produce code for .
27,445
def get_element_offset ( self , ty , position ) : offset = ffi . lib . LLVMPY_OffsetOfElement ( self , ty , position ) if offset == - 1 : raise ValueError ( "Could not determined offset of {}th " "element of the type '{}'. Is it a struct type?" . format ( position , str ( ty ) ) ) return offset
Get byte offset of type s ty element at the given position
27,446
def create_target_machine ( self , cpu = '' , features = '' , opt = 2 , reloc = 'default' , codemodel = 'jitdefault' , jitdebug = False , printmc = False ) : assert 0 <= opt <= 3 assert reloc in RELOC assert codemodel in CODEMODEL triple = self . _triple if os . name == 'nt' and codemodel == 'jitdefault' : triple += '-...
Create a new TargetMachine for this target and the given options .
27,447
def _emit_to_memory ( self , module , use_object = False ) : with ffi . OutputString ( ) as outerr : mb = ffi . lib . LLVMPY_TargetMachineEmitToMemory ( self , module , int ( use_object ) , outerr ) if not mb : raise RuntimeError ( str ( outerr ) ) bufptr = ffi . lib . LLVMPY_GetBufferStart ( mb ) bufsz = ffi . lib . L...
Returns bytes of object code of the module .
27,448
def parse_assembly ( llvmir , context = None ) : if context is None : context = get_global_context ( ) llvmir = _encode_string ( llvmir ) strbuf = c_char_p ( llvmir ) with ffi . OutputString ( ) as errmsg : mod = ModuleRef ( ffi . lib . LLVMPY_ParseAssembly ( context , strbuf , errmsg ) , context ) if errmsg : mod . cl...
Create Module from a LLVM IR string
27,449
def as_bitcode ( self ) : ptr = c_char_p ( None ) size = c_size_t ( - 1 ) ffi . lib . LLVMPY_WriteBitcodeToString ( self , byref ( ptr ) , byref ( size ) ) if not ptr : raise MemoryError try : assert size . value >= 0 return string_at ( ptr , size . value ) finally : ffi . lib . LLVMPY_DisposeString ( ptr )
Return the module s LLVM bitcode as a bytes object .
27,450
def verify ( self ) : with ffi . OutputString ( ) as outmsg : if ffi . lib . LLVMPY_VerifyModule ( self , outmsg ) : raise RuntimeError ( str ( outmsg ) )
Verify the module IR s correctness . RuntimeError is raised on error .
27,451
def data_layout ( self ) : with ffi . OutputString ( owned = False ) as outmsg : ffi . lib . LLVMPY_GetDataLayout ( self , outmsg ) return str ( outmsg )
This module s data layout specification as a string .
27,452
def triple ( self ) : with ffi . OutputString ( owned = False ) as outmsg : ffi . lib . LLVMPY_GetTarget ( self , outmsg ) return str ( outmsg )
This module s target triple specification as a string .
27,453
def global_variables ( self ) : it = ffi . lib . LLVMPY_ModuleGlobalsIter ( self ) return _GlobalsIterator ( it , dict ( module = self ) )
Return an iterator over this module s global variables . The iterator will yield a ValueRef for each global variable .
27,454
def functions ( self ) : it = ffi . lib . LLVMPY_ModuleFunctionsIter ( self ) return _FunctionsIterator ( it , dict ( module = self ) )
Return an iterator over this module s functions . The iterator will yield a ValueRef for each function .
27,455
def struct_types ( self ) : it = ffi . lib . LLVMPY_ModuleTypesIter ( self ) return _TypesIterator ( it , dict ( module = self ) )
Return an iterator over the struct types defined in the module . The iterator will yield a TypeRef .
27,456
def set_option ( name , option ) : ffi . lib . LLVMPY_SetCommandLine ( _encode_string ( name ) , _encode_string ( option ) )
Set the given LLVM command - line option .
27,457
def _get_ll_pointer_type ( self , target_data , context = None ) : from . import Module , GlobalVariable from . . binding import parse_assembly if context is None : m = Module ( ) else : m = Module ( context = context ) foo = GlobalVariable ( m , self , name = "foo" ) with parse_assembly ( str ( m ) ) as llmod : return...
Convert this type object to an LLVM type .
27,458
def structure_repr ( self ) : ret = '{%s}' % ', ' . join ( [ str ( x ) for x in self . elements ] ) return self . _wrap_packed ( ret )
Return the LLVM IR for the structure representation
27,459
def get_declaration ( self ) : if self . is_opaque : out = "{strrep} = type opaque" . format ( strrep = str ( self ) ) else : out = "{strrep} = type {struct}" . format ( strrep = str ( self ) , struct = self . structure_repr ( ) ) return out
Returns the string for the declaration of the type
27,460
def close ( self ) : try : if not self . _closed and not self . _owned : self . _dispose ( ) finally : self . detach ( )
Close this object and do any required clean - up actions .
27,461
def detach ( self ) : if not self . _closed : del self . _as_parameter_ self . _closed = True self . _ptr = None
Detach the underlying LLVM resource without disposing of it .
27,462
def load_library_permanently ( filename ) : with ffi . OutputString ( ) as outerr : if ffi . lib . LLVMPY_LoadLibraryPermanently ( _encode_string ( filename ) , outerr ) : raise RuntimeError ( str ( outerr ) )
Load an external library
27,463
def find_win32_generator ( ) : cmake_dir = os . path . join ( here_dir , 'dummy' ) generators = [ ] if os . environ . get ( "CMAKE_GENERATOR" ) : generators . append ( os . environ . get ( "CMAKE_GENERATOR" ) ) vspat = re . compile ( r'Visual Studio (\d+)' ) def drop_old_vs ( g ) : m = vspat . match ( g ) if m is None ...
Find a suitable cmake generator under Windows .
27,464
def _escape_string ( text , _map = { } ) : if isinstance ( text , str ) : text = text . encode ( 'ascii' ) assert isinstance ( text , ( bytes , bytearray ) ) if not _map : for ch in range ( 256 ) : if ch in _VALID_CHARS : _map [ ch ] = chr ( ch ) else : _map [ ch ] = '\\%02x' % ch if six . PY2 : _map [ chr ( ch ) ] = _...
Escape the given bytestring for safe use as a LLVM array constant .
27,465
def bitcast ( self , typ ) : if typ == self . type : return self op = "bitcast ({0} {1} to {2})" . format ( self . type , self . get_reference ( ) , typ ) return FormattedConstant ( typ , op )
Bitcast this pointer constant to the given type .
27,466
def inttoptr ( self , typ ) : if not isinstance ( self . type , types . IntType ) : raise TypeError ( "can only call inttoptr() on integer constants, not '%s'" % ( self . type , ) ) if not isinstance ( typ , types . PointerType ) : raise TypeError ( "can only inttoptr() to pointer type, not '%s'" % ( typ , ) ) op = "in...
Cast this integer constant to the given pointer type .
27,467
def gep ( self , indices ) : if not isinstance ( self . type , types . PointerType ) : raise TypeError ( "can only call gep() on pointer constants, not '%s'" % ( self . type , ) ) outtype = self . type for i in indices : outtype = outtype . gep ( i ) strindices = [ "{0} {1}" . format ( idx . type , idx . get_reference ...
Call getelementptr on this pointer constant .
27,468
def literal_array ( cls , elems ) : tys = [ el . type for el in elems ] if len ( tys ) == 0 : raise ValueError ( "need at least one element" ) ty = tys [ 0 ] for other in tys : if ty != other : raise TypeError ( "all elements must have the same type" ) return cls ( types . ArrayType ( ty , len ( elems ) ) , elems )
Construct a literal array constant made of the given members .
27,469
def literal_struct ( cls , elems ) : tys = [ el . type for el in elems ] return cls ( types . LiteralStructType ( tys ) , elems )
Construct a literal structure constant made of the given members .
27,470
def insert_basic_block ( self , before , name = '' ) : blk = Block ( parent = self , name = name ) self . blocks . insert ( before , blk ) return blk
Insert block before
27,471
def replace ( self , old , new ) : if old . type != new . type : raise TypeError ( "new instruction has a different type" ) pos = self . instructions . index ( old ) self . instructions . remove ( old ) self . instructions . insert ( pos , new ) for bb in self . parent . basic_blocks : for instr in bb . instructions : ...
Replace an instruction
27,472
def get_function_cfg ( func , show_inst = True ) : assert func is not None if isinstance ( func , ir . Function ) : mod = parse_assembly ( str ( func . module ) ) func = mod . get_function ( func . name ) with ffi . OutputString ( ) as dotstr : ffi . lib . LLVMPY_WriteCFG ( func , dotstr , show_inst ) return str ( dots...
Return a string of the control - flow graph of the function in DOT format . If the input func is not a materialized function the module containing the function is parsed to create an actual LLVM module . The show_inst flag controls whether the instructions of each block are printed .
27,473
def view_dot_graph ( graph , filename = None , view = False ) : import graphviz as gv src = gv . Source ( graph ) if view : return src . render ( filename , view = view ) else : try : __IPYTHON__ except NameError : return src else : import IPython . display as display format = 'svg' return display . SVG ( data = src . ...
View the given DOT source . If view is True the image is rendered and viewed by the default application in the system . The file path of the output is returned . If view is False a graphviz . Source object is returned . If view is False and the environment is in a IPython session an IPython image object is returned and...
27,474
def element_type ( self ) : if not self . is_pointer : raise ValueError ( "Type {} is not a pointer" . format ( self ) ) return TypeRef ( ffi . lib . LLVMPY_GetElementType ( self ) )
Returns the pointed - to type . When the type is not a pointer raises exception .
27,475
def add_function_attribute ( self , attr ) : if not self . is_function : raise ValueError ( 'expected function value, got %s' % ( self . _kind , ) ) attrname = str ( attr ) attrval = ffi . lib . LLVMPY_GetEnumAttributeKindForName ( _encode_string ( attrname ) , len ( attrname ) ) if attrval == 0 : raise ValueError ( 'n...
Only works on function value
27,476
def attributes ( self ) : itr = iter ( ( ) ) if self . is_function : it = ffi . lib . LLVMPY_FunctionAttributesIter ( self ) itr = _AttributeListIterator ( it ) elif self . is_instruction : if self . opcode == 'call' : it = ffi . lib . LLVMPY_CallInstAttributesIter ( self ) itr = _AttributeListIterator ( it ) elif self...
Return an iterator over this value s attributes . The iterator will yield a string for each attribute .
27,477
def blocks ( self ) : if not self . is_function : raise ValueError ( 'expected function value, got %s' % ( self . _kind , ) ) it = ffi . lib . LLVMPY_FunctionBlocksIter ( self ) parents = self . _parents . copy ( ) parents . update ( function = self ) return _BlocksIterator ( it , parents )
Return an iterator over this function s blocks . The iterator will yield a ValueRef for each block .
27,478
def arguments ( self ) : if not self . is_function : raise ValueError ( 'expected function value, got %s' % ( self . _kind , ) ) it = ffi . lib . LLVMPY_FunctionArgumentsIter ( self ) parents = self . _parents . copy ( ) parents . update ( function = self ) return _ArgumentsIterator ( it , parents )
Return an iterator over this function s arguments . The iterator will yield a ValueRef for each argument .
27,479
def instructions ( self ) : if not self . is_block : raise ValueError ( 'expected block value, got %s' % ( self . _kind , ) ) it = ffi . lib . LLVMPY_BlockInstructionsIter ( self ) parents = self . _parents . copy ( ) parents . update ( block = self ) return _InstructionsIterator ( it , parents )
Return an iterator over this block s instructions . The iterator will yield a ValueRef for each instruction .
27,480
def operands ( self ) : if not self . is_instruction : raise ValueError ( 'expected instruction value, got %s' % ( self . _kind , ) ) it = ffi . lib . LLVMPY_InstructionOperandsIter ( self ) parents = self . _parents . copy ( ) parents . update ( instruction = self ) return _OperandsIterator ( it , parents )
Return an iterator over this instruction s operands . The iterator will yield a ValueRef for each operand .
27,481
def replace_all_calls ( mod , orig , repl ) : rc = ReplaceCalls ( orig , repl ) rc . visit ( mod ) return rc . calls
Replace all calls to orig to repl in module mod . Returns the references to the returned calls
27,482
def display ( self , image ) : assert ( image . mode == self . mode ) assert ( image . size == self . size ) image = self . preprocess ( image ) if self . framebuffer . redraw_required ( image ) : left , top , right , bottom = self . _apply_offsets ( self . framebuffer . bounding_box ) width = right - left height = bot...
Renders a 24 - bit RGB image to the Color OLED display .
27,483
def events_for_onchain_secretreveal ( target_state : TargetTransferState , channel_state : NettingChannelState , block_number : BlockNumber , block_hash : BlockHash , ) -> List [ Event ] : transfer = target_state . transfer expiration = transfer . lock . expiration safe_to_wait , _ = is_safe_to_wait ( expiration , chan...
Emits the event for revealing the secret on - chain if the transfer can not be settled off - chain .
27,484
def handle_inittarget ( state_change : ActionInitTarget , channel_state : NettingChannelState , pseudo_random_generator : random . Random , block_number : BlockNumber , ) -> TransitionResult [ TargetTransferState ] : transfer = state_change . transfer route = state_change . route assert channel_state . identifier == tr...
Handles an ActionInitTarget state change .
27,485
def handle_offchain_secretreveal ( target_state : TargetTransferState , state_change : ReceiveSecretReveal , channel_state : NettingChannelState , pseudo_random_generator : random . Random , block_number : BlockNumber , ) -> TransitionResult [ TargetTransferState ] : valid_secret = is_valid_secret_reveal ( state_change...
Validates and handles a ReceiveSecretReveal state change .
27,486
def handle_onchain_secretreveal ( target_state : TargetTransferState , state_change : ContractReceiveSecretReveal , channel_state : NettingChannelState , ) -> TransitionResult [ TargetTransferState ] : valid_secret = is_valid_secret_reveal ( state_change = state_change , transfer_secrethash = target_state . transfer . ...
Validates and handles a ContractReceiveSecretReveal state change .
27,487
def handle_unlock ( target_state : TargetTransferState , state_change : ReceiveUnlock , channel_state : NettingChannelState , ) -> TransitionResult [ TargetTransferState ] : balance_proof_sender = state_change . balance_proof . sender is_valid , events , _ = channel . handle_unlock ( channel_state , state_change , ) ne...
Handles a ReceiveUnlock state change .
27,488
def handle_block ( target_state : TargetTransferState , channel_state : NettingChannelState , block_number : BlockNumber , block_hash : BlockHash , ) -> TransitionResult [ TargetTransferState ] : transfer = target_state . transfer events : List [ Event ] = list ( ) lock = transfer . lock secret_known = channel . is_sec...
After Raiden learns about a new block this function must be called to handle expiration of the hash time lock .
27,489
def state_transition ( target_state : Optional [ TargetTransferState ] , state_change : StateChange , channel_state : NettingChannelState , pseudo_random_generator : random . Random , block_number : BlockNumber , ) -> TransitionResult [ TargetTransferState ] : iteration = TransitionResult ( target_state , list ( ) ) if...
State machine for the target node of a mediated transfer .
27,490
def wrap ( data ) : try : cmdid = data [ 0 ] except IndexError : log . warning ( 'data is empty' ) return None try : message_type = CMDID_MESSAGE [ cmdid ] except KeyError : log . error ( 'unknown cmdid %s' , cmdid ) return None try : message = message_type ( data ) except ValueError : log . error ( 'trying to decode i...
Try to decode data into a message might return None if the data is invalid .
27,491
def solidity_resolve_address ( hex_code , library_symbol , library_address ) : if library_address . startswith ( '0x' ) : raise ValueError ( 'Address should not contain the 0x prefix' ) try : decode_hex ( library_address ) except TypeError : raise ValueError ( 'library_address contains invalid characters, it must be he...
Change the bytecode to use the given library address .
27,492
def solidity_library_symbol ( library_name ) : length = min ( len ( library_name ) , 36 ) library_piece = library_name [ : length ] hold_piece = '_' * ( 36 - length ) return '__{library}{hold}__' . format ( library = library_piece , hold = hold_piece , )
Return the symbol used in the bytecode to represent the library_name .
27,493
def compile_files_cwd ( * args , ** kwargs ) : compile_wd = os . path . commonprefix ( args [ 0 ] ) if os . path . isfile ( compile_wd ) : compile_wd = os . path . dirname ( compile_wd ) if compile_wd [ - 1 ] != '/' : compile_wd += '/' file_list = [ x . replace ( compile_wd , '' ) for x in args [ 0 ] ] cwd = os . getcw...
change working directory to contract s dir in order to avoid symbol name conflicts
27,494
def get_privkey ( self , address : AddressHex , password : str ) -> PrivateKey : address = add_0x_prefix ( address ) . lower ( ) if not self . address_in_keystore ( address ) : raise ValueError ( 'Keystore file not found for %s' % address ) with open ( self . accounts [ address ] ) as data_file : data = json . load ( d...
Find the keystore file for an account unlock it and get the private key
27,495
def load ( cls , path : str , password : str = None ) -> 'Account' : with open ( path ) as f : keystore = json . load ( f ) if not check_keystore_json ( keystore ) : raise ValueError ( 'Invalid keystore file' ) return Account ( keystore , password , path = path )
Load an account from a keystore file .
27,496
def dump ( self , include_address = True , include_id = True ) -> str : d = { 'crypto' : self . keystore [ 'crypto' ] , 'version' : self . keystore [ 'version' ] , } if include_address and self . address is not None : d [ 'address' ] = remove_0x_prefix ( encode_hex ( self . address ) ) if include_id and self . uuid is ...
Dump the keystore for later disk storage .
27,497
def unlock ( self , password : str ) : if self . locked : self . _privkey = decode_keyfile_json ( self . keystore , password . encode ( 'UTF-8' ) ) self . locked = False self . _fill_address ( )
Unlock the account with a password .
27,498
def uuid ( self , value ) : if value is not None : self . keystore [ 'id' ] = value elif 'id' in self . keystore : self . keystore . pop ( 'id' )
Set the UUID . Set it to None in order to remove it .
27,499
def recover_chain_id ( storage : SQLiteStorage ) -> ChainID : action_init_chain = json . loads ( storage . get_state_changes ( limit = 1 , offset = 0 ) [ 0 ] ) assert action_init_chain [ '_type' ] == 'raiden.transfer.state_change.ActionInitChain' return action_init_chain [ 'chain_id' ]
We can reasonably assume that any database has only one value for chain_id at this point in time .