idx
int64
0
252k
question
stringlengths
48
5.28k
target
stringlengths
5
1.23k
239,900
def to_attrs ( args , nocreate_if_none = [ 'id' , 'for' , 'class' ] ) : if not args : return '' s = [ '' ] for k , v in sorted ( args . items ( ) ) : k = u_str ( k ) v = u_str ( v ) if k . startswith ( '_' ) : k = k [ 1 : ] if v is None : if k not in nocreate_if_none : s . append ( k ) else : if k . lower ( ) in __noes...
Make python dict to k = v format
239,901
def _get_modpkg_path ( dotted_name , pathlist = None ) : parts = dotted_name . split ( '.' , 1 ) if len ( parts ) > 1 : try : file , pathname , description = imp . find_module ( parts [ 0 ] , pathlist ) if file : file . close ( ) except ImportError : return None if description [ 2 ] == imp . PKG_DIRECTORY : pathname = ...
Get the filesystem path for a module or a package .
239,902
def getFilesForName ( name ) : if not os . path . exists ( name ) : if containsAny ( name , "*?[]" ) : files = glob . glob ( name ) list = [ ] for file in files : list . extend ( getFilesForName ( file ) ) return list name = _get_modpkg_path ( name ) if not name : return [ ] if os . path . isdir ( name ) : list = [ ] o...
Get a list of module files for a filename a module or package name or a directory .
239,903
def unescape ( s ) : def handle_match ( m ) : name = m . group ( 1 ) if name in HTMLBuilder . _entities : return unichr ( HTMLBuilder . _entities [ name ] ) try : if name [ : 2 ] in ( '#x' , '#X' ) : return unichr ( int ( name [ 2 : ] , 16 ) ) elif name . startswith ( '#' ) : return unichr ( int ( name [ 1 : ] ) ) exce...
The reverse function of escape . This unescapes all the HTML entities not only the XML entities inserted by escape .
239,904
def append_slash_redirect ( environ , code = 301 ) : new_path = environ [ 'PATH_INFO' ] . strip ( '/' ) + '/' query_string = environ . get ( 'QUERY_STRING' ) if query_string : new_path += '?' + query_string return redirect ( new_path , code )
Redirect to the same URL but with a slash appended . The behavior of this function is undefined if the path ends with a slash already .
239,905
def parse_translation ( f , lineno ) : line = f . readline ( ) def get_line ( f , line , need_keys , lineno , default = '""' ) : line = line . rstrip ( ) if not line : return lineno , need_keys [ 0 ] , default , line key , value = line . split ( ' ' , 1 ) if key not in need_keys : print 'Error Line, need %r: %d, line='...
Read a single translation entry from the file F and return a tuple with the comments msgid and msgstr . The comments is returned as a list of lines which do not end in new - lines . The msgid and msgstr are strings possibly with embedded newlines
239,906
def get_form ( formcls ) : from uliweb . form import Form import inspect if inspect . isclass ( formcls ) and issubclass ( formcls , Form ) : return formcls elif isinstance ( formcls , ( str , unicode ) ) : path = settings . FORMS . get ( formcls ) if path : _cls = import_attr ( path ) return _cls else : raise UliwebEr...
get form class according form class path or form class object
239,907
def run ( namespace = None , action_prefix = 'action_' , args = None ) : if namespace is None : namespace = sys . _getframe ( 1 ) . f_locals actions = find_actions ( namespace , action_prefix ) if args is None : args = sys . argv [ 1 : ] if not args or args [ 0 ] in ( '-h' , '--help' ) : return print_usage ( actions ) ...
Run the script . Participating actions are looked up in the caller s namespace if no namespace is given otherwise in the dict provided . Only items that start with action_prefix are processed as actions . If you want to use all items in the namespace provided as actions set action_prefix to an empty string .
239,908
def fail ( message , code = - 1 ) : print ( 'Error: %s' % message , file = sys . stderr ) sys . exit ( code )
Fail with an error .
239,909
def find_actions ( namespace , action_prefix ) : actions = { } for key , value in iteritems ( namespace ) : if key . startswith ( action_prefix ) : actions [ key [ len ( action_prefix ) : ] ] = analyse_action ( value ) return actions
Find all the actions in the namespace .
239,910
def analyse_action ( func ) : description = inspect . getdoc ( func ) or 'undocumented action' arguments = [ ] args , varargs , kwargs , defaults = inspect . getargspec ( func ) if varargs or kwargs : raise TypeError ( 'variable length arguments for action not allowed.' ) if len ( args ) != len ( defaults or ( ) ) : ra...
Analyse a function .
239,911
def make_shell ( init_func = None , banner = None , use_ipython = True ) : if banner is None : banner = 'Interactive Werkzeug Shell' if init_func is None : init_func = dict def action ( ipython = use_ipython ) : namespace = init_func ( ) if ipython : try : try : from IPython . frontend . terminal . embed import Interac...
Returns an action callback that spawns a new interactive python shell .
239,912
def make_runserver ( app_factory , hostname = 'localhost' , port = 5000 , use_reloader = False , use_debugger = False , use_evalex = True , threaded = False , processes = 1 , static_files = None , extra_files = None , ssl_context = None ) : def action ( hostname = ( 'h' , hostname ) , port = ( 'p' , port ) , reloader =...
Returns an action callback that spawns a new development server .
239,913
def unbind ( topic , func ) : if topic in _receivers : receivers = _receivers [ topic ] for i in range ( len ( receivers ) - 1 , - 1 , - 1 ) : nice , f = receivers [ i ] if ( callable ( func ) and f [ 'func' ] == func ) or ( f [ 'func_name' ] == func ) : del receivers [ i ] return
Remove receiver function
239,914
def call ( sender , topic , * args , ** kwargs ) : if not topic in _receivers : return items = _receivers [ topic ] def _cmp ( x , y ) : return cmp ( x [ 0 ] , y [ 0 ] ) items . sort ( _cmp ) i = 0 while i < len ( items ) : nice , f = items [ i ] i = i + 1 _f = f [ 'func' ] if not _f : try : _f = import_attr ( f [ 'fun...
Invoke receiver functions according topic it ll invoke receiver functions one by one and it ll not return anything so if you want to return a value you should use get function .
239,915
def get ( sender , topic , * args , ** kwargs ) : if not topic in _receivers : return items = _receivers [ topic ] def _cmp ( x , y ) : return cmp ( x [ 0 ] , y [ 0 ] ) items . sort ( _cmp ) for i in range ( len ( items ) ) : nice , f = items [ i ] _f = f [ 'func' ] if not _f : try : _f = import_attr ( f [ 'func_name' ...
Invoke receiver functions according topic it ll invoke receiver functions one by one and if one receiver function return non - None value it ll return it and break the loop .
239,916
def __read_line ( self , f ) : g = tokenize . generate_tokens ( f . readline ) buf = [ ] time = 0 iden_existed = False while 1 : v = g . next ( ) tokentype , t , start , end , line = v if tokentype == 54 : continue if tokentype in ( token . INDENT , token . DEDENT , tokenize . COMMENT ) : continue if tokentype == token...
Get logic line according the syntax not the physical line It ll return the line text and if there is identifier existed return line bool
239,917
def freeze ( self ) : self . _lazy = False for k , v in self . items ( ) : if k in self . _env : continue for _k , _v in v . items ( ) : if isinstance ( _v , Lazy ) : if self . writable : _v . get ( ) else : try : v . __setitem__ ( _k , _v . get ( ) , replace = True ) except : print "Error ini key:" , _k raise del _v s...
Process all EvalValue to real value
239,918
def serialize ( self , expires = None ) : if self . secret_key is None : raise RuntimeError ( 'no secret key defined' ) if expires : self [ '_expires' ] = _date_to_unix ( expires ) result = [ ] mac = hmac ( self . secret_key , None , self . hash_method ) for key , value in sorted ( self . items ( ) ) : result . append ...
Serialize the secure cookie into a string .
239,919
def unserialize ( cls , string , secret_key ) : if isinstance ( string , text_type ) : string = string . encode ( 'utf-8' , 'replace' ) if isinstance ( secret_key , text_type ) : secret_key = secret_key . encode ( 'utf-8' , 'replace' ) try : base64_hash , data = string . split ( b'?' , 1 ) except ( ValueError , IndexEr...
Load the secure cookie from a serialized string .
239,920
def find_model ( sender , model_name ) : MC = get_mc ( ) model = MC . get ( ( MC . c . model_name == model_name ) & ( MC . c . uuid != '' ) ) if model : model_inst = model . get_instance ( ) orm . set_model ( model_name , model_inst . table_name , appname = __name__ , model_path = '' ) return orm . __models__ . get ( m...
Register new model to ORM
239,921
def get_model_fields ( model , add_reserver_flag = True ) : import uliweb . orm as orm fields = [ ] m = { 'type' : 'type_name' , 'hint' : 'hint' , 'default' : 'default' , 'required' : 'required' } m1 = { 'index' : 'index' , 'unique' : 'unique' } for name , prop in model . properties . items ( ) : if name == 'id' : cont...
Creating fields suit for model_config id will be skipped .
239,922
def get_model_indexes ( model , add_reserver_flag = True ) : import uliweb . orm as orm from sqlalchemy . engine . reflection import Inspector indexes = [ ] engine = model . get_engine ( ) . engine insp = Inspector . from_engine ( engine ) for index in insp . get_indexes ( model . tablename ) : d = { } d [ 'name' ] = i...
Creating indexes suit for model_config .
239,923
def timeit ( output ) : b = time . time ( ) yield print output , 'time used: %.3fs' % ( time . time ( ) - b )
If output is string then print the string and also time used
239,924
def host_is_trusted ( hostname , trusted_list ) : if not hostname : return False if isinstance ( trusted_list , string_types ) : trusted_list = [ trusted_list ] def _normalize ( hostname ) : if ':' in hostname : hostname = hostname . rsplit ( ':' , 1 ) [ 0 ] return _encode_idna ( hostname ) hostname = _normalize ( host...
Checks if a host is trusted against a list . This also takes care of port normalization .
239,925
def get_content_length ( environ ) : content_length = environ . get ( 'CONTENT_LENGTH' ) if content_length is not None : try : return max ( 0 , int ( content_length ) ) except ( ValueError , TypeError ) : pass
Returns the content length from the WSGI environment as integer . If it s not available None is returned .
239,926
def get_input_stream ( environ , safe_fallback = True ) : stream = environ [ 'wsgi.input' ] content_length = get_content_length ( environ ) if environ . get ( 'wsgi.input_terminated' ) : return stream if content_length is None : return safe_fallback and _empty_stream or stream return LimitedStream ( stream , content_le...
Returns the input stream from the WSGI environment and wraps it in the most sensible way possible . The stream returned is not the raw WSGI stream in most cases but one that is safe to read from without taking into account the content length .
239,927
def get_path_info ( environ , charset = 'utf-8' , errors = 'replace' ) : path = wsgi_get_bytes ( environ . get ( 'PATH_INFO' , '' ) ) return to_unicode ( path , charset , errors , allow_none_charset = True )
Returns the PATH_INFO from the WSGI environment and properly decodes it . This also takes care about the WSGI decoding dance on Python 3 environments . if the charset is set to None a bytestring is returned .
239,928
def pop_path_info ( environ , charset = 'utf-8' , errors = 'replace' ) : path = environ . get ( 'PATH_INFO' ) if not path : return None script_name = environ . get ( 'SCRIPT_NAME' , '' ) old_path = path path = path . lstrip ( '/' ) if path != old_path : script_name += '/' * ( len ( old_path ) - len ( path ) ) if '/' no...
Removes and returns the next segment of PATH_INFO pushing it onto SCRIPT_NAME . Returns None if there is nothing left on PATH_INFO .
239,929
def _make_chunk_iter ( stream , limit , buffer_size ) : if isinstance ( stream , ( bytes , bytearray , text_type ) ) : raise TypeError ( 'Passed a string or byte object instead of ' 'true iterator or stream.' ) if not hasattr ( stream , 'read' ) : for item in stream : if item : yield item return if not isinstance ( str...
Helper for the line and chunk iter functions .
239,930
def soap ( func = None , name = None , returns = None , args = None , doc = None , target = 'SOAP' ) : global __soap_functions__ returns = _fix_soap_kwargs ( returns ) args = _fix_soap_kwargs ( args ) if isinstance ( func , str ) and not name : return partial ( soap , name = func , returns = returns , args = args , doc...
soap supports multiple SOAP function collections it ll save functions to target dict and you can give other target but it should be keep up with SoapView . target definition .
239,931
def getJsonData ( self , params ) : try : return eval ( "self." + str ( params [ 'output_id' ] ) + "(params)" ) except AttributeError : df = self . getData ( params ) if df is None : return None return df . to_dict ( orient = 'records' )
turns the DataFrame returned by getData into a dictionary
239,932
def launch_in_notebook ( self , port = 9095 , width = 900 , height = 600 ) : from IPython . lib import backgroundjobs as bg from IPython . display import HTML jobs = bg . BackgroundJobManager ( ) jobs . new ( self . launch , kw = dict ( port = port ) ) frame = HTML ( '<iframe src=http://localhost:{} width={} height={}>...
launch the app within an iframe in ipython notebook
239,933
def launch ( self , host = "local" , port = 8080 ) : self . root . templateVars [ 'app_bar' ] = self . site_app_bar for fullRoute , _ in self . site_app_bar [ 1 : ] : parent , route = self . get_route ( fullRoute ) parent . __dict__ [ route ] . templateVars [ 'app_bar' ] = self . site_app_bar if host != "local" : cherr...
Calling the Launch method on a Site object will serve the top node of the cherrypy Root object tree
239,934
def exclude_args ( parser , args , excluded_args , target ) : msg = '"%s" option invalid for %s' for argname in excluded_args : if argname not in args : continue if args [ argname ] : optname = "--%s" % argname . replace ( "_" , "-" ) parser . error ( msg % ( optname , target ) ) del args [ argname ]
Delete options that are not appropriate for a following code path ; exit with an error if excluded options were passed in by the user .
239,935
def _varLib_finder ( source , directory = "" , ext = "ttf" ) : fname = os . path . splitext ( os . path . basename ( source ) ) [ 0 ] + "." + ext return os . path . join ( directory , fname )
Finder function to be used with varLib . build to find master TTFs given the filename of the source UFO master as specified in the designspace . It replaces the UFO directory with the one specified in directory argument and replaces the file extension with ext .
239,936
def build_master_ufos ( self , glyphs_path , designspace_path = None , master_dir = None , instance_dir = None , family_name = None , mti_source = None , ) : import glyphsLib if master_dir is None : master_dir = self . _output_dir ( "ufo" ) if not os . path . isdir ( master_dir ) : os . mkdir ( master_dir ) if instance...
Build UFOs and MutatorMath designspace from Glyphs source .
239,937
def remove_overlaps ( self , ufos , glyph_filter = lambda g : len ( g ) ) : from booleanOperations import union , BooleanOperationsError for ufo in ufos : font_name = self . _font_name ( ufo ) logger . info ( "Removing overlaps for " + font_name ) for glyph in ufo : if not glyph_filter ( glyph ) : continue contours = l...
Remove overlaps in UFOs glyphs contours .
239,938
def decompose_glyphs ( self , ufos , glyph_filter = lambda g : True ) : for ufo in ufos : logger . info ( "Decomposing glyphs for " + self . _font_name ( ufo ) ) for glyph in ufo : if not glyph . components or not glyph_filter ( glyph ) : continue self . _deep_copy_contours ( ufo , glyph , glyph , Transform ( ) ) glyph...
Move components of UFOs glyphs to their outlines .
239,939
def build_ttfs ( self , ufos , ** kwargs ) : self . save_otfs ( ufos , ttf = True , ** kwargs )
Build OpenType binaries with TrueType outlines .
239,940
def build_variable_font ( self , designspace , output_path = None , output_dir = None , master_bin_dir = None , ttf = True , ) : assert not ( output_path and output_dir ) , "mutually exclusive args" ext = "ttf" if ttf else "otf" if hasattr ( designspace , "__fspath__" ) : designspace = designspace . __fspath__ ( ) if i...
Build OpenType variable font from masters in a designspace .
239,941
def subset_otf_from_ufo ( self , otf_path , ufo ) : from fontTools import subset ufo_order = makeOfficialGlyphOrder ( ufo ) if ".notdef" not in ufo_order : ufo_order . insert ( 0 , ".notdef" ) ot_order = TTFont ( otf_path ) . getGlyphOrder ( ) assert ot_order [ 0 ] == ".notdef" assert len ( ufo_order ) == len ( ot_orde...
Subset a font using export flags set by glyphsLib .
239,942
def run_from_glyphs ( self , glyphs_path , designspace_path = None , master_dir = None , instance_dir = None , family_name = None , mti_source = None , ** kwargs ) : logger . info ( "Building master UFOs and designspace from Glyphs source" ) designspace_path = self . build_master_ufos ( glyphs_path , designspace_path =...
Run toolchain from Glyphs source .
239,943
def interpolate_instance_ufos ( self , designspace , include = None , round_instances = False , expand_features_to_instances = False , ) : from glyphsLib . interpolation import apply_instance_data from mutatorMath . ufo . document import DesignSpaceDocumentReader if any ( source . layerName is not None for source in de...
Interpolate master UFOs with MutatorMath and return instance UFOs .
239,944
def run_from_ufos ( self , ufos , output = ( ) , ** kwargs ) : if set ( output ) == { "ufo" } : return ufo_paths = [ ] if isinstance ( ufos , basestring ) : ufo_paths = glob . glob ( ufos ) ufos = [ Font ( x ) for x in ufo_paths ] elif isinstance ( ufos , list ) : ufos = [ Font ( x ) if isinstance ( x , basestring ) el...
Run toolchain from UFO sources .
239,945
def _font_name ( self , ufo ) : family_name = ( ufo . info . familyName . replace ( " " , "" ) if ufo . info . familyName is not None else "None" ) style_name = ( ufo . info . styleName . replace ( " " , "" ) if ufo . info . styleName is not None else "None" ) return "{}-{}" . format ( family_name , style_name )
Generate a postscript - style font name .
239,946
def _output_dir ( self , ext , is_instance = False , interpolatable = False , autohinted = False , is_variable = False , ) : assert not ( is_variable and any ( [ is_instance , interpolatable ] ) ) if is_variable : dir_prefix = "variable_" elif is_instance : dir_prefix = "instance_" else : dir_prefix = "master_" dir_suf...
Generate an output directory .
239,947
def _output_path ( self , ufo_or_font_name , ext , is_instance = False , interpolatable = False , autohinted = False , is_variable = False , output_dir = None , suffix = None , ) : if isinstance ( ufo_or_font_name , basestring ) : font_name = ufo_or_font_name elif ufo_or_font_name . path : font_name = os . path . split...
Generate output path for a font file with given extension .
239,948
def _designspace_locations ( self , designspace ) : maps = [ ] for elements in ( designspace . sources , designspace . instances ) : location_map = { } for element in elements : path = _normpath ( element . path ) location_map [ path ] = element . location maps . append ( location_map ) return maps
Map font filenames to their locations in a designspace .
239,949
def _closest_location ( self , location_map , target ) : def dist ( a , b ) : return math . sqrt ( sum ( ( a [ k ] - b [ k ] ) ** 2 for k in a . keys ( ) ) ) paths = iter ( location_map . keys ( ) ) closest = next ( paths ) closest_dist = dist ( target , location_map [ closest ] ) for path in paths : cur_dist = dist ( ...
Return path of font whose location is closest to target .
239,950
def ttfautohint ( in_file , out_file , args = None , ** kwargs ) : arg_list = [ "ttfautohint" ] file_args = [ in_file , out_file ] if args is not None : if kwargs : raise TypeError ( "Should not provide both cmd args and kwargs." ) rv = subprocess . call ( arg_list + args . split ( ) + file_args ) if rv != 0 : raise TT...
Thin wrapper around the ttfautohint command line tool .
239,951
def _default_json_default ( obj ) : if isinstance ( obj , ( datetime . datetime , datetime . date , datetime . time ) ) : return obj . isoformat ( ) else : return str ( obj )
Coerce everything to strings . All objects representing time get output as ISO8601 .
239,952
def format ( self , record ) : fields = record . __dict__ . copy ( ) if isinstance ( record . msg , dict ) : fields . update ( record . msg ) fields . pop ( 'msg' ) msg = "" else : msg = record . getMessage ( ) try : msg = msg . format ( ** fields ) except ( KeyError , IndexError , ValueError ) : pass except : msg = ms...
Format a log record to JSON if the message is a dict assume an empty message and use the dict as additional fields .
239,953
def _build_fields ( self , defaults , fields ) : return dict ( list ( defaults . get ( '@fields' , { } ) . items ( ) ) + list ( fields . items ( ) ) )
Return provided fields including any in defaults
239,954
def _authenticate ( self ) : self . cleanup_headers ( ) url = LOGIN_ENDPOINT data = self . query ( url , method = 'POST' , extra_params = { 'email' : self . __username , 'password' : self . __password } ) if isinstance ( data , dict ) and data . get ( 'success' ) : data = data . get ( 'data' ) self . authenticated = da...
Authenticate user and generate token .
239,955
def cleanup_headers ( self ) : headers = { 'Content-Type' : 'application/json' } headers [ 'Authorization' ] = self . __token self . __headers = headers self . __params = { }
Reset the headers and params .
239,956
def query ( self , url , method = 'GET' , extra_params = None , extra_headers = None , retry = 3 , raw = False , stream = False ) : response = None loop = 0 self . cleanup_headers ( ) while loop <= retry : if extra_params : params = self . __params params . update ( extra_params ) else : params = self . __params _LOGGE...
Return a JSON object or raw session .
239,957
def devices ( self ) : if self . _all_devices : return self . _all_devices self . _all_devices = { } self . _all_devices [ 'cameras' ] = [ ] self . _all_devices [ 'base_station' ] = [ ] url = DEVICES_ENDPOINT data = self . query ( url ) for device in data . get ( 'data' ) : name = device . get ( 'deviceName' ) if ( ( d...
Return all devices on Arlo account .
239,958
def lookup_camera_by_id ( self , device_id ) : camera = list ( filter ( lambda cam : cam . device_id == device_id , self . cameras ) ) [ 0 ] if camera : return camera return None
Return camera object by device_id .
239,959
def refresh_attributes ( self , name ) : url = DEVICES_ENDPOINT response = self . query ( url ) if not response or not isinstance ( response , dict ) : return None for device in response . get ( 'data' ) : if device . get ( 'deviceName' ) == name : return device return None
Refresh attributes from a given Arlo object .
239,960
def update ( self , update_cameras = False , update_base_station = False ) : self . _authenticate ( ) if update_cameras : url = DEVICES_ENDPOINT response = self . query ( url ) if not response or not isinstance ( response , dict ) : return for camera in self . cameras : for dev_info in response . get ( 'data' ) : if de...
Refresh object .
239,961
def load ( self , days = PRELOAD_DAYS , only_cameras = None , date_from = None , date_to = None , limit = None ) : videos = [ ] url = LIBRARY_ENDPOINT if not ( date_from and date_to ) : now = datetime . today ( ) date_from = ( now - timedelta ( days = days ) ) . strftime ( '%Y%m%d' ) date_to = now . strftime ( '%Y%m%d'...
Load Arlo videos from the given criteria
239,962
def _name ( self ) : return "{0} {1} {2}" . format ( self . _camera . name , pretty_timestamp ( self . created_at ) , self . _attrs . get ( 'mediaDuration' ) )
Define object name .
239,963
def created_at_pretty ( self , date_format = None ) : if date_format : return pretty_timestamp ( self . created_at , date_format = date_format ) return pretty_timestamp ( self . created_at )
Return pretty timestamp .
239,964
def created_today ( self ) : if self . datetime . date ( ) == datetime . today ( ) . date ( ) : return True return False
Return True if created today .
239,965
def to_datetime ( timestamp ) : return dt . fromtimestamp ( time . mktime ( time . localtime ( int ( str ( timestamp ) [ : 10 ] ) ) ) )
Return datetime object from timestamp .
239,966
def pretty_timestamp ( timestamp , date_format = '%a-%m_%d_%y:%H:%M:%S' ) : return time . strftime ( date_format , time . localtime ( int ( str ( timestamp ) [ : 10 ] ) ) )
Huminize timestamp .
239,967
def http_get ( url , filename = None ) : try : ret = requests . get ( url ) except requests . exceptions . SSLError as error : _LOGGER . error ( error ) return False if ret . status_code != 200 : return False if filename is None : return ret . content with open ( filename , 'wb' ) as data : data . write ( ret . content...
Download HTTP data .
239,968
def http_stream ( url , chunk = 4096 ) : ret = requests . get ( url , stream = True ) ret . raise_for_status ( ) for data in ret . iter_content ( chunk ) : yield data
Generate stream for a given record video .
239,969
def unseen_videos_reset ( self ) : url = RESET_CAM_ENDPOINT . format ( self . unique_id ) ret = self . _session . query ( url ) . get ( 'success' ) return ret
Reset the unseen videos counter .
239,970
def make_video_cache ( self , days = None ) : if days is None : days = self . _min_days_vdo_cache self . _cached_videos = self . videos ( days )
Save videos on _cache_videos to avoid dups .
239,971
def base_station ( self ) : try : return list ( filter ( lambda x : x . device_id == self . parent_id , self . _session . base_stations ) ) [ 0 ] except ( IndexError , AttributeError ) : return None
Return the base_station assigned for the given camera .
239,972
def _get_camera_properties ( self ) : if self . base_station and self . base_station . camera_properties : for cam in self . base_station . camera_properties : if cam [ "serialNumber" ] == self . device_id : return cam return None
Lookup camera properties from base station .
239,973
def triggers ( self ) : capabilities = self . capabilities if not capabilities : return None for capability in capabilities : if not isinstance ( capability , dict ) : continue triggers = capability . get ( "Triggers" ) if triggers : return triggers return None
Get a camera s triggers .
239,974
def motion_detection_sensitivity ( self ) : if not self . triggers : return None for trigger in self . triggers : if trigger . get ( "type" ) != "pirMotionActive" : continue sensitivity = trigger . get ( "sensitivity" ) if sensitivity : return sensitivity . get ( "default" ) return None
Sensitivity level of Camera motion detection .
239,975
def audio_detection_sensitivity ( self ) : if not self . triggers : return None for trigger in self . triggers : if trigger . get ( "type" ) != "audioAmplitude" : continue sensitivity = trigger . get ( "sensitivity" ) if sensitivity : return sensitivity . get ( "default" ) return None
Sensitivity level of Camera audio detection .
239,976
def live_streaming ( self ) : url = STREAM_ENDPOINT params = STREAMING_BODY params [ 'from' ] = "{0}_web" . format ( self . user_id ) params [ 'to' ] = self . device_id params [ 'resource' ] = "cameras/{0}" . format ( self . device_id ) params [ 'transId' ] = "web!{0}" . format ( self . xcloud_id ) headers = { 'xCloudI...
Return live streaming generator .
239,977
def schedule_snapshot ( self ) : url = SNAPSHOTS_ENDPOINT params = SNAPSHOTS_BODY params [ 'from' ] = "{0}_web" . format ( self . user_id ) params [ 'to' ] = self . device_id params [ 'resource' ] = "cameras/{0}" . format ( self . device_id ) params [ 'transId' ] = "web!{0}" . format ( self . xcloud_id ) headers = { 'x...
Trigger snapshot to be uploaded to AWS . Return success state .
239,978
def thread_function ( self ) : self . __subscribed = True url = SUBSCRIBE_ENDPOINT + "?token=" + self . _session_token data = self . _session . query ( url , method = 'GET' , raw = True , stream = True ) if not data or not data . ok : _LOGGER . debug ( "Did not receive a valid response. Aborting.." ) return None self ....
Thread function .
239,979
def _get_event_stream ( self ) : self . __event_handle = threading . Event ( ) event_thread = threading . Thread ( target = self . thread_function ) event_thread . start ( )
Spawn a thread and monitor the Arlo Event Stream .
239,980
def _unsubscribe_myself ( self ) : url = UNSUBSCRIBE_ENDPOINT return self . _session . query ( url , method = 'GET' , raw = True , stream = False )
Unsubscribe this base station for all events .
239,981
def _close_event_stream ( self ) : self . __subscribed = False del self . __events [ : ] self . __event_handle . clear ( )
Stop the Event stream thread .
239,982
def publish_and_get_event ( self , resource ) : l_subscribed = False this_event = None if not self . __subscribed : self . _get_event_stream ( ) self . _subscribe_myself ( ) l_subscribed = True status = self . publish ( action = 'get' , resource = resource , mode = None , publish_response = False ) if status == 'succes...
Publish and get the event from base station .
239,983
def publish ( self , action = 'get' , resource = None , camera_id = None , mode = None , publish_response = None , properties = None ) : url = NOTIFY_ENDPOINT . format ( self . device_id ) body = ACTION_BODY . copy ( ) if properties is None : properties = { } if resource : body [ 'resource' ] = resource if action == 'g...
Run action .
239,984
def refresh_rate ( self , value ) : if isinstance ( value , ( int , float ) ) : self . _refresh_rate = value
Override the refresh_rate attribute .
239,985
def available_modes ( self ) : if not self . _available_modes : modes = self . available_modes_with_ids if not modes : return None self . _available_modes = list ( modes . keys ( ) ) return self . _available_modes
Return list of available mode names .
239,986
def available_modes_with_ids ( self ) : if not self . _available_mode_ids : all_modes = FIXED_MODES . copy ( ) self . _available_mode_ids = all_modes modes = self . get_available_modes ( ) try : if modes : simple_modes = dict ( [ ( m . get ( "type" , m . get ( "name" ) ) , m . get ( "id" ) ) for m in modes ] ) all_mode...
Return list of objects containing available mode name and id .
239,987
def mode ( self ) : if self . is_in_schedule_mode : return "schedule" resource = "modes" mode_event = self . publish_and_get_event ( resource ) if mode_event : properties = mode_event . get ( 'properties' ) active_mode = properties . get ( 'active' ) modes = properties . get ( 'modes' ) if not modes : return None for m...
Return current mode key .
239,988
def is_in_schedule_mode ( self ) : resource = "schedule" mode_event = self . publish_and_get_event ( resource ) if mode_event and mode_event . get ( "resource" , None ) == "schedule" : properties = mode_event . get ( 'properties' ) return properties . get ( "active" , False ) return False
Returns True if base_station is currently on a scheduled mode .
239,989
def get_available_modes ( self ) : resource = "modes" resource_event = self . publish_and_get_event ( resource ) if resource_event : properties = resource_event . get ( "properties" ) return properties . get ( "modes" ) return None
Return a list of available mode objects for an Arlo user .
239,990
def get_cameras_properties ( self ) : resource = "cameras" resource_event = self . publish_and_get_event ( resource ) if resource_event : self . _last_refresh = int ( time . time ( ) ) self . _camera_properties = resource_event . get ( 'properties' )
Return camera properties .
239,991
def get_cameras_battery_level ( self ) : battery_levels = { } if not self . camera_properties : return None for camera in self . camera_properties : serialnum = camera . get ( 'serialNumber' ) cam_battery = camera . get ( 'batteryLevel' ) battery_levels [ serialnum ] = cam_battery return battery_levels
Return a list of battery levels of all cameras .
239,992
def get_cameras_signal_strength ( self ) : signal_strength = { } if not self . camera_properties : return None for camera in self . camera_properties : serialnum = camera . get ( 'serialNumber' ) cam_strength = camera . get ( 'signalStrength' ) signal_strength [ serialnum ] = cam_strength return signal_strength
Return a list of signal strength of all cameras .
239,993
def get_camera_extended_properties ( self ) : resource = 'cameras/{}' . format ( self . device_id ) resource_event = self . publish_and_get_event ( resource ) if resource_event is None : return None self . _camera_extended_properties = resource_event . get ( 'properties' ) return self . _camera_extended_properties
Return camera extended properties .
239,994
def get_speaker_muted ( self ) : if not self . camera_extended_properties : return None speaker = self . camera_extended_properties . get ( 'speaker' ) if not speaker : return None return speaker . get ( 'mute' )
Return whether or not the speaker is muted .
239,995
def get_speaker_volume ( self ) : if not self . camera_extended_properties : return None speaker = self . camera_extended_properties . get ( 'speaker' ) if not speaker : return None return speaker . get ( 'volume' )
Return the volume setting of the speaker .
239,996
def properties ( self ) : resource = "basestation" basestn_event = self . publish_and_get_event ( resource ) if basestn_event : return basestn_event . get ( 'properties' ) return None
Return the base station info .
239,997
def get_cameras_rules ( self ) : resource = "rules" rules_event = self . publish_and_get_event ( resource ) if rules_event : return rules_event . get ( 'properties' ) return None
Return the camera rules .
239,998
def get_cameras_schedule ( self ) : resource = "schedule" schedule_event = self . publish_and_get_event ( resource ) if schedule_event : return schedule_event . get ( 'properties' ) return None
Return the schedule set for cameras .
239,999
def get_ambient_sensor_data ( self ) : resource = 'cameras/{}/ambientSensors/history' . format ( self . device_id ) history_event = self . publish_and_get_event ( resource ) if history_event is None : return None properties = history_event . get ( 'properties' ) self . _ambient_sensor_data = ArloBaseStation . _decode_s...
Refresh ambient sensor history