idx
int64
0
251k
question
stringlengths
53
3.53k
target
stringlengths
5
1.23k
len_question
int64
20
893
len_target
int64
3
238
247,900
def macro_tpm_sbs ( self , state_by_state_micro_tpm ) : validate . tpm ( state_by_state_micro_tpm , check_independence = False ) mapping = self . make_mapping ( ) num_macro_states = 2 ** len ( self . macro_indices ) macro_tpm = np . zeros ( ( num_macro_states , num_macro_states ) ) micro_states = range ( 2 ** len ( sel...
Create a state - by - state coarse - grained macro TPM .
272
15
247,901
def macro_tpm ( self , micro_tpm , check_independence = True ) : if not is_state_by_state ( micro_tpm ) : micro_tpm = convert . state_by_node2state_by_state ( micro_tpm ) macro_tpm = self . macro_tpm_sbs ( micro_tpm ) if check_independence : validate . conditionally_independent ( macro_tpm ) return convert . state_by_s...
Create a coarse - grained macro TPM .
117
10
247,902
def hidden_indices ( self ) : return tuple ( sorted ( set ( self . micro_indices ) - set ( self . output_indices ) ) )
All elements hidden inside the blackboxes .
35
8
247,903
def outputs_of ( self , partition_index ) : partition = self . partition [ partition_index ] outputs = set ( partition ) . intersection ( self . output_indices ) return tuple ( sorted ( outputs ) )
The outputs of the partition at partition_index .
46
10
247,904
def reindex ( self ) : _map = dict ( zip ( self . micro_indices , reindex ( self . micro_indices ) ) ) partition = tuple ( tuple ( _map [ index ] for index in group ) for group in self . partition ) output_indices = tuple ( _map [ i ] for i in self . output_indices ) return Blackbox ( partition , output_indices )
Squeeze the indices of this blackboxing to 0 .. n .
89
14
247,905
def macro_state ( self , micro_state ) : assert len ( micro_state ) == len ( self . micro_indices ) reindexed = self . reindex ( ) return utils . state_of ( reindexed . output_indices , micro_state )
Compute the macro - state of this blackbox .
60
11
247,906
def in_same_box ( self , a , b ) : assert a in self . micro_indices assert b in self . micro_indices for part in self . partition : if a in part and b in part : return True return False
Return True if nodes a and b are in the same box .
52
13
247,907
def hidden_from ( self , a , b ) : return a in self . hidden_indices and not self . in_same_box ( a , b )
Return True if a is hidden in a different box than b .
35
13
247,908
def irreducible_purviews ( cm , direction , mechanism , purviews ) : def reducible ( purview ) : """Return ``True`` if purview is trivially reducible.""" _from , to = direction . order ( mechanism , purview ) return connectivity . block_reducible ( cm , _from , to ) return [ purview for purview in purviews if not reduc...
Return all purviews which are irreducible for the mechanism .
91
14
247,909
def _build_tpm ( tpm ) : tpm = np . array ( tpm ) validate . tpm ( tpm ) # Convert to multidimensional state-by-node form if is_state_by_state ( tpm ) : tpm = convert . state_by_state2state_by_node ( tpm ) else : tpm = convert . to_multidimensional ( tpm ) utils . np_immutable ( tpm ) return ( tpm , utils . np_hash ( t...
Validate the TPM passed by the user and convert to multidimensional form .
117
17
247,910
def _build_cm ( self , cm ) : if cm is None : # Assume all are connected. cm = np . ones ( ( self . size , self . size ) ) else : cm = np . array ( cm ) utils . np_immutable ( cm ) return ( cm , utils . np_hash ( cm ) )
Convert the passed CM to the proper format or construct the unitary CM if none was provided .
73
20
247,911
def potential_purviews ( self , direction , mechanism ) : all_purviews = utils . powerset ( self . _node_indices ) return irreducible_purviews ( self . cm , direction , mechanism , all_purviews )
All purviews which are not clearly reducible for mechanism .
54
12
247,912
def _loadable_models ( ) : classes = [ pyphi . Direction , pyphi . Network , pyphi . Subsystem , pyphi . Transition , pyphi . labels . NodeLabels , pyphi . models . Cut , pyphi . models . KCut , pyphi . models . NullCut , pyphi . models . Part , pyphi . models . Bipartition , pyphi . models . KPartition , pyphi . model...
A dictionary of loadable PyPhi models .
255
10
247,913
def jsonify ( obj ) : # pylint: disable=too-many-return-statements # Call the `to_json` method if available and add metadata. if hasattr ( obj , 'to_json' ) : d = obj . to_json ( ) _push_metadata ( d , obj ) return jsonify ( d ) # If we have a numpy array, convert it to a list. if isinstance ( obj , np . ndarray ) : re...
Return a JSON - encodable representation of an object recursively using any available to_json methods converting NumPy arrays and datatypes to native lists and types along the way .
273
38
247,914
def _check_version ( version ) : if version != pyphi . __version__ : raise pyphi . exceptions . JSONVersionError ( 'Cannot load JSON from a different version of PyPhi. ' 'JSON version = {0}, current version = {1}.' . format ( version , pyphi . __version__ ) )
Check whether the JSON version matches the PyPhi version .
71
12
247,915
def _load_object ( self , obj ) : if isinstance ( obj , dict ) : obj = { k : self . _load_object ( v ) for k , v in obj . items ( ) } # Load a serialized PyPhi model if _is_model ( obj ) : return self . _load_model ( obj ) elif isinstance ( obj , list ) : return tuple ( self . _load_object ( item ) for item in obj ) re...
Recursively load a PyPhi object .
102
10
247,916
def _load_model ( self , dct ) : classname , version , _ = _pop_metadata ( dct ) _check_version ( version ) cls = self . _models [ classname ] # Use `from_json` if available if hasattr ( cls , 'from_json' ) : return cls . from_json ( dct ) # Default to object constructor return cls ( * * dct )
Load a serialized PyPhi model .
93
9
247,917
def _compute_hamming_matrix ( N ) : possible_states = np . array ( list ( utils . all_states ( ( N ) ) ) ) return cdist ( possible_states , possible_states , 'hamming' ) * N
Compute and store a Hamming matrix for |N| nodes .
56
14
247,918
def effect_emd ( d1 , d2 ) : return sum ( abs ( marginal_zero ( d1 , i ) - marginal_zero ( d2 , i ) ) for i in range ( d1 . ndim ) )
Compute the EMD between two effect repertoires .
50
11
247,919
def entropy_difference ( d1 , d2 ) : d1 , d2 = flatten ( d1 ) , flatten ( d2 ) return abs ( entropy ( d1 , base = 2.0 ) - entropy ( d2 , base = 2.0 ) )
Return the difference in entropy between two distributions .
59
9
247,920
def psq2 ( d1 , d2 ) : d1 , d2 = flatten ( d1 ) , flatten ( d2 ) def f ( p ) : return sum ( ( p ** 2 ) * np . nan_to_num ( np . log ( p * len ( p ) ) ) ) return abs ( f ( d1 ) - f ( d2 ) )
Compute the PSQ2 measure .
82
8
247,921
def mp2q ( p , q ) : p , q = flatten ( p ) , flatten ( q ) entropy_dist = 1 / len ( p ) return sum ( entropy_dist * np . nan_to_num ( ( p ** 2 ) / q * np . log ( p / q ) ) )
Compute the MP2Q measure .
68
8
247,922
def klm ( p , q ) : p , q = flatten ( p ) , flatten ( q ) return max ( abs ( p * np . nan_to_num ( np . log ( p / q ) ) ) )
Compute the KLM divergence .
51
7
247,923
def directional_emd ( direction , d1 , d2 ) : if direction == Direction . CAUSE : func = hamming_emd elif direction == Direction . EFFECT : func = effect_emd else : # TODO: test that ValueError is raised validate . direction ( direction ) return round ( func ( d1 , d2 ) , config . PRECISION )
Compute the EMD between two repertoires for a given direction .
81
14
247,924
def repertoire_distance ( direction , r1 , r2 ) : if config . MEASURE == 'EMD' : dist = directional_emd ( direction , r1 , r2 ) else : dist = measures [ config . MEASURE ] ( r1 , r2 ) return round ( dist , config . PRECISION )
Compute the distance between two repertoires for the given direction .
71
13
247,925
def system_repertoire_distance ( r1 , r2 ) : if config . MEASURE in measures . asymmetric ( ) : raise ValueError ( '{} is asymmetric and cannot be used as a system-level ' 'irreducibility measure.' . format ( config . MEASURE ) ) return measures [ config . MEASURE ] ( r1 , r2 )
Compute the distance between two repertoires of a system .
84
12
247,926
def register ( self , name , asymmetric = False ) : def register_func ( func ) : if asymmetric : self . _asymmetric . append ( name ) self . store [ name ] = func return func return register_func
Decorator for registering a measure with PyPhi .
50
12
247,927
def partitions ( collection ) : collection = list ( collection ) # Special cases if not collection : return if len ( collection ) == 1 : yield [ collection ] return first = collection [ 0 ] for smaller in partitions ( collection [ 1 : ] ) : for n , subset in enumerate ( smaller ) : yield smaller [ : n ] + [ [ first ] +...
Generate all set partitions of a collection .
92
9
247,928
def bipartition_indices ( N ) : result = [ ] if N <= 0 : return result for i in range ( 2 ** ( N - 1 ) ) : part = [ [ ] , [ ] ] for n in range ( N ) : bit = ( i >> n ) & 1 part [ bit ] . append ( n ) result . append ( ( tuple ( part [ 1 ] ) , tuple ( part [ 0 ] ) ) ) return result
Return indices for undirected bipartitions of a sequence .
95
13
247,929
def bipartition ( seq ) : return [ ( tuple ( seq [ i ] for i in part0_idx ) , tuple ( seq [ j ] for j in part1_idx ) ) for part0_idx , part1_idx in bipartition_indices ( len ( seq ) ) ]
Return a list of bipartitions for a sequence .
69
11
247,930
def directed_bipartition ( seq , nontrivial = False ) : bipartitions = [ ( tuple ( seq [ i ] for i in part0_idx ) , tuple ( seq [ j ] for j in part1_idx ) ) for part0_idx , part1_idx in directed_bipartition_indices ( len ( seq ) ) ] if nontrivial : # The first and last partitions have a part that is empty; skip them. #...
Return a list of directed bipartitions for a sequence .
138
12
247,931
def bipartition_of_one ( seq ) : seq = list ( seq ) for i , elt in enumerate ( seq ) : yield ( ( elt , ) , tuple ( seq [ : i ] + seq [ ( i + 1 ) : ] ) )
Generate bipartitions where one part is of length 1 .
57
13
247,932
def directed_bipartition_of_one ( seq ) : bipartitions = list ( bipartition_of_one ( seq ) ) return chain ( bipartitions , reverse_elements ( bipartitions ) )
Generate directed bipartitions where one part is of length 1 .
49
14
247,933
def directed_tripartition_indices ( N ) : result = [ ] if N <= 0 : return result base = [ 0 , 1 , 2 ] for key in product ( base , repeat = N ) : part = [ [ ] , [ ] , [ ] ] for i , location in enumerate ( key ) : part [ location ] . append ( i ) result . append ( tuple ( tuple ( p ) for p in part ) ) return result
Return indices for directed tripartitions of a sequence .
95
11
247,934
def directed_tripartition ( seq ) : for a , b , c in directed_tripartition_indices ( len ( seq ) ) : yield ( tuple ( seq [ i ] for i in a ) , tuple ( seq [ j ] for j in b ) , tuple ( seq [ k ] for k in c ) )
Generator over all directed tripartitions of a sequence .
70
12
247,935
def k_partitions ( collection , k ) : collection = list ( collection ) n = len ( collection ) # Special cases if n == 0 or k < 1 : return [ ] if k == 1 : return [ [ collection ] ] a = [ 0 ] * ( n + 1 ) for j in range ( 1 , k + 1 ) : a [ n - k + j ] = j - 1 return _f ( k , n , 0 , n , a , k , collection )
Generate all k - partitions of a collection .
102
10
247,936
def mip_partitions ( mechanism , purview , node_labels = None ) : func = partition_types [ config . PARTITION_TYPE ] return func ( mechanism , purview , node_labels )
Return a generator over all mechanism - purview partitions based on the current configuration .
46
16
247,937
def mip_bipartitions ( mechanism , purview , node_labels = None ) : numerators = bipartition ( mechanism ) denominators = directed_bipartition ( purview ) for n , d in product ( numerators , denominators ) : if ( n [ 0 ] or d [ 0 ] ) and ( n [ 1 ] or d [ 1 ] ) : yield Bipartition ( Part ( n [ 0 ] , d [ 0 ] ) , Part ( n...
r Return an generator of all |small_phi| bipartitions of a mechanism over a purview .
125
22
247,938
def wedge_partitions ( mechanism , purview , node_labels = None ) : numerators = bipartition ( mechanism ) denominators = directed_tripartition ( purview ) yielded = set ( ) def valid ( factoring ) : """Return whether the factoring should be considered.""" # pylint: disable=too-many-boolean-expressions numerator , deno...
Return an iterator over all wedge partitions .
466
8
247,939
def all_partitions ( mechanism , purview , node_labels = None ) : for mechanism_partition in partitions ( mechanism ) : mechanism_partition . append ( [ ] ) n_mechanism_parts = len ( mechanism_partition ) max_purview_partition = min ( len ( purview ) , n_mechanism_parts ) for n_purview_parts in range ( 1 , max_purview_...
Return all possible partitions of a mechanism and purview .
320
11
247,940
def naturalize_string ( key ) : return [ int ( text ) if text . isdigit ( ) else text . lower ( ) for text in re . split ( numregex , key ) ]
Analyzes string in a human way to enable natural sort
42
11
247,941
def fetch_sel ( self , ipmicmd , clear = False ) : records = [ ] # First we do a fetch all without reservation, reducing the risk # of having a long lived reservation that gets canceled in the middle endat = self . _fetch_entries ( ipmicmd , 0 , records ) if clear and records : # don't bother clearing if there were no ...
Fetch SEL entries
318
5
247,942
def oem_init ( self ) : if self . _oemknown : return self . _oem , self . _oemknown = get_oem_handler ( self . _get_device_id ( ) , self )
Initialize the command object for OEM capabilities
51
8
247,943
def reset_bmc ( self ) : response = self . raw_command ( netfn = 6 , command = 2 ) if 'error' in response : raise exc . IpmiException ( response [ 'error' ] )
Do a cold reset in BMC
48
6
247,944
def xraw_command ( self , netfn , command , bridge_request = ( ) , data = ( ) , delay_xmit = None , retry = True , timeout = None ) : rsp = self . ipmi_session . raw_command ( netfn = netfn , command = command , bridge_request = bridge_request , data = data , delay_xmit = delay_xmit , retry = retry , timeout = timeout ...
Send raw ipmi command to BMC raising exception on error
151
11
247,945
def raw_command ( self , netfn , command , bridge_request = ( ) , data = ( ) , delay_xmit = None , retry = True , timeout = None ) : rsp = self . ipmi_session . raw_command ( netfn = netfn , command = command , bridge_request = bridge_request , data = data , delay_xmit = delay_xmit , retry = retry , timeout = timeout )...
Send raw ipmi command to BMC
126
7
247,946
def get_power ( self ) : response = self . raw_command ( netfn = 0 , command = 1 ) if 'error' in response : raise exc . IpmiException ( response [ 'error' ] ) assert ( response [ 'command' ] == 1 and response [ 'netfn' ] == 1 ) powerstate = 'on' if ( response [ 'data' ] [ 0 ] & 1 ) else 'off' return { 'powerstate' : po...
Get current power state of the managed system
102
8
247,947
def get_event_log ( self , clear = False ) : self . oem_init ( ) return sel . EventHandler ( self . init_sdr ( ) , self ) . fetch_sel ( self , clear )
Retrieve the log of events optionally clearing
49
8
247,948
def decode_pet ( self , specifictrap , petdata ) : self . oem_init ( ) return sel . EventHandler ( self . init_sdr ( ) , self ) . decode_pet ( specifictrap , petdata )
Decode PET to an event
55
6
247,949
def get_inventory_descriptions ( self ) : yield "System" self . init_sdr ( ) for fruid in sorted ( self . _sdr . fru ) : yield self . _sdr . fru [ fruid ] . fru_name self . oem_init ( ) for compname in self . _oem . get_oem_inventory_descriptions ( ) : yield compname
Retrieve list of things that could be inventoried
89
10
247,950
def get_inventory_of_component ( self , component ) : self . oem_init ( ) if component == 'System' : return self . _get_zero_fru ( ) self . init_sdr ( ) for fruid in self . _sdr . fru : if self . _sdr . fru [ fruid ] . fru_name == component : return self . _oem . process_fru ( fru . FRU ( ipmicmd = self , fruid = fruid...
Retrieve inventory of a component
146
6
247,951
def get_inventory ( self ) : self . oem_init ( ) yield ( "System" , self . _get_zero_fru ( ) ) self . init_sdr ( ) for fruid in sorted ( self . _sdr . fru ) : fruinf = fru . FRU ( ipmicmd = self , fruid = fruid , sdr = self . _sdr . fru [ fruid ] ) . info if fruinf is not None : fruinf = self . _oem . process_fru ( fru...
Retrieve inventory of system
177
5
247,952
def get_health ( self ) : summary = { 'badreadings' : [ ] , 'health' : const . Health . Ok } fallbackreadings = [ ] try : self . oem_init ( ) fallbackreadings = self . _oem . get_health ( summary ) for reading in self . get_sensor_data ( ) : if reading . health != const . Health . Ok : summary [ 'health' ] |= reading ....
Summarize health of managed system
149
7
247,953
def get_sensor_reading ( self , sensorname ) : self . init_sdr ( ) for sensor in self . _sdr . get_sensor_numbers ( ) : if self . _sdr . sensors [ sensor ] . name == sensorname : rsp = self . raw_command ( command = 0x2d , netfn = 4 , data = ( sensor , ) ) if 'error' in rsp : raise exc . IpmiException ( rsp [ 'error' ]...
Get a sensor reading by name
173
6
247,954
def _fetch_lancfg_param ( self , channel , param , prefixlen = False ) : fetchcmd = bytearray ( ( channel , param , 0 , 0 ) ) fetched = self . xraw_command ( 0xc , 2 , data = fetchcmd ) fetchdata = fetched [ 'data' ] if ord ( fetchdata [ 0 ] ) != 17 : return None if len ( fetchdata ) == 5 : # IPv4 address if prefixlen ...
Internal helper for fetching lan cfg parameters
284
9
247,955
def set_net_configuration ( self , ipv4_address = None , ipv4_configuration = None , ipv4_gateway = None , channel = None ) : if channel is None : channel = self . get_network_channel ( ) if ipv4_configuration is not None : cmddata = [ channel , 4 , 0 ] if ipv4_configuration . lower ( ) == 'dhcp' : cmddata [ - 1 ] = 2 ...
Set network configuration data .
407
5
247,956
def get_net_configuration ( self , channel = None , gateway_macs = True ) : if channel is None : channel = self . get_network_channel ( ) retdata = { } v4addr = self . _fetch_lancfg_param ( channel , 3 ) if v4addr is None : retdata [ 'ipv4_address' ] = None else : v4masklen = self . _fetch_lancfg_param ( channel , 6 , ...
Get network configuration data
408
4
247,957
def get_sensor_data ( self ) : self . init_sdr ( ) for sensor in self . _sdr . get_sensor_numbers ( ) : rsp = self . raw_command ( command = 0x2d , netfn = 4 , data = ( sensor , ) ) if 'error' in rsp : if rsp [ 'code' ] == 203 : # Sensor does not exist, optional dev continue raise exc . IpmiException ( rsp [ 'error' ] ...
Get sensor reading objects
175
4
247,958
def get_sensor_descriptions ( self ) : self . init_sdr ( ) for sensor in self . _sdr . get_sensor_numbers ( ) : yield { 'name' : self . _sdr . sensors [ sensor ] . name , 'type' : self . _sdr . sensors [ sensor ] . sensor_type } self . oem_init ( ) for sensor in self . _oem . get_sensor_descriptions ( ) : yield sensor
Get available sensor names
108
4
247,959
def get_network_channel ( self ) : if self . _netchannel is None : for channel in chain ( ( 0xe , ) , range ( 1 , 0xc ) ) : try : rsp = self . xraw_command ( netfn = 6 , command = 0x42 , data = ( channel , ) ) except exc . IpmiException as ie : if ie . ipmicode == 0xcc : # We have hit an invalid channel, move on to nex...
Get a reasonable default network channel .
301
7
247,960
def get_alert_destination_count ( self , channel = None ) : if channel is None : channel = self . get_network_channel ( ) rqdata = ( channel , 0x11 , 0 , 0 ) rsp = self . xraw_command ( netfn = 0xc , command = 2 , data = rqdata ) return ord ( rsp [ 'data' ] [ 1 ] )
Get the number of supported alert destinations
88
7
247,961
def get_alert_destination ( self , destination = 0 , channel = None ) : destinfo = { } if channel is None : channel = self . get_network_channel ( ) rqdata = ( channel , 18 , destination , 0 ) rsp = self . xraw_command ( netfn = 0xc , command = 2 , data = rqdata ) dtype , acktimeout , retries = struct . unpack ( 'BBB' ...
Get alert destination
365
3
247,962
def clear_alert_destination ( self , destination = 0 , channel = None ) : if channel is None : channel = self . get_network_channel ( ) self . set_alert_destination ( '0.0.0.0' , False , 0 , 0 , destination , channel )
Clear an alert destination
64
4
247,963
def set_alert_community ( self , community , channel = None ) : if channel is None : channel = self . get_network_channel ( ) community = community . encode ( 'utf-8' ) community += b'\x00' * ( 18 - len ( community ) ) cmddata = bytearray ( ( channel , 16 ) ) cmddata += community self . xraw_command ( netfn = 0xc , com...
Set the community string for alerts
104
6
247,964
def _assure_alert_policy ( self , channel , destination ) : # First we do a get PEF configuration parameters to get the count # of entries. We have no guarantee that the meaningful data will # be contiguous rsp = self . xraw_command ( netfn = 4 , command = 0x13 , data = ( 8 , 0 , 0 ) ) numpol = ord ( rsp [ 'data' ] [ 1...
Make sure an alert policy exists
347
6
247,965
def get_alert_community ( self , channel = None ) : if channel is None : channel = self . get_network_channel ( ) rsp = self . xraw_command ( netfn = 0xc , command = 2 , data = ( channel , 16 , 0 , 0 ) ) return rsp [ 'data' ] [ 1 : ] . partition ( '\x00' ) [ 0 ]
Get the current community string for alerts
86
7
247,966
def set_alert_destination ( self , ip = None , acknowledge_required = None , acknowledge_timeout = None , retries = None , destination = 0 , channel = None ) : if channel is None : channel = self . get_network_channel ( ) if ip is not None : destdata = bytearray ( ( channel , 19 , destination ) ) try : parsedip = socke...
Configure one or more parameters of an alert destination
515
10
247,967
def get_hostname ( self ) : self . oem_init ( ) try : return self . _oem . get_hostname ( ) except exc . UnsupportedFunctionality : # Use the DCMI MCI field as a fallback, since it's the closest # thing in the IPMI Spec for this return self . get_mci ( )
Get the hostname used by the BMC in various contexts
76
11
247,968
def set_hostname ( self , hostname ) : self . oem_init ( ) try : return self . _oem . set_hostname ( hostname ) except exc . UnsupportedFunctionality : return self . set_mci ( hostname )
Set the hostname to be used by the BMC in various contexts .
56
14
247,969
def get_channel_access ( self , channel = None , read_mode = 'volatile' ) : if channel is None : channel = self . get_network_channel ( ) data = [ ] data . append ( channel & 0b00001111 ) b = 0 read_modes = { 'non_volatile' : 1 , 'volatile' : 2 , } b |= ( read_modes [ read_mode ] << 6 ) & 0b11000000 data . append ( b )...
Get channel access
383
3
247,970
def get_channel_info ( self , channel = None ) : if channel is None : channel = self . get_network_channel ( ) data = [ ] data . append ( channel & 0b00001111 ) response = self . raw_command ( netfn = 0x06 , command = 0x42 , data = data ) if 'error' in response : raise Exception ( response [ 'error' ] ) data = response...
Get channel info
540
3
247,971
def get_firmware ( self , components = ( ) ) : self . oem_init ( ) mcinfo = self . xraw_command ( netfn = 6 , command = 1 ) bmcver = '{0}.{1}' . format ( ord ( mcinfo [ 'data' ] [ 2 ] ) , hex ( ord ( mcinfo [ 'data' ] [ 3 ] ) ) [ 2 : ] ) return self . _oem . get_oem_firmware ( bmcver , components )
Retrieve OEM Firmware information
114
6
247,972
def update_firmware ( self , file , data = None , progress = None , bank = None ) : self . oem_init ( ) if progress is None : progress = lambda x : True return self . _oem . update_firmware ( file , data , progress , bank )
Send file to BMC to perform firmware update
64
8
247,973
def attach_remote_media ( self , url , username = None , password = None ) : self . oem_init ( ) return self . _oem . attach_remote_media ( url , username , password )
Attach remote media by url
47
5
247,974
def upload_media ( self , filename , progress = None ) : self . oem_init ( ) return self . _oem . upload_media ( filename , progress )
Upload a file to be hosted on the target BMC
37
10
247,975
def process_event ( self , event , ipmicmd , seldata ) : event [ 'oem_handler' ] = None evdata = event [ 'event_data_bytes' ] if evdata [ 0 ] & 0b11000000 == 0b10000000 : event [ 'oem_byte2' ] = evdata [ 1 ] if evdata [ 0 ] & 0b110000 == 0b100000 : event [ 'oem_byte3' ] = evdata [ 2 ]
Modify an event according with OEM understanding .
108
9
247,976
def _got_cons_input ( self , handle ) : self . _addpendingdata ( handle . read ( ) ) if not self . awaitingack : self . _sendpendingoutput ( )
Callback for handle events detected by ipmi session
43
9
247,977
def close ( self ) : if self . ipmi_session : self . ipmi_session . unregister_keepalive ( self . keepaliveid ) if self . activated : try : self . ipmi_session . raw_command ( netfn = 6 , command = 0x49 , data = ( 1 , 1 , 0 , 0 , 0 , 0 ) ) except exc . IpmiException : # if underlying ipmi session is not working, then #...
Shut down an SOL session
106
5
247,978
def _got_sol_payload ( self , payload ) : # TODO(jbjohnso) test cases to throw some likely scenarios at functions # for example, retry with new data, retry with no new data # retry with unexpected sequence number if type ( payload ) == dict : # we received an error condition self . activated = False self . _print_error...
SOL payload callback
795
4
247,979
def is_fpc ( self ) : if self . has_imm or self . has_xcc : return None if self . _fpc_variant is not None : return self . _fpc_variant fpc_ids = ( ( 19046 , 32 , 1063 ) , ( 20301 , 32 , 462 ) ) smm_id = ( 19046 , 32 , 1180 ) currid = ( self . oemid [ 'manufacturer_id' ] , self . oemid [ 'device_id' ] , self . oemid [ ...
True if the target is a Lenovo nextscale fan power controller
179
12
247,980
def has_tsm ( self ) : if ( self . oemid [ 'manufacturer_id' ] == 19046 and self . oemid [ 'device_id' ] == 32 ) : try : self . ipmicmd . xraw_command ( netfn = 0x3a , command = 0xf ) except pygexc . IpmiException as ie : if ie . ipmicode == 193 : return False raise return True return False
True if this particular server have a TSM based service processor
98
12
247,981
def set_oem_capping_enabled ( self , enable ) : # 1 - Enable power capping(default) if enable : statecode = 1 # 0 - Disable power capping else : statecode = 0 if self . has_tsm : self . ipmicmd . xraw_command ( netfn = 0x3a , command = 0x1a , data = ( 3 , statecode ) ) return True
Set PSU based power capping
91
6
247,982
def decode_wireformat_uuid ( rawguid ) : if isinstance ( rawguid , list ) : rawguid = bytearray ( rawguid ) lebytes = struct . unpack_from ( '<IHH' , buffer ( rawguid [ : 8 ] ) ) bebytes = struct . unpack_from ( '>HHI' , buffer ( rawguid [ 8 : ] ) ) return '{0:08X}-{1:04X}-{2:04X}-{3:04X}-{4:04X}{5:08X}' . format ( leb...
Decode a wire format UUID
173
7
247,983
def urlsplit ( url ) : proto , rest = url . split ( ':' , 1 ) host = '' if rest [ : 2 ] == '//' : host , rest = rest [ 2 : ] . split ( '/' , 1 ) rest = '/' + rest return proto , host , rest
Split an arbitrary url into protocol host rest
65
8
247,984
def get_ipv4 ( hostname ) : addrinfo = socket . getaddrinfo ( hostname , None , socket . AF_INET , socket . SOCK_STREAM ) return [ addrinfo [ x ] [ 4 ] [ 0 ] for x in range ( len ( addrinfo ) ) ]
Get list of ipv4 addresses for hostname
65
10
247,985
def _aespad ( data ) : currlen = len ( data ) + 1 # need to count the pad length field as well neededpad = currlen % 16 if neededpad : # if it happens to be zero, hurray, but otherwise invert the # sense of the padding neededpad = 16 - neededpad padval = 1 pad = bytearray ( neededpad ) while padval <= neededpad : pad [...
ipmi demands a certain pad scheme per table 13 - 20 AES - CBC encrypted payload fields .
113
19
247,986
def _make_bridge_request_msg ( self , channel , netfn , command ) : head = bytearray ( ( constants . IPMI_BMC_ADDRESS , constants . netfn_codes [ 'application' ] << 2 ) ) check_sum = _checksum ( * head ) # NOTE(fengqian): according IPMI Figure 14-11, rqSWID is set to 81h boday = bytearray ( ( 0x81 , self . seqlun , con...
This function generate message for bridge request . It is a part of ipmi payload .
208
17
247,987
def wait_for_rsp ( cls , timeout = None , callout = True ) : global iosockets # Assume: # Instance A sends request to packet B # Then Instance C sends request to BMC D # BMC D was faster, so data comes back before BMC B # Instance C gets to go ahead of Instance A, because # Instance C can get work done, but instance A ...
IPMI Session Event loop iteration
869
6
247,988
def register_keepalive ( self , cmd , callback ) : regid = random . random ( ) if self . _customkeepalives is None : self . _customkeepalives = { regid : ( cmd , callback ) } else : while regid in self . _customkeepalives : regid = random . random ( ) self . _customkeepalives [ regid ] = ( cmd , callback ) return regid
Register custom keepalive IPMI command
93
8
247,989
def _keepalive ( self ) : try : keptalive = False if self . _customkeepalives : kaids = list ( self . _customkeepalives . keys ( ) ) for keepalive in kaids : try : cmd , callback = self . _customkeepalives [ keepalive ] except TypeError : # raw_command made customkeepalives None break except KeyError : # raw command ul...
Performs a keepalive to avoid idle disconnect
218
10
247,990
def download ( self , url , file ) : if isinstance ( file , str ) or isinstance ( file , unicode ) : file = open ( file , 'wb' ) webclient = self . dupe ( ) webclient . request ( 'GET' , url ) rsp = webclient . getresponse ( ) self . _currdl = rsp self . _dlfile = file for chunk in iter ( lambda : rsp . read ( 16384 ) ...
Download a file to filename or file object
123
8
247,991
def upload ( self , url , filename , data = None , formname = None , otherfields = ( ) ) : if data is None : data = open ( filename , 'rb' ) self . _upbuffer = StringIO . StringIO ( get_upload_form ( filename , data , formname , otherfields ) ) ulheaders = self . stdheaders . copy ( ) ulheaders [ 'Content-Type' ] = 'mu...
Upload a file to the url
270
6
247,992
def parse_inventory_category_entry ( raw , fields ) : r = raw obj = { } bytes_read = 0 discard = False for field in fields : value = struct . unpack_from ( field . fmt , r ) [ 0 ] read = struct . calcsize ( field . fmt ) bytes_read += read r = r [ read : ] # If this entry is not actually present, just parse and then di...
Parses one entry in an inventory category .
225
10
247,993
def sessionless_data ( self , data , sockaddr ) : if len ( data ) < 22 : return data = bytearray ( data ) if not ( data [ 0 ] == 6 and data [ 2 : 4 ] == b'\xff\x07' ) : # not ipmi return if data [ 4 ] == 6 : # ipmi 2 payload... payloadtype = data [ 5 ] if payloadtype not in ( 0 , 16 ) : return if payloadtype == 16 : # ...
Examines unsolocited packet and decides appropriate action .
408
12
247,994
def set_kg ( self , kg ) : try : self . kg = kg . encode ( 'utf-8' ) except AttributeError : self . kg = kg
Sets the Kg for the BMC to use
36
10
247,995
def source_debianize_name ( name ) : name = name . replace ( '_' , '-' ) name = name . replace ( '.' , '-' ) name = name . lower ( ) return name
make name acceptable as a Debian source package name
45
9
247,996
def get_date_822 ( ) : cmd = '/bin/date' if not os . path . exists ( cmd ) : raise ValueError ( '%s command does not exist.' % cmd ) args = [ cmd , '-R' ] result = get_cmd_stdout ( args ) . strip ( ) result = normstr ( result ) return result
return output of 822 - date command
77
8
247,997
def make_tarball ( tarball_fname , directory , cwd = None ) : if tarball_fname . endswith ( '.gz' ) : opts = 'czf' else : opts = 'cf' args = [ '/bin/tar' , opts , tarball_fname , directory ] process_command ( args , cwd = cwd )
create a tarball from a directory
83
7
247,998
def expand_tarball ( tarball_fname , cwd = None ) : if tarball_fname . endswith ( '.gz' ) : opts = 'xzf' elif tarball_fname . endswith ( '.bz2' ) : opts = 'xjf' else : opts = 'xf' args = [ '/bin/tar' , opts , tarball_fname ] process_command ( args , cwd = cwd )
expand a tarball
107
5
247,999
def expand_zip ( zip_fname , cwd = None ) : unzip_path = '/usr/bin/unzip' if not os . path . exists ( unzip_path ) : log . error ( 'ERROR: {} does not exist' . format ( unzip_path ) ) sys . exit ( 1 ) args = [ unzip_path , zip_fname ] # Does it have a top dir res = subprocess . Popen ( [ args [ 0 ] , '-l' , args [ 1 ] ...
expand a zip
261
4