idx
int64
0
63k
question
stringlengths
61
4.03k
target
stringlengths
6
1.23k
43,200
def _from_numpy ( data , origin = None , spacing = None , direction = None , has_components = False , is_rgb = False ) : if is_rgb : has_components = True ndim = data . ndim if has_components : ndim -= 1 dtype = data . dtype . name ptype = _npy_to_itk_map [ dtype ] data = np . array ( data ) if origin is None : origin ...
Internal function for creating an ANTsImage
43,201
def make_image ( imagesize , voxval = 0 , spacing = None , origin = None , direction = None , has_components = False , pixeltype = 'float' ) : if isinstance ( imagesize , iio . ANTsImage ) : img = imagesize . clone ( ) sel = imagesize > 0 if voxval . ndim > 1 : voxval = voxval . flatten ( ) if ( len ( voxval ) == int (...
Make an image with given size and voxel value or given a mask and vector
43,202
def matrix_to_images ( data_matrix , mask ) : if data_matrix . ndim > 2 : data_matrix = data_matrix . reshape ( data_matrix . shape [ 0 ] , - 1 ) numimages = len ( data_matrix ) numVoxelsInMatrix = data_matrix . shape [ 1 ] numVoxelsInMask = ( mask >= 0.5 ) . sum ( ) if numVoxelsInMask != numVoxelsInMatrix : raise Valu...
Unmasks rows of a matrix and writes as images
43,203
def images_to_matrix ( image_list , mask = None , sigma = None , epsilon = 0.5 ) : def listfunc ( x ) : if np . sum ( np . array ( x . shape ) - np . array ( mask . shape ) ) != 0 : x = reg . resample_image_to_target ( x , mask , 2 ) return x [ mask ] if mask is None : mask = utils . get_mask ( image_list [ 0 ] ) num_i...
Read images into rows of a matrix given a mask - much faster for large datasets as it is based on C ++ implementations .
43,204
def timeseries_to_matrix ( image , mask = None ) : temp = utils . ndimage_to_list ( image ) if mask is None : mask = temp [ 0 ] * 0 + 1 return image_list_to_matrix ( temp , mask )
Convert a timeseries image into a matrix .
43,205
def matrix_to_timeseries ( image , matrix , mask = None ) : if mask is None : mask = temp [ 0 ] * 0 + 1 temp = matrix_to_images ( matrix , mask ) newImage = utils . list_to_ndimage ( image , temp ) iio . copy_image_info ( image , newImage ) return ( newImage )
converts a matrix to a ND image .
43,206
def image_header_info ( filename ) : if not os . path . exists ( filename ) : raise Exception ( 'filename does not exist' ) libfn = utils . get_lib_fn ( 'antsImageHeaderInfo' ) retval = libfn ( filename ) retval [ 'dimensions' ] = tuple ( retval [ 'dimensions' ] ) retval [ 'origin' ] = tuple ( [ round ( o , 4 ) for o i...
Read file info from image header
43,207
def image_read ( filename , dimension = None , pixeltype = 'float' , reorient = False ) : if filename . endswith ( '.npy' ) : filename = os . path . expanduser ( filename ) img_array = np . load ( filename ) if os . path . exists ( filename . replace ( '.npy' , '.json' ) ) : with open ( filename . replace ( '.npy' , '....
Read an ANTsImage from file
43,208
def dicom_read ( directory , pixeltype = 'float' ) : slices = [ ] imgidx = 0 for imgpath in os . listdir ( directory ) : if imgpath . endswith ( '.dcm' ) : if imgidx == 0 : tmp = image_read ( os . path . join ( directory , imgpath ) , dimension = 3 , pixeltype = pixeltype ) origin = tmp . origin spacing = tmp . spacing...
Read a set of dicom files in a directory into a single ANTsImage . The origin of the resulting 3D image will be the origin of the first dicom image read .
43,209
def image_write ( image , filename , ri = False ) : if filename . endswith ( '.npy' ) : img_array = image . numpy ( ) img_header = { 'origin' : image . origin , 'spacing' : image . spacing , 'direction' : image . direction . tolist ( ) , 'components' : image . components } np . save ( filename , img_array ) with open (...
Write an ANTsImage to file
43,210
def otsu_segmentation ( image , k , mask = None ) : if mask is not None : image = image . mask_image ( mask ) seg = image . threshold_image ( 'Otsu' , k ) return seg
Otsu image segmentation
43,211
def crop_image ( image , label_image = None , label = 1 ) : inpixeltype = image . pixeltype ndim = image . dimension if image . pixeltype != 'float' : image = image . clone ( 'float' ) if label_image is None : label_image = get_mask ( image ) if label_image . pixeltype != 'float' : label_image = label_image . clone ( '...
Use a label image to crop a smaller ANTsImage from within a larger ANTsImage
43,212
def decrop_image ( cropped_image , full_image ) : inpixeltype = 'float' if cropped_image . pixeltype != 'float' : inpixeltype = cropped_image . pixeltype cropped_image = cropped_image . clone ( 'float' ) if full_image . pixeltype != 'float' : full_image = full_image . clone ( 'float' ) libfn = utils . get_lib_fn ( 'cro...
The inverse function for ants . crop_image
43,213
def kmeans_segmentation ( image , k , kmask = None , mrf = 0.1 ) : dim = image . dimension kmimage = utils . iMath ( image , 'Normalize' ) if kmask is None : kmask = utils . get_mask ( kmimage , 0.01 , 1 , cleanup = 2 ) kmask = utils . iMath ( kmask , 'FillHoles' ) . threshold_image ( 1 , 2 ) nhood = 'x' . join ( [ '1'...
K - means image segmentation that is a wrapper around ants . atropos
43,214
def reorient_image2 ( image , orientation = 'RAS' ) : if image . dimension != 3 : raise ValueError ( 'image must have 3 dimensions' ) inpixeltype = image . pixeltype ndim = image . dimension if image . pixeltype != 'float' : image = image . clone ( 'float' ) libfn = utils . get_lib_fn ( 'reorientImage2' ) itkimage = li...
Reorient an image .
43,215
def reorient_image ( image , axis1 , axis2 = None , doreflection = False , doscale = 0 , txfn = None ) : inpixeltype = image . pixeltype if image . pixeltype != 'float' : image = image . clone ( 'float' ) axis_was_none = False if axis2 is None : axis_was_none = True axis2 = [ 0 ] * image . dimension axis1 = np . array ...
Align image along a specified axis
43,216
def get_center_of_mass ( image ) : if image . pixeltype != 'float' : image = image . clone ( 'float' ) libfn = utils . get_lib_fn ( 'centerOfMass%s' % image . _libsuffix ) com = libfn ( image . pointer ) return tuple ( com )
Compute an image center of mass in physical space which is defined as the mean of the intensity weighted voxel coordinate system .
43,217
def to_nibabel ( image ) : if image . dimension != 3 : raise ValueError ( 'Only 3D images currently supported' ) import nibabel as nib array_data = image . numpy ( ) affine = np . hstack ( [ image . direction * np . diag ( image . spacing ) , np . array ( image . origin ) . reshape ( 3 , 1 ) ] ) affine = np . vstack ( ...
Convert an ANTsImage to a Nibabel image
43,218
def from_nibabel ( nib_image ) : tmpfile = mktemp ( suffix = '.nii.gz' ) nib_image . to_filename ( tmpfile ) new_img = iio2 . image_read ( tmpfile ) os . remove ( tmpfile ) return new_img
Convert a nibabel image to an ANTsImage
43,219
def transform ( self , X = None , y = None ) : shear_x = random . gauss ( self . shear_range [ 0 ] , self . shear_range [ 1 ] ) shear_y = random . gauss ( self . shear_range [ 0 ] , self . shear_range [ 1 ] ) shear_z = random . gauss ( self . shear_range [ 0 ] , self . shear_range [ 1 ] ) self . params = ( shear_x , sh...
Transform an image using an Affine transform with shear parameters randomly generated from the user - specified range . Return the transform if X = None .
43,220
def transform ( self , X = None , y = None ) : zoom_x = np . exp ( random . gauss ( np . log ( self . zoom_range [ 0 ] ) , np . log ( self . zoom_range [ 1 ] ) ) ) zoom_y = np . exp ( random . gauss ( np . log ( self . zoom_range [ 0 ] ) , np . log ( self . zoom_range [ 1 ] ) ) ) zoom_z = np . exp ( random . gauss ( np...
Transform an image using an Affine transform with zoom parameters randomly generated from the user - specified range . Return the transform if X = None .
43,221
def transform ( self , X = None , y = None ) : translation_x , translation_y = self . translation translation_matrix = np . array ( [ [ 1 , 0 , translation_x ] , [ 0 , 1 , translation_y ] ] ) self . tx . set_parameters ( translation_matrix ) if self . lazy or X is None : return self . tx else : return self . tx . apply...
Transform an image using an Affine transform with the given translation parameters . Return the transform if X = None .
43,222
def transform ( self , X = None , y = None ) : translation_x = random . gauss ( self . translation_range [ 0 ] , self . translation_range [ 1 ] ) translation_y = random . gauss ( self . translation_range [ 0 ] , self . translation_range [ 1 ] ) self . params = ( translation_x , translation_y ) tx = Translate2D ( ( tran...
Transform an image using an Affine transform with translation parameters randomly generated from the user - specified range . Return the transform if X = None .
43,223
def transform ( self , X = None , y = None ) : shear = [ math . pi / 180 * s for s in self . shear ] shear_x , shear_y = shear shear_matrix = np . array ( [ [ 1 , shear_x , 0 ] , [ shear_y , 1 , 0 ] ] ) self . tx . set_parameters ( shear_matrix ) if self . lazy or X is None : return self . tx else : return self . tx . ...
Transform an image using an Affine transform with the given shear parameters . Return the transform if X = None .
43,224
def transform ( self , X = None , y = None ) : zoom_x , zoom_y = self . zoom self . params = ( zoom_x , zoom_y ) zoom_matrix = np . array ( [ [ zoom_x , 0 , 0 ] , [ 0 , zoom_y , 0 ] ] ) self . tx . set_parameters ( zoom_matrix ) if self . lazy or X is None : return self . tx else : return self . tx . apply_to_image ( X...
Transform an image using an Affine transform with the given zoom parameters . Return the transform if X = None .
43,225
def kelly_kapowski ( s , g , w , its = 50 , r = 0.025 , m = 1.5 , ** kwargs ) : if isinstance ( s , iio . ANTsImage ) : s = s . clone ( 'unsigned int' ) d = s . dimension outimg = g . clone ( ) kellargs = { 'd' : d , 's' : s , 'g' : g , 'w' : w , 'c' : its , 'r' : r , 'm' : m , 'o' : outimg } for k , v in kwargs . item...
Compute cortical thickness using the DiReCT algorithm .
43,226
def new_ants_transform ( precision = 'float' , dimension = 3 , transform_type = 'AffineTransform' , parameters = None ) : libfn = utils . get_lib_fn ( 'newAntsTransform%s%i' % ( utils . short_ptype ( precision ) , dimension ) ) itk_tx = libfn ( precision , dimension , transform_type ) ants_tx = tio . ANTsTransform ( pr...
Create a new ANTsTransform
43,227
def create_ants_transform ( transform_type = 'AffineTransform' , precision = 'float' , dimension = 3 , matrix = None , offset = None , center = None , translation = None , parameters = None , fixed_parameters = None , displacement_field = None , supported_types = False ) : def _check_arg ( arg , dim = 1 ) : if arg is N...
Create and initialize an ANTsTransform
43,228
def read_transform ( filename , dimension = 2 , precision = 'float' ) : filename = os . path . expanduser ( filename ) if not os . path . exists ( filename ) : raise ValueError ( 'filename does not exist!' ) libfn1 = utils . get_lib_fn ( 'getTransformDimensionFromFile' ) dimension = libfn1 ( filename ) libfn2 = utils ....
Read a transform from file
43,229
def write_transform ( transform , filename ) : filename = os . path . expanduser ( filename ) libfn = utils . get_lib_fn ( 'writeTransform%s' % ( transform . _libsuffix ) ) libfn ( transform . pointer , filename )
Write ANTsTransform to file
43,230
def reflect_image ( image , axis = None , tx = None , metric = 'mattes' ) : if axis is None : axis = image . dimension - 1 if ( axis > image . dimension ) or ( axis < 0 ) : axis = image . dimension - 1 rflct = mktemp ( suffix = '.mat' ) libfn = utils . get_lib_fn ( 'reflectionMatrix%s' % image . _libsuffix ) libfn ( im...
Reflect an image along an axis
43,231
def create_sampler ( self , inputs , targets , input_reader = None , target_reader = None , input_transform = None , target_transform = None , co_transform = None , input_return_processor = None , target_return_processor = None , co_return_processor = None ) : pass
Create a BIDSSampler that can be used to generate infinite augmented samples
43,232
def slice_image ( image , axis = None , idx = None ) : if image . dimension < 3 : raise ValueError ( 'image must have at least 3 dimensions' ) inpixeltype = image . pixeltype ndim = image . dimension if image . pixeltype != 'float' : image = image . clone ( 'float' ) libfn = utils . get_lib_fn ( 'sliceImageF%i' % ndim ...
Slice an image .
43,233
def pad_image ( image , shape = None , pad_width = None , value = 0.0 , return_padvals = False ) : inpixeltype = image . pixeltype ndim = image . dimension if image . pixeltype != 'float' : image = image . clone ( 'float' ) if pad_width is None : if shape is None : shape = [ max ( image . shape ) ] * image . dimension ...
Pad an image to have the given shape or to be isotropic .
43,234
def set_fixed_image ( self , image ) : if not isinstance ( image , iio . ANTsImage ) : raise ValueError ( 'image must be ANTsImage type' ) if image . dimension != self . dimension : raise ValueError ( 'image dim (%i) does not match metric dim (%i)' % ( image . dimension , self . dimension ) ) self . _metric . setFixedI...
Set Fixed ANTsImage for metric
43,235
def set_moving_image ( self , image ) : if not isinstance ( image , iio . ANTsImage ) : raise ValueError ( 'image must be ANTsImage type' ) if image . dimension != self . dimension : raise ValueError ( 'image dim (%i) does not match metric dim (%i)' % ( image . dimension , self . dimension ) ) self . _metric . setMovin...
Set Moving ANTsImage for metric
43,236
def image_to_cluster_images ( image , min_cluster_size = 50 , min_thresh = 1e-06 , max_thresh = 1 ) : if not isinstance ( image , iio . ANTsImage ) : raise ValueError ( 'image must be ANTsImage type' ) clust = label_clusters ( image , min_cluster_size , min_thresh , max_thresh ) labs = np . unique ( clust [ clust > 0 ]...
Converts an image to several independent images .
43,237
def threshold_image ( image , low_thresh = None , high_thresh = None , inval = 1 , outval = 0 , binary = True ) : if high_thresh is None : high_thresh = image . max ( ) + 0.01 if low_thresh is None : low_thresh = image . min ( ) - 0.01 dim = image . dimension outimage = image . clone ( ) args = [ dim , image , outimage...
Converts a scalar image into a binary image by thresholding operations
43,238
def symmetrize_image ( image ) : imager = reflect_image ( image , axis = 0 ) imageavg = imager * 0.5 + image for i in range ( 5 ) : w1 = registration ( imageavg , image , type_of_transform = 'SyN' ) w2 = registration ( imageavg , imager , type_of_transform = 'SyN' ) xavg = w1 [ 'warpedmovout' ] * 0.5 + w2 [ 'warpedmovo...
Use registration and reflection to make an image symmetric
43,239
def _get_attachments ( self , id ) : uri = '/' . join ( [ self . base_url , self . name , id , 'Attachments' ] ) + '/' return uri , { } , 'get' , None , None , False
Retrieve a list of attachments associated with this Xero object .
43,240
def _put_attachment_data ( self , id , filename , data , content_type , include_online = False ) : uri = '/' . join ( [ self . base_url , self . name , id , 'Attachments' , filename ] ) params = { 'IncludeOnline' : 'true' } if include_online else { } headers = { 'Content-Type' : content_type , 'Content-Length' : str ( ...
Upload an attachment to the Xero object .
43,241
def page_response ( self , title = '' , body = '' ) : f = StringIO ( ) f . write ( '<!DOCTYPE html>\n' ) f . write ( '<html>\n' ) f . write ( '<head><title>{}</title><head>\n' . format ( title ) ) f . write ( '<body>\n<h2>{}</h2>\n' . format ( title ) ) f . write ( '<div class="content">{}</div>\n' . format ( body ) ) ...
Helper to render an html page with dynamic content
43,242
def redirect_response ( self , url , permanent = False ) : if permanent : self . send_response ( 301 ) else : self . send_response ( 302 ) self . send_header ( "Location" , url ) self . end_headers ( )
Generate redirect response
43,243
def _init_credentials ( self , oauth_token , oauth_token_secret ) : "Depending on the state passed in, get self._oauth up and running" if oauth_token and oauth_token_secret : if self . verified : self . _init_oauth ( oauth_token , oauth_token_secret ) else : self . oauth_token = oauth_token self . oauth_token_secret = ...
Depending on the state passed in get self . _oauth up and running
43,244
def _init_oauth ( self , oauth_token , oauth_token_secret ) : "Store and initialize a verified set of OAuth credentials" self . oauth_token = oauth_token self . oauth_token_secret = oauth_token_secret self . _oauth = OAuth1 ( self . consumer_key , client_secret = self . consumer_secret , resource_owner_key = self . oau...
Store and initialize a verified set of OAuth credentials
43,245
def _process_oauth_response ( self , response ) : "Extracts the fields from an oauth response" if response . status_code == 200 : credentials = parse_qs ( response . text ) self . _init_oauth ( credentials . get ( 'oauth_token' ) [ 0 ] , credentials . get ( 'oauth_token_secret' ) [ 0 ] ) self . oauth_session_handle = c...
Extracts the fields from an oauth response
43,246
def state ( self ) : return dict ( ( attr , getattr ( self , attr ) ) for attr in ( 'consumer_key' , 'consumer_secret' , 'callback_uri' , 'verified' , 'oauth_token' , 'oauth_token_secret' , 'oauth_session_handle' , 'oauth_expires_at' , 'oauth_authorization_expires_at' , 'scope' ) if getattr ( self , attr ) is not None ...
Obtain the useful state of this credentials object so that we can reconstruct it independently .
43,247
def verify ( self , verifier ) : "Verify an OAuth token" oauth = OAuth1 ( self . consumer_key , client_secret = self . consumer_secret , resource_owner_key = self . oauth_token , resource_owner_secret = self . oauth_token_secret , verifier = verifier , rsa_key = self . rsa_key , signature_method = self . _signature_met...
Verify an OAuth token
43,248
def url ( self ) : "Returns the URL that can be visited to obtain a verifier code" query_string = { 'oauth_token' : self . oauth_token } if self . scope : query_string [ 'scope' ] = self . scope url = XERO_BASE_URL + AUTHORIZE_URL + '?' + urlencode ( query_string ) return url
Returns the URL that can be visited to obtain a verifier code
43,249
def refresh ( self ) : "Refresh an expired token" oauth = OAuth1 ( self . consumer_key , client_secret = self . consumer_secret , resource_owner_key = self . oauth_token , resource_owner_secret = self . oauth_token_secret , rsa_key = self . rsa_key , signature_method = self . _signature_method ) headers = { 'User-Agent...
Refresh an expired token
43,250
def _get_files ( self , folderId ) : uri = '/' . join ( [ self . base_url , self . name , folderId , 'Files' ] ) return uri , { } , 'get' , None , None , False , None
Retrieve the list of files contained in a folder
43,251
def handle_cluster_request ( self , tsn , command_id , args ) : if command_id == 0 : if self . _timer_handle : self . _timer_handle . cancel ( ) loop = asyncio . get_event_loop ( ) self . _timer_handle = loop . call_later ( 30 , self . _turn_off )
Handle the cluster command .
43,252
def _parse_attributes ( self , value ) : from zigpy . zcl import foundation as f attributes = { } attribute_names = { 1 : BATTERY_VOLTAGE_MV , 3 : TEMPERATURE , 4 : XIAOMI_ATTR_4 , 5 : XIAOMI_ATTR_5 , 6 : XIAOMI_ATTR_6 , 10 : PATH } result = { } while value : skey = int ( value [ 0 ] ) svalue , value = f . TypeValue . ...
Parse non standard atrributes .
43,253
def _calculate_remaining_battery_percentage ( self , voltage ) : min_voltage = 2500 max_voltage = 3000 percent = ( voltage - min_voltage ) / ( max_voltage - min_voltage ) * 200 return min ( 200 , percent )
Calculate percentage .
43,254
def battery_reported ( self , voltage , rawVoltage ) : self . _update_attribute ( BATTERY_PERCENTAGE_REMAINING , voltage ) self . _update_attribute ( self . BATTERY_VOLTAGE_ATTR , int ( rawVoltage / 100 ) )
Battery reported .
43,255
async def configure_reporting ( self , attribute , min_interval , max_interval , reportable_change ) : result = await super ( ) . configure_reporting ( PowerConfigurationCluster . BATTERY_VOLTAGE_ATTR , self . FREQUENCY , self . FREQUENCY , self . MINIMUM_CHANGE ) return result
Configure reporting .
43,256
def update ( self , ** kwargs ) : inherit_device_group = self . __dict__ . get ( 'inheritedDevicegroup' , False ) if inherit_device_group == 'true' : self . __dict__ . pop ( 'deviceGroup' ) return self . _update ( ** kwargs )
Update the object removing device group if inherited
43,257
def sync_to ( self ) : device_group_collection = self . _meta_data [ 'container' ] cm = device_group_collection . _meta_data [ 'container' ] sync_cmd = 'config-sync to-group %s' % self . name cm . exec_cmd ( 'run' , utilCmdArgs = sync_cmd )
Wrapper method that synchronizes configuration to DG .
43,258
def _create ( self , ** kwargs ) : try : return super ( Service , self ) . _create ( ** kwargs ) except HTTPError as ex : if "The configuration was updated successfully but could not be " "retrieved" not in ex . response . text : raise if 'partition' not in kwargs : kwargs [ 'partition' ] = 'Common' kwargs_copy = kwarg...
Create service on device and create accompanying Python object .
43,259
def _build_service_uri ( self , base_uri , partition , name ) : name = name . replace ( '/' , '~' ) return '%s~%s~%s.app~%s' % ( base_uri , partition , name , name )
Build the proper uri for a service resource .
43,260
def delete ( self , ** kwargs ) : if 'id' not in kwargs : delete_uri = self . _meta_data [ 'uri' ] if delete_uri . endswith ( '/' ) : delete_uri = delete_uri [ 0 : - 1 ] kwargs [ 'id' ] = os . path . basename ( delete_uri ) uid = uuid . UUID ( kwargs [ 'id' ] , version = 4 ) if uid . hex != kwargs [ 'id' ] . replace ( ...
Deletes a member from a license pool
43,261
def _set_attributes ( self , ** kwargs ) : self . devices = kwargs [ 'devices' ] [ : ] self . partition = kwargs [ 'partition' ] self . device_group_name = 'device_trust_group' self . device_group_type = 'sync-only'
Set attributes for instance in one place
43,262
def validate ( self ) : self . _populate_domain ( ) missing = [ ] for domain_device in self . domain : for truster , trustees in iteritems ( self . domain ) : if domain_device not in trustees : missing . append ( ( domain_device , truster , trustees ) ) if missing : msg = '' for item in missing : msg += '\n%r is not tr...
Validate that devices are each trusted by one another
43,263
def _populate_domain ( self ) : self . domain = { } for device in self . devices : device_name = get_device_info ( device ) . name ca_devices = device . tm . cm . trust_domains . trust_domain . load ( name = 'Root' ) . caDevices self . domain [ device_name ] = [ d . replace ( '/%s/' % self . partition , '' ) for d in c...
Populate TrustDomain s domain attribute .
43,264
def create ( self , ** kwargs ) : self . _set_attributes ( ** kwargs ) for device in self . devices [ 1 : ] : self . _add_trustee ( device ) pollster ( self . validate ) ( )
Add trusted peers to the root bigip device .
43,265
def teardown ( self ) : for device in self . devices : self . _remove_trustee ( device ) self . _populate_domain ( ) self . domain = { }
Teardown trust domain by removing trusted devices .
43,266
def _add_trustee ( self , device ) : device_name = get_device_info ( device ) . name if device_name in self . domain : msg = 'Device: %r is already in this trust domain.' % device_name raise DeviceAlreadyInTrustDomain ( msg ) self . _modify_trust ( self . devices [ 0 ] , self . _get_add_trustee_cmd , device )
Add a single trusted device to the trust domain .
43,267
def _remove_trustee ( self , device ) : trustee_name = get_device_info ( device ) . name name_object_map = get_device_names_to_objects ( self . devices ) delete_func = self . _get_delete_trustee_cmd for truster in self . domain : if trustee_name in self . domain [ truster ] and truster != trustee_name : truster_obj = n...
Remove a trustee from the trust domain .
43,268
def _modify_trust ( self , truster , mod_peer_func , trustee ) : iapp_name = 'trusted_device' mod_peer_cmd = mod_peer_func ( trustee ) iapp_actions = self . iapp_actions . copy ( ) iapp_actions [ 'definition' ] [ 'implementation' ] = mod_peer_cmd self . _deploy_iapp ( iapp_name , iapp_actions , truster ) self . _delete...
Modify a trusted peer device by deploying an iapp .
43,269
def _delete_iapp ( self , iapp_name , deploying_device ) : iapp = deploying_device . tm . sys . application iapp_serv = iapp . services . service . load ( name = iapp_name , partition = self . partition ) iapp_serv . delete ( ) iapp_tmpl = iapp . templates . template . load ( name = iapp_name , partition = self . parti...
Delete an iapp service and template on the root device .
43,270
def _deploy_iapp ( self , iapp_name , actions , deploying_device ) : tmpl = deploying_device . tm . sys . application . templates . template serv = deploying_device . tm . sys . application . services . service tmpl . create ( name = iapp_name , partition = self . partition , actions = actions ) pollster ( deploying_de...
Deploy iapp to add trusted device
43,271
def _get_add_trustee_cmd ( self , trustee ) : trustee_info = pollster ( get_device_info ) ( trustee ) username = trustee . _meta_data [ 'username' ] password = trustee . _meta_data [ 'password' ] return 'tmsh::modify cm trust-domain Root ca-devices add ' '\\{ %s \\} name %s username %s password %s' % ( trustee_info . m...
Get tmsh command to add a trusted device .
43,272
def load ( self , ** kwargs ) : kwargs [ 'transform_name' ] = True kwargs = self . _mutate_name ( kwargs ) return self . _load ( ** kwargs )
Loads a given resource
43,273
def _get_section_end_index ( self , section , section_start ) : brace_count = 0 in_quote = False in_escape = False for index , char in enumerate ( self . template_str [ section_start : ] ) : if char == '\\' and not in_escape : in_escape = True elif char == '\\' and in_escape : in_escape = False if not in_escape : if ch...
Get end of section s content .
43,274
def _get_section_start_index ( self , section ) : sec_start_re = r'%s\s*\{' % section found = re . search ( sec_start_re , self . template_str ) if found : return found . end ( ) - 1 raise NonextantSectionException ( 'Section %s not found in template' % section )
Get start of a section s content .
43,275
def _get_template_name ( self ) : start_pattern = r"sys application template\s+" r"(\/[\w\.\-]+\/)?" r"(?P<name>[\w\.\-]+)\s*\{" template_start = re . search ( start_pattern , self . template_str ) if template_start : return template_start . group ( 'name' ) raise NonextantTemplateNameException ( 'Template name not fou...
Find template name .
43,276
def _get_template_attr ( self , attr ) : attr_re = r'{0}\s+.*' . format ( attr ) attr_found = re . search ( attr_re , self . template_str ) if attr_found : attr_value = attr_found . group ( 0 ) . replace ( attr , '' , 1 ) return attr_value . strip ( )
Find the attribute value for a specific attribute .
43,277
def _add_sections ( self ) : for section in self . template_sections : try : sec_start = self . _get_section_start_index ( section ) except NonextantSectionException : if section in self . sections_not_required : continue raise sec_end = self . _get_section_end_index ( section , sec_start ) section_value = self . templ...
Add the found and required sections to the templ_dict .
43,278
def _add_cli_scripts ( self ) : pattern = r"cli script\s+" r"(\/[\w\.\-]+\/)?" r"(?P<name>[\w\.\-]+)\s*\{" sections = re . finditer ( pattern , self . template_str ) for section in sections : if 'scripts' not in self . templ_dict : self . templ_dict [ 'scripts' ] = [ ] try : sec_start = self . _get_section_start_index ...
Add the found external sections to the templ_dict .
43,279
def _add_attrs ( self ) : for attr in self . template_attrs : attr_value = self . _get_template_attr ( attr ) if not attr_value : continue attr , attr_value = self . _transform_key_value ( attr , attr_value , self . attr_map ) self . templ_dict [ attr ] = attr_value
Add the found and required attrs to the templ_dict .
43,280
def _parse_tcl_list ( self , attr , list_str ) : list_str = list_str . strip ( ) if not list_str : return [ ] if list_str [ 0 ] != '{' and list_str [ - 1 ] != '}' : if list_str . find ( 'none' ) >= 0 : return list_str if not re . search ( self . tcl_list_patterns [ attr ] , list_str ) : raise MalformedTCLListException ...
Turns a string representation of a TCL list into a Python list .
43,281
def _transform_key_value ( self , key , value , map_dict ) : if key in self . tcl_list_patterns : value = self . _parse_tcl_list ( key , value ) if key in map_dict : key = map_dict [ key ] return key , value
Massage keys and values for iapp dict to look like JSON .
43,282
def parse_template ( self ) : self . templ_dict = { 'actions' : { 'definition' : { } } } self . templ_dict [ 'name' ] = self . _get_template_name ( ) self . _add_cli_scripts ( ) self . _add_sections ( ) self . _add_attrs ( ) return self . templ_dict
Parse the template string into a dict .
43,283
def _create ( self , ** kwargs ) : if 'uri' in self . _meta_data : error = "There was an attempt to assign a new uri to this " "resource, the _meta_data['uri'] is %s and it should" " not be changed." % ( self . _meta_data [ 'uri' ] ) raise URICreationCollision ( error ) self . _check_exclusive_parameters ( ** kwargs ) ...
wrapped by create override that in subclasses to customize
43,284
def peer ( opt_peer , opt_username , opt_password , scope = "module" ) : p = BigIP ( opt_peer , opt_username , opt_password ) return p
peer bigip fixture
43,285
def exists ( self , ** kwargs ) : kwargs . pop ( 'partition' , None ) kwargs [ 'transform_name' ] = True return self . _exists ( ** kwargs )
Providing a partition is not necessary on topology ; causes errors
43,286
def _key_dot_replace ( self , rdict ) : temp_dict = { } for key , value in iteritems ( rdict ) : if isinstance ( value , dict ) : value = self . _key_dot_replace ( value ) temp_dict [ key . replace ( '.' , '_' ) ] = value return temp_dict
Replace fullstops in returned keynames
43,287
def _get_nest_stats ( self ) : for x in self . rdict : check = urlparse ( x ) if check . scheme : nested_dict = self . rdict [ x ] [ 'nestedStats' ] tmp_dict = nested_dict [ 'entries' ] return self . _key_dot_replace ( tmp_dict ) return self . _key_dot_replace ( self . rdict )
Helper method to deal with nestedStats
43,288
def refresh ( self , ** kwargs ) : self . resource . refresh ( ** kwargs ) self . rdict = self . resource . entries self . _update_stats ( )
Refreshes stats attached to an object
43,289
def load ( self , ** kwargs ) : if LooseVersion ( self . tmos_ver ) == LooseVersion ( '11.6.0' ) : return self . _load_11_6 ( ** kwargs ) else : return super ( Rule , self ) . _load ( ** kwargs )
Custom load method to address issue in 11 . 6 . 0 Final
43,290
def poll_for_exceptionless_callable ( callable , attempts , interval ) : @ wraps ( callable ) def poll ( * args , ** kwargs ) : for attempt in range ( attempts ) : try : return callable ( * args , ** kwargs ) except Exception as ex : if attempt == attempts - 1 : raise MaximumAttemptsReached ( ex ) time . sleep ( interv...
Poll with a given callable for a specified number of times .
43,291
def exists ( self , ** kwargs ) : if LooseVersion ( self . tmos_ver ) == LooseVersion ( '11.6.0' ) : return self . _exists_11_6 ( ** kwargs ) else : return super ( Network , self ) . _exists ( ** kwargs )
Some objects when deleted still return when called by their
43,292
def _is_allowed_command ( self , command ) : cmds = self . _meta_data [ 'allowed_commands' ] if command not in self . _meta_data [ 'allowed_commands' ] : error_message = "The command value {0} does not exist. " "Valid commands are {1}" . format ( command , cmds ) raise InvalidCommand ( error_message )
Checking if the given command is allowed on a given endpoint .
43,293
def _check_command_result ( self ) : if self . commandResult . startswith ( '/bin/bash' ) : raise UtilError ( '%s' % self . commandResult . split ( ' ' , 1 ) [ 1 ] ) if self . commandResult . startswith ( '/bin/mv' ) : raise UtilError ( '%s' % self . commandResult . split ( ' ' , 1 ) [ 1 ] ) if self . commandResult . s...
If command result exists run these checks .
43,294
def exec_cmd ( self , command , ** kwargs ) : self . _is_allowed_command ( command ) self . _check_command_parameters ( ** kwargs ) return self . _exec_cmd ( command , ** kwargs )
Wrapper method that can be changed in the inheriting classes .
43,295
def _exec_cmd ( self , command , ** kwargs ) : kwargs [ 'command' ] = command self . _check_exclusive_parameters ( ** kwargs ) requests_params = self . _handle_requests_params ( kwargs ) session = self . _meta_data [ 'bigip' ] . _meta_data [ 'icr_session' ] response = session . post ( self . _meta_data [ 'uri' ] , json...
Create a new method as command has specific requirements .
43,296
def get_device_info ( self , bigip ) : coll = bigip . tm . cm . devices . get_collection ( ) device = [ device for device in coll if device . selfDevice == 'true' ] assert len ( device ) == 1 return device [ 0 ]
Get device information about a specific BigIP device .
43,297
def _check_existence_by_collection ( self , container , item_name ) : coll = container . get_collection ( ) for item in coll : if item . name == item_name : return True return False
Check existnce of item based on get collection call .
43,298
def _return_object ( self , container , item_name ) : coll = container . get_collection ( ) for item in coll : if item . name == item_name : return item
Helper method to retrieve the object
43,299
def exec_cmd ( self , command , ** kwargs ) : if command == 'load' : if kwargs : kwargs = dict ( options = [ kwargs ] ) return self . _exec_cmd ( command , ** kwargs )
Normal save and load only need the command .