idx int64 0 63k | question stringlengths 53 5.28k | target stringlengths 5 805 |
|---|---|---|
27,900 | def _find_closest_trackpoint ( self , R , vR , vT , z , vz , phi , interp = True , xy = False , usev = False ) : return self . find_closest_trackpoint ( R , vR , vT , z , vz , phi , interp = interp , xy = xy , usev = usev ) | For backward compatibility |
27,901 | def _density_par ( self , dangle , tdisrupt = None ) : if tdisrupt is None : tdisrupt = self . _tdisrupt dOmin = dangle / tdisrupt return 0.5 * ( 1. + special . erf ( ( self . _meandO - dOmin ) / numpy . sqrt ( 2. * self . _sortedSigOEig [ 2 ] ) ) ) | The raw density as a function of parallel angle |
27,902 | def _sample_aAt ( self , n ) : dO1s = bovy_ars . bovy_ars ( [ 0. , 0. ] , [ True , False ] , [ self . _meandO - numpy . sqrt ( self . _sortedSigOEig [ 2 ] ) , self . _meandO + numpy . sqrt ( self . _sortedSigOEig [ 2 ] ) ] , _h_ars , _hp_ars , nsamples = n , hxparams = ( self . _meandO , self . _sortedSigOEig [ 2 ] ) ,... | Sampling frequencies angles and times part of sampling |
27,903 | def _check_consistent_units ( self ) : if isinstance ( self . _pot , list ) : if self . _roSet and self . _pot [ 0 ] . _roSet : assert m . fabs ( self . _ro - self . _pot [ 0 ] . _ro ) < 10. ** - 10. , 'Physical conversion for the actionAngle object is not consistent with that of the Potential given to it' if self . _v... | Internal function to check that the set of units for this object is consistent with that for the potential |
27,904 | def _check_consistent_units_orbitInput ( self , orb ) : if self . _roSet and orb . _roSet : assert m . fabs ( self . _ro - orb . _ro ) < 10. ** - 10. , 'Physical conversion for the actionAngle object is not consistent with that of the Orbit given to it' if self . _voSet and orb . _voSet : assert m . fabs ( self . _vo -... | Internal function to check that the set of units for this object is consistent with that for an input orbit |
27,905 | def check_inputs_not_arrays ( func ) : @ wraps ( func ) def func_wrapper ( self , R , z , phi , t ) : if ( hasattr ( R , '__len__' ) and len ( R ) > 1 ) or ( hasattr ( z , '__len__' ) and len ( z ) > 1 ) or ( hasattr ( phi , '__len__' ) and len ( phi ) > 1 ) or ( hasattr ( t , '__len__' ) and len ( t ) > 1 ) : raise Ty... | Decorator to check inputs and throw TypeError if any of the inputs are arrays . Methods potentially return with silent errors if inputs are not checked . |
27,906 | def _JRAxiIntegrand ( r , E , L , pot ) : return nu . sqrt ( 2. * ( E - potentialAxi ( r , pot ) ) - L ** 2. / r ** 2. ) | The J_R integrand |
27,907 | def _rapRperiAxiEq ( R , E , L , pot ) : return E - potentialAxi ( R , pot ) - L ** 2. / 2. / R ** 2. | The vr = 0 equation that needs to be solved to find apo - and pericenter |
27,908 | def _rlfunc ( rl , lz , pot ) : thisvcirc = vcirc ( pot , rl , use_physical = False ) return rl * thisvcirc - lz | Function that gives rvc - lz |
27,909 | def _rlFindStart ( rl , lz , pot , lower = False ) : rtry = 2. * rl while ( 2. * lower - 1. ) * _rlfunc ( rtry , lz , pot ) > 0. : if lower : rtry /= 2. else : rtry *= 2. return rtry | find a starting interval for rl |
27,910 | def _check_roSet ( orb , kwargs , funcName ) : if not orb . _roSet and kwargs . get ( 'ro' , None ) is None : warnings . warn ( "Method %s(.) requires ro to be given at Orbit initialization or at method evaluation; using default ro which is %f kpc" % ( funcName , orb . _ro ) , galpyWarning ) | Function to check whether ro is set because it s required for funcName |
27,911 | def _check_voSet ( orb , kwargs , funcName ) : if not orb . _voSet and kwargs . get ( 'vo' , None ) is None : warnings . warn ( "Method %s(.) requires vo to be given at Orbit initialization or at method evaluation; using default vo which is %f km/s" % ( funcName , orb . _vo ) , galpyWarning ) | Function to check whether vo is set because it s required for funcName |
27,912 | def _radec ( self , * args , ** kwargs ) : lbd = self . _lbd ( * args , ** kwargs ) return coords . lb_to_radec ( lbd [ : , 0 ] , lbd [ : , 1 ] , degree = True , epoch = None ) | Calculate ra and dec |
27,913 | def _pmrapmdec ( self , * args , ** kwargs ) : lbdvrpmllpmbb = self . _lbdvrpmllpmbb ( * args , ** kwargs ) return coords . pmllpmbb_to_pmrapmdec ( lbdvrpmllpmbb [ : , 4 ] , lbdvrpmllpmbb [ : , 5 ] , lbdvrpmllpmbb [ : , 0 ] , lbdvrpmllpmbb [ : , 1 ] , degree = True , epoch = None ) | Calculate pmra and pmdec |
27,914 | def _lbd ( self , * args , ** kwargs ) : obs , ro , vo = self . _parse_radec_kwargs ( kwargs , dontpop = True ) X , Y , Z = self . _helioXYZ ( * args , ** kwargs ) bad_indx = ( X == 0. ) * ( Y == 0. ) * ( Z == 0. ) if True in bad_indx : X [ bad_indx ] += ro / 10000. return coords . XYZ_to_lbd ( X , Y , Z , degree = Tru... | Calculate l b and d |
27,915 | def _lbdvrpmllpmbb ( self , * args , ** kwargs ) : obs , ro , vo = self . _parse_radec_kwargs ( kwargs , dontpop = True ) X , Y , Z , vX , vY , vZ = self . _XYZvxvyvz ( * args , ** kwargs ) bad_indx = ( X == 0. ) * ( Y == 0. ) * ( Z == 0. ) if True in bad_indx : X [ bad_indx ] += ro / 10000. return coords . rectgal_to_... | Calculate l b d vr pmll pmbb |
27,916 | def _parse_plot_quantity ( self , quant , ** kwargs ) : kwargs [ 'quantity' ] = False if callable ( quant ) : return quant ( self . t ) def _eval ( q ) : if q == 't' : return self . time ( self . t , ** kwargs ) elif q == 'Enorm' : return self . E ( self . t , ** kwargs ) / self . E ( 0. , ** kwargs ) elif q == 'Eznorm... | Internal function to parse a quantity to be plotted based on input data |
27,917 | def _jmomentdensity ( self , R , z , n , m , o , nsigma = None , mc = True , nmc = 10000 , _returnmc = False , _vrs = None , _vts = None , _vzs = None , ** kwargs ) : if nsigma == None : nsigma = _NSIGMA sigmaR1 = self . _sr * numpy . exp ( ( self . _refr - R ) / self . _hsr ) sigmaz1 = self . _sz * numpy . exp ( ( sel... | Non - physical version of jmomentdensity otherwise the same |
27,918 | def impact_check_range ( func ) : @ wraps ( func ) def impact_wrapper ( * args , ** kwargs ) : if isinstance ( args [ 1 ] , numpy . ndarray ) : out = numpy . zeros ( len ( args [ 1 ] ) ) goodIndx = ( args [ 1 ] < args [ 0 ] . _deltaAngleTrackImpact ) * ( args [ 1 ] > 0. ) out [ goodIndx ] = func ( args [ 0 ] , args [ 1... | Decorator to check the range of interpolated kicks |
27,919 | def _density_par ( self , dangle , tdisrupt = None , approx = True , higherorder = None ) : if higherorder is None : higherorder = self . _higherorderTrack if tdisrupt is None : tdisrupt = self . _tdisrupt if approx : return self . _density_par_approx ( dangle , tdisrupt , higherorder = higherorder ) else : return inte... | The raw density as a function of parallel angle approx = use faster method that directly integrates the spline representation |
27,920 | def _density_par_approx ( self , dangle , tdisrupt , _return_array = False , higherorder = False ) : Oparb = ( dangle - self . _kick_interpdOpar_poly . x ) / self . _timpact lowbindx , lowx = self . minOpar ( dangle , tdisrupt , _return_raw = True ) lowbindx = numpy . arange ( len ( Oparb ) - 1 ) [ lowbindx ] Oparb [ l... | Compute the density as a function of parallel angle using the spline representation + approximations |
27,921 | def _density_par_approx_higherorder ( self , Oparb , lowbindx , _return_array = False , gaussxpolyInt = None ) : spline_order = self . _kick_interpdOpar_raw . _eval_args [ 2 ] if spline_order == 1 : return 0. ll = ( numpy . roll ( Oparb , - 1 ) [ : - 1 ] - self . _kick_interpdOpar_poly . c [ - 1 ] - self . _meandO - se... | Contribution from non - linear spline terms |
27,922 | def _densMoments_approx_higherorder_gaussxpolyInts ( self , ll , ul , maxj ) : gaussxpolyInt = numpy . zeros ( ( maxj , len ( ul ) ) ) gaussxpolyInt [ - 1 ] = 1. / numpy . sqrt ( numpy . pi ) * ( numpy . exp ( - ll ** 2. ) - numpy . exp ( - ul ** 2. ) ) gaussxpolyInt [ - 2 ] = 1. / numpy . sqrt ( numpy . pi ) * ( numpy... | Calculate all of the polynomial x Gaussian integrals occuring in the higher - order terms recursively |
27,923 | def _meanOmega_num_approx ( self , dangle , tdisrupt , higherorder = False ) : Oparb = ( dangle - self . _kick_interpdOpar_poly . x ) / self . _timpact lowbindx , lowx = self . minOpar ( dangle , tdisrupt , _return_raw = True ) lowbindx = numpy . arange ( len ( Oparb ) - 1 ) [ lowbindx ] Oparb [ lowbindx + 1 ] = Oparb ... | Compute the numerator going into meanOmega using the direct integration of the spline representation |
27,924 | def _interpolate_stream_track_kick_aA ( self ) : if hasattr ( self , '_kick_interpolatedObsTrackAA' ) : return None dmOs = numpy . array ( [ super ( streamgapdf , self ) . meanOmega ( da , oned = True , tdisrupt = self . _tdisrupt - self . _timpact , use_physical = False ) for da in self . _kick_interpolatedThetasTrack... | Build interpolations of the stream track near the impact in action - angle coordinates |
27,925 | def _gap_progenitor_setup ( self ) : self . _gap_progenitor = self . _progenitor ( ) . flip ( ) self . _gap_progenitor . turn_physical_off ( ) ts = numpy . linspace ( 0. , self . _tdisrupt , 1001 ) self . _gap_progenitor . integrate ( ts , self . _pot ) self . _gap_progenitor . _orb . orbit [ : , 1 ] = - self . _gap_pr... | Setup an Orbit instance that s the progenitor integrated backwards |
27,926 | def _sample_aAt ( self , n ) : Om , angle , dt = super ( streamgapdf , self ) . _sample_aAt ( n ) dangle_at_impact = angle - numpy . tile ( self . _progenitor_angle . T , ( n , 1 ) ) . T - ( Om - numpy . tile ( self . _progenitor_Omega . T , ( n , 1 ) ) . T ) * self . _timpact dangle_par_at_impact = numpy . dot ( dangl... | Sampling frequencies angles and times part of sampling for stream with gap |
27,927 | def worker ( f , ii , chunk , out_q , err_q , lock ) : vals = [ ] for val in chunk : try : result = f ( val ) except Exception as e : err_q . put ( e ) return vals . append ( result ) out_q . put ( ( ii , vals ) ) | A worker function that maps an input function over a slice of the input iterable . |
27,928 | def run_tasks ( procs , err_q , out_q , num ) : die = ( lambda vals : [ val . terminate ( ) for val in vals if val . exitcode is None ] ) try : for proc in procs : proc . start ( ) for proc in procs : proc . join ( ) except Exception as e : try : die ( procs ) finally : raise e if not err_q . empty ( ) : try : die ( pr... | A function that executes populated processes and processes the resultant array . Checks error queue for any exceptions . |
27,929 | def parallel_map ( function , sequence , numcores = None ) : if not callable ( function ) : raise TypeError ( "input function '%s' is not callable" % repr ( function ) ) if not numpy . iterable ( sequence ) : raise TypeError ( "input '%s' is not iterable" % repr ( sequence ) ) size = len ( sequence ) if not _multi or s... | A parallelized version of the native Python map function that utilizes the Python multiprocessing module to divide and conquer sequence . |
27,930 | def _u0Eq ( logu , delta , pot , E , Lz22 ) : u = numpy . exp ( logu ) sinh2u = numpy . sinh ( u ) ** 2. cosh2u = numpy . cosh ( u ) ** 2. dU = cosh2u * actionAngleStaeckel . potentialStaeckel ( u , numpy . pi / 2. , pot , delta ) return - ( E * sinh2u - dU - Lz22 / delta ** 2. / sinh2u ) | The equation that needs to be minimized to find u0 |
27,931 | def _JrSphericalIntegrand ( r , E , L , pot ) : return nu . sqrt ( 2. * ( E - potentialAxi ( r , pot ) ) - L ** 2. / r ** 2. ) | The J_r integrand |
27,932 | def rot ( self , t = 0. , transposed = False ) : rotmat = np . array ( [ [ np . cos ( self . _pa + self . _omegab * t ) , np . sin ( self . _pa + self . _omegab * t ) ] , [ - np . sin ( self . _pa + self . _omegab * t ) , np . cos ( self . _pa + self . _omegab * t ) ] ] ) if transposed : return rotmat . T else : return... | 2D Rotation matrix for non - zero pa or pattern speed to goto the aligned coordinates |
27,933 | def _JzIntegrand ( z , Ez , pot ) : return nu . sqrt ( 2. * ( Ez - potentialVertical ( z , pot ) ) ) | The J_z integrand |
27,934 | def quoted ( s ) : s = s . strip ( u'"' ) if s [ 0 ] in ( u'-' , u' ' ) : return s if u' ' in s or u'/' in s : return u'"%s"' % s else : return s | quotes a string if necessary . |
27,935 | def install ( path , remove = False , prefix = sys . prefix , recursing = False ) : if sys . platform == 'win32' and not exists ( join ( sys . prefix , '.nonadmin' ) ) : if isUserAdmin ( ) : _install ( path , remove , prefix , mode = 'system' ) else : from pywintypes import error try : if not recursing : retcode = runA... | install Menu and shortcuts |
27,936 | def add_child ( parent , tag , text = None ) : elem = ET . SubElement ( parent , tag ) if text is not None : elem . text = text return elem | Add a child element of specified tag type to parent . The new child element is returned . |
27,937 | def _writePlistInfo ( self ) : pl = Plist ( CFBundleExecutable = self . executable , CFBundleGetInfoString = '%s-1.0.0' % self . name , CFBundleIconFile = basename ( self . icns ) , CFBundleIdentifier = 'com.%s' % self . name , CFBundlePackageType = 'APPL' , CFBundleVersion = '1.0.0' , CFBundleShortVersionString = '1.0... | Writes the Info . plist file in the Contests directory . |
27,938 | def readlines ( self , offset = 0 ) : try : with open ( self . _filepath ) as fp : if self . _full_read : fp . seek ( offset ) for row in fp : yield row if self . _tail : while True : current = fp . tell ( ) row = fp . readline ( ) if row : yield row else : fp . seek ( current ) time . sleep ( self . _sleep ) except IO... | Open the file for reading and yield lines as they are added |
27,939 | def get_files ( dir_name ) : return [ ( os . path . join ( '.' , d ) , [ os . path . join ( d , f ) for f in files ] ) for d , _ , files in os . walk ( dir_name ) ] | Simple directory walker |
27,940 | def readrows ( self ) : for self . _filepath in self . _files : tmp = None if self . _filepath . endswith ( '.gz' ) : tmp = tempfile . NamedTemporaryFile ( delete = False ) with gzip . open ( self . _filepath , 'rb' ) as f_in , open ( tmp . name , 'wb' ) as f_out : shutil . copyfileobj ( f_in , f_out ) self . _filepath... | The readrows method reads simply combines the rows of multiple files OR gunzips the file and then reads the rows |
27,941 | def most_recent ( path , startswith = None , endswith = None ) : candidate_files = [ ] for filename in all_files_in_directory ( path ) : if startswith and not os . path . basename ( filename ) . startswith ( startswith ) : continue if endswith and not filename . endswith ( endswith ) : continue candidate_files . append... | Recursively inspect all files under a directory and return the most recent |
27,942 | def yara_match ( file_path , rules ) : print ( 'New Extracted File: {:s}' . format ( file_path ) ) print ( 'Mathes:' ) pprint ( rules . match ( file_path ) ) | Callback for a newly extracted file |
27,943 | def readrows ( self ) : num_rows = 0 while True : for row in self . log_reader . readrows ( ) : yield self . replace_timestamp ( row ) time . sleep ( next ( self . eps_timer ) ) num_rows += 1 if self . max_rows and ( num_rows >= self . max_rows ) : return | Using the BroLogReader this method yields each row of the log file replacing timestamps looping and emitting rows based on EPS rate |
27,944 | def _parse_bro_header ( self , bro_log ) : with open ( bro_log , 'r' ) as bro_file : _line = bro_file . readline ( ) while not _line . startswith ( '#fields' ) : _line = bro_file . readline ( ) field_names = _line . strip ( ) . split ( self . _delimiter ) [ 1 : ] _line = bro_file . readline ( ) field_types = _line . st... | Parse the Bro log header section . |
27,945 | def make_dict ( self , field_values ) : data_dict = { } for key , value , field_type , converter in zip ( self . field_names , field_values , self . field_types , self . type_converters ) : try : data_dict [ key ] = self . dash_mapper . get ( field_type , '-' ) if value == '-' else converter ( value ) except ValueError... | Internal method that makes sure any dictionary elements are properly cast into the correct types . |
27,946 | def str_to_mac ( mac_string ) : sp = mac_string . split ( ':' ) mac_string = '' . join ( sp ) return binascii . unhexlify ( mac_string ) | Convert a readable string to a MAC address |
27,947 | def inet_to_str ( inet ) : try : return socket . inet_ntop ( socket . AF_INET , inet ) except ValueError : return socket . inet_ntop ( socket . AF_INET6 , inet ) | Convert inet object to a string |
27,948 | def str_to_inet ( address ) : try : return socket . inet_pton ( socket . AF_INET , address ) except socket . error : return socket . inet_pton ( socket . AF_INET6 , address ) | Convert an a string IP address to a inet struct |
27,949 | def signal_catcher ( callback ) : def _catch_exit_signal ( sig_num , _frame ) : print ( 'Received signal {:d} invoking callback...' . format ( sig_num ) ) callback ( ) signal . signal ( signal . SIGINT , _catch_exit_signal ) signal . signal ( signal . SIGQUIT , _catch_exit_signal ) signal . signal ( signal . SIGTERM , ... | Catch signals and invoke the callback method |
27,950 | def entropy ( string ) : p , lns = Counter ( string ) , float ( len ( string ) ) return - sum ( count / lns * math . log ( count / lns , 2 ) for count in p . values ( ) ) | Compute entropy on the string |
27,951 | def on_any_event ( self , event ) : if os . path . isfile ( event . src_path ) : self . callback ( event . src_path , ** self . kwargs ) | File created or modified |
27,952 | def lookup ( self , ip_address ) : if self . ip_lookup_cache . get ( ip_address ) : domain = self . ip_lookup_cache . get ( ip_address ) elif not self . lookup_internal and net_utils . is_internal ( ip_address ) : domain = 'internal' elif net_utils . is_special ( ip_address ) : domain = net_utils . is_special ( ip_addr... | Try to do a reverse dns lookup on the given ip_address |
27,953 | def add_rows ( self , list_of_rows ) : for row in list_of_rows : self . row_deque . append ( row ) self . time_deque . append ( time . time ( ) ) self . update ( ) | Add a list of rows to the DataFrameCache class |
27,954 | def update ( self ) : expire_time = time . time ( ) - self . max_time while self . row_deque and self . time_deque [ 0 ] < expire_time : self . row_deque . popleft ( ) self . time_deque . popleft ( ) | Update the deque removing rows based on time |
27,955 | def _compress ( self ) : now = time . time ( ) if self . _last_compression + self . _compression_timer < now : self . _last_compression = now for key in list ( self . _store . keys ( ) ) : self . get ( key ) | Internal method to compress the cache . This method will expire any old items in the cache making the cache smaller |
27,956 | def save_vtq ( ) : global vtq print ( 'Saving VirusTotal Query Cache...' ) pickle . dump ( vtq , open ( 'vtq.pkl' , 'wb' ) , protocol = pickle . HIGHEST_PROTOCOL ) sys . exit ( ) | Exit on Signal |
27,957 | def fit_transform ( self , df ) : self . index_ = df . index self . columns_ = df . columns self . cat_columns_ = df . select_dtypes ( include = [ 'category' ] ) . columns self . non_cat_columns_ = df . columns . drop ( self . cat_columns_ ) self . cat_map_ = { col : df [ col ] . cat for col in self . cat_columns_ } le... | Fit method for the DummyEncoder |
27,958 | def _make_df ( rows ) : df = pd . DataFrame ( rows ) . set_index ( 'ts' ) for column in df . columns : if ( df [ column ] . dtype == 'timedelta64[ns]' ) : print ( 'Converting timedelta column {:s}...' . format ( column ) ) df [ column ] = df [ column ] . astype ( str ) return df | Internal Method to make and clean the dataframe in preparation for sending to Parquet |
27,959 | def create_queue ( self , credentials ) : if credentials : session = self . session or aiohttp . ClientSession ( loop = self . event_loop ) return Queue ( options = { 'credentials' : credentials , 'rootUrl' : self . config [ 'taskcluster_root_url' ] , } , session = session ) | Create a taskcluster queue . |
27,960 | def write_json ( self , path , contents , message ) : log . debug ( message . format ( path = path ) ) makedirs ( os . path . dirname ( path ) ) with open ( path , "w" ) as fh : json . dump ( contents , fh , indent = 2 , sort_keys = True ) | Write json to disk . |
27,961 | async def populate_projects ( self , force = False ) : if force or not self . projects : with tempfile . TemporaryDirectory ( ) as tmpdirname : self . projects = await load_json_or_yaml_from_url ( self , self . config [ 'project_configuration_url' ] , os . path . join ( tmpdirname , 'projects.yml' ) ) | Download the projects . yml file and populate self . projects . |
27,962 | async def do_run_task ( context , run_cancellable , to_cancellable_process ) : status = 0 try : if context . config [ 'verify_chain_of_trust' ] : chain = ChainOfTrust ( context , context . config [ 'cot_job_type' ] ) await run_cancellable ( verify_chain_of_trust ( chain ) ) status = await run_task ( context , to_cancel... | Run the task logic . |
27,963 | async def do_upload ( context , files ) : status = 0 try : await upload_artifacts ( context , files ) except ScriptWorkerException as e : status = worst_level ( status , e . exit_code ) log . error ( "Hit ScriptWorkerException: {}" . format ( e ) ) except aiohttp . ClientError as e : status = worst_level ( status , STA... | Upload artifacts and return status . |
27,964 | async def run_tasks ( context ) : running_tasks = RunTasks ( ) context . running_tasks = running_tasks status = await running_tasks . invoke ( context ) context . running_tasks = None return status | Run any tasks returned by claimWork . |
27,965 | async def async_main ( context , credentials ) : conn = aiohttp . TCPConnector ( limit = context . config [ 'aiohttp_max_connections' ] ) async with aiohttp . ClientSession ( connector = conn ) as session : context . session = session context . credentials = credentials await run_tasks ( context ) | Set up and run tasks for this iteration . |
27,966 | async def invoke ( self , context ) : try : tasks = await self . _run_cancellable ( claim_work ( context ) ) if not tasks or not tasks . get ( 'tasks' , [ ] ) : await self . _run_cancellable ( asyncio . sleep ( context . config [ 'poll_interval' ] ) ) return None status = None for task_defn in tasks . get ( 'tasks' , [... | Claims and processes Taskcluster work . |
27,967 | async def cancel ( self ) : self . is_cancelled = True if self . future is not None : self . future . cancel ( ) if self . task_process is not None : log . warning ( "Worker is shutting down, but a task is running. Terminating task" ) await self . task_process . worker_shutdown_stop ( ) | Cancel current work . |
27,968 | async def request ( context , url , timeout = 60 , method = 'get' , good = ( 200 , ) , retry = tuple ( range ( 500 , 512 ) ) , return_type = 'text' , ** kwargs ) : session = context . session loggable_url = get_loggable_url ( url ) async with async_timeout . timeout ( timeout ) : log . debug ( "{} {}" . format ( method... | Async aiohttp request wrapper . |
27,969 | async def retry_request ( * args , retry_exceptions = ( asyncio . TimeoutError , ScriptWorkerRetryException ) , retry_async_kwargs = None , ** kwargs ) : retry_async_kwargs = retry_async_kwargs or { } return await retry_async ( request , retry_exceptions = retry_exceptions , args = args , kwargs = kwargs , ** retry_asy... | Retry the request function . |
27,970 | def makedirs ( path ) : if path : if not os . path . exists ( path ) : log . debug ( "makedirs({})" . format ( path ) ) os . makedirs ( path ) else : realpath = os . path . realpath ( path ) if not os . path . isdir ( realpath ) : raise ScriptWorkerException ( "makedirs: {} already exists and is not a directory!" . for... | Equivalent to mkdir - p . |
27,971 | def rm ( path ) : if path and os . path . exists ( path ) : if os . path . isdir ( path ) : shutil . rmtree ( path ) else : os . remove ( path ) | Equivalent to rm - rf . |
27,972 | def cleanup ( context ) : for name in 'work_dir' , 'artifact_dir' , 'task_log_dir' : path = context . config [ name ] if os . path . exists ( path ) : log . debug ( "rm({})" . format ( path ) ) rm ( path ) makedirs ( path ) | Clean up the work_dir and artifact_dir between task runs then recreate . |
27,973 | def calculate_sleep_time ( attempt , delay_factor = 5.0 , randomization_factor = .5 , max_delay = 120 ) : if attempt <= 0 : return 0 delay = float ( 2 ** ( attempt - 1 ) ) * float ( delay_factor ) delay = delay * ( randomization_factor * random . random ( ) + 1 ) return min ( delay , max_delay ) | Calculate the sleep time between retries in seconds . |
27,974 | async def retry_async ( func , attempts = 5 , sleeptime_callback = calculate_sleep_time , retry_exceptions = Exception , args = ( ) , kwargs = None , sleeptime_kwargs = None ) : kwargs = kwargs or { } attempt = 1 while True : try : return await func ( * args , ** kwargs ) except retry_exceptions : attempt += 1 if attem... | Retry func where func is an awaitable . |
27,975 | def create_temp_creds ( client_id , access_token , start = None , expires = None , scopes = None , name = None ) : now = arrow . utcnow ( ) . replace ( minutes = - 10 ) start = start or now . datetime expires = expires or now . replace ( days = 31 ) . datetime scopes = scopes or [ 'assume:project:taskcluster:worker-tes... | Request temp TC creds with our permanent creds . |
27,976 | def filepaths_in_dir ( path ) : filepaths = [ ] for root , directories , filenames in os . walk ( path ) : for filename in filenames : filepath = os . path . join ( root , filename ) filepath = filepath . replace ( path , '' ) . lstrip ( '/' ) filepaths . append ( filepath ) return filepaths | Find all files in a directory and return the relative paths to those files . |
27,977 | def get_hash ( path , hash_alg = "sha256" ) : h = hashlib . new ( hash_alg ) with open ( path , "rb" ) as f : for chunk in iter ( functools . partial ( f . read , 4096 ) , b'' ) : h . update ( chunk ) return h . hexdigest ( ) | Get the hash of the file at path . |
27,978 | def load_json_or_yaml ( string , is_path = False , file_type = 'json' , exception = ScriptWorkerTaskException , message = "Failed to load %(file_type)s: %(exc)s" ) : if file_type == 'json' : _load_fh = json . load _load_str = json . loads else : _load_fh = yaml . safe_load _load_str = yaml . safe_load try : if is_path ... | Load json or yaml from a filehandle or string and raise a custom exception on failure . |
27,979 | def write_to_file ( path , contents , file_type = 'text' ) : FILE_TYPES = ( 'json' , 'text' , 'binary' ) if file_type not in FILE_TYPES : raise ScriptWorkerException ( "Unknown file_type {} not in {}!" . format ( file_type , FILE_TYPES ) ) if file_type == 'json' : contents = format_json ( contents ) if file_type == 'bi... | Write contents to path with optional formatting . |
27,980 | def read_from_file ( path , file_type = 'text' , exception = ScriptWorkerException ) : FILE_TYPE_MAP = { 'text' : 'r' , 'binary' : 'rb' } if file_type not in FILE_TYPE_MAP : raise exception ( "Unknown file_type {} not in {}!" . format ( file_type , FILE_TYPE_MAP ) ) try : with open ( path , FILE_TYPE_MAP [ file_type ] ... | Read from path . |
27,981 | async def download_file ( context , url , abs_filename , session = None , chunk_size = 128 ) : session = session or context . session loggable_url = get_loggable_url ( url ) log . info ( "Downloading %s" , loggable_url ) parent_dir = os . path . dirname ( abs_filename ) async with session . get ( url ) as resp : if res... | Download a file async . |
27,982 | def get_loggable_url ( url ) : loggable_url = url or "" for secret_string in ( "bewit=" , "AWSAccessKeyId=" , "access_token=" ) : parts = loggable_url . split ( secret_string ) loggable_url = parts [ 0 ] if loggable_url != url : loggable_url = "{}<snip>" . format ( loggable_url ) return loggable_url | Strip out secrets from taskcluster urls . |
27,983 | def match_url_regex ( rules , url , callback ) : parts = urlparse ( url ) path = unquote ( parts . path ) for rule in rules : if parts . scheme not in rule [ 'schemes' ] : continue if parts . netloc not in rule [ 'netlocs' ] : continue for regex in rule [ 'path_regexes' ] : m = re . search ( regex , path ) if m is None... | Given rules and a callback find the rule that matches the url . |
27,984 | def add_enumerable_item_to_dict ( dict_ , key , item ) : dict_ . setdefault ( key , [ ] ) if isinstance ( item , ( list , tuple ) ) : dict_ [ key ] . extend ( item ) else : dict_ [ key ] . append ( item ) | Add an item to a list contained in a dict . |
27,985 | def get_single_item_from_sequence ( sequence , condition , ErrorClass = ValueError , no_item_error_message = 'No item matched condition' , too_many_item_error_message = 'Too many items matched condition' , append_sequence_to_error_message = True ) : filtered_sequence = [ item for item in sequence if condition ( item ) ... | Return an item from a python sequence based on the given condition . |
27,986 | def get_task ( config ) : path = os . path . join ( config [ 'work_dir' ] , "task.json" ) message = "Can't read task from {}!\n%(exc)s" . format ( path ) contents = load_json_or_yaml ( path , is_path = True , message = message ) return contents | Read the task . json from work_dir . |
27,987 | def validate_json_schema ( data , schema , name = "task" ) : try : jsonschema . validate ( data , schema ) except jsonschema . exceptions . ValidationError as exc : raise ScriptWorkerTaskException ( "Can't validate {} schema!\n{}" . format ( name , str ( exc ) ) , exit_code = STATUSES [ 'malformed-payload' ] ) | Given data and a jsonschema let s validate it . |
27,988 | def validate_task_schema ( context , schema_key = 'schema_file' ) : schema_path = context . config schema_keys = schema_key . split ( '.' ) for key in schema_keys : schema_path = schema_path [ key ] task_schema = load_json_or_yaml ( schema_path , is_path = True ) log . debug ( 'Task is validated against this schema: {}... | Validate the task definition . |
27,989 | def validate_artifact_url ( valid_artifact_rules , valid_artifact_task_ids , url ) : def callback ( match ) : path_info = match . groupdict ( ) if 'taskId' in path_info and path_info [ 'taskId' ] not in valid_artifact_task_ids : return if 'filepath' not in path_info : return return path_info [ 'filepath' ] filepath = m... | Ensure a URL fits in given scheme netloc and path restrictions . |
27,990 | def sync_main ( async_main , config_path = None , default_config = None , should_validate_task = True , loop_function = asyncio . get_event_loop ) : context = _init_context ( config_path , default_config ) _init_logging ( context ) if should_validate_task : validate_task_schema ( context ) loop = loop_function ( ) loop... | Entry point for scripts using scriptworker . |
27,991 | async def stop ( self ) : pgid = - self . process . pid try : os . kill ( pgid , signal . SIGTERM ) await asyncio . sleep ( 1 ) os . kill ( pgid , signal . SIGKILL ) except ( OSError , ProcessLookupError ) : return | Stop the current task process . |
27,992 | def ed25519_private_key_from_string ( string ) : try : return Ed25519PrivateKey . from_private_bytes ( base64 . b64decode ( string ) ) except ( UnsupportedAlgorithm , Base64Error ) as exc : raise ScriptWorkerEd25519Error ( "Can't create Ed25519PrivateKey: {}!" . format ( str ( exc ) ) ) | Create an ed25519 private key from string which is a seed . |
27,993 | def ed25519_public_key_from_string ( string ) : try : return Ed25519PublicKey . from_public_bytes ( base64 . b64decode ( string ) ) except ( UnsupportedAlgorithm , Base64Error ) as exc : raise ScriptWorkerEd25519Error ( "Can't create Ed25519PublicKey: {}!" . format ( str ( exc ) ) ) | Create an ed25519 public key from string which is a seed . |
27,994 | def _ed25519_key_from_file ( fn , path ) : try : return fn ( read_from_file ( path , exception = ScriptWorkerEd25519Error ) ) except ScriptWorkerException as exc : raise ScriptWorkerEd25519Error ( "Failed calling {} for {}: {}!" . format ( fn , path , str ( exc ) ) ) | Create an ed25519 key from the contents of path . |
27,995 | def ed25519_private_key_to_string ( key ) : return base64 . b64encode ( key . private_bytes ( encoding = serialization . Encoding . Raw , format = serialization . PrivateFormat . Raw , encryption_algorithm = serialization . NoEncryption ( ) ) , None ) . decode ( 'utf-8' ) | Convert an ed25519 private key to a base64 - encoded string . |
27,996 | def ed25519_public_key_to_string ( key ) : return base64 . b64encode ( key . public_bytes ( encoding = serialization . Encoding . Raw , format = serialization . PublicFormat . Raw , ) , None ) . decode ( 'utf-8' ) | Convert an ed25519 public key to a base64 - encoded string . |
27,997 | def verify_ed25519_signature ( public_key , contents , signature , message ) : try : public_key . verify ( signature , contents ) except InvalidSignature as exc : raise ScriptWorkerEd25519Error ( message % { 'exc' : str ( exc ) } ) | Verify that signature comes from public_key and contents . |
27,998 | def get_reversed_statuses ( context ) : _rev = { v : k for k , v in STATUSES . items ( ) } _rev . update ( dict ( context . config [ 'reversed_statuses' ] ) ) return _rev | Return a mapping of exit codes to status strings . |
27,999 | def get_repo ( task , source_env_prefix ) : repo = _extract_from_env_in_payload ( task , source_env_prefix + '_HEAD_REPOSITORY' ) if repo is not None : repo = repo . rstrip ( '/' ) return repo | Get the repo for a task . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.