idx
int64
0
63k
question
stringlengths
53
5.28k
target
stringlengths
5
805
61,900
def put_object ( self , url , container , container_object , local_object , object_headers , meta = None ) : headers , container_uri = self . _return_base_data ( url = url , container = container , container_object = container_object , container_headers = object_headers , object_headers = meta ) return self . _putter ( uri = container_uri , headers = headers , local_object = local_object )
This is the Sync method which uploads files to the swift repository
61,901
def get_items ( self , url , container , container_object , local_object ) : headers , container_uri = self . _return_base_data ( url = url , container = container , container_object = container_object ) return self . _getter ( uri = container_uri , headers = headers , local_object = local_object )
Get an objects from a container .
61,902
def delete_items ( self , url , container , container_object = None ) : headers , container_uri = self . _return_base_data ( url = url , container = container , container_object = container_object ) return self . _deleter ( uri = container_uri , headers = headers )
Deletes an objects in a container .
61,903
def _get_bmu ( self , activations ) : if self . argfunc == 'argmax' : activations = - activations sort = np . argsort ( activations , 1 ) return sort . argsort ( )
Get indices of bmus sorted by their distance from input .
61,904
def _calculate_influence ( self , influence_lambda ) : return np . exp ( - np . arange ( self . num_neurons ) / influence_lambda ) [ : , None ]
Calculate the ranking influence .
61,905
def _update_params ( self , constants ) : constants = np . max ( np . min ( constants , 1 ) ) self . params [ 'r' ] [ 'value' ] = max ( [ self . params [ 'r' ] [ 'value' ] , constants ] ) epsilon = constants / self . params [ 'r' ] [ 'value' ] influence = self . _calculate_influence ( epsilon ) return influence * epsilon
Update the params .
61,906
def _shuffle_items ( items , bucket_key = None , disable = None , seed = None , session = None ) : if seed is not None : random . seed ( seed ) if not bucket_key and not disable : random . shuffle ( items ) return def get_full_bucket_key ( item ) : assert bucket_key or disable if bucket_key and disable : return ItemKey ( bucket = bucket_key ( item , session ) , disabled = disable ( item , session ) ) elif disable : return ItemKey ( disabled = disable ( item , session ) ) else : return ItemKey ( bucket = bucket_key ( item , session ) ) buckets = OrderedDict ( ) for item in items : full_bucket_key = get_full_bucket_key ( item ) if full_bucket_key not in buckets : buckets [ full_bucket_key ] = [ ] buckets [ full_bucket_key ] . append ( item ) bucket_keys = list ( buckets . keys ( ) ) for full_bucket_key in buckets . keys ( ) : if full_bucket_key . bucket == FAILED_FIRST_LAST_FAILED_BUCKET_KEY : continue if not full_bucket_key . disabled : random . shuffle ( buckets [ full_bucket_key ] ) if bucket_keys and bucket_keys [ 0 ] . bucket == FAILED_FIRST_LAST_FAILED_BUCKET_KEY : new_bucket_keys = list ( buckets . keys ( ) ) [ 1 : ] random . shuffle ( new_bucket_keys ) new_bucket_keys . insert ( 0 , bucket_keys [ 0 ] ) else : new_bucket_keys = list ( buckets . keys ( ) ) random . shuffle ( new_bucket_keys ) items [ : ] = [ item for bk in new_bucket_keys for item in buckets [ bk ] ] return
Shuffles a list of items in place .
61,907
def bucket_type_key ( bucket_type ) : def decorator ( f ) : @ functools . wraps ( f ) def wrapped ( item , session ) : key = f ( item ) if session is not None : for handler in session . random_order_bucket_type_key_handlers : key = handler ( item , key ) return key bucket_type_keys [ bucket_type ] = wrapped return wrapped return decorator
Registers a function that calculates test item key for the specified bucket type .
61,908
def unsigned_request ( self , path , payload = None ) : headers = { "content-type" : "application/json" , "accept" : "application/json" , "X-accept-version" : "2.0.0" } try : if payload : response = requests . post ( self . uri + path , verify = self . verify , data = json . dumps ( payload ) , headers = headers ) else : response = requests . get ( self . uri + path , verify = self . verify , headers = headers ) except Exception as pro : raise BitPayConnectionError ( 'Connection refused' ) return response
generic bitpay usigned wrapper passing a payload will do a POST otherwise a GET
61,909
def main ( ) : try : device = AlarmDecoder ( SerialDevice ( interface = SERIAL_DEVICE ) ) device . on_rfx_message += handle_rfx with device . open ( baudrate = BAUDRATE ) : while True : time . sleep ( 1 ) except Exception as ex : print ( 'Exception:' , ex )
Example application that watches for an event from a specific RF device .
61,910
def handle_rfx ( sender , message ) : if message . serial_number == RF_DEVICE_SERIAL_NUMBER and message . loop [ 0 ] == True : print ( message . serial_number , 'triggered loop #1' )
Handles RF message events from the AlarmDecoder .
61,911
def fire ( self , * args , ** kwargs ) : for func in self . _getfunctionlist ( ) : if type ( func ) == EventHandler : func . fire ( * args , ** kwargs ) else : func ( self . obj , * args , ** kwargs )
Fire event and call all handler functions
61,912
def main ( ) : try : device = AlarmDecoder ( SerialDevice ( interface = SERIAL_DEVICE ) ) device . on_message += handle_message with device . open ( baudrate = BAUDRATE ) : while True : time . sleep ( 1 ) except Exception as ex : print ( 'Exception:' , ex )
Example application that opens a serial device and prints messages to the terminal .
61,913
def _init_ssl ( self ) : if not have_openssl : raise ImportError ( 'SSL sockets have been disabled due to missing requirement: pyopenssl.' ) try : ctx = SSL . Context ( SSL . TLSv1_METHOD ) if isinstance ( self . ssl_key , crypto . PKey ) : ctx . use_privatekey ( self . ssl_key ) else : ctx . use_privatekey_file ( self . ssl_key ) if isinstance ( self . ssl_certificate , crypto . X509 ) : ctx . use_certificate ( self . ssl_certificate ) else : ctx . use_certificate_file ( self . ssl_certificate ) if isinstance ( self . ssl_ca , crypto . X509 ) : store = ctx . get_cert_store ( ) store . add_cert ( self . ssl_ca ) else : ctx . load_verify_locations ( self . ssl_ca , None ) verify_method = SSL . VERIFY_PEER if ( self . _ssl_allow_self_signed ) : verify_method = SSL . VERIFY_NONE ctx . set_verify ( verify_method , self . _verify_ssl_callback ) self . _device = SSL . Connection ( ctx , self . _device ) except SSL . Error as err : raise CommError ( 'Error setting up SSL connection.' , err )
Initializes our device as an SSL connection .
61,914
def get_best_frequencies ( self ) : return self . freq [ self . best_local_optima ] , self . per [ self . best_local_optima ]
Returns the best n_local_max frequencies
61,915
def finetune_best_frequencies ( self , fresolution = 1e-5 , n_local_optima = 10 ) : local_optima_index = [ ] for k in range ( 1 , len ( self . per ) - 1 ) : if self . per [ k - 1 ] < self . per [ k ] and self . per [ k + 1 ] < self . per [ k ] : local_optima_index . append ( k ) local_optima_index = np . array ( local_optima_index ) if ( len ( local_optima_index ) < n_local_optima ) : print ( "Warning: Not enough local maxima found in the periodogram, skipping finetuning" ) return best_local_optima = local_optima_index [ np . argsort ( self . per [ local_optima_index ] ) ] [ : : - 1 ] if n_local_optima > 0 : best_local_optima = best_local_optima [ : n_local_optima ] else : best_local_optima = best_local_optima [ 0 ] for j in range ( n_local_optima ) : freq_fine = self . freq [ best_local_optima [ j ] ] - self . fres_grid for k in range ( 0 , int ( 2.0 * self . fres_grid / fresolution ) ) : cost = self . compute_metric ( freq_fine ) if cost > self . per [ best_local_optima [ j ] ] : self . per [ best_local_optima [ j ] ] = cost self . freq [ best_local_optima [ j ] ] = freq_fine freq_fine += fresolution idx = np . argsort ( self . per [ best_local_optima ] ) [ : : - 1 ] if n_local_optima > 0 : self . best_local_optima = best_local_optima [ idx ] else : self . best_local_optima = best_local_optima
Computes the selected criterion over a grid of frequencies around a specified amount of local optima of the periodograms . This function is intended for additional fine tuning of the results obtained with grid_search
61,916
def update ( self , message ) : if message . version == 1 : if message . event_type == 'ALARM_PANIC' : self . _alarmdecoder . _update_panic_status ( True ) elif message . event_type == 'CANCEL' : self . _alarmdecoder . _update_panic_status ( False ) elif message . version == 2 : source = message . event_source if source == LRR_EVENT_TYPE . CID : self . _handle_cid_message ( message ) elif source == LRR_EVENT_TYPE . DSC : self . _handle_dsc_message ( message ) elif source == LRR_EVENT_TYPE . ADEMCO : self . _handle_ademco_message ( message ) elif source == LRR_EVENT_TYPE . ALARMDECODER : self . _handle_alarmdecoder_message ( message ) elif source == LRR_EVENT_TYPE . UNKNOWN : self . _handle_unknown_message ( message ) else : pass
Updates the states in the primary AlarmDecoder object based on the LRR message provided .
61,917
def _handle_cid_message ( self , message ) : status = self . _get_event_status ( message ) if status is None : return if message . event_code in LRR_FIRE_EVENTS : if message . event_code == LRR_CID_EVENT . OPENCLOSE_CANCEL_BY_USER : status = False self . _alarmdecoder . _update_fire_status ( status = status ) if message . event_code in LRR_ALARM_EVENTS : kwargs = { } field_name = 'zone' if not status : field_name = 'user' kwargs [ field_name ] = int ( message . event_data ) self . _alarmdecoder . _update_alarm_status ( status = status , ** kwargs ) if message . event_code in LRR_POWER_EVENTS : self . _alarmdecoder . _update_power_status ( status = status ) if message . event_code in LRR_BYPASS_EVENTS : self . _alarmdecoder . _update_zone_bypass_status ( status = status , zone = int ( message . event_data ) ) if message . event_code in LRR_BATTERY_EVENTS : self . _alarmdecoder . _update_battery_status ( status = status ) if message . event_code in LRR_PANIC_EVENTS : if message . event_code == LRR_CID_EVENT . OPENCLOSE_CANCEL_BY_USER : status = False self . _alarmdecoder . _update_panic_status ( status = status ) if message . event_code in LRR_ARM_EVENTS : status_stay = ( message . event_status == LRR_EVENT_STATUS . RESTORE and message . event_code in LRR_STAY_EVENTS ) if status_stay : status = False else : status = not status self . _alarmdecoder . _update_armed_status ( status = status , status_stay = status_stay )
Handles ContactID LRR events .
61,918
def _get_event_status ( self , message ) : status = None if message . event_status == LRR_EVENT_STATUS . TRIGGER : status = True elif message . event_status == LRR_EVENT_STATUS . RESTORE : status = False return status
Retrieves the boolean status of an LRR message .
61,919
def find_all ( pattern = None ) : devices = [ ] try : if pattern : devices = serial . tools . list_ports . grep ( pattern ) else : devices = serial . tools . list_ports . comports ( ) except serial . SerialException as err : raise CommError ( 'Error enumerating serial devices: {0}' . format ( str ( err ) ) , err ) return devices
Returns all serial ports present .
61,920
def _parse_message ( self , data ) : match = self . _regex . match ( str ( data ) ) if match is None : raise InvalidMessageError ( 'Received invalid message: {0}' . format ( data ) ) header , self . bitfield , self . numeric_code , self . panel_data , alpha = match . group ( 1 , 2 , 3 , 4 , 5 ) is_bit_set = lambda bit : not self . bitfield [ bit ] == "0" self . ready = is_bit_set ( 1 ) self . armed_away = is_bit_set ( 2 ) self . armed_home = is_bit_set ( 3 ) self . backlight_on = is_bit_set ( 4 ) self . programming_mode = is_bit_set ( 5 ) self . beeps = int ( self . bitfield [ 6 ] , 16 ) self . zone_bypassed = is_bit_set ( 7 ) self . ac_power = is_bit_set ( 8 ) self . chime_on = is_bit_set ( 9 ) self . alarm_event_occurred = is_bit_set ( 10 ) self . alarm_sounding = is_bit_set ( 11 ) self . battery_low = is_bit_set ( 12 ) self . entry_delay_off = is_bit_set ( 13 ) self . fire_alarm = is_bit_set ( 14 ) self . check_zone = is_bit_set ( 15 ) self . perimeter_only = is_bit_set ( 16 ) self . system_fault = is_bit_set ( 17 ) if self . bitfield [ 18 ] in list ( PANEL_TYPES ) : self . panel_type = PANEL_TYPES [ self . bitfield [ 18 ] ] self . text = alpha . strip ( '"' ) self . mask = int ( self . panel_data [ 3 : 3 + 8 ] , 16 ) if self . panel_type in ( ADEMCO , DSC ) : if int ( self . panel_data [ 19 : 21 ] , 16 ) & 0x01 > 0 : self . cursor_location = int ( self . panel_data [ 21 : 23 ] , 16 )
Parse the message from the device .
61,921
def parse_numeric_code ( self , force_hex = False ) : code = None got_error = False if not force_hex : try : code = int ( self . numeric_code ) except ValueError : got_error = True if force_hex or got_error : try : code = int ( self . numeric_code , 16 ) except ValueError : raise return code
Parses and returns the numeric code as an integer .
61,922
def LoadCHM ( self , archiveName ) : if self . filename is not None : self . CloseCHM ( ) self . file = chmlib . chm_open ( archiveName ) if self . file is None : return 0 self . filename = archiveName self . GetArchiveInfo ( ) return 1
Loads a CHM archive . This function will also call GetArchiveInfo to obtain information such as the index file name and the topics file . It returns 1 on success and 0 if it fails .
61,923
def CloseCHM ( self ) : if self . filename is not None : chmlib . chm_close ( self . file ) self . file = None self . filename = '' self . title = "" self . home = "/" self . index = None self . topics = None self . encoding = None
Closes the CHM archive . This function will close the CHM file if it is open . All variables are also reset .
61,924
def GetTopicsTree ( self ) : if self . topics is None : return None if self . topics : res , ui = chmlib . chm_resolve_object ( self . file , self . topics ) if ( res != chmlib . CHM_RESOLVE_SUCCESS ) : return None size , text = chmlib . chm_retrieve_object ( self . file , ui , 0l , ui . length ) if ( size == 0 ) : sys . stderr . write ( 'GetTopicsTree: file size = 0\n' ) return None return text
Reads and returns the topics tree . This auxiliary function reads and returns the topics tree file contents for the CHM archive .
61,925
def GetIndex ( self ) : if self . index is None : return None if self . index : res , ui = chmlib . chm_resolve_object ( self . file , self . index ) if ( res != chmlib . CHM_RESOLVE_SUCCESS ) : return None size , text = chmlib . chm_retrieve_object ( self . file , ui , 0l , ui . length ) if ( size == 0 ) : sys . stderr . write ( 'GetIndex: file size = 0\n' ) return None return text
Reads and returns the index tree . This auxiliary function reads and returns the index tree file contents for the CHM archive .
61,926
def ResolveObject ( self , document ) : if self . file : path = os . path . abspath ( document ) return chmlib . chm_resolve_object ( self . file , path ) else : return ( 1 , None )
Tries to locate a document in the archive . This function tries to locate the document inside the archive . It returns a tuple where the first element is zero if the function was successful and the second is the UnitInfo for that document . The UnitInfo is used to retrieve the document contents
61,927
def RetrieveObject ( self , ui , start = - 1 , length = - 1 ) : if self . file and ui : if length == - 1 : len = ui . length else : len = length if start == - 1 : st = 0l else : st = long ( start ) return chmlib . chm_retrieve_object ( self . file , ui , st , len ) else : return ( 0 , '' )
Retrieves the contents of a document . This function takes a UnitInfo and two optional arguments the first being the start address and the second is the length . These define the amount of data to be read from the archive .
61,928
def Search ( self , text , wholewords = 0 , titleonly = 0 ) : if text and text != '' and self . file : return extra . search ( self . file , text , wholewords , titleonly ) else : return None
Performs full - text search on the archive . The first parameter is the word to look for the second indicates if the search should be for whole words only and the third parameter indicates if the search should be restricted to page titles . This method will return a tuple the first item indicating if the search results were partial and the second item being a dictionary containing the results .
61,929
def GetEncoding ( self ) : if self . encoding : vals = string . split ( self . encoding , ',' ) if len ( vals ) > 2 : try : return charset_table [ int ( vals [ 2 ] ) ] except KeyError : pass return None
Returns a string that can be used with the codecs python package to encode or decode the files in the chm archive . If an error is found or if it is not possible to find the encoding None is returned .
61,930
def main ( ) : try : device = AlarmDecoder ( SocketDevice ( interface = ( HOSTNAME , PORT ) ) ) device . on_message += handle_message with device . open ( ) : while True : time . sleep ( 1 ) except Exception as ex : print ( 'Exception:' , ex )
Example application that opens a device that has been exposed to the network with ser2sock or similar serial - to - IP software .
61,931
def _parse_message ( self , data ) : try : header , values = data . split ( ':' ) address , channel , value = values . split ( ',' ) self . address = int ( address ) self . channel = int ( channel ) self . value = int ( value ) except ValueError : raise InvalidMessageError ( 'Received invalid message: {0}' . format ( data ) ) if header == '!EXP' : self . type = ExpanderMessage . ZONE elif header == '!REL' : self . type = ExpanderMessage . RELAY else : raise InvalidMessageError ( 'Unknown expander message header: {0}' . format ( data ) )
Parse the raw message from the device .
61,932
def get_event_description ( event_type , event_code ) : description = 'Unknown' lookup_map = LRR_TYPE_MAP . get ( event_type , None ) if lookup_map is not None : description = lookup_map . get ( event_code , description ) return description
Retrieves the human - readable description of an LRR event .
61,933
def get_event_source ( prefix ) : source = LRR_EVENT_TYPE . UNKNOWN if prefix == 'CID' : source = LRR_EVENT_TYPE . CID elif prefix == 'DSC' : source = LRR_EVENT_TYPE . DSC elif prefix == 'AD2' : source = LRR_EVENT_TYPE . ALARMDECODER elif prefix == 'ADEMCO' : source = LRR_EVENT_TYPE . ADEMCO return source
Retrieves the LRR_EVENT_TYPE corresponding to the prefix provided . abs
61,934
def send ( self , data ) : if self . _device : if isinstance ( data , str ) : data = str . encode ( data ) if sys . version_info < ( 3 , ) : if isinstance ( data , unicode ) : data = bytes ( data ) self . _device . write ( data )
Sends data to the AlarmDecoder _ device .
61,935
def get_config_string ( self ) : config_entries = [ ] config_entries . append ( ( 'ADDRESS' , '{0}' . format ( self . address ) ) ) config_entries . append ( ( 'CONFIGBITS' , '{0:x}' . format ( self . configbits ) ) ) config_entries . append ( ( 'MASK' , '{0:x}' . format ( self . address_mask ) ) ) config_entries . append ( ( 'EXP' , '' . join ( [ 'Y' if z else 'N' for z in self . emulate_zone ] ) ) ) config_entries . append ( ( 'REL' , '' . join ( [ 'Y' if r else 'N' for r in self . emulate_relay ] ) ) ) config_entries . append ( ( 'LRR' , 'Y' if self . emulate_lrr else 'N' ) ) config_entries . append ( ( 'DEDUPLICATE' , 'Y' if self . deduplicate else 'N' ) ) config_entries . append ( ( 'MODE' , list ( PANEL_TYPES ) [ list ( PANEL_TYPES . values ( ) ) . index ( self . mode ) ] ) ) config_entries . append ( ( 'COM' , 'Y' if self . emulate_com else 'N' ) ) config_string = '&' . join ( [ '=' . join ( t ) for t in config_entries ] ) return '&' . join ( [ '=' . join ( t ) for t in config_entries ] )
Build a configuration string that s compatible with the AlarmDecoder configuration command from the current values in the object .
61,936
def fault_zone ( self , zone , simulate_wire_problem = False ) : if isinstance ( zone , tuple ) : expander_idx , channel = zone zone = self . _zonetracker . expander_to_zone ( expander_idx , channel ) status = 2 if simulate_wire_problem else 1 self . send ( "L{0:02}{1}\r" . format ( zone , status ) )
Faults a zone if we are emulating a zone expander .
61,937
def _wire_events ( self ) : self . _device . on_open += self . _on_open self . _device . on_close += self . _on_close self . _device . on_read += self . _on_read self . _device . on_write += self . _on_write self . _zonetracker . on_fault += self . _on_zone_fault self . _zonetracker . on_restore += self . _on_zone_restore
Wires up the internal device events .
61,938
def _handle_message ( self , data ) : try : data = data . decode ( 'utf-8' ) except : raise InvalidMessageError ( 'Decode failed for message: {0}' . format ( data ) ) if data is not None : data = data . lstrip ( '\0' ) if data is None or data == '' : raise InvalidMessageError ( ) msg = None header = data [ 0 : 4 ] if header [ 0 ] != '!' or header == '!KPM' : msg = self . _handle_keypad_message ( data ) elif header == '!EXP' or header == '!REL' : msg = self . _handle_expander_message ( data ) elif header == '!RFX' : msg = self . _handle_rfx ( data ) elif header == '!LRR' : msg = self . _handle_lrr ( data ) elif header == '!AUI' : msg = self . _handle_aui ( data ) elif data . startswith ( '!Ready' ) : self . on_boot ( ) elif data . startswith ( '!CONFIG' ) : self . _handle_config ( data ) elif data . startswith ( '!VER' ) : self . _handle_version ( data ) elif data . startswith ( '!Sending' ) : self . _handle_sending ( data ) return msg
Parses keypad messages from the panel .
61,939
def _handle_keypad_message ( self , data ) : msg = Message ( data ) if self . _internal_address_mask & msg . mask > 0 : if not self . _ignore_message_states : self . _update_internal_states ( msg ) self . on_message ( message = msg ) return msg
Handle keypad messages .
61,940
def _handle_expander_message ( self , data ) : msg = ExpanderMessage ( data ) self . _update_internal_states ( msg ) self . on_expander_message ( message = msg ) return msg
Handle expander messages .
61,941
def _handle_rfx ( self , data ) : msg = RFMessage ( data ) self . on_rfx_message ( message = msg ) return msg
Handle RF messages .
61,942
def _handle_lrr ( self , data ) : msg = LRRMessage ( data ) if not self . _ignore_lrr_states : self . _lrr_system . update ( msg ) self . on_lrr_message ( message = msg ) return msg
Handle Long Range Radio messages .
61,943
def _handle_aui ( self , data ) : msg = AUIMessage ( data ) self . on_aui_message ( message = msg ) return msg
Handle AUI messages .
61,944
def _handle_version ( self , data ) : _ , version_string = data . split ( ':' ) version_parts = version_string . split ( ',' ) self . serial_number = version_parts [ 0 ] self . version_number = version_parts [ 1 ] self . version_flags = version_parts [ 2 ]
Handles received version data .
61,945
def _handle_config ( self , data ) : _ , config_string = data . split ( '>' ) for setting in config_string . split ( '&' ) : key , val = setting . split ( '=' ) if key == 'ADDRESS' : self . address = int ( val ) elif key == 'CONFIGBITS' : self . configbits = int ( val , 16 ) elif key == 'MASK' : self . address_mask = int ( val , 16 ) elif key == 'EXP' : self . emulate_zone = [ val [ z ] == 'Y' for z in list ( range ( 5 ) ) ] elif key == 'REL' : self . emulate_relay = [ val [ r ] == 'Y' for r in list ( range ( 4 ) ) ] elif key == 'LRR' : self . emulate_lrr = ( val == 'Y' ) elif key == 'DEDUPLICATE' : self . deduplicate = ( val == 'Y' ) elif key == 'MODE' : self . mode = PANEL_TYPES [ val ] elif key == 'COM' : self . emulate_com = ( val == 'Y' ) self . on_config_received ( )
Handles received configuration data .
61,946
def _handle_sending ( self , data ) : matches = re . match ( '^!Sending(\.{1,5})done.*' , data ) if matches is not None : good_send = False if len ( matches . group ( 1 ) ) < 5 : good_send = True self . on_sending_received ( status = good_send , message = data )
Handles results of a keypress send .
61,947
def _update_internal_states ( self , message ) : if isinstance ( message , Message ) and not self . _ignore_message_states : self . _update_armed_ready_status ( message ) self . _update_power_status ( message ) self . _update_chime_status ( message ) self . _update_alarm_status ( message ) self . _update_zone_bypass_status ( message ) self . _update_battery_status ( message ) self . _update_fire_status ( message ) elif isinstance ( message , ExpanderMessage ) : self . _update_expander_status ( message ) self . _update_zone_tracker ( message )
Updates internal device states .
61,948
def _update_power_status ( self , message = None , status = None ) : power_status = status if isinstance ( message , Message ) : power_status = message . ac_power if power_status is None : return if power_status != self . _power_status : self . _power_status , old_status = power_status , self . _power_status if old_status is not None : self . on_power_changed ( status = self . _power_status ) return self . _power_status
Uses the provided message to update the AC power state .
61,949
def _update_chime_status ( self , message = None , status = None ) : chime_status = status if isinstance ( message , Message ) : chime_status = message . chime_on if chime_status is None : return if chime_status != self . _chime_status : self . _chime_status , old_status = chime_status , self . _chime_status if old_status is not None : self . on_chime_changed ( status = self . _chime_status ) return self . _chime_status
Uses the provided message to update the Chime state .
61,950
def _update_alarm_status ( self , message = None , status = None , zone = None , user = None ) : alarm_status = status alarm_zone = zone if isinstance ( message , Message ) : alarm_status = message . alarm_sounding alarm_zone = message . parse_numeric_code ( ) if alarm_status != self . _alarm_status : self . _alarm_status , old_status = alarm_status , self . _alarm_status if old_status is not None or status is not None : if self . _alarm_status : self . on_alarm ( zone = alarm_zone ) else : self . on_alarm_restored ( zone = alarm_zone , user = user ) return self . _alarm_status
Uses the provided message to update the alarm state .
61,951
def _update_zone_bypass_status ( self , message = None , status = None , zone = None ) : bypass_status = status if isinstance ( message , Message ) : bypass_status = message . zone_bypassed if bypass_status is None : return old_bypass_status = self . _bypass_status . get ( zone , None ) if bypass_status != old_bypass_status : if bypass_status == False and zone is None : self . _bypass_status = { } else : self . _bypass_status [ zone ] = bypass_status if old_bypass_status is not None or message is None or ( old_bypass_status is None and bypass_status is True ) : self . on_bypass ( status = bypass_status , zone = zone ) return bypass_status
Uses the provided message to update the zone bypass state .
61,952
def _update_armed_status ( self , message = None , status = None , status_stay = None ) : arm_status = status stay_status = status_stay if isinstance ( message , Message ) : arm_status = message . armed_away stay_status = message . armed_home if arm_status is None or stay_status is None : return self . _armed_status , old_status = arm_status , self . _armed_status self . _armed_stay , old_stay = stay_status , self . _armed_stay if arm_status != old_status or stay_status != old_stay : if old_status is not None or message is None : if self . _armed_status or self . _armed_stay : self . on_arm ( stay = stay_status ) else : self . on_disarm ( ) return self . _armed_status or self . _armed_stay
Uses the provided message to update the armed state .
61,953
def _update_battery_status ( self , message = None , status = None ) : battery_status = status if isinstance ( message , Message ) : battery_status = message . battery_low if battery_status is None : return last_status , last_update = self . _battery_status if battery_status == last_status : self . _battery_status = ( last_status , time . time ( ) ) else : if battery_status is True or time . time ( ) > last_update + self . _battery_timeout : self . _battery_status = ( battery_status , time . time ( ) ) self . on_low_battery ( status = battery_status ) return self . _battery_status [ 0 ]
Uses the provided message to update the battery state .
61,954
def _update_fire_status ( self , message = None , status = None ) : fire_status = status last_status = self . _fire_status if isinstance ( message , Message ) : if self . mode == ADEMCO and message . text . startswith ( "SYSTEM" ) : fire_status = last_status else : fire_status = message . fire_alarm if fire_status is None : return if fire_status != self . _fire_status : self . _fire_status , old_status = fire_status , self . _fire_status if old_status is not None : self . on_fire ( status = self . _fire_status ) return self . _fire_status
Uses the provided message to update the fire alarm state .
61,955
def _update_panic_status ( self , status = None ) : if status is None : return if status != self . _panic_status : self . _panic_status , old_status = status , self . _panic_status if old_status is not None : self . on_panic ( status = self . _panic_status ) return self . _panic_status
Updates the panic status of the alarm panel .
61,956
def _update_expander_status ( self , message ) : if message . type == ExpanderMessage . RELAY : self . _relay_status [ ( message . address , message . channel ) ] = message . value self . on_relay_changed ( message = message ) return self . _relay_status [ ( message . address , message . channel ) ]
Uses the provided message to update the expander states .
61,957
def _on_open ( self , sender , * args , ** kwargs ) : self . get_config ( ) self . get_version ( ) self . on_open ( )
Internal handler for opening the device .
61,958
def _on_read ( self , sender , * args , ** kwargs ) : data = kwargs . get ( 'data' , None ) self . on_read ( data = data ) self . _handle_message ( data )
Internal handler for reading from the device .
61,959
def _on_write ( self , sender , * args , ** kwargs ) : self . on_write ( data = kwargs . get ( 'data' , None ) )
Internal handler for writing to the device .
61,960
def update ( self , message ) : if isinstance ( message , ExpanderMessage ) : zone = - 1 if message . type == ExpanderMessage . ZONE : zone = self . expander_to_zone ( message . address , message . channel , self . alarmdecoder_object . mode ) if zone != - 1 : status = Zone . CLEAR if message . value == 1 : status = Zone . FAULT elif message . value == 2 : status = Zone . CHECK try : self . _update_zone ( zone , status = status ) except IndexError : self . _add_zone ( zone , status = status , expander = True ) else : if message . ready and not message . text . startswith ( "SYSTEM" ) : for zone in self . _zones_faulted : self . _update_zone ( zone , Zone . CLEAR ) self . _last_zone_fault = 0 elif self . alarmdecoder_object . mode != DSC and ( message . check_zone or message . text . startswith ( "FAULT" ) or message . text . startswith ( "ALARM" ) ) : zone = message . parse_numeric_code ( ) if zone == 191 : zone_regex = re . compile ( '^CHECK (\d+).*$' ) match = zone_regex . match ( message . text ) if match is None : return zone = match . group ( 1 ) if zone in self . _zones_faulted : self . _update_zone ( zone ) self . _clear_zones ( zone ) else : status = Zone . FAULT if message . check_zone : status = Zone . CHECK self . _add_zone ( zone , status = status ) self . _zones_faulted . append ( zone ) self . _zones_faulted . sort ( ) self . _last_zone_fault = zone self . _clear_expired_zones ( )
Update zone statuses based on the current message .
61,961
def expander_to_zone ( self , address , channel , panel_type = ADEMCO ) : zone = - 1 if panel_type == ADEMCO : idx = address - 7 zone = address + channel + ( idx * 7 ) + 1 elif panel_type == DSC : zone = ( address * 8 ) + channel return zone
Convert an address and channel into a zone number .
61,962
def _clear_zones ( self , zone ) : cleared_zones = [ ] found_last_faulted = found_current = at_end = False it = iter ( self . _zones_faulted ) try : while not found_last_faulted : z = next ( it ) if z == self . _last_zone_fault : found_last_faulted = True break except StopIteration : at_end = True try : while not at_end and not found_current : z = next ( it ) if z == zone : found_current = True break else : cleared_zones += [ z ] except StopIteration : pass if not found_current : it = iter ( self . _zones_faulted ) try : while not found_current : z = next ( it ) if z == zone : found_current = True break else : cleared_zones += [ z ] except StopIteration : pass for z in cleared_zones : self . _update_zone ( z , Zone . CLEAR )
Clear all expired zones from our status list .
61,963
def _clear_expired_zones ( self ) : zones = [ ] for z in list ( self . _zones . keys ( ) ) : zones += [ z ] for z in zones : if self . _zones [ z ] . status != Zone . CLEAR and self . _zone_expired ( z ) : self . _update_zone ( z , Zone . CLEAR )
Update zone status for all expired zones .
61,964
def _add_zone ( self , zone , name = '' , status = Zone . CLEAR , expander = False ) : if not zone in self . _zones : self . _zones [ zone ] = Zone ( zone = zone , name = name , status = None , expander = expander ) self . _update_zone ( zone , status = status )
Adds a zone to the internal zone list .
61,965
def _update_zone ( self , zone , status = None ) : if not zone in self . _zones : raise IndexError ( 'Zone does not exist and cannot be updated: %d' , zone ) old_status = self . _zones [ zone ] . status if status is None : status = old_status self . _zones [ zone ] . status = status self . _zones [ zone ] . timestamp = time . time ( ) if status == Zone . CLEAR : if zone in self . _zones_faulted : self . _zones_faulted . remove ( zone ) self . on_restore ( zone = zone ) else : if old_status != status and status is not None : self . on_fault ( zone = zone )
Updates a zones status .
61,966
def _zone_expired ( self , zone ) : return ( time . time ( ) > self . _zones [ zone ] . timestamp + Zonetracker . EXPIRE ) and self . _zones [ zone ] . expander is False
Determine if a zone is expired or not .
61,967
def main ( ) : try : device = AlarmDecoder ( SerialDevice ( interface = SERIAL_DEVICE ) ) device . on_zone_fault += handle_zone_fault device . on_zone_restore += handle_zone_restore with device . open ( baudrate = BAUDRATE ) : last_update = time . time ( ) while True : if time . time ( ) - last_update > WAIT_TIME : last_update = time . time ( ) device . fault_zone ( TARGET_ZONE ) time . sleep ( 1 ) except Exception as ex : print ( 'Exception:' , ex )
Example application that periodically faults a virtual zone and then restores it .
61,968
def bytes_available ( device ) : bytes_avail = 0 if isinstance ( device , alarmdecoder . devices . SerialDevice ) : if hasattr ( device . _device , "in_waiting" ) : bytes_avail = device . _device . in_waiting else : bytes_avail = device . _device . inWaiting ( ) elif isinstance ( device , alarmdecoder . devices . SocketDevice ) : bytes_avail = 4096 return bytes_avail
Determines the number of bytes available for reading from an AlarmDecoder device
61,969
def bytes_hack ( buf ) : ub = None if sys . version_info > ( 3 , ) : ub = buf else : ub = bytes ( buf ) return ub
Hacky workaround for old installs of the library on systems without python - future that were keeping the 2to3 update from working after auto - update .
61,970
def read_firmware_file ( file_path ) : data_queue = deque ( ) with open ( file_path ) as firmware_handle : for line in firmware_handle : line = line . rstrip ( ) if line != '' and line [ 0 ] == ':' : data_queue . append ( line + "\r" ) return data_queue
Reads a firmware file into a dequeue for processing .
61,971
def read ( device ) : response = None bytes_avail = bytes_available ( device ) if isinstance ( device , alarmdecoder . devices . SerialDevice ) : response = device . _device . read ( bytes_avail ) elif isinstance ( device , alarmdecoder . devices . SocketDevice ) : response = device . _device . recv ( bytes_avail ) return response
Reads data from the specified device .
61,972
def upload ( device , file_path , progress_callback = None , debug = False ) : def progress_stage ( stage , ** kwargs ) : if progress_callback is not None : progress_callback ( stage , ** kwargs ) return stage if device is None : raise NoDeviceError ( 'No device specified for firmware upload.' ) fds = [ device . _device . fileno ( ) ] try : write_queue = read_firmware_file ( file_path ) except IOError as err : stage = progress_stage ( Firmware . STAGE_ERROR , error = str ( err ) ) return data_read = '' got_response = False running = True stage = progress_stage ( Firmware . STAGE_START ) if device . is_reader_alive ( ) : device . stop_reader ( ) while device . _read_thread . is_alive ( ) : stage = progress_stage ( Firmware . STAGE_WAITING ) time . sleep ( 0.5 ) time . sleep ( 3 ) try : while running : rr , wr , _ = select . select ( fds , fds , [ ] , 0.5 ) if len ( rr ) != 0 : response = Firmware . read ( device ) for c in response : if isinstance ( c , int ) : c = chr ( c ) if c == '\xff' or c == '\r' : if data_read . startswith ( "!sn" ) : stage = progress_stage ( Firmware . STAGE_BOOT ) elif data_read . startswith ( "!load" ) : got_response = True stage = progress_stage ( Firmware . STAGE_UPLOADING ) elif data_read == '!ce' : running = False raise UploadChecksumError ( "Checksum error in {0}" . format ( file_path ) ) elif data_read == '!no' : running = False raise UploadError ( "Incorrect data sent to bootloader." ) elif data_read == '!ok' : running = False stage = progress_stage ( Firmware . STAGE_DONE ) else : got_response = True if stage == Firmware . STAGE_UPLOADING : progress_stage ( stage ) data_read = '' elif c == '\n' : pass else : data_read += c if len ( wr ) != 0 : if stage in [ Firmware . STAGE_START , Firmware . STAGE_WAITING ] : device . write ( '=' ) stage = progress_stage ( Firmware . STAGE_WAITING_ON_LOADER ) elif stage == Firmware . STAGE_BOOT : device . write ( '=' ) stage = progress_stage ( Firmware . STAGE_LOAD ) elif stage == Firmware . STAGE_UPLOADING : if len ( write_queue ) > 0 and got_response == True : got_response = False device . write ( write_queue . popleft ( ) ) except UploadError as err : stage = progress_stage ( Firmware . STAGE_ERROR , error = str ( err ) ) else : stage = progress_stage ( Firmware . STAGE_DONE )
Uploads firmware to an AlarmDecoder _ device .
61,973
def create_device ( device_args ) : device = AlarmDecoder ( USBDevice . find ( device_args ) ) device . on_message += handle_message device . open ( ) return device
Creates an AlarmDecoder from the specified USB device arguments .
61,974
def encode ( cls , string , errors = 'strict' ) : if errors != 'strict' : raise UnicodeError ( 'Unsupported error handling {0}' . format ( errors ) ) unicode_string = cls . _ensure_unicode_string ( string ) encoded = unicode_string . translate ( cls . _encoding_table ) return encoded , len ( string )
Return the encoded version of a string .
61,975
def decode ( cls , string , errors = 'strict' ) : if errors != 'strict' : raise UnicodeError ( 'Unsupported error handling {0}' . format ( errors ) ) unicode_string = cls . _ensure_unicode_string ( string ) decoded = unicode_string . translate ( cls . _decoding_table ) return decoded , len ( string )
Return the decoded version of a string .
61,976
def search_function ( cls , encoding ) : if encoding == cls . _codec_name : return codecs . CodecInfo ( name = cls . _codec_name , encode = cls . encode , decode = cls . decode , ) return None
Search function to find rotunicode codec .
61,977
def _ensure_unicode_string ( string ) : if not isinstance ( string , six . text_type ) : string = string . decode ( 'utf-8' ) return string
Returns a unicode string for string .
61,978
def _get ( url , params = None ) : try : response = requests . get ( url , params = params ) response . raise_for_status ( ) try : return response . json ( ) except ValueError : return response . text except NameError : url = '{0}?{1}' . format ( url , urllib . urlencode ( params ) ) return json . loads ( urllib2 . urlopen ( url ) . read ( ) . decode ( ENCODING ) )
HTTP GET request .
61,979
def _post ( url , data , content_type , params = None ) : try : response = requests . post ( url , params = params , data = data , headers = { 'Content-Type' : content_type , } ) response . raise_for_status ( ) return response . json ( ) except NameError : url = '{0}?{1}' . format ( url , urllib . urlencode ( params ) ) req = urllib2 . Request ( url , data . encode ( ENCODING ) , { 'Content-Type' : content_type , } ) return json . loads ( urllib2 . urlopen ( req ) . read ( ) . decode ( ENCODING ) )
HTTP POST request .
61,980
def api ( self , name , url , ** kwargs ) : if name not in self . _apis : raise ValueError ( 'API name must be one of {0}, not {1!r}.' . format ( tuple ( self . _apis ) , name ) ) fields = kwargs . get ( 'fields' ) timeout = kwargs . get ( 'timeout' ) text = kwargs . get ( 'text' ) html = kwargs . get ( 'html' ) if text and html : raise ValueError ( u'Both `text` and `html` arguments provided!' ) params = { 'url' : url , 'token' : self . _token } if timeout : params [ 'timeout' ] = timeout if fields : if not isinstance ( fields , str ) : fields = ',' . join ( sorted ( fields ) ) params [ 'fields' ] = fields url = self . endpoint ( name ) if text or html : content_type = html and 'text/html' or 'text/plain' return self . _post ( url , text or html , content_type , params = params ) return self . _get ( url , params = params )
Generic API method .
61,981
def crawl ( self , urls , name = 'crawl' , api = 'analyze' , ** kwargs ) : if isinstance ( urls , list ) : urls = ' ' . join ( urls ) url = self . endpoint ( 'crawl' ) process_url = self . endpoint ( api ) params = { 'token' : self . _token , 'seeds' : urls , 'name' : name , 'apiUrl' : process_url , } params [ 'maxToCrawl' ] = 10 params . update ( kwargs ) self . _get ( url , params = params ) return Job ( self . _token , name , self . _version )
Crawlbot API .
61,982
def handle_lrr_message ( sender , message ) : print ( sender , message . partition , message . event_type , message . event_data )
Handles message events from the AlarmDecoder .
61,983
def main ( ) : try : device = AlarmDecoder ( SerialDevice ( interface = SERIAL_DEVICE ) ) device . on_alarm += handle_alarm with device . open ( baudrate = BAUDRATE ) : while True : time . sleep ( 1 ) except Exception as ex : print ( 'Exception:' , ex )
Example application that sends an email when an alarm event is detected .
61,984
def handle_alarm ( sender , ** kwargs ) : zone = kwargs . pop ( 'zone' , None ) text = "Alarm: Zone {0}" . format ( zone ) msg = MIMEText ( text ) msg [ 'Subject' ] = SUBJECT msg [ 'From' ] = FROM_ADDRESS msg [ 'To' ] = TO_ADDRESS s = smtplib . SMTP ( SMTP_SERVER ) if SMTP_USERNAME is not None : s . login ( SMTP_USERNAME , SMTP_PASSWORD ) s . sendmail ( FROM_ADDRESS , TO_ADDRESS , msg . as_string ( ) ) s . quit ( ) print ( 'sent alarm email:' , text )
Handles alarm events from the AlarmDecoder .
61,985
def main ( ) : try : ssl_device = SocketDevice ( interface = ( 'localhost' , 10000 ) ) ssl_device . ssl = True ssl_device . ssl_ca = SSL_CA ssl_device . ssl_key = SSL_KEY ssl_device . ssl_certificate = SSL_CERT device = AlarmDecoder ( ssl_device ) device . on_message += handle_message with device . open ( ) : while True : time . sleep ( 1 ) except Exception as ex : print ( 'Exception:' , ex )
Example application that opens a device that has been exposed to the network with ser2sock and SSL encryption and authentication .
61,986
def ruencode ( string , extension = False ) : if extension : file_name = string file_ext = '' else : file_name , file_ext = splitext ( string ) encoded_value , _ = _ROT_UNICODE . encode ( file_name ) return encoded_value + file_ext
Encode a string using rotunicode codec .
61,987
def parse_escape_sequences ( string ) : string = safe_unicode ( string ) characters = [ ] i = 0 string_len = len ( string ) while i < string_len : character = string [ i ] if character == '\\' : if string [ ( i + 1 ) : ( i + 2 ) ] == 'u' : offset = 6 else : offset = 2 try : json_string = '"' + string [ i : ( i + offset ) ] + '"' character = scanstring ( json_string , 1 ) [ 0 ] characters . append ( character ) i += offset except ValueError : raise_from ( ValueError ( string ) , None ) else : characters . append ( character ) i += 1 return '' . join ( characters )
Parse a string for possible escape sequences .
61,988
def find_all ( cls , vid = None , pid = None ) : if not have_pyftdi : raise ImportError ( 'The USBDevice class has been disabled due to missing requirement: pyftdi or pyusb.' ) cls . __devices = [ ] query = cls . PRODUCT_IDS if vid and pid : query = [ ( vid , pid ) ] try : cls . __devices = Ftdi . find_all ( query , nocache = True ) except ( usb . core . USBError , FtdiError ) as err : raise CommError ( 'Error enumerating AD2USB devices: {0}' . format ( str ( err ) ) , err ) return cls . __devices
Returns all FTDI devices matching our vendor and product IDs .
61,989
def start_detection ( cls , on_attached = None , on_detached = None ) : if not have_pyftdi : raise ImportError ( 'The USBDevice class has been disabled due to missing requirement: pyftdi or pyusb.' ) cls . __detect_thread = USBDevice . DetectThread ( on_attached , on_detached ) try : cls . find_all ( ) except CommError : pass cls . __detect_thread . start ( )
Starts the device detection thread .
61,990
def interface ( self , value ) : self . _interface = value if isinstance ( value , int ) : self . _device_number = value else : self . _serial_number = value
Sets the interface used to connect to the device .
61,991
def _get_serial_number ( self ) : return usb . util . get_string ( self . _device . usb_dev , 64 , self . _device . usb_dev . iSerialNumber )
Retrieves the FTDI device serial number .
61,992
def parse_color ( color ) : if len ( color ) not in ( 3 , 4 , 6 , 8 ) : raise ValueError ( 'bad color %s' % repr ( color ) ) if len ( color ) in ( 3 , 4 ) : r = int ( color [ 0 ] , 16 ) * 0x11 g = int ( color [ 1 ] , 16 ) * 0x11 b = int ( color [ 2 ] , 16 ) * 0x11 elif len ( color ) in ( 6 , 8 ) : r = int ( color [ 0 : 2 ] , 16 ) g = int ( color [ 2 : 4 ] , 16 ) b = int ( color [ 4 : 6 ] , 16 ) if len ( color ) == 4 : a = int ( color [ 3 ] , 16 ) * 0x11 elif len ( color ) == 8 : a = int ( color [ 6 : 8 ] , 16 ) else : a = 0xff return ( r , g , b , a )
Parse a color value .
61,993
def check_color ( option , opt , value ) : try : return parse_color ( value ) except ValueError : raise optparse . OptionValueError ( "option %s: invalid color value: %r" % ( opt , value ) )
Validate and convert an option value of type color .
61,994
def pick_orientation ( img1 , img2 , spacing , desired_aspect = 1.618 ) : w1 , h1 = img1 . size w2 , h2 = img2 . size size_a = ( w1 + spacing + w2 , max ( h1 , h2 , 1 ) ) size_b = ( max ( w1 , w2 , 1 ) , h1 + spacing + h2 ) aspect_a = size_a [ 0 ] / size_a [ 1 ] aspect_b = size_b [ 0 ] / size_b [ 1 ] goodness_a = min ( desired_aspect , aspect_a ) / max ( desired_aspect , aspect_a ) goodness_b = min ( desired_aspect , aspect_b ) / max ( desired_aspect , aspect_b ) return 'lr' if goodness_a >= goodness_b else 'tb'
Pick a tiling orientation for two images .
61,995
def tile_images ( img1 , img2 , mask1 , mask2 , opts ) : w1 , h1 = img1 . size w2 , h2 = img2 . size if opts . orientation == 'auto' : opts . orientation = pick_orientation ( img1 , img2 , opts . spacing ) B , S = opts . border , opts . spacing if opts . orientation == 'lr' : w , h = ( B + w1 + S + w2 + B , B + max ( h1 , h2 ) + B ) pos1 = ( B , ( h - h1 ) // 2 ) pos2 = ( B + w1 + S , ( h - h2 ) // 2 ) separator_line = [ ( B + w1 + S // 2 , 0 ) , ( B + w1 + S // 2 , h ) ] else : w , h = ( B + max ( w1 , w2 ) + B , B + h1 + S + h2 + B ) pos1 = ( ( w - w1 ) // 2 , B ) pos2 = ( ( w - w2 ) // 2 , B + h1 + S ) separator_line = [ ( 0 , B + h1 + S // 2 ) , ( w , B + h1 + S // 2 ) ] img = Image . new ( 'RGBA' , ( w , h ) , opts . bgcolor ) img . paste ( img1 , pos1 , mask1 ) img . paste ( img2 , pos2 , mask2 ) ImageDraw . Draw ( img ) . line ( separator_line , fill = opts . sepcolor ) return img
Combine two images into one by tiling them .
61,996
def spawn_viewer ( viewer , img , filename , grace ) : tempdir = tempfile . mkdtemp ( prefix = 'imgdiff-' ) try : imgfile = os . path . join ( tempdir , filename ) img . save ( imgfile ) started = time . time ( ) subprocess . call ( [ viewer , imgfile ] ) elapsed = time . time ( ) - started if elapsed < grace : time . sleep ( grace - elapsed ) finally : shutil . rmtree ( tempdir )
Launch an external program to view an image .
61,997
def tweak_diff ( diff , opacity ) : mask = diff . point ( lambda i : opacity + i * ( 255 - opacity ) // 255 ) return mask
Adjust a difference map into an opacity mask for a given lowest opacity .
61,998
def diff ( img1 , img2 , x1y1 , x2y2 ) : x1 , y1 = x1y1 x2 , y2 = x2y2 w1 , h1 = img1 . size w2 , h2 = img2 . size w , h = min ( w1 , w2 ) , min ( h1 , h2 ) diff = ImageChops . difference ( img1 . crop ( ( x1 , y1 , x1 + w , y1 + h ) ) , img2 . crop ( ( x2 , y2 , x2 + w , y2 + h ) ) ) diff = diff . convert ( 'L' ) return diff
Compare two images with given alignments .
61,999
def diff_badness ( diff ) : return sum ( i * n for i , n in enumerate ( diff . histogram ( ) ) )
Estimate the badness value of a difference map .