idx
int64
0
63k
question
stringlengths
61
4.03k
target
stringlengths
6
1.23k
49,200
def get_status ( self , status_value , message = None ) : status = etree . Element ( 'Status' ) status_code = etree . SubElement ( status , 'StatusCode' ) status_code . set ( 'Value' , 'samlp:' + status_value ) if message : status_message = etree . SubElement ( status , 'StatusMessage' ) status_message . text = message...
Build a Status XML block for a SAML 1 . 1 Response .
49,201
def get_assertion ( self , ticket , attributes ) : assertion = etree . Element ( 'Assertion' ) assertion . set ( 'xmlns' , 'urn:oasis:names:tc:SAML:1.0:assertion' ) assertion . set ( 'AssertionID' , self . generate_id ( ) ) assertion . set ( 'IssueInstant' , self . instant ( ) ) assertion . set ( 'Issuer' , 'localhost'...
Build a SAML 1 . 1 Assertion XML block .
49,202
def get_conditions ( self , service_id ) : conditions = etree . Element ( 'Conditions' ) conditions . set ( 'NotBefore' , self . instant ( ) ) conditions . set ( 'NotOnOrAfter' , self . instant ( offset = 30 ) ) restriction = etree . SubElement ( conditions , 'AudienceRestrictionCondition' ) audience = etree . SubEleme...
Build a Conditions XML block for a SAML 1 . 1 Assertion .
49,203
def get_attribute_statement ( self , subject , attributes ) : attribute_statement = etree . Element ( 'AttributeStatement' ) attribute_statement . append ( subject ) for name , value in attributes . items ( ) : attribute = etree . SubElement ( attribute_statement , 'Attribute' ) attribute . set ( 'AttributeName' , name...
Build an AttributeStatement XML block for a SAML 1 . 1 Assertion .
49,204
def get_authentication_statement ( self , subject , ticket ) : authentication_statement = etree . Element ( 'AuthenticationStatement' ) authentication_statement . set ( 'AuthenticationInstant' , self . instant ( instant = ticket . consumed ) ) authentication_statement . set ( 'AuthenticationMethod' , self . authn_metho...
Build an AuthenticationStatement XML block for a SAML 1 . 1 Assertion .
49,205
def get_subject ( self , identifier ) : subject = etree . Element ( 'Subject' ) name = etree . SubElement ( subject , 'NameIdentifier' ) name . text = identifier subject_confirmation = etree . SubElement ( subject , 'SubjectConfirmation' ) method = etree . SubElement ( subject_confirmation , 'ConfirmationMethod' ) meth...
Build a Subject XML block for a SAML 1 . 1 AuthenticationStatement or AttributeStatement .
49,206
def is_bytes ( string ) : if six . PY3 and isinstance ( string , ( bytes , memoryview , bytearray ) ) : return True elif six . PY2 and isinstance ( string , ( buffer , bytearray ) ) : return True return False
Check if a string is a bytes instance
49,207
def partialclass ( cls , * args , ** kwargs ) : name_attrs = [ n for n in ( getattr ( cls , name , str ( cls ) ) for name in ( "__name__" , "__qualname__" ) ) if n is not None ] name_attrs = name_attrs [ 0 ] type_ = type ( name_attrs , ( cls , ) , { "__init__" : partialmethod ( cls . __init__ , * args , ** kwargs ) } )...
Returns a partially instantiated class
49,208
def replace_with_text_stream ( stream_name ) : new_stream = TEXT_STREAMS . get ( stream_name ) if new_stream is not None : new_stream = new_stream ( ) setattr ( sys , stream_name , new_stream ) return None
Given a stream name replace the target stream with a text - converted equivalent
49,209
def _sanitize_params ( prefix , suffix , dir ) : output_type = _infer_return_type ( prefix , suffix , dir ) if suffix is None : suffix = output_type ( ) if prefix is None : if output_type is str : prefix = "tmp" else : prefix = os . fsencode ( "tmp" ) if dir is None : if output_type is str : dir = gettempdir ( ) else :...
Common parameter processing for most APIs in this module .
49,210
def fromdict ( model , data , exclude = None , exclude_underscore = None , allow_pk = None , follow = None , include = None , only = None ) : follow = arg_to_dict ( follow ) info = inspect ( model ) columns = [ c . key for c in info . mapper . column_attrs ] synonyms = [ c . key for c in info . mapper . synonyms ] rela...
Update a model from a dict
49,211
def make_class_dictable ( cls , exclude = constants . default_exclude , exclude_underscore = constants . default_exclude_underscore , fromdict_allow_pk = constants . default_fromdict_allow_pk , include = None , asdict_include = None , fromdict_include = None ) : setattr ( cls , 'dictalchemy_exclude' , exclude ) setattr...
Make a class dictable
49,212
def parse_GFF_attribute_string ( attrStr , extra_return_first_value = False ) : if attrStr . endswith ( "\n" ) : attrStr = attrStr [ : - 1 ] d = { } first_val = "_unnamed_" for ( i , attr ) in itertools . izip ( itertools . count ( ) , _HTSeq . quotesafe_split ( attrStr ) ) : if _re_attr_empty . match ( attr ) : contin...
Parses a GFF attribute string and returns it as a dictionary .
49,213
def pair_SAM_alignments ( alignments , bundle = False , primary_only = False ) : mate_missing_count = [ 0 ] def process_list ( almnt_list ) : while len ( almnt_list ) > 0 : a1 = almnt_list . pop ( 0 ) for a2 in almnt_list : if a1 . pe_which == a2 . pe_which : continue if a1 . aligned != a2 . mate_aligned or a1 . mate_a...
Iterate over SAM aligments name - sorted paired - end
49,214
def pair_SAM_alignments_with_buffer ( alignments , max_buffer_size = 30000000 , primary_only = False ) : almnt_buffer = { } ambiguous_pairing_counter = 0 for almnt in alignments : if not almnt . paired_end : raise ValueError ( "Sequence of paired-end alignments expected, but got single-end alignment." ) if almnt . pe_w...
Iterate over SAM aligments with buffer position - sorted paired - end
49,215
def ensure_v8_src ( ) : path = local_path ( 'v8' ) if not os . path . isdir ( path ) : fetch_v8 ( path ) else : update_v8 ( path ) checkout_v8_version ( local_path ( "v8/v8" ) , V8_VERSION ) dependencies_sync ( path )
Ensure that v8 src are presents and up - to - date
49,216
def get_filenames ( directory ) : for filename in os . listdir ( directory ) : if re . search ( r"cp\d{2}mu?-manylinux1_\S+\.whl" , filename ) : yield filename
Get all the file to copy
49,217
def copy_file ( filename ) : print ( "Updating file %s" % filename ) out_dir = os . path . abspath ( DIRECTORY ) tags = filename [ : - 4 ] . split ( "-" ) tags [ - 2 ] = tags [ - 2 ] . replace ( "m" , "" ) new_name = "-" . join ( tags ) + ".whl" wheel_flag = "-" . join ( tags [ 2 : ] ) with InWheelCtx ( os . path . joi...
Copy the file and put the correct tag
49,218
def is_unicode ( value ) : python_version = sys . version_info [ 0 ] if python_version == 2 : return isinstance ( value , unicode ) elif python_version == 3 : return isinstance ( value , str ) else : raise NotImplementedError ( )
Check if a value is a valid unicode string compatible with python 2 and python 3
49,219
def execute ( self , js_str , timeout = 0 , max_memory = 0 ) : wrapped = "(function(){return (%s)})()" % js_str return self . eval ( wrapped , timeout , max_memory )
Exec the given JS value
49,220
def eval ( self , js_str , timeout = 0 , max_memory = 0 ) : if is_unicode ( js_str ) : bytes_val = js_str . encode ( "utf8" ) else : bytes_val = js_str res = None self . lock . acquire ( ) try : res = self . ext . mr_eval_context ( self . ctx , bytes_val , len ( bytes_val ) , ctypes . c_ulong ( timeout ) , ctypes . c_s...
Eval the JavaScript string
49,221
def call ( self , identifier , * args , ** kwargs ) : encoder = kwargs . get ( 'encoder' , None ) timeout = kwargs . get ( 'timeout' , 0 ) max_memory = kwargs . get ( 'max_memory' , 0 ) json_args = json . dumps ( args , separators = ( ',' , ':' ) , cls = encoder ) js = "{identifier}.apply(this, {json_args})" return sel...
Call the named function with provided arguments You can pass a custom JSON encoder by passing it in the encoder keyword only argument .
49,222
def heap_stats ( self ) : self . lock . acquire ( ) res = self . ext . mr_heap_stats ( self . ctx ) self . lock . release ( ) python_value = res . contents . to_python ( ) self . free ( res ) return python_value
Return heap statistics
49,223
def heap_snapshot ( self ) : self . lock . acquire ( ) res = self . ext . mr_heap_snapshot ( self . ctx ) self . lock . release ( ) python_value = res . contents . to_python ( ) self . free ( res ) return python_value
Return heap snapshot
49,224
def to_python ( self ) : result = None if self . type == PythonTypes . null : result = None elif self . type == PythonTypes . bool : result = self . value == 1 elif self . type == PythonTypes . integer : if self . value is None : result = 0 else : result = ctypes . c_int32 ( self . value ) . value elif self . type == P...
Return an object as native Python
49,225
def libv8_object ( object_name ) : filename = join ( V8_LIB_DIRECTORY , 'out.gn/x64.release/obj/{}' . format ( object_name ) ) if not isfile ( filename ) : filename = join ( local_path ( 'vendor/v8/out.gn/libv8/obj/{}' . format ( object_name ) ) ) if not isfile ( filename ) : filename = join ( V8_LIB_DIRECTORY , 'out.g...
Return a path for object_name which is OS independent
49,226
def get_static_lib_paths ( ) : libs = [ ] is_linux = sys . platform . startswith ( 'linux' ) if is_linux : libs += [ '-Wl,--start-group' ] libs += get_raw_static_lib_path ( ) if is_linux : libs += [ '-Wl,--end-group' ] return libs
Return the required static libraries path
49,227
def get_dag_params ( self ) -> Dict [ str , Any ] : try : dag_params : Dict [ str , Any ] = utils . merge_configs ( self . dag_config , self . default_config ) except Exception as e : raise Exception ( f"Failed to merge config with default config, err: {e}" ) dag_params [ "dag_id" ] : str = self . dag_name try : dag_pa...
Merges default config with dag config sets dag_id and extropolates dag_start_date
49,228
def make_task ( operator : str , task_params : Dict [ str , Any ] ) -> BaseOperator : try : operator_obj : Callable [ ... , BaseOperator ] = import_string ( operator ) except Exception as e : raise Exception ( f"Failed to import operator: {operator}. err: {e}" ) try : task : BaseOperator = operator_obj ( ** task_params...
Takes an operator and params and creates an instance of that operator .
49,229
def build ( self ) -> Dict [ str , Union [ str , DAG ] ] : dag_params : Dict [ str , Any ] = self . get_dag_params ( ) dag : DAG = DAG ( dag_id = dag_params [ "dag_id" ] , schedule_interval = dag_params [ "schedule_interval" ] , description = dag_params . get ( "description" , "" ) , max_active_runs = dag_params . get ...
Generates a DAG from the DAG parameters .
49,230
def merge_configs ( config : Dict [ str , Any ] , default_config : Dict [ str , Any ] ) -> Dict [ str , Any ] : for key in default_config : if key in config : if isinstance ( config [ key ] , dict ) and isinstance ( default_config [ key ] , dict ) : merge_configs ( config [ key ] , default_config [ key ] ) else : confi...
Merges a default config with DAG config . Used to set default values for a group of DAGs .
49,231
def _load_config ( config_filepath : str ) -> Dict [ str , Any ] : try : config : Dict [ str , Any ] = yaml . load ( stream = open ( config_filepath , "r" ) ) except Exception as e : raise Exception ( f"Invalid DAG Factory config file; err: {e}" ) return config
Loads YAML config file to dictionary
49,232
def get_dag_configs ( self ) -> Dict [ str , Dict [ str , Any ] ] : return { dag : self . config [ dag ] for dag in self . config . keys ( ) if dag != "default" }
Returns configuration for each the DAG in factory
49,233
def generate_dags ( self , globals : Dict [ str , Any ] ) -> None : dag_configs : Dict [ str , Dict [ str , Any ] ] = self . get_dag_configs ( ) default_config : Dict [ str , Any ] = self . get_default_config ( ) for dag_name , dag_config in dag_configs . items ( ) : dag_builder : DagBuilder = DagBuilder ( dag_name = d...
Generates DAGs from YAML config
49,234
def attributes ( self ) : attr = { 'name' : self . name , 'id' : self . sync_id , 'network_id' : self . network_id , 'serial' : self . serial , 'status' : self . status , 'region' : self . region , 'region_id' : self . region_id , } return attr
Return sync attributes .
49,235
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 .
49,236
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 .
49,237
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 .
49,238
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 .
49,239
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 .
49,240
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 .
49,241
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 .
49,242
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 .
49,243
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 .
49,244
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 .
49,245
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 .
49,246
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 .
49,247
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 .
49,248
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 .
49,249
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 .
49,250
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 .
49,251
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 .
49,252
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 .
49,253
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 .
49,254
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 .
49,255
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 .
49,256
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 .
49,257
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 .
49,258
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 .
49,259
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 .
49,260
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 .
49,261
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 .
49,262
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 .
49,263
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 .
49,264
def request_networks ( blink ) : url = "{}/networks" . format ( blink . urls . base_url ) return http_get ( blink , url )
Request all networks information .
49,265
def request_network_status ( blink , network ) : url = "{}/network/{}" . format ( blink . urls . base_url , network ) return http_get ( blink , url )
Request network information .
49,266
def request_syncmodule ( blink , network ) : url = "{}/network/{}/syncmodules" . format ( blink . urls . base_url , network ) return http_get ( blink , url )
Request sync module info .
49,267
def request_system_arm ( blink , network ) : url = "{}/network/{}/arm" . format ( blink . urls . base_url , network ) return http_post ( blink , url )
Arm system .
49,268
def request_system_disarm ( blink , network ) : url = "{}/network/{}/disarm" . format ( blink . urls . base_url , network ) return http_post ( blink , url )
Disarm system .
49,269
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 .
49,270
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 .
49,271
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 .
49,272
def request_video_count ( blink ) : url = "{}/api/v2/videos/count" . format ( blink . urls . base_url ) return http_get ( blink , url )
Request total video count .
49,273
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 .
49,274
def request_cameras ( blink , network ) : url = "{}/network/{}/cameras" . format ( blink . urls . base_url , network ) return http_get ( blink , url )
Request all camera information .
49,275
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 .
49,276
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 .
49,277
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 .
49,278
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 .
49,279
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 .
49,280
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 .
49,281
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 .
49,282
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 .
49,283
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 .
49,284
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 .
49,285
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 .
49,286
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
49,287
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 .
49,288
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 .
49,289
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 .
49,290
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 .
49,291
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 .
49,292
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...
49,293
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...
49,294
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 .
49,295
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
49,296
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 .
49,297
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 .
49,298
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 .
49,299
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 .