idx
int64
0
252k
question
stringlengths
48
5.28k
target
stringlengths
5
1.23k
238,100
def arm ( self , value ) : if value : return api . request_system_arm ( self . blink , self . network_id ) return api . request_system_disarm ( self . blink , self . network_id )
Arm or disarm system .
238,101
def start ( self ) : response = api . request_syncmodule ( self . blink , self . network_id , force = True ) try : self . summary = response [ 'syncmodule' ] self . network_id = self . summary [ 'network_id' ] except ( TypeError , KeyError ) : _LOGGER . error ( ( "Could not retrieve sync module information " "with resp...
Initialize the system .
238,102
def get_events ( self , ** kwargs ) : force = kwargs . pop ( 'force' , False ) response = api . request_sync_events ( self . blink , self . network_id , force = force ) try : return response [ 'event' ] except ( TypeError , KeyError ) : _LOGGER . error ( "Could not extract events: %s" , response , exc_info = True ) ret...
Retrieve events from server .
238,103
def get_camera_info ( self , camera_id ) : response = api . request_camera_info ( self . blink , self . network_id , camera_id ) try : return response [ 'camera' ] [ 0 ] except ( TypeError , KeyError ) : _LOGGER . error ( "Could not extract camera info: %s" , response , exc_info = True ) return [ ]
Retrieve camera information .
238,104
def refresh ( self , force_cache = False ) : self . network_info = api . request_network_status ( self . blink , self . network_id ) self . check_new_videos ( ) for camera_name in self . cameras . keys ( ) : camera_id = self . cameras [ camera_name ] . camera_id camera_info = self . get_camera_info ( camera_id ) self ....
Get all blink cameras and pulls their most recent status .
238,105
def check_new_videos ( self ) : resp = api . request_videos ( self . blink , time = self . blink . last_refresh , page = 0 ) for camera in self . cameras . keys ( ) : self . motion [ camera ] = False try : info = resp [ 'videos' ] except ( KeyError , TypeError ) : _LOGGER . warning ( "Could not check for motion. Respon...
Check if new videos since last refresh .
238,106
def attributes ( self ) : attributes = { 'name' : self . name , 'camera_id' : self . camera_id , 'serial' : self . serial , 'temperature' : self . temperature , 'temperature_c' : self . temperature_c , 'temperature_calibrated' : self . temperature_calibrated , 'battery' : self . battery , 'thumbnail' : self . thumbnail...
Return dictionary of all camera attributes .
238,107
def snap_picture ( self ) : return api . request_new_image ( self . sync . blink , self . network_id , self . camera_id )
Take a picture with camera to create a new thumbnail .
238,108
def set_motion_detect ( self , enable ) : if enable : return api . request_motion_detection_enable ( self . sync . blink , self . network_id , self . camera_id ) return api . request_motion_detection_disable ( self . sync . blink , self . network_id , self . camera_id )
Set motion detection .
238,109
def update ( self , config , force_cache = False , ** kwargs ) : self . name = config [ 'name' ] self . camera_id = str ( config [ 'id' ] ) self . network_id = str ( config [ 'network_id' ] ) self . serial = config [ 'serial' ] self . motion_enabled = config [ 'enabled' ] self . battery_voltage = config [ 'battery_volt...
Update camera info .
238,110
def image_to_file ( self , path ) : _LOGGER . debug ( "Writing image from %s to %s" , self . name , path ) response = self . _cached_image if response . status_code == 200 : with open ( path , 'wb' ) as imgfile : copyfileobj ( response . raw , imgfile ) else : _LOGGER . error ( "Cannot write image to file, response %s"...
Write image to file .
238,111
def video_to_file ( self , path ) : _LOGGER . debug ( "Writing video from %s to %s" , self . name , path ) response = self . _cached_video if response is None : _LOGGER . error ( "No saved video exist for %s." , self . name , exc_info = True ) return with open ( path , 'wb' ) as vidfile : copyfileobj ( response . raw ,...
Write video to file .
238,112
def get_thumb_from_homescreen ( self ) : for device in self . sync . homescreen [ 'devices' ] : try : device_type = device [ 'device_type' ] device_name = device [ 'name' ] device_thumb = device [ 'thumbnail' ] if device_type == 'camera' and device_name == self . name : return device_thumb except KeyError : pass _LOGGE...
Retrieve thumbnail from homescreen .
238,113
def get_time ( time_to_convert = None ) : if time_to_convert is None : time_to_convert = time . time ( ) return time . strftime ( TIMESTAMP_FORMAT , time . localtime ( time_to_convert ) )
Create blink - compatible timestamp .
238,114
def merge_dicts ( dict_a , dict_b ) : duplicates = [ val for val in dict_a if val in dict_b ] if duplicates : _LOGGER . warning ( ( "Duplicates found during merge: %s. " "Renaming is recommended." ) , duplicates ) return { ** dict_a , ** dict_b }
Merge two dictionaries into one .
238,115
def attempt_reauthorization ( blink ) : _LOGGER . info ( "Auth token expired, attempting reauthorization." ) headers = blink . get_auth_token ( is_retry = True ) return headers
Attempt to refresh auth token and links .
238,116
def http_req ( blink , url = 'http://example.com' , data = None , headers = None , reqtype = 'get' , stream = False , json_resp = True , is_retry = False ) : if reqtype == 'post' : req = Request ( 'POST' , url , headers = headers , data = data ) elif reqtype == 'get' : req = Request ( 'GET' , url , headers = headers ) ...
Perform server requests and check if reauthorization neccessary .
238,117
def start ( self ) : if self . _username is None or self . _password is None : if not self . login ( ) : return elif not self . get_auth_token ( ) : return camera_list = self . get_cameras ( ) networks = self . get_ids ( ) for network_name , network_id in networks . items ( ) : if network_id not in camera_list . keys (...
Perform full system setup .
238,118
def login ( self ) : self . _username = input ( "Username:" ) self . _password = getpass . getpass ( "Password:" ) if self . get_auth_token ( ) : _LOGGER . debug ( "Login successful!" ) return True _LOGGER . warning ( "Unable to login with %s." , self . _username ) return False
Prompt user for username and password .
238,119
def get_auth_token ( self , is_retry = False ) : if not isinstance ( self . _username , str ) : raise BlinkAuthenticationException ( ERROR . USERNAME ) if not isinstance ( self . _password , str ) : raise BlinkAuthenticationException ( ERROR . PASSWORD ) login_urls = [ LOGIN_URL , OLD_LOGIN_URL , LOGIN_BACKUP_URL ] res...
Retrieve the authentication token from Blink .
238,120
def login_request ( self , login_urls , is_retry = False ) : try : login_url = login_urls . pop ( 0 ) except IndexError : _LOGGER . error ( "Could not login to blink servers." ) return False _LOGGER . info ( "Attempting login with %s" , login_url ) response = api . request_login ( self , login_url , self . _username , ...
Make a login request .
238,121
def get_ids ( self ) : response = api . request_networks ( self ) all_networks = [ ] network_dict = { } for network , status in self . networks . items ( ) : if status [ 'onboarded' ] : all_networks . append ( '{}' . format ( network ) ) network_dict [ status [ 'name' ] ] = network for resp in response [ 'networks' ] :...
Set the network ID and Account ID .
238,122
def get_cameras ( self ) : response = api . request_homescreen ( self ) try : all_cameras = { } for camera in response [ 'cameras' ] : camera_network = str ( camera [ 'network_id' ] ) camera_name = camera [ 'name' ] camera_id = camera [ 'id' ] camera_info = { 'name' : camera_name , 'id' : camera_id } if camera_network ...
Retrieve a camera list for each onboarded network .
238,123
def refresh ( self , force_cache = False ) : if self . check_if_ok_to_update ( ) or force_cache : for sync_name , sync_module in self . sync . items ( ) : _LOGGER . debug ( "Attempting refresh of sync %s" , sync_name ) sync_module . refresh ( force_cache = force_cache ) if not force_cache : self . last_refresh = int ( ...
Perform a system refresh .
238,124
def check_if_ok_to_update ( self ) : current_time = int ( time . time ( ) ) last_refresh = self . last_refresh if last_refresh is None : last_refresh = 0 if current_time >= ( last_refresh + self . refresh_rate ) : return True return False
Check if it is ok to perform an http request .
238,125
def merge_cameras ( self ) : combined = CaseInsensitiveDict ( { } ) for sync in self . sync : combined = merge_dicts ( combined , self . sync [ sync ] . cameras ) return combined
Merge all sync camera dicts into one .
238,126
def download_videos ( self , path , since = None , camera = 'all' , stop = 10 ) : if since is None : since_epochs = self . last_refresh else : parsed_datetime = parse ( since , fuzzy = True ) since_epochs = parsed_datetime . timestamp ( ) formatted_date = get_time ( time_to_convert = since_epochs ) _LOGGER . info ( "Re...
Download all videos from server since specified time .
238,127
def _parse_downloaded_items ( self , result , camera , path ) : for item in result : try : created_at = item [ 'created_at' ] camera_name = item [ 'camera_name' ] is_deleted = item [ 'deleted' ] address = item [ 'address' ] except KeyError : _LOGGER . info ( "Missing clip information, skipping..." ) continue if camera_...
Parse downloaded videos .
238,128
def request_login ( blink , url , username , password , is_retry = False ) : headers = { 'Host' : DEFAULT_URL , 'Content-Type' : 'application/json' } data = dumps ( { 'email' : username , 'password' : password , 'client_specifier' : 'iPhone 9.2 | 2.2 | 222' } ) return http_req ( blink , url = url , headers = headers , ...
Login request .
238,129
def request_networks ( blink ) : url = "{}/networks" . format ( blink . urls . base_url ) return http_get ( blink , url )
Request all networks information .
238,130
def request_network_status ( blink , network ) : url = "{}/network/{}" . format ( blink . urls . base_url , network ) return http_get ( blink , url )
Request network information .
238,131
def request_syncmodule ( blink , network ) : url = "{}/network/{}/syncmodules" . format ( blink . urls . base_url , network ) return http_get ( blink , url )
Request sync module info .
238,132
def request_system_arm ( blink , network ) : url = "{}/network/{}/arm" . format ( blink . urls . base_url , network ) return http_post ( blink , url )
Arm system .
238,133
def request_system_disarm ( blink , network ) : url = "{}/network/{}/disarm" . format ( blink . urls . base_url , network ) return http_post ( blink , url )
Disarm system .
238,134
def request_command_status ( blink , network , command_id ) : url = "{}/network/{}/command/{}" . format ( blink . urls . base_url , network , command_id ) return http_get ( blink , url )
Request command status .
238,135
def request_homescreen ( blink ) : url = "{}/api/v3/accounts/{}/homescreen" . format ( blink . urls . base_url , blink . account_id ) return http_get ( blink , url )
Request homescreen info .
238,136
def request_sync_events ( blink , network ) : url = "{}/events/network/{}" . format ( blink . urls . base_url , network ) return http_get ( blink , url )
Request events from sync module .
238,137
def request_video_count ( blink ) : url = "{}/api/v2/videos/count" . format ( blink . urls . base_url ) return http_get ( blink , url )
Request total video count .
238,138
def request_videos ( blink , time = None , page = 0 ) : timestamp = get_time ( time ) url = "{}/api/v2/videos/changed?since={}&page={}" . format ( blink . urls . base_url , timestamp , page ) return http_get ( blink , url )
Perform a request for videos .
238,139
def request_cameras ( blink , network ) : url = "{}/network/{}/cameras" . format ( blink . urls . base_url , network ) return http_get ( blink , url )
Request all camera information .
238,140
def request_camera_sensors ( blink , network , camera_id ) : url = "{}/network/{}/camera/{}/signals" . format ( blink . urls . base_url , network , camera_id ) return http_get ( blink , url )
Request camera sensor info for one camera .
238,141
def request_motion_detection_enable ( blink , network , camera_id ) : url = "{}/network/{}/camera/{}/enable" . format ( blink . urls . base_url , network , camera_id ) return http_post ( blink , url )
Enable motion detection for a camera .
238,142
def http_get ( blink , url , stream = False , json = True , is_retry = False ) : if blink . auth_header is None : raise BlinkException ( ERROR . AUTH_TOKEN ) _LOGGER . debug ( "Making GET request to %s" , url ) return http_req ( blink , url = url , headers = blink . auth_header , reqtype = 'get' , stream = stream , jso...
Perform an http get request .
238,143
def http_post ( blink , url , is_retry = False ) : if blink . auth_header is None : raise BlinkException ( ERROR . AUTH_TOKEN ) _LOGGER . debug ( "Making POST request to %s" , url ) return http_req ( blink , url = url , headers = blink . auth_header , reqtype = 'post' , is_retry = is_retry )
Perform an http post request .
238,144
def sls ( minuend , subtrahend , metric = "ssd" , noise = "global" , signed = True , sn_size = None , sn_footprint = None , sn_mode = "reflect" , sn_cval = 0.0 , pn_size = None , pn_footprint = None , pn_mode = "reflect" , pn_cval = 0.0 ) : r minuend = numpy . asarray ( minuend ) subtrahend = numpy . asarray ( subtrahe...
r Computes the signed local similarity between two images .
238,145
def average_filter ( input , size = None , footprint = None , output = None , mode = "reflect" , cval = 0.0 , origin = 0 ) : r footprint = __make_footprint ( input , size , footprint ) filter_size = footprint . sum ( ) output = _get_output ( output , input ) sum_filter ( input , footprint = footprint , output = output ...
r Calculates a multi - dimensional average filter .
238,146
def sum_filter ( input , size = None , footprint = None , output = None , mode = "reflect" , cval = 0.0 , origin = 0 ) : r footprint = __make_footprint ( input , size , footprint ) slicer = [ slice ( None , None , - 1 ) ] * footprint . ndim return convolve ( input , footprint [ slicer ] , output , mode , cval , origin ...
r Calculates a multi - dimensional sum filter .
238,147
def _gaussian_membership_sigma ( smoothness , eps = 0.0005 ) : r error = 0 deltas = [ 0.1 , 0.01 , 0.001 , 0.0001 ] sigma = smoothness * 0.3 point = - 1. * ( smoothness + 0.5 ) for delta in deltas : while error < eps : sigma += delta error = scipy . stats . norm . cdf ( 0.5 , point , sigma ) - scipy . stats . norm . cd...
r Compute the sigma required for a gaussian such that in a neighbourhood of smoothness the maximum error is eps . The error is here the difference between the clipped integral and one .
238,148
def out_of_date ( original , derived ) : return ( not os . path . exists ( derived ) or os . stat ( derived ) . st_mtime < os . stat ( original ) . st_mtime )
Returns True if derivative is out - of - date wrt original both of which are full file paths .
238,149
def local_maxima ( vector , min_distance = 4 , brd_mode = "wrap" ) : fits = gaussian_filter ( numpy . asarray ( vector , dtype = numpy . float32 ) , 1. , mode = brd_mode ) for ii in range ( len ( fits ) ) : if fits [ ii ] == fits [ ii - 1 ] : fits [ ii - 1 ] = 0.0 maxfits = maximum_filter ( fits , size = min_distance ,...
Internal finder for local maxima . Returns UNSORTED indices of maxima in input vector .
238,150
def local_minima ( vector , min_distance = 4 , brd_mode = "wrap" ) : fits = gaussian_filter ( numpy . asarray ( vector , dtype = numpy . float32 ) , 1. , mode = brd_mode ) for ii in range ( len ( fits ) ) : if fits [ ii ] == fits [ ii - 1 ] : fits [ ii - 1 ] = numpy . pi / 2.0 minfits = minimum_filter ( fits , size = m...
Internal finder for local minima . Returns UNSORTED indices of minima in input vector .
238,151
def find_valley_range ( vector , min_distance = 4 ) : mode = "wrap" minima = local_minima ( vector , min_distance , mode ) maxima = local_maxima ( vector , min_distance , mode ) if len ( maxima ) > len ( minima ) : if vector [ maxima [ 0 ] ] >= vector [ maxima [ - 1 ] ] : maxima = maxima [ 1 : ] else : maxima = maxima ...
Internal finder peaks and valley ranges . Returns UNSORTED indices of maxima in input vector . Returns range of valleys before and after maximum
238,152
def gauss_xminus1d ( img , sigma , dim = 2 ) : r img = numpy . array ( img , copy = False ) return xminus1d ( img , gaussian_filter , dim , sigma = sigma )
r Applies a X - 1D gauss to a copy of a XD image slicing it along dim .
238,153
def anisotropic_diffusion ( img , niter = 1 , kappa = 50 , gamma = 0.1 , voxelspacing = None , option = 1 ) : r if option == 1 : def condgradient ( delta , spacing ) : return numpy . exp ( - ( delta / kappa ) ** 2. ) / float ( spacing ) elif option == 2 : def condgradient ( delta , spacing ) : return 1. / ( 1. + ( delt...
r Edge - preserving XD Anisotropic diffusion .
238,154
def __voxel_4conectedness ( shape ) : shape = list ( shape ) while 1 in shape : shape . remove ( 1 ) return int ( round ( sum ( [ ( dim - 1 ) / float ( dim ) for dim in shape ] ) * scipy . prod ( shape ) ) )
Returns the number of edges for the supplied image shape assuming 4 - connectedness . The name of the function has historical reasons . Essentially it returns the number of edges assuming 4 - connectedness only for 2D . For 3D it assumes 6 - connectedness etc .
238,155
def __skeleton_base ( graph , image , boundary_term , neighbourhood_function , spacing ) : image = scipy . asarray ( image ) image = image . astype ( scipy . float_ ) for dim in range ( image . ndim ) : slices_exclude_last = [ slice ( None ) ] * image . ndim slices_exclude_last [ dim ] = slice ( - 1 ) slices_exclude_fi...
Base of the skeleton for voxel based boundary term calculation . This function holds the low level procedures shared by nearly all boundary terms .
238,156
def __range ( a , bins ) : a = numpy . asarray ( a ) a_max = a . max ( ) a_min = a . min ( ) s = 0.5 * ( a_max - a_min ) / float ( bins - 1 ) return ( a_min - s , a_max + s )
Compute the histogram range of the values in the array a according to scipy . stats . histogram .
238,157
def centerdistance ( image , voxelspacing = None , mask = slice ( None ) ) : r if type ( image ) == tuple or type ( image ) == list : image = image [ 0 ] return _extract_feature ( _extract_centerdistance , image , mask , voxelspacing = voxelspacing )
r Takes a simple or multi - spectral image and returns its voxel - wise center distance in mm . A multi - spectral image must be supplied as a list or tuple of its spectra . Optionally a binary mask can be supplied to select the voxels for which the feature should be extracted . The center distance is the exact euclide...
238,158
def mask_distance ( image , voxelspacing = None , mask = slice ( None ) ) : r if type ( image ) == tuple or type ( image ) == list : image = image [ 0 ] return _extract_mask_distance ( image , mask = mask , voxelspacing = voxelspacing )
r Computes the distance of each point under the mask to the mask border taking the voxel - spacing into account . Note that this feature is independent of the actual image content but depends solely the mask image . Therefore always a one - dimensional feature is returned even if a multi - spectral image has been suppl...
238,159
def _extract_hemispheric_difference ( image , mask = slice ( None ) , sigma_active = 7 , sigma_reference = 7 , cut_plane = 0 , voxelspacing = None ) : INTERPOLATION_RANGE = int ( 10 ) if cut_plane >= image . ndim : raise ArgumentError ( 'The suppliedc cut-plane ({}) is invalid, the image has only {} dimensions.' . form...
Internal single - image version of hemispheric_difference .
238,160
def _extract_local_histogram ( image , mask = slice ( None ) , bins = 19 , rang = "image" , cutoffp = ( 0.0 , 100.0 ) , size = None , footprint = None , output = None , mode = "ignore" , origin = 0 ) : if "constant" == mode : raise RuntimeError ( 'boundary mode not supported' ) elif "ignore" == mode : mode = "constant"...
Internal single - image version of
238,161
def _extract_median ( image , mask = slice ( None ) , size = 1 , voxelspacing = None ) : if voxelspacing is None : voxelspacing = [ 1. ] * image . ndim size = _create_structure_array ( size , voxelspacing ) return _extract_intensities ( median_filter ( image , size ) , mask )
Internal single - image version of median .
238,162
def _extract_gaussian_gradient_magnitude ( image , mask = slice ( None ) , sigma = 1 , voxelspacing = None ) : if voxelspacing is None : voxelspacing = [ 1. ] * image . ndim sigma = _create_structure_array ( sigma , voxelspacing ) return _extract_intensities ( scipy_gaussian_gradient_magnitude ( image , sigma ) , mask ...
Internal single - image version of gaussian_gradient_magnitude .
238,163
def _extract_shifted_mean_gauss ( image , mask = slice ( None ) , offset = None , sigma = 1 , voxelspacing = None ) : if voxelspacing is None : voxelspacing = [ 1. ] * image . ndim if offset is None : offset = [ 0 ] * image . ndim sigma = _create_structure_array ( sigma , voxelspacing ) smoothed = gaussian_filter ( ima...
Internal single - image version of shifted_mean_gauss .
238,164
def _extract_mask_distance ( image , mask = slice ( None ) , voxelspacing = None ) : if isinstance ( mask , slice ) : mask = numpy . ones ( image . shape , numpy . bool ) distance_map = distance_transform_edt ( mask , sampling = voxelspacing ) return _extract_intensities ( distance_map , mask )
Internal single - image version of mask_distance .
238,165
def _extract_local_mean_gauss ( image , mask = slice ( None ) , sigma = 1 , voxelspacing = None ) : if voxelspacing is None : voxelspacing = [ 1. ] * image . ndim sigma = _create_structure_array ( sigma , voxelspacing ) return _extract_intensities ( gaussian_filter ( image , sigma ) , mask )
Internal single - image version of local_mean_gauss .
238,166
def _extract_centerdistance ( image , mask = slice ( None ) , voxelspacing = None ) : image = numpy . array ( image , copy = False ) if None == voxelspacing : voxelspacing = [ 1. ] * image . ndim centers = [ ( x - 1 ) / 2. for x in image . shape ] indices = numpy . indices ( image . shape , dtype = numpy . float ) for ...
Internal single - image version of centerdistance .
238,167
def _extract_intensities ( image , mask = slice ( None ) ) : return numpy . array ( image , copy = True ) [ mask ] . ravel ( )
Internal single - image version of intensities .
238,168
def _substract_hemispheres ( active , reference , active_sigma , reference_sigma , voxel_spacing ) : active_kernel = _create_structure_array ( active_sigma , voxel_spacing ) active_smoothed = gaussian_filter ( active , sigma = active_kernel ) reference_kernel = _create_structure_array ( reference_sigma , voxel_spacing ...
Helper function for _extract_hemispheric_difference . Smoothes both images and then substracts the reference from the active image .
238,169
def _dispatch ( self , tree ) : "_dispatcher function, _dispatching tree type T to method _T." if isinstance ( tree , list ) : for t in tree : self . _dispatch ( t ) return meth = getattr ( self , "_" + tree . __class__ . __name__ ) if tree . __class__ . __name__ == 'NoneType' and not self . _do_indent : return meth ( ...
_dispatcher function _dispatching tree type T to method _T .
238,170
def _AssAttr ( self , t ) : self . _dispatch ( t . expr ) self . _write ( '.' + t . attrname )
Handle assigning an attribute of an object
238,171
def _Assign ( self , t ) : self . _fill ( ) for target in t . nodes : self . _dispatch ( target ) self . _write ( " = " ) self . _dispatch ( t . expr ) if not self . _do_indent : self . _write ( '; ' )
Expression Assignment such as a = 1 .
238,172
def _AssTuple ( self , t ) : for element in t . nodes [ : - 1 ] : self . _dispatch ( element ) self . _write ( ", " ) last_element = t . nodes [ - 1 ] self . _dispatch ( last_element )
Tuple on left hand side of an expression .
238,173
def _CallFunc ( self , t ) : self . _dispatch ( t . node ) self . _write ( "(" ) comma = False for e in t . args : if comma : self . _write ( ", " ) else : comma = True self . _dispatch ( e ) if t . star_args : if comma : self . _write ( ", " ) else : comma = True self . _write ( "*" ) self . _dispatch ( t . star_args ...
Function call .
238,174
def _From ( self , t ) : self . _fill ( "from " ) self . _write ( t . modname ) self . _write ( " import " ) for i , ( name , asname ) in enumerate ( t . names ) : if i != 0 : self . _write ( ", " ) self . _write ( name ) if asname is not None : self . _write ( " as " + asname )
Handle from xyz import foo bar as baz .
238,175
def _Function ( self , t ) : if t . decorators is not None : self . _fill ( "@" ) self . _dispatch ( t . decorators ) self . _fill ( "def " + t . name + "(" ) defaults = [ None ] * ( len ( t . argnames ) - len ( t . defaults ) ) + list ( t . defaults ) for i , arg in enumerate ( zip ( t . argnames , defaults ) ) : self...
Handle function definitions
238,176
def _Getattr ( self , t ) : if isinstance ( t . expr , ( Div , Mul , Sub , Add ) ) : self . _write ( '(' ) self . _dispatch ( t . expr ) self . _write ( ')' ) else : self . _dispatch ( t . expr ) self . _write ( '.' + t . attrname )
Handle getting an attribute of an object
238,177
def _Import ( self , t ) : self . _fill ( "import " ) for i , ( name , asname ) in enumerate ( t . names ) : if i != 0 : self . _write ( ", " ) self . _write ( name ) if asname is not None : self . _write ( " as " + asname )
Handle import xyz . foo .
238,178
def _Keyword ( self , t ) : self . _write ( t . name ) self . _write ( "=" ) self . _dispatch ( t . expr )
Keyword value assignment within function calls and definitions .
238,179
def __sequenceAscendingStrict ( l ) : "Test a sequences values to be in strictly ascending order." it = iter ( l ) next ( it ) if not all ( b > a for a , b in zip ( l , it ) ) : raise argparse . ArgumentTypeError ( 'All values must be given in strictly ascending order.' ) return l
Test a sequences values to be in strictly ascending order .
238,180
def __check_mapping ( self , landmarks ) : sc_udiff = numpy . asarray ( self . __sc_umaxs ) [ 1 : ] - numpy . asarray ( self . __sc_umins ) [ : - 1 ] l_diff = numpy . asarray ( landmarks ) [ 1 : ] - numpy . asarray ( landmarks ) [ : - 1 ] return numpy . all ( sc_udiff > numpy . asarray ( l_diff ) )
Checks whether the image from which the supplied landmarks were extracted can be transformed to the learned standard intensity space without loss of information .
238,181
def is_in_interval ( n , l , r , border = 'included' ) : if 'included' == border : return ( n >= l ) and ( n <= r ) elif 'excluded' == border : return ( n > l ) and ( n < r ) else : raise ValueError ( 'borders must be either \'included\' or \'excluded\'' )
Checks whether a number is inside the interval l r .
238,182
def are_in_interval ( s , l , r , border = 'included' ) : return numpy . all ( [ IntensityRangeStandardization . is_in_interval ( x , l , r , border ) for x in s ] )
Checks whether all number in the sequence s lie inside the interval formed by l and r .
238,183
def template_sphere ( radius , dimensions ) : r if int ( dimensions ) != dimensions : raise TypeError ( 'The supplied dimension parameter must be of type integer.' ) dimensions = int ( dimensions ) return template_ellipsoid ( dimensions * [ radius * 2 ] )
r Returns a spherical binary structure of a of the supplied radius that can be used as template input to the generalized hough transform .
238,184
def looks_like_issubclass ( obj , classname ) : t = obj if t . __name__ == classname : return True for klass in t . __mro__ : if klass . __name__ == classname : return True return False
Return True if the object has a class or superclass with the given class name .
238,185
def __make_footprint ( input , size , footprint ) : "Creates a standard footprint element ala scipy.ndimage." if footprint is None : if size is None : raise RuntimeError ( "no footprint or filter size provided" ) sizes = _ni_support . _normalize_sequence ( size , input . ndim ) footprint = numpy . ones ( sizes , dtype ...
Creates a standard footprint element ala scipy . ndimage .
238,186
def __check_label_image ( label_image ) : encountered_indices = scipy . unique ( label_image ) expected_indices = scipy . arange ( 1 , label_image . max ( ) + 1 ) if not encountered_indices . size == expected_indices . size or not ( encountered_indices == expected_indices ) . all ( ) : raise AttributeError ( 'The suppl...
Check the label image for consistent labelling starting from 1 .
238,187
def __xd_iterator_pass_on ( arr , view , fun ) : iterations = [ [ None ] if dim in view else list ( range ( arr . shape [ dim ] ) ) for dim in range ( arr . ndim ) ] passon = None for indices in itertools . product ( * iterations ) : slicer = [ slice ( None ) if idx is None else slice ( idx , idx + 1 ) for idx in indic...
Like xd_iterator but the fun return values are always passed on to the next and only the last returned .
238,188
def set_pixel_spacing ( hdr , spacing ) : r warnings . warn ( 'get_pixel_spacing() is depreciated, use set_voxel_spacing() instead' , category = DeprecationWarning ) set_voxel_spacing ( hdr , spacing )
r Depreciated synonym of ~medpy . io . header . set_voxel_spacing .
238,189
def copy_to ( self , sitkimage ) : if self . sitkimage is not None : for k in self . sitkimage . GetMetaDataKeys ( ) : sitkimage . SetMetaData ( k , self . sitkimage . GetMetaData ( k ) ) ndim = len ( sitkimage . GetSize ( ) ) spacing , offset , direction = self . get_info_consistent ( ndim ) sitkimage . SetSpacing ( s...
Copy all stored meta information info to an sitk Image .
238,190
def get_info_consistent ( self , ndim ) : if ndim > len ( self . spacing ) : spacing = self . spacing + ( 1.0 , ) * ( ndim - len ( self . spacing ) ) else : spacing = self . spacing [ : ndim ] if ndim > len ( self . offset ) : offset = self . offset + ( 0.0 , ) * ( ndim - len ( self . offset ) ) else : offset = self . ...
Returns the main meta - data information adapted to the supplied image dimensionality .
238,191
def hd95 ( result , reference , voxelspacing = None , connectivity = 1 ) : hd1 = __surface_distances ( result , reference , voxelspacing , connectivity ) hd2 = __surface_distances ( reference , result , voxelspacing , connectivity ) hd95 = numpy . percentile ( numpy . hstack ( ( hd1 , hd2 ) ) , 95 ) return hd95
95th percentile of the Hausdorff Distance .
238,192
def __surface_distances ( result , reference , voxelspacing = None , connectivity = 1 ) : result = numpy . atleast_1d ( result . astype ( numpy . bool ) ) reference = numpy . atleast_1d ( reference . astype ( numpy . bool ) ) if voxelspacing is not None : voxelspacing = _ni_support . _normalize_sequence ( voxelspacing ...
The distances between the surface voxel of binary objects in result and their nearest partner surface voxel of a binary object in reference .
238,193
def __minowski_low_positive_integer_p ( h1 , h2 , p = 2 ) : mult = scipy . absolute ( h1 - h2 ) dif = mult for _ in range ( p - 1 ) : dif = scipy . multiply ( dif , mult ) return math . pow ( scipy . sum ( dif ) , 1. / p )
A faster implementation of the Minowski distance for positive integer < 25 .
238,194
def __kullback_leibler ( h1 , h2 ) : result = h1 . astype ( scipy . float_ ) mask = h1 != 0 result [ mask ] = scipy . multiply ( h1 [ mask ] , scipy . log ( h1 [ mask ] / h2 [ mask ] ) ) return scipy . sum ( result )
The actual KL implementation .
238,195
def __prepare_histogram ( h1 , h2 ) : h1 = h1 if scipy . ndarray == type ( h1 ) else scipy . asarray ( h1 ) h2 = h2 if scipy . ndarray == type ( h2 ) else scipy . asarray ( h2 ) if h1 . shape != h2 . shape or h1 . size != h2 . size : raise ValueError ( 'h1 and h2 must be of same shape and size' ) return h1 , h2
Convert the histograms to scipy . ndarrays if required .
238,196
def find ( ) : spark_home = os . environ . get ( 'SPARK_HOME' , None ) if not spark_home : for path in [ '/usr/local/opt/apache-spark/libexec' , '/usr/lib/spark/' , '/usr/local/spark/' , '/opt/spark/' , ] : if os . path . exists ( path ) : spark_home = path break if not spark_home : raise ValueError ( "Couldn't find Sp...
Find a local spark installation .
238,197
def change_rc ( spark_home , spark_python , py4j ) : bashrc_location = os . path . expanduser ( "~/.bashrc" ) if os . path . isfile ( bashrc_location ) : with open ( bashrc_location , 'a' ) as bashrc : bashrc . write ( "\n# Added by findspark\n" ) bashrc . write ( "export SPARK_HOME=" + spark_home + "\n" ) bashrc . wri...
Persists changes to environment by changing shell config .
238,198
def edit_ipython_profile ( spark_home , spark_python , py4j ) : from IPython import get_ipython ip = get_ipython ( ) if ip : profile_dir = ip . profile_dir . location else : from IPython . utils . path import locate_profile profile_dir = locate_profile ( ) startup_file_loc = os . path . join ( profile_dir , "startup" ,...
Adds a startup file to the current IPython profile to import pyspark .
238,199
def init ( spark_home = None , python_path = None , edit_rc = False , edit_profile = False ) : if not spark_home : spark_home = find ( ) if not python_path : python_path = os . environ . get ( 'PYSPARK_PYTHON' , sys . executable ) os . environ [ 'SPARK_HOME' ] = spark_home os . environ [ 'PYSPARK_PYTHON' ] = python_pat...
Make pyspark importable .