idx int64 0 251k | question stringlengths 53 3.53k | target stringlengths 5 1.23k | len_question int64 20 893 | len_target int64 3 238 |
|---|---|---|---|---|
236,000 | def print_projects ( self , projects ) : for project in projects : print ( '{}: {}' . format ( project . name , project . id ) ) | Print method for projects . | 34 | 5 |
236,001 | def print_operating_systems ( self , operating_systems ) : for _os in operating_systems : print ( '{}: {}' . format ( _os . name , _os . slug ) ) | Print method for operating systems . | 47 | 6 |
236,002 | def print_plans ( self , plans ) : for plan in plans : print ( 'Name: {} "{}" Price: {} USD' . format ( plan . name , plan . slug , plan . pricing [ 'hour' ] ) ) self . pprint ( plan . specs ) print ( '\n' ) | Print method for plans . | 66 | 5 |
236,003 | def print_facilities ( self , facilities ) : for facility in facilities : print ( '{} - ({}): {}' . format ( facility . code , facility . name , "," . join ( facility . features ) ) ) | Print method for facilities . | 49 | 5 |
236,004 | def list_devices ( self , project_id , conditions = None , params = None ) : default_params = { 'per_page' : 1000 } if params : default_params . update ( params ) data = self . api ( 'projects/%s/devices' % project_id , params = default_params ) devices = [ ] for device in self . filter ( conditions , data [ 'devices' ] ) : devices . append ( packet . Device ( device , self . manager ) ) return devices | Retrieve list of devices in a project by one of more conditions . | 107 | 14 |
236,005 | def print_devices ( self , devices ) : for device in devices : print ( 'ID: {} OS: {} IP: {} State: {} ({}) Tags: {}' . format ( device . id , device . operating_system . slug , self . get_public_ip ( device . ip_addresses ) , device . state , 'spot' if device . spot_instance else 'on-demand' , device . tags ) ) | Print method for devices . | 92 | 5 |
236,006 | def filter ( criterias , devices ) : # pylint: disable=too-many-branches if not criterias : return devices result = [ ] for device in devices : # pylint: disable=too-many-nested-blocks for criteria_name , criteria_values in criterias . items ( ) : if criteria_name in device . keys ( ) : if isinstance ( device [ criteria_name ] , list ) : for criteria_value in criteria_values : if criteria_value in device [ criteria_name ] : result . append ( device ) break elif isinstance ( device [ criteria_name ] , str ) : for criteria_value in criteria_values : if criteria_value == device [ criteria_name ] : result . append ( device ) elif isinstance ( device [ criteria_name ] , int ) : for criteria_value in criteria_values : if criteria_value == device [ criteria_name ] : result . append ( device ) else : continue return result | Filter a device by criterias on the root level of the dictionary . | 214 | 15 |
236,007 | def get_public_ip ( addresses , version = 4 ) : for addr in addresses : if addr [ 'public' ] and addr [ 'address_family' ] == version : return addr . get ( 'address' ) return None | Return either the devices public IPv4 or IPv6 address . | 49 | 12 |
236,008 | def validate_capacity ( self , servers ) : try : return self . manager . validate_capacity ( servers ) except packet . baseapi . Error as msg : raise PacketManagerException ( msg ) | Validates if a deploy can be fulfilled . | 41 | 9 |
236,009 | def create_volume ( self , project_id , plan , size , facility , label = "" ) : try : return self . manager . create_volume ( project_id , label , plan , size , facility ) except packet . baseapi . Error as msg : raise PacketManagerException ( msg ) | Creates a new volume . | 63 | 6 |
236,010 | def attach_volume_to_device ( self , volume_id , device_id ) : try : volume = self . manager . get_volume ( volume_id ) volume . attach ( device_id ) except packet . baseapi . Error as msg : raise PacketManagerException ( msg ) return volume | Attaches the created Volume to a Device . | 64 | 9 |
236,011 | def create_demand ( self , project_id , facility , plan , operating_system , tags = None , userdata = '' , hostname = None , count = 1 ) : tags = { } if tags is None else tags hostname = self . get_random_hostname ( ) if hostname is None else hostname devices = [ ] for i in range ( 1 , count + 1 ) : new_hostname = hostname if count == 1 else hostname + '-' + str ( i ) self . logger . info ( 'Adding to project %s: %s, %s, %s, %s, %r' , project_id , new_hostname , facility , plan , operating_system , tags ) try : device = self . manager . create_device ( project_id = project_id , hostname = new_hostname , facility = facility , plan = plan , tags = tags , userdata = userdata , operating_system = operating_system ) devices . append ( device ) except packet . baseapi . Error as msg : raise PacketManagerException ( msg ) return devices | Create a new on demand device under the given project . | 235 | 11 |
236,012 | def stop ( self , devices ) : for device in devices : self . logger . info ( 'Stopping: %s' , device . id ) try : device . power_off ( ) except packet . baseapi . Error : raise PacketManagerException ( 'Unable to stop instance "{}"' . format ( device . id ) ) | Power - Off one or more running devices . | 71 | 9 |
236,013 | def reboot ( self , devices ) : for device in devices : self . logger . info ( 'Rebooting: %s' , device . id ) try : device . reboot ( ) except packet . baseapi . Error : raise PacketManagerException ( 'Unable to reboot instance "{}"' . format ( device . id ) ) | Reboot one or more devices . | 69 | 7 |
236,014 | def terminate ( self , devices ) : for device in devices : self . logger . info ( 'Terminating: %s' , device . id ) try : device . delete ( ) except packet . baseapi . Error : raise PacketManagerException ( 'Unable to terminate instance "{}"' . format ( device . id ) ) | Terminate one or more running or stopped instances . | 69 | 10 |
236,015 | def parse_args ( cls ) : # Initialize configuration and userdata directories. dirs = appdirs . AppDirs ( __title__ , 'Mozilla Security' ) if not os . path . isdir ( dirs . user_config_dir ) : shutil . copytree ( os . path . join ( cls . HOME , 'examples' ) , dirs . user_config_dir ) shutil . copytree ( os . path . join ( cls . HOME , 'userdata' ) , os . path . join ( dirs . user_config_dir , 'userdata' ) ) parser = argparse . ArgumentParser ( description = 'Laniakea Runtime v{}' . format ( cls . VERSION ) , prog = __title__ , add_help = False , formatter_class = lambda prog : argparse . ArgumentDefaultsHelpFormatter ( prog , max_help_position = 40 , width = 120 ) , epilog = 'The exit status is 0 for non-failures and 1 for failures.' ) subparsers = parser . add_subparsers ( dest = 'provider' , description = 'Use -h to see the help menu of each provider.' , title = 'Laniakea Cloud Providers' , metavar = '' ) modules = ModuleLoader ( ) modules . load ( cls . HOME , 'core/providers' , 'laniakea' ) for name , module in modules . modules . items ( ) : globals ( ) [ name ] = module for module , cli in modules . command_line_interfaces ( ) : getattr ( module , cli ) . add_arguments ( subparsers , dirs ) base = parser . add_argument_group ( 'Laniakea Base Parameters' ) base . add_argument ( '-verbosity' , default = 2 , type = int , choices = list ( range ( 1 , 6 , 1 ) ) , help = 'Log sensitivity.' ) base . add_argument ( '-focus' , action = 'store_true' , default = True , help = argparse . SUPPRESS ) base . add_argument ( '-settings' , metavar = 'path' , type = argparse . FileType ( ) , default = os . path . join ( dirs . user_config_dir , 'laniakea.json' ) , help = 'Laniakea core settings.' ) base . add_argument ( '-h' , '-help' , '--help' , action = 'help' , help = argparse . SUPPRESS ) base . add_argument ( '-version' , action = 'version' , version = '%(prog)s {}' . format ( cls . VERSION ) , help = argparse . SUPPRESS ) userdata = parser . add_argument_group ( 'UserData Parameters' ) userdata . add_argument ( '-userdata' , metavar = 'path' , type = argparse . FileType ( ) , help = 'UserData script for the provisioning process.' ) userdata . add_argument ( '-list-userdata-macros' , action = 'store_true' , help = 'List available macros.' ) userdata . add_argument ( '-print-userdata' , action = 'store_true' , help = 'Print the UserData script to stdout.' ) userdata . add_argument ( '-userdata-macros' , metavar = 'k=v' , nargs = '+' , type = str , help = 'Custom macros for the UserData.' ) return parser . parse_args ( ) | Main argument parser of Laniakea . | 800 | 9 |
236,016 | def main ( cls ) : args = cls . parse_args ( ) if args . focus : Focus . init ( ) else : Focus . disable ( ) logging . basicConfig ( format = '[Laniakea] %(asctime)s %(levelname)s: %(message)s' , level = args . verbosity * 10 , datefmt = '%Y-%m-%d %H:%M:%S' ) # Laniakea base configuration logger . info ( 'Loading Laniakea configuration from %s' , Focus . data ( args . settings . name ) ) try : settings = json . loads ( args . settings . read ( ) ) except ValueError as msg : logger . error ( 'Unable to parse %s: %s' , args . settings . name , msg ) return 1 # UserData userdata = '' if args . userdata : logger . info ( 'Reading user data script content from %s' , Focus . info ( args . userdata . name ) ) try : userdata = UserData . handle_import_tags ( args . userdata . read ( ) , os . path . dirname ( args . userdata . name ) ) except UserDataException as msg : logging . error ( msg ) return 1 if args . list_userdata_macros : UserData . list_tags ( userdata ) return 0 if args . userdata_macros : args . userdata_macros = UserData . convert_pair_to_dict ( args . userdata_macros or '' ) userdata = UserData . handle_tags ( userdata , args . userdata_macros ) if args . print_userdata : logger . info ( 'Combined UserData script:\n%s' , userdata ) return 0 if args . provider : provider = getattr ( globals ( ) [ args . provider ] , args . provider . title ( ) + 'CommandLine' ) provider ( ) . main ( args , settings , userdata ) return 0 | Main entry point of Laniakea . | 434 | 9 |
236,017 | def tags ( self , tags = None ) : if tags is None or not tags : return self nodes = [ ] for node in self . nodes : if any ( tag in node . extra [ 'tags' ] for tag in tags ) : nodes . append ( node ) self . nodes = nodes return self | Filter by tags . | 63 | 4 |
236,018 | def state ( self , states = None ) : if states is None or not states : return self nodes = [ ] for node in self . nodes : if any ( state . lower ( ) == node . state . lower ( ) for state in states ) : nodes . append ( node ) self . nodes = nodes return self | Filter by state . | 66 | 4 |
236,019 | def name ( self , names = None ) : if names is None or not names : return self nodes = [ ] for node in self . nodes : if any ( name == node . name for name in names ) : nodes . append ( node ) self . nodes = nodes return self | Filter by node name . | 58 | 5 |
236,020 | def is_preemptible ( self ) : nodes = [ ] for node in self . nodes : if Kurz . is_preemtible ( node ) : nodes . append ( node ) return self | Filter by preemptible scheduling . | 43 | 6 |
236,021 | def expr ( self , callback ) : nodes = [ ] for node in self . nodes : if callback ( node ) : nodes . append ( node ) self . nodes = nodes return self | Filter by custom expression . | 38 | 5 |
236,022 | def connect ( self , * * kwargs ) : try : self . gce = get_driver ( Provider . GCE ) ( self . user_id , self . key , project = self . project , * * kwargs ) except : raise ComputeEngineManagerException ( "Unable to connect to Google Compute Engine." ) | Connect to Google Compute Engine . | 72 | 7 |
236,023 | def is_connected ( self , attempts = 3 ) : if self . gce is None : while attempts > 0 : self . logger . info ( "Attempting to connect ..." ) try : self . connect ( ) except ComputeEngineManagerException : attempts -= 1 continue self . logger . info ( "Connection established." ) return True self . logger . error ( "Unable to connect to Google Compute Engine." ) return False return True | Try to reconnect if neccessary . | 91 | 8 |
236,024 | def create ( self , size , number , meta , name = None , image = None , attempts = 3 ) : if name is None : name = Common . get_random_hostname ( ) if image is None and number == 1 : raise ComputeEngineManagerException ( "Base image not provided." ) successful = 0 nodes = [ ] while number - successful > 0 and attempts > 0 : if number == 1 : # Used because of suffix naming scheme in ex_create_multiple_nodes() for a single node. nodes = [ self . gce . create_node ( name , size , image , * * meta ) ] else : nodes = self . gce . ex_create_multiple_nodes ( name , size , None , number - successful , ignore_errors = False , poll_interval = 1 , * * meta ) for node in nodes : if isinstance ( node , GCEFailedNode ) : self . logger . error ( "Node failed to create, code %s error: %s" , node . code , node . error ) continue successful += 1 self . nodes . append ( node ) attempts -= 1 if number != successful : self . logger . error ( "We tried but %d nodes failed to create." , number - successful ) return nodes | Create container VM nodes . Uses a container declaration which is undocumented . | 268 | 13 |
236,025 | def stop ( self , nodes = None ) : if not self . is_connected ( ) : return None nodes = nodes or self . nodes result = [ ] for node in nodes : if node . state == 'stopped' : logging . warning ( 'Node %s is already "stopped".' , node . name ) continue try : status = self . gce . ex_stop_node ( node ) if status : result . append ( node ) except InvalidRequestError as err : raise ComputeEngineManagerException ( err ) return result | Stop one or many nodes . | 113 | 6 |
236,026 | def start ( self , nodes = None ) : if not self . is_connected ( ) : return None nodes = nodes or self . nodes result = [ ] for node in nodes : if node . state == 'running' : logging . warning ( 'Node %s is already "running".' , node . name ) continue try : status = self . gce . ex_start_node ( node ) if status : result . append ( node ) except InvalidRequestError as err : raise ComputeEngineManagerException ( err ) return result | Start one or many nodes . | 111 | 6 |
236,027 | def reboot ( self , nodes = None ) : if not self . is_connected ( ) : return None nodes = nodes or self . nodes result = [ ] for node in nodes : if node . state == 'stopped' : logging . warning ( 'Node %s is "stopped" and can not be rebooted.' , node . name ) continue try : status = self . gce . reboot_node ( node ) if status : result . append ( node ) except InvalidRequestError as err : raise ComputeEngineManagerException ( err ) return result | Reboot one or many nodes . | 116 | 7 |
236,028 | def terminate ( self , nodes = None ) : if not self . is_connected ( ) : return None nodes = nodes or self . nodes failed_kill = [ ] result = self . gce . ex_destroy_multiple_nodes ( nodes , poll_interval = 1 , ignore_errors = False ) # Verify whether all instances have been terminated. for i , success in enumerate ( result ) : if success : logging . info ( 'Successfully destroyed: %s' , nodes [ i ] . name ) else : logging . error ( 'Failed to destroy: %s' , nodes [ i ] . name ) failed_kill . append ( nodes [ i ] ) return failed_kill | Destroy one or many nodes . | 147 | 6 |
236,029 | def terminate_with_threads ( self , nodes = None ) : if not self . is_connected ( ) : return None nodes = nodes or self . nodes failed_kill = [ ] def worker ( gce , node ) : self . logger . info ( "Terminating node: %s" , node . name ) terminated = gce . destroy_node ( node ) if not terminated : failed_kill . append ( node ) threads = [ ] for node in nodes : thread = threading . Thread ( target = worker , args = ( self . gce , node ) ) threads . append ( thread ) thread . start ( ) self . logger . info ( "Waiting for nodes to shut down ..." ) for thread in threads : thread . join ( ) return failed_kill | Destroy one or many nodes threaded . | 163 | 7 |
236,030 | def terminate_ex ( self , nodes , threads = False , attempts = 3 ) : while nodes and attempts > 0 : if threads : nodes = self . terminate_with_threads ( nodes ) else : nodes = self . terminate ( nodes ) if nodes : logger . info ( "Attempt to terminate the remaining instances once more." ) attempts -= 1 return nodes | Wrapper method for terminate . | 74 | 6 |
236,031 | def build_bootdisk ( self , image , size = 10 , auto_delete = True ) : if image is None : raise ComputeEngineManagerException ( "Image must not be None." ) return { 'boot' : True , 'autoDelete' : auto_delete , 'initializeParams' : { 'sourceImage' : "projects/cos-cloud/global/images/{}" . format ( image ) , 'diskSizeGb' : size , } } | Buid a disk struct . | 100 | 6 |
236,032 | def build_container_vm ( self , container , disk , zone = "us-east1-b" , tags = None , preemptible = True ) : if tags is None : tags = [ ] if container is None : raise ComputeEngineManagerException ( "Container declaration must not be None." ) if disk is None : raise ComputeEngineManagerException ( "Disk structure must not be None." ) return { 'ex_metadata' : { "gce-container-declaration" : container , "google-logging-enabled" : "true" } , 'location' : zone , 'ex_tags' : tags , 'ex_disks_gce_struct' : [ disk ] , 'ex_preemptible' : preemptible } | Build kwargs for a container VM . | 161 | 9 |
236,033 | def filter ( self , zone = 'all' ) : if not self . is_connected ( ) : return None nodes = self . gce . list_nodes ( zone ) return Filter ( nodes ) | Filter nodes by their attributes . | 43 | 6 |
236,034 | def enu2aer ( e : np . ndarray , n : np . ndarray , u : np . ndarray , deg : bool = True ) -> Tuple [ float , float , float ] : # 1 millimeter precision for singularity e = np . asarray ( e ) n = np . asarray ( n ) u = np . asarray ( u ) with np . errstate ( invalid = 'ignore' ) : e [ abs ( e ) < 1e-3 ] = 0. n [ abs ( n ) < 1e-3 ] = 0. u [ abs ( u ) < 1e-3 ] = 0. r = hypot ( e , n ) slantRange = hypot ( r , u ) elev = arctan2 ( u , r ) az = arctan2 ( e , n ) % tau if deg : az = degrees ( az ) elev = degrees ( elev ) return az , elev , slantRange | ENU to Azimuth Elevation Range | 206 | 9 |
236,035 | def aer2enu ( az : float , el : float , srange : float , deg : bool = True ) -> Tuple [ float , float , float ] : if deg : el = radians ( el ) az = radians ( az ) with np . errstate ( invalid = 'ignore' ) : if ( np . asarray ( srange ) < 0 ) . any ( ) : raise ValueError ( 'Slant range [0, Infinity)' ) r = srange * cos ( el ) return r * sin ( az ) , r * cos ( az ) , srange * sin ( el ) | Azimuth Elevation Slant range to target to East north Up | 129 | 14 |
236,036 | def enu2geodetic ( e : float , n : float , u : float , lat0 : float , lon0 : float , h0 : float , ell = None , deg : bool = True ) -> Tuple [ float , float , float ] : x , y , z = enu2ecef ( e , n , u , lat0 , lon0 , h0 , ell , deg = deg ) return ecef2geodetic ( x , y , z , ell , deg = deg ) | East North Up to target to geodetic coordinates | 113 | 10 |
236,037 | def track2 ( lat1 : float , lon1 : float , lat2 : float , lon2 : float , ell : Ellipsoid = None , npts : int = 100 , deg : bool = True ) : if ell is None : ell = Ellipsoid ( ) if npts <= 1 : raise ValueError ( 'npts must be greater than 1' ) if npts == 2 : return [ lat1 , lat2 ] , [ lon1 , lon2 ] if deg is True : rlat1 , rlon1 , rlat2 , rlon2 = np . radians ( [ lat1 , lon1 , lat2 , lon2 ] ) else : rlat1 , rlon1 , rlat2 , rlon2 = lat1 , lon1 , lat2 , lon2 gcarclen = 2. * np . arcsin ( np . sqrt ( ( np . sin ( ( rlat1 - rlat2 ) / 2 ) ) ** 2 + np . cos ( rlat1 ) * np . cos ( rlat2 ) * ( np . sin ( ( rlon1 - rlon2 ) / 2 ) ) ** 2 ) ) # check to see if points are antipodal (if so, route is undefined). if np . allclose ( gcarclen , pi ) : raise ValueError ( 'cannot compute intermediate points on a great circle whose endpoints are antipodal' ) distance , azimuth , _ = vdist ( lat1 , lon1 , lat2 , lon2 ) incdist = distance / ( npts - 1 ) latpt = lat1 lonpt = lon1 lons = [ lonpt ] lats = [ latpt ] for n in range ( npts - 2 ) : latptnew , lonptnew , _ = vreckon ( latpt , lonpt , incdist , azimuth ) _ , azimuth , _ = vdist ( latptnew , lonptnew , lat2 , lon2 , ell = ell ) lats . append ( latptnew ) lons . append ( lonptnew ) latpt = latptnew lonpt = lonptnew lons . append ( lon2 ) lats . append ( lat2 ) if not deg : lats = np . radians ( lats ) lons = np . radians ( lons ) return lats , lons | computes great circle tracks starting at the point lat1 lon1 and ending at lat2 lon2 | 535 | 22 |
236,038 | def datetime2sidereal ( time : datetime , lon_radians : float , usevallado : bool = True ) -> float : usevallado = usevallado or Time is None if usevallado : jd = juliandate ( str2dt ( time ) ) # %% Greenwich Sidereal time RADIANS gst = julian2sidereal ( jd ) # %% Algorithm 15 p. 188 rotate GST to LOCAL SIDEREAL TIME tsr = gst + lon_radians else : tsr = Time ( time ) . sidereal_time ( kind = 'apparent' , longitude = Longitude ( lon_radians , unit = u . radian ) ) . radian return tsr | Convert datetime to sidereal time | 165 | 8 |
236,039 | def juliandate ( time : datetime ) -> float : times = np . atleast_1d ( time ) assert times . ndim == 1 jd = np . empty ( times . size ) for i , t in enumerate ( times ) : if t . month < 3 : year = t . year - 1 month = t . month + 12 else : year = t . year month = t . month A = int ( year / 100.0 ) B = 2 - A + int ( A / 4. ) C = ( ( t . second / 60. + t . minute ) / 60. + t . hour ) / 24. jd [ i ] = ( int ( 365.25 * ( year + 4716 ) ) + int ( 30.6001 * ( month + 1 ) ) + t . day + B - 1524.5 + C ) return jd . squeeze ( ) | Python datetime to Julian time | 193 | 6 |
236,040 | def julian2sidereal ( Jdate : float ) -> float : jdate = np . atleast_1d ( Jdate ) assert jdate . ndim == 1 tsr = np . empty ( jdate . size ) for i , jd in enumerate ( jdate ) : # %% Vallado Eq. 3-42 p. 184, Seidelmann 3.311-1 tUT1 = ( jd - 2451545.0 ) / 36525. # Eqn. 3-47 p. 188 gmst_sec = ( 67310.54841 + ( 876600 * 3600 + 8640184.812866 ) * tUT1 + 0.093104 * tUT1 ** 2 - 6.2e-6 * tUT1 ** 3 ) # 1/86400 and %(2*pi) implied by units of radians tsr [ i ] = gmst_sec * ( 2 * pi ) / 86400. % ( 2 * pi ) return tsr . squeeze ( ) | Convert Julian time to sidereal time | 229 | 8 |
236,041 | def get_radius_normal ( lat_radians : float , ell : Ellipsoid = None ) -> float : if ell is None : ell = Ellipsoid ( ) a = ell . a b = ell . b return a ** 2 / sqrt ( a ** 2 * cos ( lat_radians ) ** 2 + b ** 2 * sin ( lat_radians ) ** 2 ) | Compute normal radius of planetary body | 85 | 7 |
236,042 | def ecef2enuv ( u : float , v : float , w : float , lat0 : float , lon0 : float , deg : bool = True ) -> Tuple [ float , float , float ] : if deg : lat0 = radians ( lat0 ) lon0 = radians ( lon0 ) t = cos ( lon0 ) * u + sin ( lon0 ) * v uEast = - sin ( lon0 ) * u + cos ( lon0 ) * v wUp = cos ( lat0 ) * t + sin ( lat0 ) * w vNorth = - sin ( lat0 ) * t + cos ( lat0 ) * w return uEast , vNorth , wUp | VECTOR from observer to target ECEF = > ENU | 157 | 14 |
236,043 | def ecef2enu ( x : float , y : float , z : float , lat0 : float , lon0 : float , h0 : float , ell : Ellipsoid = None , deg : bool = True ) -> Tuple [ float , float , float ] : x0 , y0 , z0 = geodetic2ecef ( lat0 , lon0 , h0 , ell , deg = deg ) return uvw2enu ( x - x0 , y - y0 , z - z0 , lat0 , lon0 , deg = deg ) | from observer to target ECEF = > ENU | 129 | 11 |
236,044 | def eci2geodetic ( eci : np . ndarray , t : datetime , useastropy : bool = True ) -> Tuple [ float , float , float ] : ecef = np . atleast_2d ( eci2ecef ( eci , t , useastropy = useastropy ) ) return np . asarray ( ecef2geodetic ( ecef [ : , 0 ] , ecef [ : , 1 ] , ecef [ : , 2 ] ) ) . squeeze ( ) | convert ECI to geodetic coordinates | 121 | 9 |
236,045 | def enu2ecef ( e1 : float , n1 : float , u1 : float , lat0 : float , lon0 : float , h0 : float , ell : Ellipsoid = None , deg : bool = True ) -> Tuple [ float , float , float ] : x0 , y0 , z0 = geodetic2ecef ( lat0 , lon0 , h0 , ell , deg = deg ) dx , dy , dz = enu2uvw ( e1 , n1 , u1 , lat0 , lon0 , deg = deg ) return x0 + dx , y0 + dy , z0 + dz | ENU to ECEF | 147 | 6 |
236,046 | def aer2ned ( az : float , elev : float , slantRange : float , deg : bool = True ) -> Tuple [ float , float , float ] : e , n , u = aer2enu ( az , elev , slantRange , deg = deg ) return n , e , - u | converts azimuth elevation range to target from observer to North East Down | 66 | 15 |
236,047 | def ned2aer ( n : float , e : float , d : float , deg : bool = True ) -> Tuple [ float , float , float ] : return enu2aer ( e , n , - d , deg = deg ) | converts North East Down to azimuth elevation range | 52 | 11 |
236,048 | def ned2geodetic ( n : float , e : float , d : float , lat0 : float , lon0 : float , h0 : float , ell : Ellipsoid = None , deg : bool = True ) -> Tuple [ float , float , float ] : x , y , z = enu2ecef ( e , n , - d , lat0 , lon0 , h0 , ell , deg = deg ) return ecef2geodetic ( x , y , z , ell , deg = deg ) | Converts North East Down to target latitude longitude altitude | 119 | 11 |
236,049 | def ned2ecef ( n : float , e : float , d : float , lat0 : float , lon0 : float , h0 : float , ell : Ellipsoid = None , deg : bool = True ) -> Tuple [ float , float , float ] : return enu2ecef ( e , n , - d , lat0 , lon0 , h0 , ell , deg = deg ) | North East Down to target ECEF coordinates | 93 | 9 |
236,050 | def ecef2ned ( x : float , y : float , z : float , lat0 : float , lon0 : float , h0 : float , ell : Ellipsoid = None , deg : bool = True ) -> Tuple [ float , float , float ] : e , n , u = ecef2enu ( x , y , z , lat0 , lon0 , h0 , ell , deg = deg ) return n , e , - u | Convert ECEF x y z to North East Down | 103 | 12 |
236,051 | def ecef2nedv ( x : float , y : float , z : float , lat0 : float , lon0 : float , deg : bool = True ) -> Tuple [ float , float , float ] : e , n , u = ecef2enuv ( x , y , z , lat0 , lon0 , deg = deg ) return n , e , - u | for VECTOR between two points | 85 | 7 |
236,052 | def azel2radec ( az_deg : float , el_deg : float , lat_deg : float , lon_deg : float , time : datetime ) -> Tuple [ float , float ] : az = atleast_1d ( az_deg ) el = atleast_1d ( el_deg ) lat = atleast_1d ( lat_deg ) lon = atleast_1d ( lon_deg ) if az . shape != el . shape : raise ValueError ( 'az and el must be same shape ndarray' ) if not ( lat . size == 1 and lon . size == 1 ) : raise ValueError ( 'need one observer and one or more (az,el).' ) if ( ( lat < - 90 ) | ( lat > 90 ) ) . any ( ) : raise ValueError ( '-90 <= lat <= 90' ) az = radians ( az ) el = radians ( el ) lat = radians ( lat ) lon = radians ( lon ) # %% Vallado "algorithm 28" p 268 dec = arcsin ( sin ( el ) * sin ( lat ) + cos ( el ) * cos ( lat ) * cos ( az ) ) lha = arctan2 ( - ( sin ( az ) * cos ( el ) ) / cos ( dec ) , ( sin ( el ) - sin ( lat ) * sin ( dec ) ) / ( cos ( dec ) * cos ( lat ) ) ) lst = datetime2sidereal ( time , lon ) # lon, ra in RADIANS """ by definition right ascension [0, 360) degrees """ return degrees ( lst - lha ) % 360 , degrees ( dec ) | converts azimuth elevation to right ascension declination | 373 | 12 |
236,053 | def radec2azel ( ra_deg : float , dec_deg : float , lat_deg : float , lon_deg : float , time : datetime ) -> Tuple [ float , float ] : ra = atleast_1d ( ra_deg ) dec = atleast_1d ( dec_deg ) lat = atleast_1d ( lat_deg ) lon = atleast_1d ( lon_deg ) if ra . shape != dec . shape : raise ValueError ( 'az and el must be same shape ndarray' ) if not ( lat . size == 1 and lon . size == 1 ) : raise ValueError ( 'need one observer and one or more (az,el).' ) if ( ( lat < - 90 ) | ( lat > 90 ) ) . any ( ) : raise ValueError ( '-90 <= lat <= 90' ) ra = radians ( ra ) dec = radians ( dec ) lat = radians ( lat ) lon = radians ( lon ) lst = datetime2sidereal ( time , lon ) # RADIANS # %% Eq. 4-11 p. 267 LOCAL HOUR ANGLE lha = lst - ra # %% #Eq. 4-12 p. 267 el = arcsin ( sin ( lat ) * sin ( dec ) + cos ( lat ) * cos ( dec ) * cos ( lha ) ) # %% combine Eq. 4-13 and 4-14 p. 268 az = arctan2 ( - sin ( lha ) * cos ( dec ) / cos ( el ) , ( sin ( dec ) - sin ( el ) * sin ( lat ) ) / ( cos ( el ) * cos ( lat ) ) ) return degrees ( az ) % 360.0 , degrees ( el ) | converts right ascension declination to azimuth elevation | 393 | 12 |
236,054 | def ecef2aer ( x : float , y : float , z : float , lat0 : float , lon0 : float , h0 : float , ell = None , deg : bool = True ) -> Tuple [ float , float , float ] : xEast , yNorth , zUp = ecef2enu ( x , y , z , lat0 , lon0 , h0 , ell , deg = deg ) return enu2aer ( xEast , yNorth , zUp , deg = deg ) | gives azimuth elevation and slant range from an Observer to a Point with ECEF coordinates . | 113 | 22 |
236,055 | def geodetic2aer ( lat : float , lon : float , h : float , lat0 : float , lon0 : float , h0 : float , ell = None , deg : bool = True ) -> Tuple [ float , float , float ] : e , n , u = geodetic2enu ( lat , lon , h , lat0 , lon0 , h0 , ell , deg = deg ) return enu2aer ( e , n , u , deg = deg ) | gives azimuth elevation and slant range from an Observer to a Point with geodetic coordinates . | 109 | 22 |
236,056 | def aer2geodetic ( az : float , el : float , srange : float , lat0 : float , lon0 : float , h0 : float , ell = None , deg : bool = True ) -> Tuple [ float , float , float ] : x , y , z = aer2ecef ( az , el , srange , lat0 , lon0 , h0 , ell = ell , deg = deg ) return ecef2geodetic ( x , y , z , ell = ell , deg = deg ) | gives geodetic coordinates of a point with az el range from an observer at lat0 lon0 h0 | 117 | 24 |
236,057 | def eci2aer ( eci : Tuple [ float , float , float ] , lat0 : float , lon0 : float , h0 : float , t : datetime , useastropy : bool = True ) -> Tuple [ float , float , float ] : ecef = np . atleast_2d ( eci2ecef ( eci , t , useastropy ) ) return ecef2aer ( ecef [ : , 0 ] , ecef [ : , 1 ] , ecef [ : , 2 ] , lat0 , lon0 , h0 ) | takes ECI coordinates of point and gives az el slant range from Observer | 133 | 16 |
236,058 | def aer2eci ( az : float , el : float , srange : float , lat0 : float , lon0 : float , h0 : float , t : datetime , ell = None , deg : bool = True , useastropy : bool = True ) -> np . ndarray : x , y , z = aer2ecef ( az , el , srange , lat0 , lon0 , h0 , ell , deg ) return ecef2eci ( np . column_stack ( ( x , y , z ) ) , t , useastropy ) | gives ECI of a point from an observer at az el slant range | 127 | 16 |
236,059 | def aer2ecef ( az : float , el : float , srange : float , lat0 : float , lon0 : float , alt0 : float , ell = None , deg : bool = True ) -> Tuple [ float , float , float ] : # Origin of the local system in geocentric coordinates. x0 , y0 , z0 = geodetic2ecef ( lat0 , lon0 , alt0 , ell , deg = deg ) # Convert Local Spherical AER to ENU e1 , n1 , u1 = aer2enu ( az , el , srange , deg = deg ) # Rotating ENU to ECEF dx , dy , dz = enu2uvw ( e1 , n1 , u1 , lat0 , lon0 , deg = deg ) # Origin + offset from origin equals position in ECEF return x0 + dx , y0 + dy , z0 + dz | converts target azimuth elevation range from observer at lat0 lon0 alt0 to ECEF coordinates . | 207 | 24 |
236,060 | def isometric ( lat : float , ell : Ellipsoid = None , deg : bool = True ) : if ell is None : ell = Ellipsoid ( ) f = ell . f # flattening of ellipsoid if deg is True : lat = np . deg2rad ( lat ) e2 = f * ( 2 - f ) # eccentricity-squared e = np . sqrt ( e2 ) # eccentricity of ellipsoid x = e * np . sin ( lat ) y = ( 1 - x ) / ( 1 + x ) z = np . pi / 4 + lat / 2 # calculate the isometric latitude isolat = np . log ( np . tan ( z ) * ( y ** ( e / 2 ) ) ) if deg is True : isolat = np . degrees ( isolat ) return isolat | computes isometric latitude of a point on an ellipsoid | 181 | 14 |
236,061 | def loxodrome_inverse ( lat1 : float , lon1 : float , lat2 : float , lon2 : float , ell : Ellipsoid = None , deg : bool = True ) : # set ellipsoid parameters if ell is None : ell = Ellipsoid ( ) if deg is True : lat1 , lon1 , lat2 , lon2 = np . radians ( [ lat1 , lon1 , lat2 , lon2 ] ) # compute isometric latitude of P1 and P2 isolat1 = isometric ( lat1 , deg = False , ell = ell ) isolat2 = isometric ( lat2 , deg = False , ell = ell ) # compute changes in isometric latitude and longitude between points disolat = isolat2 - isolat1 dlon = lon2 - lon1 # compute azimuth az12 = np . arctan2 ( dlon , disolat ) # compute distance along loxodromic curve m1 = meridian_dist ( lat1 , deg = False , ell = ell ) m2 = meridian_dist ( lat2 , deg = False , ell = ell ) dm = m2 - m1 lox_s = dm / np . cos ( az12 ) if deg is True : az12 = np . degrees ( az12 ) % 360. return lox_s , az12 | computes the arc length and azimuth of the loxodrome between two points on the surface of the reference ellipsoid | 306 | 28 |
236,062 | def eci2ecef ( eci : np . ndarray , time : datetime , useastropy : bool = True ) -> np . ndarray : useastropy = useastropy and Time if useastropy : gst = Time ( time ) . sidereal_time ( 'apparent' , 'greenwich' ) . radian else : gst = datetime2sidereal ( time , 0. ) gst = np . atleast_1d ( gst ) assert gst . ndim == 1 and isinstance ( gst [ 0 ] , float ) # must be in radians! eci = np . atleast_2d ( eci ) assert eci . shape [ 0 ] == gst . size , 'length of time does not match number of ECI positions' N , trip = eci . shape if eci . ndim > 2 or trip != 3 : raise ValueError ( 'eci triplets must be shape (N,3)' ) ecef = np . empty_like ( eci ) for i in range ( N ) : ecef [ i , : ] = _rottrip ( gst [ i ] ) @ eci [ i , : ] return ecef . squeeze ( ) | Observer = > Point ECI = > ECEF | 273 | 12 |
236,063 | def describe_vpc ( record ) : account_id = record [ 'account' ] vpc_name = cloudwatch . filter_request_parameters ( 'vpcName' , record ) vpc_id = cloudwatch . filter_request_parameters ( 'vpcId' , record ) try : if vpc_id and vpc_name : # pylint: disable=R1705 return describe_vpcs ( account_number = account_id , assume_role = HISTORICAL_ROLE , region = CURRENT_REGION , Filters = [ { 'Name' : 'vpc-id' , 'Values' : [ vpc_id ] } ] ) elif vpc_id : return describe_vpcs ( account_number = account_id , assume_role = HISTORICAL_ROLE , region = CURRENT_REGION , VpcIds = [ vpc_id ] ) else : raise Exception ( '[X] Describe requires VpcId.' ) except ClientError as exc : if exc . response [ 'Error' ] [ 'Code' ] == 'InvalidVpc.NotFound' : return [ ] raise exc | Attempts to describe vpc ids . | 255 | 8 |
236,064 | def create_delete_model ( record ) : data = cloudwatch . get_historical_base_info ( record ) vpc_id = cloudwatch . filter_request_parameters ( 'vpcId' , record ) arn = get_arn ( vpc_id , cloudwatch . get_region ( record ) , record [ 'account' ] ) LOG . debug ( F'[-] Deleting Dynamodb Records. Hash Key: {arn}' ) # tombstone these records so that the deletion event time can be accurately tracked. data . update ( { 'configuration' : { } } ) items = list ( CurrentVPCModel . query ( arn , limit = 1 ) ) if items : model_dict = items [ 0 ] . __dict__ [ 'attribute_values' ] . copy ( ) model_dict . update ( data ) model = CurrentVPCModel ( * * model_dict ) model . save ( ) return model return None | Create a vpc model from a record . | 207 | 9 |
236,065 | def handler ( event , context ) : # pylint: disable=W0613 records = deserialize_records ( event [ 'Records' ] ) # Split records into two groups, update and delete. # We don't want to query for deleted records. update_records , delete_records = group_records_by_type ( records , UPDATE_EVENTS ) capture_delete_records ( delete_records ) # filter out error events update_records = [ e for e in update_records if not e [ 'detail' ] . get ( 'errorCode' ) ] # pylint: disable=C0103 # group records by account for more efficient processing LOG . debug ( f'[@] Update Records: {records}' ) capture_update_records ( update_records ) | Historical vpc event collector . This collector is responsible for processing Cloudwatch events and polling events . | 180 | 20 |
236,066 | def default_diff ( latest_config , current_config ) : # Pop off the fields we don't care about: pop_no_diff_fields ( latest_config , current_config ) diff = DeepDiff ( latest_config , current_config , ignore_order = True ) return diff | Determine if two revisions have actually changed . | 62 | 10 |
236,067 | def pop_no_diff_fields ( latest_config , current_config ) : for field in [ 'userIdentity' , 'principalId' , 'userAgent' , 'sourceIpAddress' , 'requestParameters' , 'eventName' ] : latest_config . pop ( field , None ) current_config . pop ( field , None ) | Pops off fields that should not be included in the diff . | 78 | 13 |
236,068 | def modify_record ( durable_model , current_revision , arn , event_time , diff_func ) : # We want the newest items first. # See: http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Query.html items = list ( durable_model . query ( arn , ( durable_model . eventTime <= event_time ) , scan_index_forward = False , limit = 1 , consistent_read = True ) ) if items : latest_revision = items [ 0 ] latest_config = latest_revision . _get_json ( ) [ 1 ] [ 'attributes' ] # pylint: disable=W0212 current_config = current_revision . _get_json ( ) [ 1 ] [ 'attributes' ] # pylint: disable=W0212 # Determine if there is truly a difference, disregarding Ephemeral Paths diff = diff_func ( latest_config , current_config ) if diff : LOG . debug ( f'[~] Difference found saving new revision to durable table. Arn: {arn} LatestConfig: {latest_config} ' f'CurrentConfig: {json.dumps(current_config)}' ) current_revision . save ( ) else : current_revision . save ( ) LOG . info ( f'[?] Got modify event but no current revision found. Arn: {arn}' ) | Handles a DynamoDB MODIFY event type . | 312 | 11 |
236,069 | def deserialize_current_record_to_durable_model ( record , current_model , durable_model ) : # Was the item in question too big for SNS? If so, then we need to fetch the item from the current Dynamo table: if record . get ( EVENT_TOO_BIG_FLAG ) : record = get_full_current_object ( record [ 'dynamodb' ] [ 'Keys' ] [ 'arn' ] [ 'S' ] , current_model ) if not record : return None serialized = record . _serialize ( ) # pylint: disable=W0212 record = { 'dynamodb' : { 'NewImage' : serialized [ 'attributes' ] } } # The ARN isn't added because it's in the HASH key section: record [ 'dynamodb' ] [ 'NewImage' ] [ 'arn' ] = { 'S' : serialized [ 'HASH' ] } new_image = remove_current_specific_fields ( record [ 'dynamodb' ] [ 'NewImage' ] ) data = { } for item , value in new_image . items ( ) : # This could end up as loss of precision data [ item ] = DESER . deserialize ( value ) return durable_model ( * * data ) | Utility function that will take a dynamo event record and turn it into the proper pynamo object . | 291 | 22 |
236,070 | def deserialize_current_record_to_current_model ( record , current_model ) : # Was the item in question too big for SNS? If so, then we need to fetch the item from the current Dynamo table: if record . get ( EVENT_TOO_BIG_FLAG ) : return get_full_current_object ( record [ 'dynamodb' ] [ 'Keys' ] [ 'arn' ] [ 'S' ] , current_model ) new_image = remove_global_dynamo_specific_fields ( record [ 'dynamodb' ] [ 'NewImage' ] ) data = { } for item , value in new_image . items ( ) : # This could end up as loss of precision data [ item ] = DESER . deserialize ( value ) return current_model ( * * data ) | Utility function that will take a Dynamo event record and turn it into the proper Current Dynamo object . | 185 | 20 |
236,071 | def deserialize_durable_record_to_durable_model ( record , durable_model ) : # Was the item in question too big for SNS? If so, then we need to fetch the item from the current Dynamo table: if record . get ( EVENT_TOO_BIG_FLAG ) : return get_full_durable_object ( record [ 'dynamodb' ] [ 'Keys' ] [ 'arn' ] [ 'S' ] , record [ 'dynamodb' ] [ 'NewImage' ] [ 'eventTime' ] [ 'S' ] , durable_model ) new_image = remove_global_dynamo_specific_fields ( record [ 'dynamodb' ] [ 'NewImage' ] ) data = { } for item , value in new_image . items ( ) : # This could end up as loss of precision data [ item ] = DESER . deserialize ( value ) return durable_model ( * * data ) | Utility function that will take a Dynamo event record and turn it into the proper Durable Dynamo object . | 215 | 21 |
236,072 | def deserialize_durable_record_to_current_model ( record , current_model ) : # Was the item in question too big for SNS? If so, then we need to fetch the item from the current Dynamo table: if record . get ( EVENT_TOO_BIG_FLAG ) : # Try to get the data from the current table vs. grabbing the data from the Durable table: return get_full_current_object ( record [ 'dynamodb' ] [ 'Keys' ] [ 'arn' ] [ 'S' ] , current_model ) new_image = remove_durable_specific_fields ( record [ 'dynamodb' ] [ 'NewImage' ] ) data = { } for item , value in new_image . items ( ) : # This could end up as loss of precision data [ item ] = DESER . deserialize ( value ) return current_model ( * * data ) | Utility function that will take a Durable Dynamo event record and turn it into the proper Current Dynamo object . | 204 | 22 |
236,073 | def serialize_me ( self , account_id , region , next_token = None ) : payload = { 'account_id' : account_id , 'region' : region } if next_token : payload [ 'next_token' ] = next_token return self . dumps ( payload ) . data | Dumps the proper JSON for the schema . | 66 | 9 |
236,074 | def serialize_me ( self , arn , event_time , tech , item = None ) : payload = { 'arn' : arn , 'event_time' : event_time , 'tech' : tech } if item : payload [ 'item' ] = item else : payload [ 'event_too_big' ] = True return self . dumps ( payload ) . data . replace ( '<empty>' , '' ) | Dumps the proper JSON for the schema . If the event is too big then don t include the item . | 93 | 22 |
236,075 | def fix_decimals ( obj ) : if isinstance ( obj , list ) : for i in range ( len ( obj ) ) : obj [ i ] = fix_decimals ( obj [ i ] ) return obj elif isinstance ( obj , dict ) : for key , value in obj . items ( ) : obj [ key ] = fix_decimals ( value ) return obj elif isinstance ( obj , decimal . Decimal ) : if obj % 1 == 0 : return int ( obj ) else : return float ( obj ) else : return obj | Removes the stupid Decimals | 120 | 7 |
236,076 | def serialize ( self , value ) : if isinstance ( value , str ) : return value return value . strftime ( DATETIME_FORMAT ) | Takes a datetime object and returns a string | 34 | 10 |
236,077 | def pull_tag_dict ( data ) : # If there are tags, set them to a normal dict, vs. a list of dicts: tags = data . pop ( 'Tags' , { } ) or { } if tags : proper_tags = { } for tag in tags : proper_tags [ tag [ 'Key' ] ] = tag [ 'Value' ] tags = proper_tags return tags | This will pull out a list of Tag Name - Value objects and return it as a dictionary . | 86 | 19 |
236,078 | def create_delete_model ( record ) : arn = f"arn:aws:s3:::{cloudwatch.filter_request_parameters('bucketName', record)}" LOG . debug ( f'[-] Deleting Dynamodb Records. Hash Key: {arn}' ) data = { 'arn' : arn , 'principalId' : cloudwatch . get_principal ( record ) , 'userIdentity' : cloudwatch . get_user_identity ( record ) , 'accountId' : record [ 'account' ] , 'eventTime' : record [ 'detail' ] [ 'eventTime' ] , 'BucketName' : cloudwatch . filter_request_parameters ( 'bucketName' , record ) , 'Region' : cloudwatch . get_region ( record ) , 'Tags' : { } , 'configuration' : { } , 'eventSource' : record [ 'detail' ] [ 'eventSource' ] , 'version' : VERSION } return CurrentS3Model ( * * data ) | Create an S3 model from a record . | 231 | 9 |
236,079 | def process_delete_records ( delete_records ) : for rec in delete_records : arn = f"arn:aws:s3:::{rec['detail']['requestParameters']['bucketName']}" # Need to check if the event is NEWER than the previous event in case # events are out of order. This could *possibly* happen if something # was deleted, and then quickly re-created. It could be *possible* for the # deletion event to arrive after the creation event. Thus, this will check # if the current event timestamp is newer and will only delete if the deletion # event is newer. try : LOG . debug ( f'[-] Deleting bucket: {arn}' ) model = create_delete_model ( rec ) model . save ( condition = ( CurrentS3Model . eventTime <= rec [ 'detail' ] [ 'eventTime' ] ) ) model . delete ( ) except PynamoDBConnectionError as pdce : LOG . warning ( f"[?] Unable to delete bucket: {arn}. Either it doesn't exist, or this deletion event is stale " f"(arrived before a NEWER creation/update). The specific exception is: {pdce}" ) | Process the requests for S3 bucket deletions | 266 | 9 |
236,080 | def handler ( event , context ) : # pylint: disable=W0613 records = deserialize_records ( event [ 'Records' ] ) # Split records into two groups, update and delete. # We don't want to query for deleted records. update_records , delete_records = group_records_by_type ( records , UPDATE_EVENTS ) LOG . debug ( '[@] Processing update records...' ) process_update_records ( update_records ) LOG . debug ( '[@] Completed processing of update records.' ) LOG . debug ( '[@] Processing delete records...' ) process_delete_records ( delete_records ) LOG . debug ( '[@] Completed processing of delete records.' ) LOG . debug ( '[@] Successfully updated current Historical table' ) | Historical S3 event collector . | 176 | 7 |
236,081 | def get_historical_accounts ( ) : if os . environ . get ( 'SWAG_BUCKET' , False ) : swag_opts = { 'swag.type' : 's3' , 'swag.bucket_name' : os . environ [ 'SWAG_BUCKET' ] , 'swag.data_file' : os . environ . get ( 'SWAG_DATA_FILE' , 'accounts.json' ) , 'swag.region' : os . environ . get ( 'SWAG_REGION' , 'us-east-1' ) } swag = SWAGManager ( * * parse_swag_config_options ( swag_opts ) ) search_filter = f"[?provider=='aws' && owner=='{os.environ['SWAG_OWNER']}' && account_status!='deleted'" if parse_boolean ( os . environ . get ( 'TEST_ACCOUNTS_ONLY' ) ) : search_filter += " && environment=='test'" search_filter += ']' accounts = swag . get_service_enabled ( 'historical' , search_filter = search_filter ) else : accounts = [ { 'id' : account_id } for account_id in os . environ [ 'ENABLED_ACCOUNTS' ] . split ( ',' ) ] return accounts | Fetches valid accounts from SWAG if enabled or a list accounts . | 315 | 15 |
236,082 | def poller_processor_handler ( event , context ) : # pylint: disable=W0613 LOG . debug ( '[@] Running Poller...' ) queue_url = get_queue_url ( os . environ . get ( 'POLLER_QUEUE_NAME' , 'HistoricalS3Poller' ) ) records = deserialize_records ( event [ 'Records' ] ) for record in records : # Skip accounts that have role assumption errors: try : # List all buckets in the account: all_buckets = list_buckets ( account_number = record [ 'account_id' ] , assume_role = HISTORICAL_ROLE , session_name = "historical-cloudwatch-s3list" , region = record [ 'region' ] ) [ "Buckets" ] events = [ S3_POLLING_SCHEMA . serialize_me ( record [ 'account_id' ] , bucket ) for bucket in all_buckets ] produce_events ( events , queue_url , randomize_delay = RANDOMIZE_POLLER ) except ClientError as exc : LOG . error ( f"[X] Unable to generate events for account. Account Id: {record['account_id']} Reason: {exc}" ) LOG . debug ( f"[@] Finished generating polling events for account: {record['account_id']}. Events Created:" f" {len(record['account_id'])}" ) | Historical S3 Poller Processor . | 322 | 8 |
236,083 | def detect_global_table_updates ( record ) : # This only affects MODIFY events. if record [ 'eventName' ] == 'MODIFY' : # Need to compare the old and new images to check for GT specific changes only (just pop off the GT fields) old_image = remove_global_dynamo_specific_fields ( record [ 'dynamodb' ] [ 'OldImage' ] ) new_image = remove_global_dynamo_specific_fields ( record [ 'dynamodb' ] [ 'NewImage' ] ) if json . dumps ( old_image , sort_keys = True ) == json . dumps ( new_image , sort_keys = True ) : return True return False | This will detect DDB Global Table updates that are not relevant to application data updates . These need to be skipped over as they are pure noise . | 160 | 29 |
236,084 | def handler ( event , context ) : # pylint: disable=W0613 # De-serialize the records: records = deserialize_records ( event [ 'Records' ] ) for record in records : process_dynamodb_differ_record ( record , CurrentS3Model , DurableS3Model ) | Historical S3 event differ . | 73 | 7 |
236,085 | def new ( ) : dir_path = os . path . dirname ( os . path . realpath ( __file__ ) ) cookiecutter ( os . path . join ( dir_path , 'historical-cookiecutter/' ) ) | Creates a new historical technology . | 53 | 7 |
236,086 | def poller_tasker_handler ( event , context ) : # pylint: disable=W0613 LOG . debug ( '[@] Running Poller Tasker...' ) queue_url = get_queue_url ( os . environ . get ( 'POLLER_TASKER_QUEUE_NAME' , 'HistoricalVPCPollerTasker' ) ) poller_task_schema = HistoricalPollerTaskEventModel ( ) events = [ ] for account in get_historical_accounts ( ) : for region in POLL_REGIONS : events . append ( poller_task_schema . serialize_me ( account [ 'id' ] , region ) ) try : produce_events ( events , queue_url , randomize_delay = RANDOMIZE_POLLER ) except ClientError as exc : LOG . error ( f'[X] Unable to generate poller tasker events! Reason: {exc}' ) LOG . debug ( '[@] Finished tasking the pollers.' ) | Historical VPC Poller Tasker . | 224 | 9 |
236,087 | def chunks ( event_list , chunk_size ) : for i in range ( 0 , len ( event_list ) , chunk_size ) : yield event_list [ i : i + chunk_size ] | Yield successive n - sized chunks from the event list . | 44 | 12 |
236,088 | def get_queue_url ( queue_name ) : client = boto3 . client ( "sqs" , CURRENT_REGION ) queue = client . get_queue_url ( QueueName = queue_name ) return queue [ "QueueUrl" ] | Get the URL of the SQS queue to send events to . | 57 | 13 |
236,089 | def produce_events ( events , queue_url , batch_size = 10 , randomize_delay = 0 ) : client = boto3 . client ( 'sqs' , region_name = CURRENT_REGION ) for chunk in chunks ( events , batch_size ) : records = [ make_sqs_record ( event , delay_seconds = get_random_delay ( randomize_delay ) ) for event in chunk ] client . send_message_batch ( Entries = records , QueueUrl = queue_url ) | Efficiently sends events to the SQS event queue . | 114 | 12 |
236,090 | def describe_group ( record , region ) : account_id = record [ 'account' ] group_name = cloudwatch . filter_request_parameters ( 'groupName' , record ) vpc_id = cloudwatch . filter_request_parameters ( 'vpcId' , record ) group_id = cloudwatch . filter_request_parameters ( 'groupId' , record , look_in_response = True ) # Did this get collected already by the poller? if cloudwatch . get_collected_details ( record ) : LOG . debug ( f"[<--] Received already collected security group data: {record['detail']['collected']}" ) return [ record [ 'detail' ] [ 'collected' ] ] try : # Always depend on Group ID first: if group_id : # pylint: disable=R1705 return describe_security_groups ( account_number = account_id , assume_role = HISTORICAL_ROLE , region = region , GroupIds = [ group_id ] ) [ 'SecurityGroups' ] elif vpc_id and group_name : return describe_security_groups ( account_number = account_id , assume_role = HISTORICAL_ROLE , region = region , Filters = [ { 'Name' : 'group-name' , 'Values' : [ group_name ] } , { 'Name' : 'vpc-id' , 'Values' : [ vpc_id ] } ] ) [ 'SecurityGroups' ] else : raise Exception ( '[X] Did not receive Group ID or VPC/Group Name pairs. ' f'We got: ID: {group_id} VPC/Name: {vpc_id}/{group_name}.' ) except ClientError as exc : if exc . response [ 'Error' ] [ 'Code' ] == 'InvalidGroup.NotFound' : return [ ] raise exc | Attempts to describe group ids . | 421 | 7 |
236,091 | def create_delete_model ( record ) : data = cloudwatch . get_historical_base_info ( record ) group_id = cloudwatch . filter_request_parameters ( 'groupId' , record ) # vpc_id = cloudwatch.filter_request_parameters('vpcId', record) # group_name = cloudwatch.filter_request_parameters('groupName', record) arn = get_arn ( group_id , cloudwatch . get_region ( record ) , record [ 'account' ] ) LOG . debug ( f'[-] Deleting Dynamodb Records. Hash Key: {arn}' ) # Tombstone these records so that the deletion event time can be accurately tracked. data . update ( { 'configuration' : { } } ) items = list ( CurrentSecurityGroupModel . query ( arn , limit = 1 ) ) if items : model_dict = items [ 0 ] . __dict__ [ 'attribute_values' ] . copy ( ) model_dict . update ( data ) model = CurrentSecurityGroupModel ( * * model_dict ) model . save ( ) return model return None | Create a security group model from a record . | 246 | 9 |
236,092 | def extract_log_level_from_environment ( k , default ) : return LOG_LEVELS . get ( os . environ . get ( k ) ) or int ( os . environ . get ( k , default ) ) | Gets the log level from the environment variable . | 50 | 10 |
236,093 | def filter_request_parameters ( field_name , msg , look_in_response = False ) : val = msg [ 'detail' ] . get ( field_name , None ) try : if not val : val = msg [ 'detail' ] . get ( 'requestParameters' , { } ) . get ( field_name , None ) # If we STILL didn't find it -- check if it's in the response element (default off) if not val and look_in_response : if msg [ 'detail' ] . get ( 'responseElements' ) : val = msg [ 'detail' ] [ 'responseElements' ] . get ( field_name , None ) # Just in case... We didn't find the value, so just make it None: except AttributeError : val = None return val | From an event extract the field name from the message . Different API calls put this information in different places so check a few places . | 175 | 26 |
236,094 | def get_historical_base_info ( event ) : data = { 'principalId' : get_principal ( event ) , 'userIdentity' : get_user_identity ( event ) , 'accountId' : event [ 'account' ] , 'userAgent' : event [ 'detail' ] . get ( 'userAgent' ) , 'sourceIpAddress' : event [ 'detail' ] . get ( 'sourceIPAddress' ) , 'requestParameters' : event [ 'detail' ] . get ( 'requestParameters' ) } if event [ 'detail' ] . get ( 'eventTime' ) : data [ 'eventTime' ] = event [ 'detail' ] [ 'eventTime' ] if event [ 'detail' ] . get ( 'eventSource' ) : data [ 'eventSource' ] = event [ 'detail' ] [ 'eventSource' ] if event [ 'detail' ] . get ( 'eventName' ) : data [ 'eventName' ] = event [ 'detail' ] [ 'eventName' ] return data | Gets the base details from the CloudWatch Event . | 233 | 11 |
236,095 | def splitText ( text ) : segments = [ ] remaining_text = __class__ . cleanSpaces ( text ) while len ( remaining_text ) > __class__ . MAX_SEGMENT_SIZE : cur_text = remaining_text [ : __class__ . MAX_SEGMENT_SIZE ] # try to split at punctuation split_idx = __class__ . findLastCharIndexMatching ( cur_text , # https://en.wikipedia.org/wiki/Unicode_character_property#General_Category lambda x : unicodedata . category ( x ) in ( "Ps" , "Pe" , "Pi" , "Pf" , "Po" ) ) if split_idx is None : # try to split at whitespace split_idx = __class__ . findLastCharIndexMatching ( cur_text , lambda x : unicodedata . category ( x ) . startswith ( "Z" ) ) if split_idx is None : # try to split at anything not a letter or number split_idx = __class__ . findLastCharIndexMatching ( cur_text , lambda x : not ( unicodedata . category ( x ) [ 0 ] in ( "L" , "N" ) ) ) if split_idx is None : # split at the last char split_idx = __class__ . MAX_SEGMENT_SIZE - 1 new_segment = cur_text [ : split_idx + 1 ] . rstrip ( ) segments . append ( new_segment ) remaining_text = remaining_text [ split_idx + 1 : ] . lstrip ( string . whitespace + string . punctuation ) if remaining_text : segments . append ( remaining_text ) return segments | Split text into sub segments of size not bigger than MAX_SEGMENT_SIZE . | 381 | 18 |
236,096 | def play ( self , sox_effects = ( ) ) : # build the segments preloader_threads = [ ] if self . text != "-" : segments = list ( self ) # start preloader thread(s) preloader_threads = [ PreloaderThread ( name = "PreloaderThread-%u" % ( i ) ) for i in range ( PRELOADER_THREAD_COUNT ) ] for preloader_thread in preloader_threads : preloader_thread . segments = segments preloader_thread . start ( ) else : segments = iter ( self ) # play segments for segment in segments : segment . play ( sox_effects ) if self . text != "-" : # destroy preloader threads for preloader_thread in preloader_threads : preloader_thread . join ( ) | Play a speech . | 177 | 4 |
236,097 | def isInCache ( self ) : url = self . buildUrl ( cache_friendly = True ) return url in __class__ . cache | Return True if audio data for this segment is present in cache False otherwise . | 29 | 15 |
236,098 | def preLoad ( self ) : logging . getLogger ( ) . debug ( "Preloading segment '%s'" % ( self ) ) real_url = self . buildUrl ( ) cache_url = self . buildUrl ( cache_friendly = True ) audio_data = self . download ( real_url ) assert ( audio_data ) __class__ . cache [ cache_url ] = audio_data | Store audio data in cache for fast playback . | 87 | 9 |
236,099 | def getAudioData ( self ) : with self . preload_mutex : cache_url = self . buildUrl ( cache_friendly = True ) if cache_url in __class__ . cache : logging . getLogger ( ) . debug ( "Got data for URL '%s' from cache" % ( cache_url ) ) audio_data = __class__ . cache [ cache_url ] assert ( audio_data ) else : real_url = self . buildUrl ( ) audio_data = self . download ( real_url ) assert ( audio_data ) __class__ . cache [ cache_url ] = audio_data return audio_data | Fetch the audio data . | 140 | 6 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.