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 ( dir... | 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' , F... | 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 ( "Unab... | 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 >... | 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 ... | 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 : resul... | 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... | 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... | 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 ( ... | 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'... | 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... | 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 ] ... | 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... | 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... | 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' , longitud... | 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 ... | 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... | 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 ) ... | 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 ... | 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 s... | 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 sa... | 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 , ... | 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 ) ) ... | 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 = enu2uv... | 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 ... | 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 ) isola... | 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 ... | 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 ... | 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 . ... | 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... | 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 ... | 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 = { 'dynam... | 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 = { }... | 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_spec... | 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 i... | 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... | 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 ( recor... | 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' ] [ 'even... | 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' ] [ 'requestPara... | 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 recor... | 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' ) }... | 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 = rec... | 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 ) == jso... | 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 ( ) : f... | 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 . se... | 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 ) ... | 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}' ) d... | 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' ) ... | 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'... | 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 (... | 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 pr... | 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 = se... | 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 ( ( "... | 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 . ... | 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 ( sort... | 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 ... | 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' ] [ ... | 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 ( '... | 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' ] rais... | Raises LookupError if wikidata error found |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.