idx int64 0 251k | question stringlengths 53 3.53k | target stringlengths 5 1.23k | len_question int64 20 893 | len_target int64 3 238 |
|---|---|---|---|---|
13,400 | 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 | 58 | 8 |
13,401 | 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 | 41 | 7 |
13,402 | def user_stats ( request ) : user = get_user_id ( request ) language = get_language ( request ) concepts = None # meaning all concept 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 | 130 | 7 |
13,403 | 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 | 345 | 7 |
13,404 | 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 | 290 | 8 |
13,405 | 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 | 114 | 8 |
13,406 | 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 . | 133 | 11 |
13,407 | 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 . | 409 | 10 |
13,408 | 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 . | 123 | 10 |
13,409 | 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 . | 49 | 24 |
13,410 | 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 . ) | 108 | 40 |
13,411 | def generate_docs ( app ) : # Figure out the correct directories to use 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 # Remove any files generated by earlier builds cleanup ( output_root ) # Generate the actual reST files 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?' ) # Convert the absolute paths in the file listing to relative ones 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 | 493 | 11 |
13,412 | 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 | 94 | 6 |
13,413 | 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 . | 61 | 22 |
13,414 | 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 | 103 | 6 |
13,415 | 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 | 154 | 3 |
13,416 | 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 | 180 | 5 |
13,417 | 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 | 116 | 3 |
13,418 | 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 | 121 | 3 |
13,419 | 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 | 140 | 3 |
13,420 | 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 . | 70 | 7 |
13,421 | 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 | 72 | 4 |
13,422 | 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 | 85 | 8 |
13,423 | 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 . | 112 | 7 |
13,424 | 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 . | 154 | 5 |
13,425 | def get_device_model ( self ) -> str : output , _ = self . _execute ( '-s' , self . device_sn , 'shell' , 'getprop' , 'ro.product.model' ) return output . strip ( ) | Show device model . | 55 | 4 |
13,426 | 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 . | 98 | 5 |
13,427 | def get_resolution ( self ) -> list : output , _ = self . _execute ( '-s' , self . device_sn , 'shell' , 'wm' , 'size' ) return output . split ( ) [ 2 ] . split ( 'x' ) | Show device resolution . | 58 | 4 |
13,428 | def get_displays_params ( self ) -> str : output , error = self . _execute ( '-s' , self . device_sn , 'shell' , 'dumpsys' , 'window' , 'displays' ) return output | Show displays parameters . | 54 | 4 |
13,429 | 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 . | 60 | 4 |
13,430 | 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 . | 57 | 4 |
13,431 | 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 . | 60 | 4 |
13,432 | def get_cpu_info ( self ) -> str : output , _ = self . _execute ( '-s' , self . device_sn , 'shell' , 'cat' , '/proc/cpuinfo' ) return output | Show device CPU information . | 49 | 5 |
13,433 | def get_memory_info ( self ) -> str : output , _ = self . _execute ( '-s' , self . device_sn , 'shell' , 'cat' , '/proc/meminfo' ) return output | Show device memory information . | 49 | 5 |
13,434 | 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 . | 59 | 5 |
13,435 | 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 . | 59 | 8 |
13,436 | 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 . | 45 | 12 |
13,437 | 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 . | 190 | 4 |
13,438 | 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 . | 96 | 6 |
13,439 | 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 . | 111 | 9 |
13,440 | 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 . | 70 | 8 |
13,441 | 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 . | 149 | 4 |
13,442 | def view_package_path ( self , package : str ) -> _PATH : if package not in self . view_packgets_list ( ) : raise NoSuchPackageException ( f'There is no such package {package!r}.' ) output , _ = self . _execute ( '-s' , self . device_sn , 'shell' , 'pm' , 'path' , package ) return output [ 8 : - 1 ] | Print the path to the APK of the given . | 94 | 11 |
13,443 | def view_focused_activity ( self ) -> str : output , _ = self . _execute ( '-s' , self . device_sn , 'shell' , 'dumpsys' , 'activity' , 'activities' ) return re . findall ( r'mFocusedActivity: .+(com[a-zA-Z0-9\.]+/.[a-zA-Z0-9\.]+)' , output ) [ 0 ] | View focused activity . | 100 | 4 |
13,444 | def view_running_services ( self , package : str = '' ) -> str : output , _ = self . _execute ( '-s' , self . device_sn , 'shell' , 'dumpsys' , 'activity' , 'services' , package ) return output | View running services . | 60 | 4 |
13,445 | def view_package_info ( self , package : str = '' ) -> str : output , _ = self . _execute ( '-s' , self . device_sn , 'shell' , 'dumpsys' , 'package' , package ) return output | View package detail information . | 56 | 5 |
13,446 | def view_current_app_behavior ( self ) -> str : output , _ = self . _execute ( '-s' , self . device_sn , 'shell' , 'dumpsys' , 'window' , 'windows' ) return re . findall ( r'mCurrentFocus=.+(com[a-zA-Z0-9\.]+/.[a-zA-Z0-9\.]+)' , output ) [ 0 ] | View application behavior in the current window . | 100 | 8 |
13,447 | def view_surface_app_activity ( self ) -> str : output , error = self . _execute ( '-s' , self . device_sn , 'shell' , 'dumpsys' , 'window' , 'w' ) return re . findall ( r"name=([a-zA-Z0-9\.]+/.[a-zA-Z0-9\.]+)" , output ) | Get package with activity of applications that are running in the foreground . | 93 | 13 |
13,448 | def app_start_service ( self , * args ) -> None : _ , error = self . _execute ( '-s' , self . device_sn , 'shell' , 'am' , 'startservice' , * args ) if error and error . startswith ( 'Error' ) : raise ApplicationsException ( error . split ( ':' , 1 ) [ - 1 ] . strip ( ) ) | Start a service . | 87 | 4 |
13,449 | def app_broadcast ( self , * args ) -> None : _ , error = self . _execute ( '-s' , self . device_sn , 'shell' , 'am' , 'broadcast' , * args ) if error : raise ApplicationsException ( error . split ( ':' , 1 ) [ - 1 ] . strip ( ) ) | Send a broadcast . | 75 | 4 |
13,450 | def app_trim_memory ( self , pid : int or str , level : str = 'RUNNING_LOW' ) -> None : _ , error = self . _execute ( '-s' , self . device_sn , 'shell' , 'am' , 'send-trim-memory' , str ( pid ) , level ) if error and error . startswith ( 'Error' ) : raise ApplicationsException ( error . split ( ':' , 1 ) [ - 1 ] . strip ( ) ) | Trim memory . | 112 | 4 |
13,451 | def app_start_up_time ( self , package : str ) -> str : output , _ = self . _execute ( '-s' , self . device_sn , 'shell' , 'am' , 'start' , '-W' , package ) return re . findall ( 'TotalTime: \d+' , output ) [ 0 ] | Get the time it took to launch your application . | 77 | 10 |
13,452 | def click ( self , x : int , y : int ) -> None : self . _execute ( '-s' , self . device_sn , 'shell' , 'input' , 'tap' , str ( x ) , str ( y ) ) | Simulate finger click . | 54 | 5 |
13,453 | def send_keyevents ( self , keyevent : int ) -> None : self . _execute ( '-s' , self . device_sn , 'shell' , 'input' , 'keyevent' , str ( keyevent ) ) | Simulates typing keyevents . | 51 | 6 |
13,454 | def send_keyevents_long_press ( self , keyevent : int ) -> None : self . _execute ( '-s' , self . device_sn , 'shell' , 'input' , 'keyevent' , '--longpress' , str ( keyevent ) ) | Simulates typing keyevents long press . | 61 | 8 |
13,455 | def uidump ( self , local : _PATH = None ) -> None : local = local if local else self . _temp self . _execute ( '-s' , self . device_sn , 'shell' , 'uiautomator' , 'dump' , '--compressed' , '/data/local/tmp/uidump.xml' ) self . pull ( '/data/local/tmp/uidump.xml' , local ) ui = html . fromstring ( open ( local , 'rb' ) . read ( ) ) self . _nodes = ui . iter ( tag = "node" ) | Get the current interface layout file . | 135 | 7 |
13,456 | def find_element ( self , value , by = By . ID , update = False ) -> Elements : if update or not self . _nodes : self . uidump ( ) for node in self . _nodes : if node . attrib [ by ] == value : bounds = node . attrib [ 'bounds' ] coord = list ( map ( int , re . findall ( r'\d+' , bounds ) ) ) click_point = ( coord [ 0 ] + coord [ 2 ] ) / 2 , ( coord [ 1 ] + coord [ 3 ] ) / 2 return self . _element_cls ( self , node . attrib , by , value , coord , click_point ) raise NoSuchElementException ( f'No such element: {by}={value!r}.' ) | Find a element or the first element . | 174 | 8 |
13,457 | def find_elements_by_name ( self , name , update = False ) -> Elements : return self . find_elements ( by = By . NAME , value = name , update = update ) | Finds multiple elements by name . | 43 | 7 |
13,458 | def find_element_by_class ( self , class_ , update = False ) -> Elements : return self . find_element ( by = By . CLASS , value = class_ , update = update ) | Finds an element by class . | 43 | 7 |
13,459 | def find_elements_by_class ( self , class_ , update = False ) -> Elements : return self . find_elements ( by = By . CLASS , value = class_ , update = update ) | Finds multiple elements by class . | 45 | 7 |
13,460 | def unlock ( self , password , width = 1080 , length = 1920 ) -> None : self . wake ( ) self . swipe_up ( width , length ) self . send_keys ( str ( password ) ) | Unlock screen . | 44 | 4 |
13,461 | def make_a_call ( self , number : int or str = 18268237856 ) -> None : self . app_start_action ( Actions . CALL , '-d' , 'tel:{}' . format ( str ( number ) ) ) | Make a call . | 55 | 4 |
13,462 | def swipe_left ( self , width : int = 1080 , length : int = 1920 ) -> None : self . swipe ( 0.8 * width , 0.5 * length , 0.2 * width , 0.5 * length ) | Swipe left . | 50 | 4 |
13,463 | def swipe_right ( self , width : int = 1080 , length : int = 1920 ) -> None : self . swipe ( 0.2 * width , 0.5 * length , 0.8 * width , 0.5 * length ) | Swipe right . | 50 | 4 |
13,464 | def swipe_up ( self , width : int = 1080 , length : int = 1920 ) -> None : self . swipe ( 0.5 * width , 0.8 * length , 0.5 * width , 0.2 * length ) | Swipe up . | 50 | 4 |
13,465 | def swipe_down ( self , width : int = 1080 , length : int = 1920 ) -> None : self . swipe ( 0.5 * width , 0.2 * length , 0.5 * width , 0.8 * length ) | Swipe down . | 50 | 4 |
13,466 | def _register ( cls , app , * * kwargs ) : # nav nav = __options__ . get ( "nav" , { } ) nav . setdefault ( "title" , "Contact" ) nav . setdefault ( "visible" , True ) nav . setdefault ( "order" , 100 ) title = nav . pop ( "title" ) render . nav . add ( title , cls . page , * * nav ) # route kwargs [ "base_route" ] = __options__ . get ( "route" , "/contact/" ) # App Option data = { "recipients" : __options__ . get ( "recipients" ) , "success_message" : __options__ . get ( "success_message" , "Message sent. Thanks!" ) } @ app . before_first_request def setup ( ) : if db . _IS_OK_ : try : app_data . set ( APP_DATA_KEY , data , init = True ) except Exception as ex : logging . fatal ( "mocha.contrib.app_data has not been setup. Need to run `mocha :dbsync`" ) abort ( 500 ) # Call the register super ( cls , cls ) . _register ( app , * * kwargs ) | Reset some params | 282 | 4 |
13,467 | def saturateHexColor ( hexcolor , adjustment = 1.0 ) : assert ( adjustment >= 0 and len ( hexcolor ) >= 1 ) prefix = "" if hexcolor [ 0 ] == '#' : hexcolor = hexcolor [ 1 : ] prefix = "#" assert ( len ( hexcolor ) == 6 ) if adjustment == 1.0 : return "%s%s" % ( prefix , hexcolor ) else : hsvColor = list ( colorsys . rgb_to_hsv ( int ( hexcolor [ 0 : 2 ] , 16 ) / 255.0 , int ( hexcolor [ 2 : 4 ] , 16 ) / 255.0 , int ( hexcolor [ 4 : 6 ] , 16 ) / 255.0 ) ) hsvColor [ 1 ] = min ( 1.0 , hsvColor [ 1 ] * adjustment ) rgbColor = [ min ( 255 , 255 * v ) for v in colorsys . hsv_to_rgb ( hsvColor [ 0 ] , hsvColor [ 1 ] , hsvColor [ 2 ] ) ] return "%s%.2x%.2x%.2x" % ( prefix , rgbColor [ 0 ] , rgbColor [ 1 ] , rgbColor [ 2 ] ) | Takes in an RGB color in 6 - character hexadecimal with an optional preceding hash character . Returns the RGB color in the same format adjusted by saturation by the second parameter . | 263 | 37 |
13,468 | async def get_constants ( self ) : url = self . BASE + '/constants' data = await self . request ( url ) return Constants ( self , data ) | Get clash royale constants . | 38 | 6 |
13,469 | def pack_turret ( turret , temp_files , base_config_path , path = None ) : file_name = turret [ 'name' ] files = temp_files [ : ] for fname in turret . get ( 'extra_files' , [ ] ) : if os . path . isabs ( fname ) or path is None : files . append ( fname ) else : files . append ( os . path . join ( path , fname ) ) if path is not None : file_name = os . path . join ( path , file_name ) tar_file = tarfile . open ( file_name + ".tar.gz" , 'w:gz' ) for f in files : tar_file . add ( os . path . abspath ( f ) , arcname = os . path . basename ( f ) ) script_path = os . path . join ( os . path . abspath ( base_config_path ) , turret [ 'script' ] ) tar_file . add ( script_path , arcname = turret [ 'script' ] ) for f in tar_file . getnames ( ) : print ( "Added %s" % f ) tar_file . close ( ) print ( "Archive %s created" % ( tar_file . name ) ) print ( "=========================================" ) | pack a turret into a tar file based on the turret configuration | 286 | 12 |
13,470 | def clear ( self ) -> None : self . click ( ) for i in self . text : self . _parent . send_keyevents ( Keys . DEL ) | Clears the text if it s a text entry element . | 34 | 12 |
13,471 | def add ( self , domain_accession , domain_type , match_quality ) : self . matches [ domain_type ] = self . matches . get ( domain_type , { } ) self . matches [ domain_type ] [ domain_accession ] = match_quality | match_quality should be a value between 0 and 1 . | 59 | 12 |
13,472 | def _validate ( self ) : # I used to use the assertion "self.atom_to_uniparc_sequence_maps.keys() == self.atom_to_seqres_sequence_maps.keys() == self.seqres_to_uniparc_sequence_maps.keys()" # but that failed for 2IMM where "self.atom_to_uniparc_sequence_maps.keys() == self.seqres_to_uniparc_sequence_maps.keys() == []" but THAT fails for 1IR3 so I removed # the assertions entirely. for c , m in self . atom_to_seqres_sequence_maps . iteritems ( ) : if self . seqres_to_uniparc_sequence_maps . keys ( ) : atom_uniparc_keys = set ( self . atom_to_uniparc_sequence_maps . get ( c , { } ) . keys ( ) ) atom_seqres_keys = set ( self . atom_to_seqres_sequence_maps . get ( c , { } ) . keys ( ) ) assert ( atom_uniparc_keys . intersection ( atom_seqres_keys ) == atom_uniparc_keys ) for k , v in m . map . iteritems ( ) : uparc_id_1 , uparc_id_2 = None , None try : uparc_id_1 = self . seqres_to_uniparc_sequence_maps [ c ] . map [ v ] uparc_id_2 = self . atom_to_uniparc_sequence_maps [ c ] . map [ k ] except : continue assert ( uparc_id_1 == uparc_id_2 ) | Tests that the maps agree through composition . | 379 | 9 |
13,473 | def classes ( request ) : if not request . user . is_authenticated ( ) or not hasattr ( request . user , "userprofile" ) : return render_json ( request , { 'error' : _ ( 'User is not logged in' ) , 'error_type' : 'user_unauthorized' } , template = 'user_json.html' , status = 401 ) clss = [ c . to_json ( ) for c in Class . objects . filter ( owner = request . user . userprofile ) ] return render_json ( request , clss , status = 200 , template = 'user_json.html' , help_text = classes . __doc__ ) | Get all classes of current user | 149 | 6 |
13,474 | def create_class ( request ) : if request . method == 'GET' : return render ( request , 'classes_create.html' , { } , help_text = create_class . __doc__ ) if request . method == 'POST' : if not request . user . is_authenticated ( ) or not hasattr ( request . user , "userprofile" ) : return render_json ( request , { 'error' : _ ( 'User is not logged in.' ) , 'error_type' : 'user_unauthorized' } , template = 'classes_create.html' , status = 401 ) data = json_body ( request . body . decode ( "utf-8" ) ) if 'code' in data and Class . objects . filter ( code = data [ 'code' ] ) . exists ( ) : return render_json ( request , { 'error' : _ ( 'A class with this code already exists.' ) , 'error_type' : 'class_with_code_exists' } , template = 'classes_create.html' , status = 400 ) if 'name' not in data or not data [ 'name' ] : return render_json ( request , { 'error' : _ ( 'Class name is missing.' ) , 'error_type' : 'missing_class_name' } , template = 'classes_create.html' , status = 400 ) cls = Class ( name = data [ 'name' ] , owner = request . user . userprofile ) if 'code' in data : cls . code = data [ 'code' ] cls . save ( ) return render_json ( request , cls . to_json ( ) , template = 'classes_create.html' , status = 201 ) else : return HttpResponseBadRequest ( "method %s is not allowed" . format ( request . method ) ) | Create new class | 405 | 3 |
13,475 | def join_class ( request ) : if request . method == 'GET' : return render ( request , 'classes_join.html' , { } , help_text = join_class . __doc__ ) if request . method == 'POST' : if not request . user . is_authenticated ( ) or not hasattr ( request . user , "userprofile" ) : return render_json ( request , { 'error' : _ ( 'User is not logged in.' ) , 'error_type' : 'user_unauthorized' } , template = 'classes_join.html' , status = 401 ) data = json_body ( request . body . decode ( "utf-8" ) ) if 'code' not in data or not data [ 'code' ] : return render_json ( request , { 'error' : _ ( 'Class code is missing.' ) , 'error_type' : 'missing_class_code' } , template = 'classes_join.html' , status = 400 ) try : cls = Class . objects . get ( code = data [ 'code' ] ) except Class . DoesNotExist : return render_json ( request , { 'error' : _ ( 'Class with given code not found.' ) , 'error_type' : 'class_not_found' , } , template = 'classes_join.html' , status = 404 ) cls . members . add ( request . user . userprofile ) return render_json ( request , cls . to_json ( ) , template = 'classes_join.html' , status = 200 ) else : return HttpResponseBadRequest ( "method %s is not allowed" . format ( request . method ) ) | Join a class | 370 | 3 |
13,476 | def create_student ( request ) : if not get_config ( 'proso_user' , 'allow_create_students' , default = False ) : return render_json ( request , { 'error' : _ ( 'Creation of new users is not allowed.' ) , 'error_type' : 'student_creation_not_allowed' } , template = 'class_create_student.html' , help_text = create_student . __doc__ , status = 403 ) if request . method == 'GET' : return render ( request , 'class_create_student.html' , { } , help_text = create_student . __doc__ ) if request . method == 'POST' : if not request . user . is_authenticated ( ) or not hasattr ( request . user , "userprofile" ) : return render_json ( request , { 'error' : _ ( 'User is not logged in.' ) , 'error_type' : 'user_unauthorized' } , template = 'class_create_student.html' , status = 401 ) data = json_body ( request . body . decode ( "utf-8" ) ) try : cls = Class . objects . get ( pk = data [ 'class' ] , owner = request . user . userprofile ) except ( Class . DoesNotExist , KeyError ) : return render_json ( request , { 'error' : _ ( 'Class with given id not found.' ) , 'error_type' : 'class_not_found' , } , template = 'class_create_student.html' , status = 404 ) if 'first_name' not in data or not data [ 'first_name' ] : return render_json ( request , { 'error' : _ ( 'First name code is missing.' ) , 'error_type' : 'missing_first_name' } , template = 'class_create_student.html' , status = 400 ) user = User ( first_name = data [ 'first_name' ] ) if data . get ( 'last_name' ) : user . last_name = data [ 'last_name' ] if data . get ( 'email' ) : if User . objects . filter ( email = data [ 'email' ] ) . exists ( ) : return render_json ( request , { 'error' : _ ( 'There is already a user with the given e-mail.' ) , 'error_type' : 'email_exists' } , template = 'class_create_student.html' , status = 400 ) user . email = data [ 'email' ] if data . get ( 'username' ) : if User . objects . filter ( username = data [ 'username' ] ) . exists ( ) : return render_json ( request , { 'error' : _ ( 'There is already a user with the given username.' ) , 'error_type' : 'username_exists' } , template = 'class_create_student.html' , status = 400 ) user . username = data [ 'username' ] else : user . username = get_unused_username ( user ) if data . get ( 'password' ) : user . set_password ( data [ 'password' ] ) user . save ( ) cls . members . add ( user . userprofile ) return render_json ( request , user . userprofile . to_json ( nested = True ) , template = 'class_create_student.html' , status = 201 ) else : return HttpResponseBadRequest ( "method %s is not allowed" . format ( request . method ) ) | Create new user in class | 785 | 5 |
13,477 | def login_student ( request ) : if not get_config ( 'proso_user' , 'allow_login_students' , default = False ) : return render_json ( request , { 'error' : _ ( 'Log in as student is not allowed.' ) , 'error_type' : 'login_student_not_allowed' } , template = 'class_create_student.html' , help_text = login_student . __doc__ , status = 403 ) if request . method == 'GET' : return render ( request , 'class_login_student.html' , { } , help_text = login_student . __doc__ ) elif request . method == 'POST' : if not request . user . is_authenticated ( ) or not hasattr ( request . user , "userprofile" ) : return render_json ( request , { 'error' : _ ( 'User is not logged in.' ) , 'error_type' : 'user_unauthorized' } , template = 'class_create_student.html' , status = 401 ) data = json_body ( request . body . decode ( "utf-8" ) ) try : student = User . objects . get ( userprofile = data . get ( 'student' ) , userprofile__classes__owner = request . user . userprofile ) except User . DoesNotExist : return render_json ( request , { 'error' : _ ( 'Student not found' ) , 'error_type' : 'student_not_found' } , template = 'class_login_student.html' , status = 401 ) if not student . is_active : return render_json ( request , { 'error' : _ ( 'The account has not been activated.' ) , 'error_type' : 'account_not_activated' } , template = 'class_login_student.html' , status = 401 ) student . backend = 'django.contrib.auth.backends.ModelBackend' login ( request , student ) request . method = "GET" return profile ( request ) else : return HttpResponseBadRequest ( "method %s is not allowed" . format ( request . method ) ) | Log in student | 476 | 3 |
13,478 | def create ( tournament , name , * * params ) : params . update ( { "name" : name } ) return api . fetch_and_parse ( "POST" , "tournaments/%s/participants" % tournament , "participant" , * * params ) | Add a participant to a tournament . | 59 | 7 |
13,479 | def _build_cmd ( self , args : Union [ list , tuple ] ) -> str : cmd = [ self . path ] cmd . extend ( args ) return cmd | Build command . | 35 | 3 |
13,480 | def get_local_time ( index ) : dt = index . to_pydatetime ( ) dt = dt . replace ( tzinfo = pytz . utc ) return dt . astimezone ( tzlocal ( ) ) . time ( ) | Localize datetime for better output in graphs | 59 | 9 |
13,481 | def resp_graph_raw ( dataframe , image_name , dir = './' ) : factor = int ( len ( dataframe ) / 10 ) df = dataframe . reset_index ( ) fig = pygal . Dot ( stroke = False , x_label_rotation = 25 , x_title = 'Elapsed Time In Test (secs)' , y_title = 'Average Response Time (secs)' , js = ( 'scripts/pygal-tooltip.min.js' , ) ) try : grp = df . groupby ( pd . cut ( df . index , np . arange ( 0 , len ( df ) , factor ) ) ) fig . x_labels = [ x for x in grp . first ( ) [ 'epoch' ] ] fig . title = image_name . split ( '.' ) [ 0 ] fig . add ( 'Time' , [ x for x in grp . describe ( ) [ 'scriptrun_time' ] . unstack ( ) [ 'mean' ] . round ( 2 ) ] ) except ZeroDivisionError : print ( "Not enough data for raw graph" ) fig . render_to_file ( filename = os . path . join ( dir , image_name ) ) | Response time graph for raw data | 270 | 6 |
13,482 | def resp_graph ( dataframe , image_name , dir = './' ) : fig = pygal . TimeLine ( x_title = 'Elapsed Time In Test (secs)' , y_title = 'Response Time (secs)' , x_label_rotation = 25 , js = ( 'scripts/pygal-tooltip.min.js' , ) ) fig . add ( 'AVG' , [ ( get_local_time ( index ) , row [ 'mean' ] if pd . notnull ( row [ 'mean' ] ) else None ) for index , row in dataframe . iterrows ( ) ] ) fig . add ( '90%' , [ ( get_local_time ( index ) , row [ '90%' ] if pd . notnull ( row [ '90%' ] ) else None ) for index , row in dataframe . iterrows ( ) ] ) fig . add ( '80%' , [ ( get_local_time ( index ) , row [ '80%' ] if pd . notnull ( row [ '80%' ] ) else None ) for index , row in dataframe . iterrows ( ) ] ) fig . render_to_file ( filename = os . path . join ( dir , image_name ) ) | Response time graph for bucketed data | 280 | 7 |
13,483 | def add_eval ( self , agent , e , fr = None ) : self . _evals [ agent . name ] = e self . _framings [ agent . name ] = fr | Add or change agent s evaluation of the artifact with given framing information . | 40 | 14 |
13,484 | def attach ( self , stdout = True , stderr = True , stream = True , logs = False ) : try : data = parse_stream ( self . client . attach ( self . id , stdout , stderr , stream , logs ) ) except KeyboardInterrupt : logger . warning ( "service container: {0} has been interrupted. " "The container will be stopped but will not be deleted." . format ( self . name ) ) data = None self . stop ( ) return data | Keeping this simple until we need to extend later . | 106 | 10 |
13,485 | def start ( self , attach = False ) : if self . state ( ) [ 'running' ] : logger . info ( 'is already running.' , extra = { 'formatter' : 'container' , 'container' : self . name } ) return True else : try : logger . info ( 'is being started.' , extra = { 'formatter' : 'container' , 'container' : self . name } ) # returns None on success self . client . start ( self . id ) if self . _transcribe : self . start_transcribing ( ) except APIError as e : # # This is some bs... I assume that its needed because of dockers changes in 1.18 api. # I will resolve this next week when we stop passing properties to start. if e . response . status_code == 500 : self . client . start ( self . id ) else : raise RuntimeError ( "Docker Error: {0}" . format ( e . explanation ) ) if attach : self . attach ( ) exit_code = self . wait ( ) else : exit_code = self . _wait_for_exit_code ( ) return True if exit_code == 0 else False | Start a container . If the container is running it will return itself . | 255 | 14 |
13,486 | def stop ( self ) : logger . info ( 'is being stopped' , extra = { 'formatter' : 'container' , 'container' : self . name } ) response = self . client . stop ( self . id ) while self . state ( ) [ 'running' ] : time . sleep ( 1 ) return response | stop the container | 69 | 3 |
13,487 | def dump_logs ( self ) : msg = "log dump: \n" if self . _transcribe : if self . _transcribe_queue : while not self . _transcribe_queue . empty ( ) : logs = self . _transcribe_queue . get ( ) if isinstance ( logs , six . binary_type ) : logs = logs . decode ( encoding = 'UTF-8' , errors = "ignore" ) msg = '{0} {1}' . format ( msg , logs ) else : logs = self . client . logs ( self . id , stdout = True , stderr = True , stream = False , timestamps = False , tail = 'all' ) if isinstance ( logs , six . binary_type ) : logs = logs . decode ( encoding = 'UTF-8' , errors = "ignore" ) msg = '{0}{1}' . format ( msg , logs ) logger . error ( msg ) | dump entirety of the container logs to stdout | 211 | 9 |
13,488 | def _registrations_for_section_with_active_flag ( section , is_active , transcriptable_course = "" ) : instructor_reg_id = "" if ( section . is_independent_study and section . independent_study_instructor_regid is not None ) : instructor_reg_id = section . independent_study_instructor_regid params = [ ( "curriculum_abbreviation" , section . curriculum_abbr ) , ( "instructor_reg_id" , instructor_reg_id ) , ( "course_number" , section . course_number ) , ( "verbose" , "true" ) , ( "year" , section . term . year ) , ( "quarter" , section . term . quarter ) , ( "is_active" , "true" if is_active else "" ) , ( "section_id" , section . section_id ) , ] if transcriptable_course != "" : params . append ( ( "transcriptable_course" , transcriptable_course , ) ) url = "{}?{}" . format ( registration_res_url_prefix , urlencode ( params ) ) return _json_to_registrations ( get_resource ( url ) , section ) | Returns a list of all uw_sws . models . Registration objects for a section . There can be duplicates for a person . If is_active is True the objects will have is_active set to True . Otherwise is_active is undefined and out of scope for this method . | 276 | 59 |
13,489 | def _json_to_registrations ( data , section ) : registrations = [ ] person_threads = { } for reg_data in data . get ( "Registrations" , [ ] ) : registration = Registration ( ) registration . section = section registration . is_active = reg_data [ "IsActive" ] registration . is_credit = reg_data [ "IsCredit" ] registration . is_auditor = reg_data [ "Auditor" ] registration . is_independent_start = reg_data [ "IsIndependentStart" ] if len ( reg_data [ "StartDate" ] ) : registration . start_date = parse ( reg_data [ "StartDate" ] ) if len ( reg_data [ "EndDate" ] ) : registration . end_date = parse ( reg_data [ "EndDate" ] ) if len ( reg_data [ "RequestDate" ] ) : registration . request_date = parse ( reg_data [ "RequestDate" ] ) registration . request_status = reg_data [ "RequestStatus" ] registration . duplicate_code = reg_data [ "DuplicateCode" ] registration . credits = reg_data [ "Credits" ] registration . repository_timestamp = datetime . strptime ( reg_data [ "RepositoryTimeStamp" ] , "%m/%d/%Y %H:%M:%S %p" ) registration . repeat_course = reg_data [ "RepeatCourse" ] registration . grade = reg_data [ "Grade" ] registration . _uwregid = reg_data [ "Person" ] [ "RegID" ] if registration . _uwregid not in person_threads : thread = SWSPersonByRegIDThread ( ) thread . regid = registration . _uwregid thread . start ( ) person_threads [ registration . _uwregid ] = thread registrations . append ( registration ) for registration in registrations : thread = person_threads [ registration . _uwregid ] thread . join ( ) registration . person = thread . person del registration . _uwregid return registrations | Returns a list of all uw_sws . models . Registration objects | 461 | 15 |
13,490 | def get_credits_by_section_and_regid ( section , regid ) : deprecation ( "Use get_credits_by_reg_url" ) # note trailing comma in URL, it's required for the optional dup_code param url = "{}{},{},{},{},{},{},.json" . format ( reg_credits_url_prefix , section . term . year , section . term . quarter , re . sub ( ' ' , '%20' , section . curriculum_abbr ) , section . course_number , section . section_id , regid ) reg_data = get_resource ( url ) try : return Decimal ( reg_data [ 'Credits' ] . strip ( ) ) except InvalidOperation : pass | Returns a uw_sws . models . Registration object for the section and regid passed in . | 167 | 21 |
13,491 | def get_schedule_by_regid_and_term ( regid , term , non_time_schedule_instructors = True , per_section_prefetch_callback = None , transcriptable_course = "" , * * kwargs ) : if "include_instructor_not_on_time_schedule" in kwargs : include = kwargs [ "include_instructor_not_on_time_schedule" ] non_time_schedule_instructors = include params = [ ( 'reg_id' , regid ) , ] if transcriptable_course != "" : params . append ( ( "transcriptable_course" , transcriptable_course , ) ) params . extend ( [ ( 'quarter' , term . quarter ) , ( 'is_active' , 'true' ) , ( 'year' , term . year ) , ] ) url = "{}?{}" . format ( registration_res_url_prefix , urlencode ( params ) ) return _json_to_schedule ( get_resource ( url ) , term , regid , non_time_schedule_instructors , per_section_prefetch_callback ) | Returns a uw_sws . models . ClassSchedule object for the regid and term passed in . | 265 | 23 |
13,492 | def _add_credits_grade_to_section ( url , section ) : section_reg_data = get_resource ( url ) if section_reg_data is not None : section . student_grade = section_reg_data [ 'Grade' ] section . is_auditor = section_reg_data [ 'Auditor' ] if len ( section_reg_data [ 'GradeDate' ] ) > 0 : section . grade_date = parse ( section_reg_data [ "GradeDate" ] ) . date ( ) try : raw_credits = section_reg_data [ 'Credits' ] . strip ( ) section . student_credits = Decimal ( raw_credits ) except InvalidOperation : pass | Given the registration url passed in add credits grade grade date in the section object | 157 | 15 |
13,493 | def find_transition ( self , gene : Gene , multiplexes : Tuple [ Multiplex , ... ] ) -> Transition : multiplexes = tuple ( multiplex for multiplex in multiplexes if gene in multiplex . genes ) for transition in self . transitions : if transition . gene == gene and set ( transition . multiplexes ) == set ( multiplexes ) : return transition raise AttributeError ( f'transition K_{gene.name}' + '' . join ( f"+{multiplex!r}" for multiplex in multiplexes ) + ' does not exist' ) | Find and return a transition in the model for the given gene and multiplexes . Raise an AttributeError if there is no multiplex in the graph with the given name . | 123 | 35 |
13,494 | def available_state ( self , state : State ) -> Tuple [ State , ... ] : result = [ ] for gene in self . genes : result . extend ( self . available_state_for_gene ( gene , state ) ) if len ( result ) > 1 and state in result : result . remove ( state ) return tuple ( result ) | Return the state reachable from a given state . | 74 | 10 |
13,495 | def available_state_for_gene ( self , gene : Gene , state : State ) -> Tuple [ State , ... ] : result : List [ State ] = [ ] active_multiplex : Tuple [ Multiplex ] = gene . active_multiplex ( state ) transition : Transition = self . find_transition ( gene , active_multiplex ) current_state : int = state [ gene ] done = set ( ) for target_state in transition . states : target_state : int = self . _state_after_transition ( current_state , target_state ) if target_state not in done : done . add ( target_state ) new_state : State = state . copy ( ) new_state [ gene ] = target_state result . append ( new_state ) return tuple ( result ) | Return the state reachable from a given state for a particular gene . | 175 | 14 |
13,496 | def convert_single ( ID , from_type , to_type ) : if from_type not in converter_types : raise PubMedConverterTypeException ( from_type ) if to_type not in converter_types : raise PubMedConverterTypeException ( to_type ) results = convert ( [ ID ] , from_type ) if ID in results : return results [ ID ] . get ( to_type ) else : return results [ ID . upper ( ) ] . get ( to_type ) | Convenience function wrapper for convert . Takes a single ID and converts it from from_type to to_type . The return value is the ID in the scheme of to_type . | 107 | 38 |
13,497 | def cli_main ( ) : # pragma: no cover if '--debug' in sys . argv : LOG . setLevel ( logging . DEBUG ) elif '--verbose' in sys . argv : LOG . setLevel ( logging . INFO ) args = _get_arguments ( ) try : plugin , folder = get_plugin_and_folder ( inputzip = args . inputzip , inputdir = args . inputdir , inputfile = args . inputfile ) LOG . debug ( 'Plugin: %s -- Folder: %s' % ( plugin . name , folder ) ) run_mq2 ( plugin , folder , lod_threshold = args . lod , session = args . session ) except MQ2Exception as err : print ( err ) return 1 return 0 | Main function when running from CLI . | 168 | 7 |
13,498 | def loop ( self ) : logging . info ( "Running %s in loop mode." % self . service_name ) res = None while True : try : res = self . run ( ) time . sleep ( self . loop_duration ) except KeyboardInterrupt : logging . warning ( "Keyboard Interrupt during loop, stopping %s service now..." % self . service_name ) break except Exception as e : logging . exception ( "Error in %s main loop! (%s)" % ( self . service_name , e ) ) raise e return res | Run the demo suite in a loop . | 116 | 8 |
13,499 | def prep ( s , p , o ) : def bnode_check ( r ) : return isinstance ( r , mock_bnode ) or r . startswith ( 'VERSABLANKNODE_' ) s = BNode ( ) if bnode_check ( s ) else URIRef ( s ) p = URIRef ( p ) o = BNode ( ) if bnode_check ( o ) else ( URIRef ( o ) if isinstance ( o , I ) else Literal ( o ) ) return s , p , o | Prepare a triple for rdflib | 119 | 9 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.