idx
int64
0
63k
question
stringlengths
53
5.28k
target
stringlengths
5
805
13,400
def get_reference_fields ( self , exclude_models = None ) : if exclude_models is None : exclude_models = [ ] result = [ ] for django_model in django . apps . apps . get_models ( ) : if any ( [ issubclass ( django_model , m ) for m in exclude_models ] ) : continue for django_field in django_model . _meta . fields : if isinstance ( django_field , models . ForeignKey ) and django_field . related . to == Item : result = [ ( m , f ) for ( m , f ) in result if not issubclass ( django_model , m ) ] result . append ( ( django_model , django_field ) ) return result
Get all Django model fields which reference the Item model .
13,401
def override_parent_subgraph ( self , parent_subgraph , invisible_edges = None ) : with transaction . atomic ( ) : if invisible_edges is None : invisible_edges = set ( ) children = list ( parent_subgraph . keys ( ) ) all_old_relations = dict ( proso . list . group_by ( list ( ItemRelation . objects . filter ( child_id__in = children ) ) , by = lambda relation : relation . child_id ) ) to_delete = set ( ) for child_id , parents in parent_subgraph . items ( ) : old_relations = { relation . parent_id : relation for relation in all_old_relations . get ( child_id , [ ] ) } for parent_id in parents : if parent_id not in old_relations : ItemRelation . objects . create ( parent_id = parent_id , child_id = child_id , visible = ( child_id , parent_id ) not in invisible_edges ) elif old_relations [ parent_id ] . visible != ( ( child_id , parent_id ) not in invisible_edges ) : old_relations [ parent_id ] . visible = ( child_id , parent_id ) not in invisible_edges old_relations [ parent_id ] . save ( ) to_delete |= { old_relations [ parent_id ] . pk for parent_id in set ( old_relations . keys ( ) ) - set ( parents ) } ItemRelation . objects . filter ( pk__in = to_delete ) . delete ( )
Get all items with outcoming edges from the given subgraph drop all their parent relations and then add parents according to the given subgraph .
13,402
def query_api ( self , data = None , endpoint = 'SMS' ) : url = self . api_url % endpoint if data : response = requests . post ( url , data = data , auth = self . auth ) else : response = requests . get ( url , auth = self . auth ) try : response . raise_for_status ( ) except HTTPError as e : raise HTTPError ( 'HTTP %s\n%s' % ( response . status_code , response . text ) ) return response . text
Send a request to the 46elks API . Fetches SMS history as JSON by default sends a HTTP POST request with the incoming data dictionary as a urlencoded query if data is provided otherwise HTTP GET
13,403
def validate_number ( self , number ) : if not isinstance ( number , str ) : raise ElksException ( 'Recipient phone number may not be empty' ) if number [ 0 ] == '+' and len ( number ) > 2 and len ( number ) < 16 : return True else : raise ElksException ( "Phone number must be of format +CCCXXX..." )
Checks if a number looks somewhat like a E . 164 number . Not an exhaustive check as the API takes care of that
13,404
def format_sms_payload ( self , message , to , sender = 'elkme' , options = [ ] ) : self . validate_number ( to ) if not isinstance ( message , str ) : message = " " . join ( message ) message = message . rstrip ( ) sms = { 'from' : sender , 'to' : to , 'message' : message } for option in options : if option not in [ 'dontlog' , 'dryrun' , 'flashsms' ] : raise ElksException ( 'Option %s not supported' % option ) sms [ option ] = 'yes' return sms
Helper function to create a SMS payload with little effort
13,405
def send_sms ( self , message , to , sender = 'elkme' , options = [ ] ) : sms = self . format_sms_payload ( message = message , to = to , sender = sender , options = options ) return self . query_api ( sms )
Sends a text message to a configuration conf containing the message in the message paramter
13,406
async def get_types ( self ) : async with aiohttp . ClientSession ( ) as session : async with session . get ( 'https://api.weeb.sh/images/types' , headers = self . __headers ) as resp : if resp . status == 200 : return ( await resp . json ( ) ) [ 'types' ] else : raise Exception ( ( await resp . json ( ) ) [ 'message' ] )
Gets all available types .
13,407
async def get_image ( self , imgtype = None , tags = None , nsfw = None , hidden = None , filetype = None ) : if not imgtype and not tags : raise MissingTypeOrTags ( "'get_image' requires at least one of either type or tags." ) if imgtype and not isinstance ( imgtype , str ) : raise TypeError ( "type of 'imgtype' must be str." ) if tags and not isinstance ( tags , list ) : raise TypeError ( "type of 'tags' must be list or None." ) if hidden and not isinstance ( hidden , bool ) : raise TypeError ( "type of 'hidden' must be bool or None." ) if nsfw and not isinstance ( nsfw , bool ) and ( isinstance ( nsfw , str ) and nsfw == 'only' ) : raise TypeError ( "type of 'nsfw' must be str, bool or None." ) if filetype and not isinstance ( filetype , str ) : raise TypeError ( "type of 'filetype' must be str." ) url = 'https://api.weeb.sh/images/random' + ( f'?type={imgtype}' if imgtype else '' ) + ( f'{"?" if not imgtype else "&"}tags={",".join(tags)}' if tags else '' ) + ( f'&nsfw={nsfw.lower()}' if nsfw else '' ) + ( f'&hidden={hidden}' if hidden else '' ) + ( f'&filetype={filetype}' if filetype else '' ) async with aiohttp . ClientSession ( ) as session : async with session . get ( url , headers = self . __headers ) as resp : if resp . status == 200 : js = await resp . json ( ) return [ js [ 'url' ] , js [ 'id' ] , js [ 'fileType' ] ] else : raise Exception ( ( await resp . json ( ) ) [ 'message' ] )
Request an image from weeb . sh .
13,408
async def generate_image ( self , imgtype , face = None , hair = None ) : if not isinstance ( imgtype , str ) : raise TypeError ( "type of 'imgtype' must be str." ) if face and not isinstance ( face , str ) : raise TypeError ( "type of 'face' must be str." ) if hair and not isinstance ( hair , str ) : raise TypeError ( "type of 'hair' must be str." ) if ( face or hair ) and imgtype != 'awooo' : raise InvalidArguments ( '\'face\' and \'hair\' are arguments only available on the \'awoo\' image type' ) url = f'https://api.weeb.sh/auto-image/generate?type={imgtype}' + ( "&face=" + face if face else "" ) + ( "&hair=" + hair if hair else "" ) async with aiohttp . ClientSession ( ) as session : async with session . get ( url , headers = self . __headers ) as resp : if resp . status == 200 : return await resp . read ( ) else : raise Exception ( ( await resp . json ( ) ) [ 'message' ] )
Generate a basic image using the auto - image endpoint of weeb . sh .
13,409
async def generate_status ( self , status , avatar = None ) : if not isinstance ( status , str ) : raise TypeError ( "type of 'status' must be str." ) if avatar and not isinstance ( avatar , str ) : raise TypeError ( "type of 'avatar' must be str." ) url = f'https://api.weeb.sh/auto-image/discord-status?status={status}' + ( f'&avatar={urllib.parse.quote(avatar, safe="")}' if avatar else '' ) async with aiohttp . ClientSession ( ) as session : async with session . get ( url , headers = self . __headers ) as resp : if resp . status == 200 : return await resp . read ( ) else : raise Exception ( ( await resp . json ( ) ) [ 'message' ] )
Generate a discord status icon below the image provided .
13,410
async def generate_waifu_insult ( self , avatar ) : if not isinstance ( avatar , str ) : raise TypeError ( "type of 'avatar' must be str." ) async with aiohttp . ClientSession ( ) as session : async with session . post ( "https://api.weeb.sh/auto-image/waifu-insult" , headers = self . __headers , data = { "avatar" : avatar } ) as resp : if resp . status == 200 : return await resp . read ( ) else : raise Exception ( ( await resp . json ( ) ) [ 'message' ] )
Generate a waifu insult image .
13,411
async def generate_license ( self , title , avatar , badges = None , widgets = None ) : if not isinstance ( title , str ) : raise TypeError ( "type of 'title' must be str." ) if not isinstance ( avatar , str ) : raise TypeError ( "type of 'avatar' must be str." ) if badges and not isinstance ( badges , list ) : raise TypeError ( "type of 'badges' must be list." ) if widgets and not isinstance ( widgets , list ) : raise TypeError ( "type of 'widgets' must be list." ) data = { "title" : title , "avatar" : avatar } if badges and len ( badges ) <= 3 : data [ 'badges' ] = badges if widgets and len ( widgets ) <= 3 : data [ 'widgets' ] = widgets async with aiohttp . ClientSession ( ) as session : async with session . post ( "https://api.weeb.sh/auto-image/license" , headers = self . __headers , data = data ) as resp : if resp . status == 200 : return await resp . read ( ) else : raise Exception ( ( await resp . json ( ) ) [ 'message' ] )
Generate a license .
13,412
async def generate_love_ship ( self , target_one , target_two ) : if not isinstance ( target_one , str ) : raise TypeError ( "type of 'target_one' must be str." ) if not isinstance ( target_two , str ) : raise TypeError ( "type of 'target_two' must be str." ) data = { "targetOne" : target_one , "targetTwo" : target_two } async with aiohttp . ClientSession ( ) as session : async with session . post ( "https://api.weeb.sh/auto-image/love-ship" , headers = self . __headers , data = data ) as resp : if resp . status == 200 : return await resp . read ( ) else : raise Exception ( ( await resp . json ( ) ) [ 'message' ] )
Generate a love ship .
13,413
def launch_command ( command , parameter = '' ) : result = '' if not isinstance ( parameter , list ) : parameter = [ parameter ] for name in parameter : result += subprocess . Popen ( 'cozy-monitor {} {}' . format ( command , name ) , shell = True , stdout = subprocess . PIPE ) . stdout . read ( ) return result
Can launch a cozy - monitor command
13,414
def status ( app_name = None , only_cozy = False , as_boolean = False ) : apps = { } apps_status = subprocess . Popen ( 'cozy-monitor status' , shell = True , stdout = subprocess . PIPE ) . stdout . read ( ) apps_status = apps_status . split ( '\n' ) for app_status in apps_status : if app_status : app_status = ANSI_ESCAPE . sub ( '' , app_status ) . split ( ': ' ) if len ( app_status ) == 2 : current_status = app_status [ 1 ] if as_boolean : if app_status [ 1 ] == 'up' : current_status = True else : current_status = False if only_cozy and app_status [ 0 ] not in SYSTEM_APPS : apps [ app_status [ 0 ] ] = current_status else : apps [ app_status [ 0 ] ] = current_status if app_name : return apps . get ( app_name , None ) else : return apps
Get apps status
13,415
def transitive_closure ( m , orig , rel ) : links = list ( m . match ( orig , rel ) ) for link in links : yield link [ 0 ] [ TARGET ] yield from transitive_closure ( m , target , rel )
Generate the closure over a transitive relationship in depth - first fashion
13,416
def all_origins ( m ) : seen = set ( ) for link in m . match ( ) : origin = link [ ORIGIN ] if origin not in seen : seen . add ( origin ) yield origin
Generate all unique statement origins in the given model
13,417
def column ( m , linkpart ) : assert linkpart in ( 0 , 1 , 2 , 3 ) seen = set ( ) for link in m . match ( ) : val = link [ linkpart ] if val not in seen : seen . add ( val ) yield val
Generate all parts of links according to the parameter
13,418
def resourcetypes ( rid , model ) : types = [ ] for o , r , t , a in model . match ( rid , VTYPE_REL ) : types . append ( t ) return types
Return a list of Versa types for a resource
13,419
def replace_values ( in_m , out_m , map_from = ( ) , map_to = ( ) ) : for link in in_m . match ( ) : new_link = list ( link ) if map_from : if link [ ORIGIN ] in map_from : new_link [ ORIGIN ] = map_to [ map_from . index ( link [ ORIGIN ] ) ] new_link [ ATTRIBUTES ] = link [ ATTRIBUTES ] . copy ( ) out_m . add ( * new_link ) return
Make a copy of a model with one value replaced with another
13,420
def replace_entity_resource ( model , oldres , newres ) : oldrids = set ( ) for rid , link in model : if link [ ORIGIN ] == oldres or link [ TARGET ] == oldres or oldres in link [ ATTRIBUTES ] . values ( ) : oldrids . add ( rid ) new_link = ( newres if o == oldres else o , r , newres if t == oldres else t , dict ( ( k , newres if v == oldres else v ) for k , v in a . items ( ) ) ) model . add ( * new_link ) model . delete ( oldrids ) return
Replace one entity in the model with another with the same links
13,421
def duplicate_statements ( model , oldorigin , neworigin , rfilter = None ) : for o , r , t , a in model . match ( oldorigin ) : if rfilter is None or rfilter ( o , r , t , a ) : model . add ( I ( neworigin ) , r , t , a ) return
Take links with a given origin and create duplicate links with the same information but a new origin
13,422
def uniquify ( model ) : seen = set ( ) to_remove = set ( ) for ix , ( o , r , t , a ) in model : hashable_link = ( o , r , t ) + tuple ( sorted ( a . items ( ) ) ) if hashable_link in seen : to_remove . add ( ix ) seen . add ( hashable_link ) model . remove ( to_remove ) return
Remove all duplicate relationships
13,423
def jsonload ( model , fp ) : dumped_list = json . load ( fp ) for link in dumped_list : if len ( link ) == 2 : sid , ( s , p , o , a ) = link elif len ( link ) == 4 : ( s , p , o , a ) = link tt = a . get ( '@target-type' ) if tt == '@iri-ref' : o = I ( o ) a . pop ( '@target-type' , None ) else : continue model . add ( s , p , o , a ) return
Load Versa model dumped into JSON form either raw or canonical
13,424
def jsondump ( model , fp ) : fp . write ( '[' ) links_ser = [ ] for link in model : links_ser . append ( json . dumps ( link ) ) fp . write ( ',\n' . join ( links_ser ) ) fp . write ( ']' )
Dump Versa model into JSON form
13,425
def set_statics ( self ) : if not os . path . exists ( self . results_dir ) : return None try : shutil . copytree ( os . path . join ( self . templates_dir , 'css' ) , os . path . join ( self . results_dir , 'css' ) ) shutil . copytree ( os . path . join ( self . templates_dir , 'scripts' ) , os . path . join ( self . results_dir , 'scripts' ) ) shutil . copytree ( os . path . join ( self . templates_dir , 'fonts' ) , os . path . join ( self . results_dir , 'fonts' ) ) except OSError as e : if e . errno == 17 : print ( "WARNING : existing output directory for static files, will not replace them" ) else : raise try : shutil . copytree ( os . path . join ( self . templates_dir , 'img' ) , os . path . join ( self . results_dir , 'img' ) ) except OSError as e : pass
Create statics directory and copy files in it
13,426
def write_report ( self , template ) : with open ( self . fn , 'w' ) as f : f . write ( template )
Write the compiled jinja template to the results file
13,427
def set_raw_holding_register ( self , name , value ) : self . _conn . write_register ( unit = self . _slave , address = ( self . _holding_regs [ name ] [ 'addr' ] ) , value = value )
Write to register by name .
13,428
def unzip ( filepath , output_path ) : filename = os . path . split ( filepath ) [ 1 ] ( name , extension ) = os . path . splitext ( filename ) extension = extension [ 1 : ] . lower ( ) extension2 = os . path . splitext ( name ) [ 1 ] [ 1 : ] . lower ( ) if extension not in ZIP_EXTENSIONS : raise Exception ( "Impossible to extract archive file %s" % filepath ) extract_command = "unzip" output_args = "-d" if extension == 'bz2' and extension2 == 'tar' : extract_command = "tar -xjf" output_args = "-C" elif extension == 'gz' and extension2 == 'tar' : extract_command = "tar -xzf" output_args = "-C" elif extension == 'xz' and extension2 == 'tar' : extract_command = "tar -xJf" output_args = "-C" elif extension == 'bz2' : extract_command = "bunzip2 -dc " output_args = ">" output_path = os . path . join ( output_path , name ) elif extension == 'rar' : extract_command = "unrar x" output_args = "" elif extension == 'gz' : extract_command = "gunzip" output_args = "" elif extension == 'tar' : extract_command = "tar -xf" output_args = "-C" elif extension == 'tbz2' : extract_command = "tar -xjf" output_args = "-C" elif extension == 'tgz' : extract_command = "tar -xzf" output_args = "-C" elif extension == 'zip' : extract_command = "unzip" output_args = "-d" elif extension == 'Z' : extract_command = "uncompress" output_args = "" elif extension == '7z' : extract_command = "7z x" output_args = "" elif extension == 'xz' : extract_command = "unxz" output_args = "" elif extension == 'ace' : extract_command = "unace" output_args = "" elif extension == 'iso' : extract_command = "7z x" output_args = "" elif extension == 'arj' : extract_command = "7z x" output_args = "" command = params = { 'extract_command' : extract_command , 'filepath' : filepath , 'output_folder' : output_path , 'output_args' : output_args , } result = os . system ( command % params ) return result
Unzip an archive file
13,429
def _configure_sockets ( self , config , with_streamer = False , with_forwarder = False ) : rc_port = config . get ( 'rc_port' , 5001 ) self . result_collector . set_hwm ( 0 ) self . result_collector . bind ( "tcp://*:{}" . format ( rc_port ) ) self . poller . register ( self . result_collector , zmq . POLLIN )
Configure sockets for HQ
13,430
def wait_turrets ( self , wait_for ) : print ( "Waiting for %d turrets" % ( wait_for - len ( self . turrets_manager . turrets ) ) ) while len ( self . turrets_manager . turrets ) < wait_for : self . turrets_manager . status_request ( ) socks = dict ( self . poller . poll ( 2000 ) ) if self . result_collector in socks : data = self . result_collector . recv_json ( ) self . turrets_manager . process_message ( data ) print ( "Waiting for %d turrets" % ( wait_for - len ( self . turrets_manager . turrets ) ) )
Wait until wait_for turrets are connected and ready
13,431
def run ( self ) : elapsed = 0 run_time = self . config [ 'run_time' ] start_time = time . time ( ) t = time . time self . turrets_manager . start ( self . transaction_context ) self . started = True while elapsed <= run_time : try : self . _run_loop_action ( ) self . _print_status ( elapsed ) elapsed = t ( ) - start_time except ( Exception , KeyboardInterrupt ) : print ( "\nStopping test, sending stop command to turrets" ) self . turrets_manager . stop ( ) self . stats_handler . write_remaining ( ) traceback . print_exc ( ) break self . turrets_manager . stop ( ) print ( "\n\nProcessing all remaining messages... This could take time depending on message volume" ) t = time . time ( ) self . result_collector . unbind ( self . result_collector . LAST_ENDPOINT ) self . _clean_queue ( ) print ( "took %s" % ( time . time ( ) - t ) )
Run the hight quarter lunch the turrets and wait for results
13,432
def query ( logfile , jobID = None ) : joblist = logfile . readFromLogfile ( ) if jobID and type ( jobID ) == type ( 1 ) : command = [ 'qstat' , '-j' , str ( jobID ) ] else : command = [ 'qstat' ] processoutput = subprocess . Popen ( command , stdout = subprocess . PIPE , stderr = subprocess . PIPE ) . communicate ( ) output = processoutput [ 0 ] serror = processoutput [ 1 ] jobs = { } if type ( jobID ) == type ( 1 ) : if serror . find ( "Following jobs do not exist" ) != - 1 : return False else : return True if not output . strip ( ) : colorprinter . message ( "No jobs running at present." ) output = output . strip ( ) . split ( "\n" ) if len ( output ) > 2 : for line in output [ 2 : ] : tokens = line . split ( ) jid = int ( tokens [ 0 ] ) jobstate = tokens [ 4 ] details = { "jobid" : jid , "prior" : tokens [ 1 ] , "name" : tokens [ 2 ] , "user" : tokens [ 3 ] , "state" : jobstate , "submit/start at" : "%s %s" % ( tokens [ 5 ] , tokens [ 6 ] ) } jataskID = 0 if jobstate == "r" : details [ "queue" ] = tokens [ 7 ] details [ "slots" ] = tokens [ 8 ] elif jobstate == "qw" : details [ "slots" ] = tokens [ 7 ] if len ( tokens ) >= 9 : jataskID = tokens [ 8 ] details [ "ja-task-ID" ] = jataskID if len ( tokens ) > 9 : jataskID = tokens [ 9 ] details [ "ja-task-ID" ] = jataskID jobs [ jid ] = jobs . get ( jid ) or { } jobs [ jid ] [ jataskID ] = details if joblist . get ( jid ) : jobdir = joblist [ jid ] [ "Directory" ] jobtime = joblist [ jid ] [ "TimeInSeconds" ] colorprinter . message ( "Job %d submitted %d minutes ago. Status: '%s'. Destination directory: %s." % ( jid , jobtime / 60 , jobstate , jobdir ) ) else : colorprinter . message ( "Job %d submitted at %s %s. Status: '%s'. Destination directory unknown." % ( jid , tokens [ 5 ] , tokens [ 6 ] , jobstate ) ) return True
If jobID is an integer then return False if the job has finished and True if it is still running . Otherwise returns a table of jobs run by the user .
13,433
def set_tmp_folder ( ) : output = "%s" % datetime . datetime . now ( ) for char in [ ' ' , ':' , '.' , '-' ] : output = output . replace ( char , '' ) output . strip ( ) tmp_folder = os . path . join ( tempfile . gettempdir ( ) , output ) return tmp_folder
Create a temporary folder using the current time in which the zip can be extracted and which should be destroyed afterward .
13,434
def file_logger ( app , level = None ) : path = os . path . join ( os . getcwd ( ) , 'var' , 'logs' , 'app.log' ) max_bytes = 1024 * 1024 * 2 file_handler = RotatingFileHandler ( filename = path , mode = 'a' , maxBytes = max_bytes , backupCount = 10 ) if level is None : level = logging . INFO file_handler . setLevel ( level ) log_format = '%(asctime)s %(levelname)s: %(message)s' log_format += ' [in %(pathname)s:%(lineno)d]' file_handler . setFormatter ( logging . Formatter ( log_format ) ) return file_handler
Get file logger Returns configured fire logger ready to be attached to app
13,435
def tag ( self , repository_tag , tags = [ ] ) : if not isinstance ( repository_tag , six . string_types ) : raise TypeError ( 'repository_tag must be a string' ) if not isinstance ( tags , list ) : raise TypeError ( 'tags must be a list.' ) if ':' in repository_tag : repository , tag = repository_tag . split ( ':' ) tags . append ( tag ) else : repository = repository_tag if not tags : tags . append ( 'latest' ) for tag in tags : repo_tag = "{0}:{1}" . format ( repository , tag ) if repo_tag not in self . repo_tags : logger . info ( "Tagging Image: {0} Repo Tag: {1}" . format ( self . identifier , repo_tag ) ) self . repo_tags = self . repo_tags + ( repo_tag , ) try : self . client . tag ( self . id , repository , tag ) except : self . client . tag ( self . id , repository , tag , force = True )
Tags image with one or more tags .
13,436
def build ( client , repository_tag , docker_file , tag = None , use_cache = False ) : if not isinstance ( client , docker . Client ) : raise TypeError ( "client needs to be of type docker.Client." ) if not isinstance ( docker_file , six . string_types ) or not os . path . exists ( docker_file ) : raise Exception ( "docker file path doesn't exist: {0}" . format ( docker_file ) ) if not isinstance ( repository_tag , six . string_types ) : raise TypeError ( 'repository must be a string' ) if not tag : tag = 'latest' if not isinstance ( use_cache , bool ) : raise TypeError ( "use_cache must be a bool. {0} was passed." . format ( use_cache ) ) no_cache = not use_cache if ':' not in repository_tag : repository_tag = "{0}:{1}" . format ( repository_tag , tag ) file_obj = None try : if os . path . isfile ( docker_file ) : path = os . getcwd ( ) docker_file = "./{0}" . format ( os . path . relpath ( docker_file ) ) response = client . build ( path = path , nocache = no_cache , dockerfile = docker_file , tag = repository_tag , rm = True , stream = True ) else : response = client . build ( path = docker_file , tag = repository_tag , rm = True , nocache = no_cache , stream = True ) except Exception as e : raise e finally : if file_obj : file_obj . close ( ) parse_stream ( response ) client . close ( ) return Image ( client , repository_tag )
Build a docker image
13,437
def get_grades_by_regid_and_term ( regid , term ) : url = "{}/{},{},{}.json" . format ( enrollment_res_url_prefix , term . year , term . quarter , regid ) return _json_to_grades ( get_resource ( url ) , regid , term )
Returns a StudentGrades model for the regid and term .
13,438
def _requires_refresh_token ( self ) : expires_on = datetime . datetime . strptime ( self . login_data [ 'token' ] [ 'expiresOn' ] , '%Y-%m-%dT%H:%M:%SZ' ) refresh = datetime . datetime . utcnow ( ) + datetime . timedelta ( seconds = 30 ) return expires_on < refresh
Check if a refresh of the token is needed
13,439
def _request_token ( self , force = False ) : if self . login_data is None : raise RuntimeError ( "Don't have a token to refresh" ) if not force : if not self . _requires_refresh_token ( ) : return True headers = { "Accept" : "application/json" , 'Authorization' : 'Bearer ' + self . login_data [ 'token' ] [ 'accessToken' ] } url = self . api_base_url + "account/RefreshToken" response = requests . get ( url , headers = headers , timeout = 10 ) if response . status_code != 200 : return False refresh_data = response . json ( ) if 'token' not in refresh_data : return False self . login_data [ 'token' ] [ 'accessToken' ] = refresh_data [ 'accessToken' ] self . login_data [ 'token' ] [ 'issuedOn' ] = refresh_data [ 'issuedOn' ] self . login_data [ 'token' ] [ 'expiresOn' ] = refresh_data [ 'expiresOn' ] return True
Request a new auth token
13,440
def get_home ( self , home_id = None ) : now = datetime . datetime . utcnow ( ) if self . home and now < self . home_refresh_at : return self . home if not self . _do_auth ( ) : raise RuntimeError ( "Unable to login" ) if home_id is None : home_id = self . home_id url = self . api_base_url + "Home/GetHomeById" params = { "homeId" : home_id } headers = { "Accept" : "application/json" , 'Authorization' : 'bearer ' + self . login_data [ 'token' ] [ 'accessToken' ] } response = requests . get ( url , params = params , headers = headers , timeout = 10 ) if response . status_code != 200 : raise RuntimeError ( "{} response code when getting home" . format ( response . status_code ) ) home = response . json ( ) if self . cache_home : self . home = home self . home_refresh_at = ( datetime . datetime . utcnow ( ) + datetime . timedelta ( minutes = 5 ) ) return home
Get the data about a home
13,441
def get_zones ( self ) : home_data = self . get_home ( ) if not home_data [ 'isSuccess' ] : return [ ] zones = [ ] for receiver in home_data [ 'data' ] [ 'receivers' ] : for zone in receiver [ 'zones' ] : zones . append ( zone ) return zones
Get all zones
13,442
def get_zone_names ( self ) : zone_names = [ ] for zone in self . get_zones ( ) : zone_names . append ( zone [ 'name' ] ) return zone_names
Get the name of all zones
13,443
def get_zone ( self , zone_name ) : for zone in self . get_zones ( ) : if zone_name == zone [ 'name' ] : return zone raise RuntimeError ( "Unknown zone" )
Get the information about a particular zone
13,444
def get_zone_temperature ( self , zone_name ) : zone = self . get_zone ( zone_name ) if zone is None : raise RuntimeError ( "Unknown zone" ) return zone [ 'currentTemperature' ]
Get the temperature for a zone
13,445
def set_target_temperature_by_id ( self , zone_id , target_temperature ) : if not self . _do_auth ( ) : raise RuntimeError ( "Unable to login" ) data = { "ZoneId" : zone_id , "TargetTemperature" : target_temperature } headers = { "Accept" : "application/json" , "Content-Type" : "application/json" , 'Authorization' : 'Bearer ' + self . login_data [ 'token' ] [ 'accessToken' ] } url = self . api_base_url + "Home/ZoneTargetTemperature" response = requests . post ( url , data = json . dumps ( data ) , headers = headers , timeout = 10 ) if response . status_code != 200 : return False zone_change_data = response . json ( ) return zone_change_data . get ( "isSuccess" , False )
Set the target temperature for a zone by id
13,446
def set_target_temperture_by_name ( self , zone_name , target_temperature ) : zone = self . get_zone ( zone_name ) if zone is None : raise RuntimeError ( "Unknown zone" ) return self . set_target_temperature_by_id ( zone [ "zoneId" ] , target_temperature )
Set the target temperature for a zone by name
13,447
def activate_boost_by_id ( self , zone_id , target_temperature , num_hours = 1 ) : if not self . _do_auth ( ) : raise RuntimeError ( "Unable to login" ) zones = [ zone_id ] data = { "ZoneIds" : zones , "NumberOfHours" : num_hours , "TargetTemperature" : target_temperature } headers = { "Accept" : "application/json" , "Content-Type" : "application/json" , 'Authorization' : 'Bearer ' + self . login_data [ 'token' ] [ 'accessToken' ] } url = self . api_base_url + "Home/ActivateZoneBoost" response = requests . post ( url , data = json . dumps ( data ) , headers = headers , timeout = 10 ) if response . status_code != 200 : return False boost_data = response . json ( ) return boost_data . get ( "isSuccess" , False )
Activate boost for a zone based on the numeric id
13,448
def activate_boost_by_name ( self , zone_name , target_temperature , num_hours = 1 ) : zone = self . get_zone ( zone_name ) if zone is None : raise RuntimeError ( "Unknown zone" ) return self . activate_boost_by_id ( zone [ "zoneId" ] , target_temperature , num_hours )
Activate boost by the name of the zone
13,449
def deactivate_boost_by_name ( self , zone_name ) : zone = self . get_zone ( zone_name ) if zone is None : raise RuntimeError ( "Unknown zone" ) return self . deactivate_boost_by_id ( zone [ "zoneId" ] )
Deactivate boost by the name of the zone
13,450
def set_mode_by_id ( self , zone_id , mode ) : if not self . _do_auth ( ) : raise RuntimeError ( "Unable to login" ) data = { "ZoneId" : zone_id , "mode" : mode . value } headers = { "Accept" : "application/json" , "Content-Type" : "application/json" , 'Authorization' : 'Bearer ' + self . login_data [ 'token' ] [ 'accessToken' ] } url = self . api_base_url + "Home/SetZoneMode" response = requests . post ( url , data = json . dumps ( data ) , headers = headers , timeout = 10 ) if response . status_code != 200 : return False mode_data = response . json ( ) return mode_data . get ( "isSuccess" , False )
Set the mode by using the zone id Supported zones are available in the enum Mode
13,451
def set_mode_by_name ( self , zone_name , mode ) : zone = self . get_zone ( zone_name ) if zone is None : raise RuntimeError ( "Unknown zone" ) return self . set_mode_by_id ( zone [ "zoneId" ] , mode )
Set the mode by using the name of the zone
13,452
def get_zone_mode ( self , zone_name ) : zone = self . get_zone ( zone_name ) if zone is None : raise RuntimeError ( "Unknown zone" ) return ZoneMode ( zone [ 'mode' ] )
Get the mode for a zone
13,453
def _convertToElementList ( elements_list ) : elements = [ ] current_element = [ ] for node_index in elements_list : if node_index == - 1 : elements . append ( current_element ) current_element = [ ] else : current_element . append ( node_index ) return elements
Take a list of element node indexes deliminated by - 1 and convert it into a list element node indexes list .
13,454
def get_locale ( self ) : if not self . locale : try : import flask_babel as babel self . locale = str ( babel . get_locale ( ) ) . lower ( ) except ImportError : from flask import current_app self . locale = current_app . config [ 'DEFAULT_LOCALE' ] . lower return self . locale
Get locale Will extract locale from application trying to get one from babel first then if not available will get one from app config
13,455
def get_language ( self ) : locale = self . get_locale ( ) language = locale if '_' in locale : language = locale [ 0 : locale . index ( '_' ) ] return language
Get language If locale contains region will cut that off . Returns just the language code
13,456
def localize_humanize ( self ) : import humanize language = self . get_language ( ) if language != 'en' : humanize . i18n . activate ( language )
Setts current language to humanize
13,457
def get_filters ( self ) : filters = dict ( ) for filter in self . get_filter_names ( ) : filters [ filter ] = getattr ( self , filter ) return filters
Returns a dictionary of filters
13,458
def _render ( self , value , format ) : template = '<script>\ndocument.write(moment(\"{t}\").{f});\n</script>' return Markup ( template . format ( t = value , f = format ) )
Writes javascript to call momentjs function
13,459
def get_filters ( self ) : return dict ( moment_format = self . format , moment_calendar = self . calendar , moment_fromnow = self . from_now , )
Returns a collection of momentjs filters
13,460
def user_stats ( request ) : user = get_user_id ( request ) language = get_language ( request ) concepts = None if "concepts" in request . GET : concepts = Concept . objects . filter ( lang = language , active = True , identifier__in = load_query_json ( request . GET , "concepts" ) ) data = UserStat . objects . get_user_stats ( user , language , concepts ) return render_json ( request , data , template = 'concepts_json.html' , help_text = user_stats . __doc__ )
JSON of user stats of the user
13,461
def user_stats_bulk ( request ) : language = get_language ( request ) users = load_query_json ( request . GET , "users" ) if request . user . is_staff : if not hasattr ( request . user , 'userprofile' ) or User . objects . filter ( pk__in = users , userprofile__classes__owner = request . user . userprofile ) . count ( ) < len ( users ) : return render_json ( request , { 'error' : _ ( 'Some requested users are not in owned classes' ) , 'error_type' : 'permission_denied' } , template = 'concepts_json.html' , status = 401 ) since = None if 'since' in request . GET : since = datetime . datetime . fromtimestamp ( int ( request . GET [ 'since' ] ) ) concepts = None if "concepts" in request . GET : concepts = Concept . objects . filter ( lang = language , active = True , identifier__in = load_query_json ( request . GET , "concepts" ) ) stats = UserStat . objects . get_user_stats ( users , language , concepts = concepts , since = since ) data = { "users" : [ ] } for user , s in stats . items ( ) : data [ "users" ] . append ( { "user_id" : user , "concepts" : s , } ) return render_json ( request , data , template = 'concepts_json.html' , help_text = user_stats_bulk . __doc__ )
Get statistics for selected users and concepts
13,462
def user_stats_api ( request , provider ) : if 'key' not in request . GET or provider not in settings . USER_STATS_API_KEY or request . GET [ 'key' ] != settings . USER_STATS_API_KEY [ provider ] : return HttpResponse ( 'Unauthorized' , status = 401 ) since = None if 'since' in request . GET : since = datetime . datetime . fromtimestamp ( int ( request . GET [ 'since' ] ) ) social_users = list ( UserSocialAuth . objects . filter ( provider = provider ) . select_related ( 'user' ) ) user_map = { u . user . id : u for u in social_users } stats = UserStat . objects . get_user_stats ( [ u . user for u in social_users ] , lang = None , since = since , recalculate = False ) data = { "users" : [ ] } for user , s in stats . items ( ) : data [ "users" ] . append ( { "user_id" : user_map [ user ] . uid , "concepts" : s , } ) return render_json ( request , data , template = 'concepts_json.html' , help_text = user_stats_bulk . __doc__ )
Get statistics for selected Edookit users
13,463
def tag_values ( request ) : data = defaultdict ( lambda : { "values" : { } } ) for tag in Tag . objects . filter ( lang = get_language ( request ) ) : data [ tag . type ] [ "name" ] = tag . type_name data [ tag . type ] [ "values" ] [ tag . value ] = tag . value_name return render_json ( request , data , template = 'concepts_json.html' , help_text = tag_values . __doc__ )
Get tags types and values with localized names
13,464
def add_to_grid ( self , agent ) : for i in range ( len ( self . grid ) ) : for j in range ( len ( self . grid [ 0 ] ) ) : if self . grid [ i ] [ j ] is None : x = self . origin [ 0 ] + i y = self . origin [ 1 ] + j self . grid [ i ] [ j ] = agent return ( x , y ) raise ValueError ( "Trying to add an agent to a full grid." . format ( len ( self . _grid [ 0 ] ) , len ( self . _grid [ 1 ] ) ) )
Add agent to the next available spot in the grid .
13,465
async def set_agent_neighbors ( self ) : for i in range ( len ( self . grid ) ) : for j in range ( len ( self . grid [ 0 ] ) ) : agent = self . grid [ i ] [ j ] xy = ( self . origin [ 0 ] + i , self . origin [ 1 ] + j ) nxy = _get_neighbor_xy ( 'N' , xy ) exy = _get_neighbor_xy ( 'E' , xy ) sxy = _get_neighbor_xy ( 'S' , xy ) wxy = _get_neighbor_xy ( 'W' , xy ) if j == 0 : naddr = await self . _get_xy_address_from_neighbor ( 'N' , nxy ) else : naddr = self . get_xy ( nxy , addr = True ) if i == 0 : waddr = await self . _get_xy_address_from_neighbor ( 'W' , wxy ) else : waddr = self . get_xy ( wxy , addr = True ) if j == len ( self . grid [ 0 ] ) - 1 : saddr = await self . _get_xy_address_from_neighbor ( 'S' , sxy ) else : saddr = self . get_xy ( sxy , addr = True ) if i == len ( self . grid ) - 1 : eaddr = await self . _get_xy_address_from_neighbor ( 'E' , exy ) else : eaddr = self . get_xy ( exy , addr = True ) agent . neighbors [ 'N' ] = naddr agent . neighbors [ 'E' ] = eaddr agent . neighbors [ 'S' ] = saddr agent . neighbors [ 'W' ] = waddr
Set neighbors for each agent in each cardinal direction .
13,466
async def set_slave_params ( self ) : self . _slave_origins = [ ] cur_x = self . origin [ 0 ] for addr in self . addrs : new_origin = ( cur_x , self . origin [ 1 ] ) await self . set_origin ( addr , new_origin ) await self . set_gs ( addr , self . _gs ) self . _slave_origins . append ( ( new_origin , addr ) ) new_x = cur_x + self . gs [ 0 ] cur_x = new_x
Set origin and grid size for each slave environment .
13,467
async def set_agent_neighbors ( self ) : for addr in self . addrs : r_manager = await self . env . connect ( addr ) await r_manager . set_agent_neighbors ( )
Set neighbors for all the agents in all the slave environments . Assumes that all the slave environments have their neighbors set .
13,468
async def populate ( self , agent_cls , * args , ** kwargs ) : n = self . gs [ 0 ] * self . gs [ 1 ] tasks = [ ] for addr in self . addrs : task = asyncio . ensure_future ( self . _populate_slave ( addr , agent_cls , n , * args , ** kwargs ) ) tasks . append ( task ) rets = await asyncio . gather ( * tasks ) return rets
Populate all the slave grid environments with agents . Assumes that no agents have been spawned yet to the slave environment grids . This excludes the slave environment managers as they are not in the grids . )
13,469
def generate_docs ( app ) : config = app . config config_dir = app . env . srcdir javascript_root = os . path . join ( config_dir , config . jsdoc_source_root ) if javascript_root [ - 1 ] != os . path . sep : javascript_root += os . path . sep if not javascript_root : return output_root = os . path . join ( config_dir , config . jsdoc_output_root ) execution_dir = os . path . join ( config_dir , '..' ) exclude = config . jsdoc_exclude cleanup ( output_root ) jsdoc_toolkit_dir = os . path . join ( SOURCE_PATH , 'jsdoc-toolkit' ) jsdoc_rst_dir = os . path . join ( SOURCE_PATH , 'jsdoc-toolkit-rst-template' ) build_xml_path = os . path . join ( jsdoc_rst_dir , 'build.xml' ) command = [ 'ant' , '-f' , build_xml_path , '-Djsdoc-toolkit.dir=%s' % jsdoc_toolkit_dir , '-Djs.src.dir=%s' % javascript_root , '-Djs.rst.dir=%s' % output_root ] if exclude : exclude_args = [ '--exclude=\\"%s\\"' % path for path in exclude ] command . append ( '-Djs.exclude="%s"' % ' ' . join ( exclude_args ) ) try : process = Popen ( command , cwd = execution_dir ) process . wait ( ) except OSError : raise JSDocError ( 'Error running ant; is it installed?' ) path = os . path . join ( output_root , 'files.rst' ) with open ( path , 'r' ) as f : content = f . read ( ) content = content . replace ( javascript_root , '' ) with open ( path , 'w' ) as f : f . write ( content )
Generate the reST documentation files for the JavaScript code
13,470
def setup ( app ) : app . add_config_value ( 'jsdoc_source_root' , '..' , 'env' ) app . add_config_value ( 'jsdoc_output_root' , 'javascript' , 'env' ) app . add_config_value ( 'jsdoc_exclude' , [ ] , 'env' ) app . connect ( 'builder-inited' , generate_docs )
Sphinx extension entry point
13,471
def find_user ( search_params ) : user = None params = { prop : value for prop , value in search_params . items ( ) if value } if 'id' in params or 'email' in params : user = user_service . first ( ** params ) return user
Find user Attempts to find a user by a set of search params . You must be in application context .
13,472
def create ( email , password ) : with get_app ( ) . app_context ( ) : user = User ( email = email , password = password ) result = user_service . save ( user ) if not isinstance ( result , User ) : print_validation_errors ( result ) return click . echo ( green ( '\nUser created:' ) ) click . echo ( green ( '-' * 40 ) ) click . echo ( str ( user ) + '\n' )
Creates a new user record
13,473
def change_password ( * _ , user_id = None , password = None ) : click . echo ( green ( '\nChange password:' ) ) click . echo ( green ( '-' * 40 ) ) with get_app ( ) . app_context ( ) : user = find_user ( dict ( id = user_id ) ) if not user : click . echo ( red ( 'User not found\n' ) ) return result = user_service . change_password ( user , password ) if isinstance ( result , User ) : msg = 'Changed password for user {} \n' . format ( user . email ) click . echo ( green ( msg ) ) return print_validation_errors ( result ) return
Change user password
13,474
def change_email ( * _ , user_id = None , new_email = None ) : click . echo ( green ( '\nChange email:' ) ) click . echo ( green ( '-' * 40 ) ) with get_app ( ) . app_context ( ) : user = find_user ( dict ( id = user_id ) ) if not user : click . echo ( red ( 'User not found\n' ) ) return user . email = new_email result = user_service . save ( user ) if not isinstance ( result , User ) : print_validation_errors ( result ) return user . confirm_email ( ) user_service . save ( user ) msg = 'Change email for user {} to {} \n' click . echo ( green ( msg . format ( user . email , new_email ) ) )
Change email for a user
13,475
def create_role ( * _ , ** kwargs ) : click . echo ( green ( '\nCreating new role:' ) ) click . echo ( green ( '-' * 40 ) ) with get_app ( ) . app_context ( ) : role = Role ( ** kwargs ) result = role_service . save ( role ) if not isinstance ( result , Role ) : print_validation_errors ( result ) click . echo ( green ( 'Created: ' ) + str ( role ) + '\n' )
Create user role
13,476
def list_roles ( ) : click . echo ( green ( '\nListing roles:' ) ) click . echo ( green ( '-' * 40 ) ) with get_app ( ) . app_context ( ) : roles = Role . query . all ( ) if not roles : click . echo ( red ( 'No roles found' ) ) return for index , role in enumerate ( roles ) : click . echo ( '{}. {}: {}' . format ( index + 1 , yellow ( role . handle ) , role . title ) ) click . echo ( )
List existing roles
13,477
def list_user_roles ( * _ , user_id ) : click . echo ( green ( '\nListing user roles:' ) ) click . echo ( green ( '-' * 40 ) ) with get_app ( ) . app_context ( ) : user = find_user ( dict ( id = user_id ) ) if not user : click . echo ( red ( 'User not found\n' ) ) return for index , role in enumerate ( user . roles ) : click . echo ( '{}. {}: {}' . format ( index + 1 , yellow ( role . handle ) , role . title ) ) click . echo ( )
List user roles
13,478
async def update ( self ) : if self . client . session . closed : async with core . Client ( ) as client : data = await client . request ( self . url ) else : data = await self . client . request ( self . url ) self . raw_data = data self . from_data ( data ) return self
Update an object with current info .
13,479
def clan_badge_url ( self ) : if self . clan_tag is None : return None url = self . raw_data . get ( 'clan' ) . get ( 'badge' ) . get ( 'url' ) if not url : return None return "http://api.cr-api.com" + url
Returns clan badge url
13,480
def get_chest ( self , index = 0 ) : index += self . chest_cycle . position if index == self . chest_cycle . super_magical : return 'Super Magical' if index == self . chest_cycle . epic : return 'Epic' if index == self . chest_cycle . legendary : return 'Legendary' return CHESTS [ index % len ( CHESTS ) ]
Get your current chest + - the index
13,481
def update ( ) : with settings ( warn_only = True ) : print ( cyan ( '\nInstalling/Updating required packages...' ) ) pip = local ( 'venv/bin/pip install -U --allow-all-external --src libs -r requirements.txt' , capture = True ) if pip . failed : print ( red ( pip ) ) abort ( "pip exited with return code %i" % pip . return_code ) print ( green ( 'Packages requirements updated.' ) )
Update virtual env with requirements packages .
13,482
def _detect_devices ( self ) -> None : devices_num = len ( self . devices_list ) if devices_num == 0 : raise DeviceConnectionException ( 'No devices are connected. Please connect the device with USB or via WLAN and turn on the USB debugging option.' ) elif not self . device_sn and devices_num > 1 : raise DeviceConnectionException ( f"Multiple devices detected: {' | '.join(self.devices_list)}, please specify device serial number or host." ) else : self . device_sn = self . devices_list [ 0 ] if self . get_state ( ) == 'offline' : raise DeviceConnectionException ( 'The device is offline. Please reconnect.' )
Detect whether devices connected .
13,483
def get_device_model ( self ) -> str : output , _ = self . _execute ( '-s' , self . device_sn , 'shell' , 'getprop' , 'ro.product.model' ) return output . strip ( )
Show device model .
13,484
def get_battery_info ( self ) -> dict : output , _ = self . _execute ( '-s' , self . device_sn , 'shell' , 'dumpsys' , 'battery' ) battery_status = re . split ( '\n |: ' , output [ 33 : ] . strip ( ) ) return dict ( zip ( battery_status [ : : 2 ] , battery_status [ 1 : : 2 ] ) )
Show device battery information .
13,485
def get_resolution ( self ) -> list : output , _ = self . _execute ( '-s' , self . device_sn , 'shell' , 'wm' , 'size' ) return output . split ( ) [ 2 ] . split ( 'x' )
Show device resolution .
13,486
def get_displays_params ( self ) -> str : output , error = self . _execute ( '-s' , self . device_sn , 'shell' , 'dumpsys' , 'window' , 'displays' ) return output
Show displays parameters .
13,487
def get_android_id ( self ) -> str : output , _ = self . _execute ( '-s' , self . device_sn , 'shell' , 'settings' , 'get' , 'secure' , 'android_id' ) return output . strip ( )
Show Android ID .
13,488
def get_android_version ( self ) -> str : output , _ = self . _execute ( '-s' , self . device_sn , 'shell' , 'getprop' , 'ro.build.version.release' ) return output . strip ( )
Show Android version .
13,489
def get_device_mac ( self ) -> str : output , _ = self . _execute ( '-s' , self . device_sn , 'shell' , 'cat' , '/sys/class/net/wlan0/address' ) return output . strip ( )
Show device MAC .
13,490
def get_cpu_info ( self ) -> str : output , _ = self . _execute ( '-s' , self . device_sn , 'shell' , 'cat' , '/proc/cpuinfo' ) return output
Show device CPU information .
13,491
def get_memory_info ( self ) -> str : output , _ = self . _execute ( '-s' , self . device_sn , 'shell' , 'cat' , '/proc/meminfo' ) return output
Show device memory information .
13,492
def get_sdk_version ( self ) -> str : output , _ = self . _execute ( '-s' , self . device_sn , 'shell' , 'getprop' , 'ro.build.version.sdk' ) return output . strip ( )
Show Android SDK version .
13,493
def root ( self ) -> None : output , _ = self . _execute ( '-s' , self . device_sn , 'root' ) if not output : raise PermissionError ( f'{self.device_sn!r} does not have root permission.' )
Restart adbd with root permissions .
13,494
def tcpip ( self , port : int or str = 5555 ) -> None : self . _execute ( '-s' , self . device_sn , 'tcpip' , str ( port ) )
Restart adb server listening on TCP on PORT .
13,495
def get_ip_addr ( self ) -> str : output , _ = self . _execute ( '-s' , self . device_sn , 'shell' , 'ip' , '-f' , 'inet' , 'addr' , 'show' , 'wlan0' ) ip_addr = re . findall ( r"\b(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\b" , output ) if not ip_addr : raise ConnectionError ( 'The device is not connected to WLAN or not connected via USB.' ) return ip_addr [ 0 ]
Show IP Address .
13,496
def sync_l ( self , option : str = 'all' ) -> None : if option in [ 'system' , 'vendor' , 'oem' , 'data' , 'all' ] : self . _execute ( '-s' , self . device_sn , 'sync' , '-l' , option ) else : raise ValueError ( 'There is no option named: {!r}.' . format ( option ) )
List but don t copy .
13,497
def install ( self , package : str , option : str = '-r' ) -> None : if not os . path . isfile ( package ) : raise FileNotFoundError ( f'{package!r} does not exist.' ) for i in option : if i not in '-lrtsdg' : raise ValueError ( f'There is no option named: {option!r}.' ) self . _execute ( '-s' , self . device_sn , 'install' , option , package )
Push package to the device and install it .
13,498
def uninstall ( self , package : str ) -> None : if package not in self . view_packgets_list ( ) : raise NoSuchPackageException ( f'There is no such package {package!r}.' ) self . _execute ( '-s' , self . device_sn , 'uninstall' , package )
Remove this app package from the device .
13,499
def view_packgets_list ( self , option : str = '-e' , keyword : str = '' ) -> list : if option not in [ '-f' , '-d' , '-e' , '-s' , '-3' , '-i' , '-u' ] : raise ValueError ( f'There is no option called {option!r}.' ) output , _ = self . _execute ( '-s' , self . device_sn , 'shell' , 'pm' , 'list' , 'packages' , option , keyword ) return list ( map ( lambda x : x [ 8 : ] , output . splitlines ( ) ) )
Show all packages .