idx
int64
0
63k
question
stringlengths
61
4.03k
target
stringlengths
6
1.23k
48,100
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 .
48,101
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 .
48,102
def parse_args ( cls ) : 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 .
48,103
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' ) 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 = '' 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 .
48,104
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 .
48,105
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 .
48,106
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 .
48,107
def is_preemptible ( self ) : nodes = [ ] for node in self . nodes : if Kurz . is_preemtible ( node ) : nodes . append ( node ) return self
Filter by preemptible scheduling .
48,108
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 .
48,109
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 .
48,110
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 .
48,111
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 : 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 .
48,112
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 .
48,113
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 .
48,114
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 .
48,115
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 ) 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 .
48,116
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 .
48,117
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 .
48,118
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 .
48,119
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 .
48,120
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 .
48,121
def enu2aer ( e : np . ndarray , n : np . ndarray , u : np . ndarray , deg : bool = True ) -> Tuple [ float , float , float ] : 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
48,122
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
48,123
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
48,124
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 ) ) 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
48,125
def datetime2sidereal ( time : datetime , lon_radians : float , usevallado : bool = True ) -> float : usevallado = usevallado or Time is None if usevallado : jd = juliandate ( str2dt ( time ) ) gst = julian2sidereal ( jd ) 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
48,126
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
48,127
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 ) : tUT1 = ( jd - 2451545.0 ) / 36525. gmst_sec = ( 67310.54841 + ( 876600 * 3600 + 8640184.812866 ) * tUT1 + 0.093104 * tUT1 ** 2 - 6.2e-6 * tUT1 ** 3 ) tsr [ i ] = gmst_sec * ( 2 * pi ) / 86400. % ( 2 * pi ) return tsr . squeeze ( )
Convert Julian time to sidereal time
48,128
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
48,129
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
48,130
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
48,131
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
48,132
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
48,133
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
48,134
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
48,135
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
48,136
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
48,137
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
48,138
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
48,139
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 ) 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 ) return degrees ( lst - lha ) % 360 , degrees ( dec )
converts azimuth elevation to right ascension declination
48,140
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 ) lha = lst - ra el = arcsin ( sin ( lat ) * sin ( dec ) + cos ( lat ) * cos ( dec ) * cos ( lha ) ) 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
48,141
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 .
48,142
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 .
48,143
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
48,144
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
48,145
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
48,146
def aer2ecef ( az : float , el : float , srange : float , lat0 : float , lon0 : float , alt0 : float , ell = None , deg : bool = True ) -> Tuple [ float , float , float ] : x0 , y0 , z0 = geodetic2ecef ( lat0 , lon0 , alt0 , ell , deg = deg ) e1 , n1 , u1 = aer2enu ( az , el , srange , deg = deg ) dx , dy , dz = enu2uvw ( e1 , n1 , u1 , lat0 , lon0 , deg = deg ) return x0 + dx , y0 + dy , z0 + dz
converts target azimuth elevation range from observer at lat0 lon0 alt0 to ECEF coordinates .
48,147
def isometric ( lat : float , ell : Ellipsoid = None , deg : bool = True ) : if ell is None : ell = Ellipsoid ( ) f = ell . f if deg is True : lat = np . deg2rad ( lat ) e2 = f * ( 2 - f ) e = np . sqrt ( e2 ) x = e * np . sin ( lat ) y = ( 1 - x ) / ( 1 + x ) z = np . pi / 4 + lat / 2 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
48,148
def loxodrome_inverse ( lat1 : float , lon1 : float , lat2 : float , lon2 : float , ell : Ellipsoid = None , deg : bool = True ) : if ell is None : ell = Ellipsoid ( ) if deg is True : lat1 , lon1 , lat2 , lon2 = np . radians ( [ lat1 , lon1 , lat2 , lon2 ] ) isolat1 = isometric ( lat1 , deg = False , ell = ell ) isolat2 = isometric ( lat2 , deg = False , ell = ell ) disolat = isolat2 - isolat1 dlon = lon2 - lon1 az12 = np . arctan2 ( dlon , disolat ) 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
48,149
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 ) 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
48,150
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 : 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 .
48,151
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}' ) 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 .
48,152
def handler ( event , context ) : records = deserialize_records ( event [ 'Records' ] ) update_records , delete_records = group_records_by_type ( records , UPDATE_EVENTS ) capture_delete_records ( delete_records ) update_records = [ e for e in update_records if not e [ 'detail' ] . get ( 'errorCode' ) ] 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 .
48,153
def default_diff ( latest_config , current_config ) : 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 .
48,154
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 .
48,155
def modify_record ( durable_model , current_revision , arn , event_time , diff_func ) : 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' ] current_config = current_revision . _get_json ( ) [ 1 ] [ 'attributes' ] 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 .
48,156
def deserialize_current_record_to_durable_model ( record , current_model , durable_model ) : 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 ( ) record = { 'dynamodb' : { 'NewImage' : serialized [ 'attributes' ] } } record [ 'dynamodb' ] [ 'NewImage' ] [ 'arn' ] = { 'S' : serialized [ 'HASH' ] } new_image = remove_current_specific_fields ( record [ 'dynamodb' ] [ 'NewImage' ] ) data = { } for item , value in new_image . items ( ) : 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 .
48,157
def deserialize_current_record_to_current_model ( record , current_model ) : 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 ( ) : 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 .
48,158
def deserialize_durable_record_to_durable_model ( record , durable_model ) : 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 ( ) : 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 .
48,159
def deserialize_durable_record_to_current_model ( record , current_model ) : if record . get ( EVENT_TOO_BIG_FLAG ) : 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 ( ) : 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 .
48,160
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 .
48,161
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 .
48,162
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
48,163
def serialize ( self , value ) : if isinstance ( value , str ) : return value return value . strftime ( DATETIME_FORMAT )
Takes a datetime object and returns a string
48,164
def pull_tag_dict ( data ) : 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 .
48,165
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 .
48,166
def process_delete_records ( delete_records ) : for rec in delete_records : arn = f"arn:aws:s3:::{rec['detail']['requestParameters']['bucketName']}" 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
48,167
def process_update_records ( update_records ) : events = sorted ( update_records , key = lambda x : x [ 'account' ] ) for account_id , events in groupby ( events , lambda x : x [ 'account' ] ) : events = list ( events ) buckets = { } for event in events : bucket_event = buckets . get ( event [ 'detail' ] [ 'requestParameters' ] [ 'bucketName' ] , { 'creationDate' : event [ 'detail' ] [ 'requestParameters' ] . get ( 'creationDate' ) } ) bucket_event . update ( event [ 'detail' ] [ 'requestParameters' ] ) buckets [ event [ 'detail' ] [ 'requestParameters' ] [ 'bucketName' ] ] = bucket_event buckets [ event [ 'detail' ] [ 'requestParameters' ] [ 'bucketName' ] ] [ 'eventDetails' ] = event for b_name , item in buckets . items ( ) : LOG . debug ( f'[~] Processing Create/Update for: {b_name}' ) try : bucket_details = get_bucket ( b_name , account_number = account_id , include_created = ( item . get ( 'creationDate' ) is None ) , assume_role = HISTORICAL_ROLE , region = CURRENT_REGION ) if bucket_details . get ( 'Error' ) : LOG . error ( f"[X] Unable to fetch details about bucket: {b_name}. " f"The error details are: {bucket_details['Error']}" ) continue except ClientError as cerr : if cerr . response [ 'Error' ] [ 'Code' ] == 'NoSuchBucket' : LOG . warning ( f'[?] Received update request for bucket: {b_name} that does not ' 'currently exist. Skipping.' ) continue if cerr . response [ 'Error' ] [ 'Code' ] == 'AccessDenied' : LOG . error ( f'[X] Unable to fetch details for S3 Bucket: {b_name} in {account_id}. Access is Denied. ' 'Skipping...' ) continue raise Exception ( cerr ) data = { 'arn' : f'arn:aws:s3:::{b_name}' , 'principalId' : cloudwatch . get_principal ( item [ 'eventDetails' ] ) , 'userIdentity' : cloudwatch . get_user_identity ( item [ 'eventDetails' ] ) , 'userAgent' : item [ 'eventDetails' ] [ 'detail' ] . get ( 'userAgent' ) , 'sourceIpAddress' : item [ 'eventDetails' ] [ 'detail' ] . get ( 'sourceIPAddress' ) , 'requestParameters' : item [ 'eventDetails' ] [ 'detail' ] . get ( 'requestParameters' ) , 'accountId' : account_id , 'eventTime' : item [ 'eventDetails' ] [ 'detail' ] [ 'eventTime' ] , 'BucketName' : b_name , 'Region' : bucket_details . pop ( 'Region' ) , 'Tags' : bucket_details . pop ( 'Tags' , { } ) or { } , 'eventSource' : item [ 'eventDetails' ] [ 'detail' ] [ 'eventSource' ] , 'eventName' : item [ 'eventDetails' ] [ 'detail' ] [ 'eventName' ] , 'version' : VERSION } del bucket_details [ 'Arn' ] del bucket_details [ 'GrantReferences' ] del bucket_details [ '_version' ] del bucket_details [ 'Name' ] if not bucket_details . get ( 'CreationDate' ) : bucket_details [ 'CreationDate' ] = item [ 'creationDate' ] data [ 'configuration' ] = bucket_details current_revision = CurrentS3Model ( ** data ) current_revision . save ( )
Process the requests for S3 bucket update requests
48,168
def handler ( event , context ) : records = deserialize_records ( event [ '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 .
48,169
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 .
48,170
def poller_processor_handler ( event , context ) : 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 : try : 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 .
48,171
def detect_global_table_updates ( record ) : if record [ 'eventName' ] == 'MODIFY' : 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 .
48,172
def handler ( event , context ) : records = deserialize_records ( event [ 'Records' ] ) for record in records : process_dynamodb_differ_record ( record , CurrentS3Model , DurableS3Model )
Historical S3 event differ .
48,173
def new ( ) : dir_path = os . path . dirname ( os . path . realpath ( __file__ ) ) cookiecutter ( os . path . join ( dir_path , 'historical-cookiecutter/' ) )
Creates a new historical technology .
48,174
def poller_tasker_handler ( event , context ) : 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 .
48,175
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 .
48,176
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 .
48,177
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 .
48,178
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 ) if cloudwatch . get_collected_details ( record ) : LOG . debug ( f"[<--] Received already collected security group data: {record['detail']['collected']}" ) return [ record [ 'detail' ] [ 'collected' ] ] try : if group_id : 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 .
48,179
def create_delete_model ( record ) : data = cloudwatch . get_historical_base_info ( record ) group_id = cloudwatch . filter_request_parameters ( 'groupId' , record ) arn = get_arn ( group_id , cloudwatch . get_region ( record ) , record [ 'account' ] ) LOG . debug ( f'[-] Deleting Dynamodb Records. Hash Key: {arn}' ) 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 .
48,180
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 .
48,181
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 not val and look_in_response : if msg [ 'detail' ] . get ( 'responseElements' ) : val = msg [ 'detail' ] [ 'responseElements' ] . get ( field_name , 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 .
48,182
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 .
48,183
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 ] split_idx = __class__ . findLastCharIndexMatching ( cur_text , lambda x : unicodedata . category ( x ) in ( "Ps" , "Pe" , "Pi" , "Pf" , "Po" ) ) if split_idx is None : split_idx = __class__ . findLastCharIndexMatching ( cur_text , lambda x : unicodedata . category ( x ) . startswith ( "Z" ) ) if split_idx is None : split_idx = __class__ . findLastCharIndexMatching ( cur_text , lambda x : not ( unicodedata . category ( x ) [ 0 ] in ( "L" , "N" ) ) ) if split_idx is None : 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 .
48,184
def play ( self , sox_effects = ( ) ) : preloader_threads = [ ] if self . text != "-" : segments = list ( self ) 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 ) for segment in segments : segment . play ( sox_effects ) if self . text != "-" : for preloader_thread in preloader_threads : preloader_thread . join ( )
Play a speech .
48,185
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 .
48,186
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 .
48,187
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 .
48,188
def play ( self , sox_effects = ( ) ) : audio_data = self . getAudioData ( ) logging . getLogger ( ) . info ( "Playing speech segment (%s): '%s'" % ( self . lang , self ) ) cmd = [ "sox" , "-q" , "-t" , "mp3" , "-" ] if sys . platform . startswith ( "win32" ) : cmd . extend ( ( "-t" , "waveaudio" ) ) cmd . extend ( ( "-d" , "trim" , "0.1" , "reverse" , "trim" , "0.07" , "reverse" ) ) cmd . extend ( sox_effects ) logging . getLogger ( ) . debug ( "Start player process" ) p = subprocess . Popen ( cmd , stdin = subprocess . PIPE , stdout = subprocess . DEVNULL ) p . communicate ( input = audio_data ) if p . returncode != 0 : raise RuntimeError ( ) logging . getLogger ( ) . debug ( "Done playing" )
Play the segment .
48,189
def buildUrl ( self , cache_friendly = False ) : params = collections . OrderedDict ( ) params [ "client" ] = "tw-ob" params [ "ie" ] = "UTF-8" params [ "idx" ] = str ( self . segment_num ) if self . segment_count is not None : params [ "total" ] = str ( self . segment_count ) params [ "textlen" ] = str ( len ( self . text ) ) params [ "tl" ] = self . lang lower_text = self . text . lower ( ) params [ "q" ] = lower_text return "%s?%s" % ( __class__ . BASE_URL , urllib . parse . urlencode ( params ) )
Construct the URL to get the sound from Goggle API .
48,190
def download ( self , url ) : logging . getLogger ( ) . debug ( "Downloading '%s'..." % ( url ) ) response = __class__ . session . get ( url , headers = { "User-Agent" : "Mozilla/5.0" } , timeout = 3.1 ) response . raise_for_status ( ) return response . content
Download a sound file .
48,191
def to_param_dict ( self ) : param_dict = { } for index , dictionary in enumerate ( self . value ) : for key , value in dictionary . items ( ) : param_name = '{param_name}[{index}][{key}]' . format ( param_name = self . param_name , index = index , key = key ) param_dict [ param_name ] = value return OrderedDict ( sorted ( param_dict . items ( ) ) )
Sorts to ensure Order is consistent for Testing
48,192
def _get ( cls , kwarg_name ) : param_classes = cls . _discover_params ( ) try : param_class = param_classes [ kwarg_name ] except KeyError : raise ValueError ( 'invalid param keyword {}' . format ( kwarg_name ) ) else : return param_class
Returns a Param Class Instance by its kwarg or param name
48,193
def _process_params ( self , params ) : new_params = OrderedDict ( ) for param_name , param_value in sorted ( params . items ( ) ) : param_value = params [ param_name ] ParamClass = AirtableParams . _get ( param_name ) new_params . update ( ParamClass ( param_value ) . to_param_dict ( ) ) return new_params
Process params names or values as needed using filters
48,194
def _batch_request ( self , func , iterable ) : responses = [ ] for item in iterable : responses . append ( func ( item ) ) time . sleep ( self . API_LIMIT ) return responses
Internal Function to limit batch calls to API limit
48,195
def _add_members ( self , catmembers ) : members = [ x for x in catmembers if x [ 'ns' ] == 0 ] subcats = [ x for x in catmembers if x [ 'ns' ] == 14 ] if 'members' in self . data : self . data [ 'members' ] . extend ( members ) else : self . data . update ( { 'members' : members } ) if subcats : if 'subcategories' in self . data : self . data [ 'subcategories' ] . extend ( subcats ) else : self . data . update ( { 'subcategories' : subcats } )
Adds category members and subcategories to data
48,196
def _query ( self , action , qobj ) : title = self . params . get ( 'title' ) pageid = self . params . get ( 'pageid' ) if action == 'random' : return qobj . random ( namespace = 14 ) elif action == 'category' : return qobj . category ( title , pageid , self . _continue_params ( ) )
Form query to enumerate category
48,197
def _set_data ( self , action ) : data = self . _load_response ( action ) self . _handle_continuations ( data , 'category' ) if action == 'category' : members = data . get ( 'query' ) . get ( 'categorymembers' ) if members : self . _add_members ( members ) if action == 'random' : rand = data [ 'query' ] [ 'random' ] [ 0 ] data = { 'pageid' : rand . get ( 'id' ) , 'title' : rand . get ( 'title' ) } self . data . update ( data ) self . params . update ( data )
Set category member data from API response
48,198
def _sitelist ( self , matrix ) : _list = [ ] for item in matrix : sites = [ ] if isinstance ( matrix [ item ] , list ) : sites = matrix [ item ] elif isinstance ( matrix [ item ] , dict ) : sites = matrix [ item ] [ 'site' ] for site in sites : if len ( site . keys ( ) ) > 4 : continue domain = self . params . get ( 'domain' ) if domain : if domain in site [ 'url' ] : _list . append ( site [ 'url' ] ) else : _list . append ( site [ 'url' ] ) return _list
Returns a list of sites from a SiteMatrix optionally filtered by domain param
48,199
def handle_wikidata_errors ( data , query ) : entities = data . get ( 'entities' ) if not entities : raise LookupError ( query ) elif '-1' in entities : raise LookupError ( query ) else : item = list ( entities . values ( ) ) [ 0 ] if 'missing' in item : errmsg = "wikidata item %s has been deleted" % item [ 'id' ] raise LookupError ( errmsg )
Raises LookupError if wikidata error found