idx int64 0 63k | question stringlengths 53 5.28k | target stringlengths 5 805 |
|---|---|---|
35,700 | def gauss ( x , sigma ) : return ( np . exp ( - np . power ( x , 2 ) / ( 2 * np . power ( sigma , 2 ) ) ) / ( sigma * np . sqrt ( 2 * np . pi ) ) ) | Compute 1 - D value of gaussian at position x relative to center . |
35,701 | def find_xy_peak ( img , center = None , sigma = 3.0 ) : istats = imagestats . ImageStats ( img . astype ( np . float32 ) , nclip = 1 , fields = 'stddev,mode,mean,max,min' ) if istats . stddev == 0.0 : istats = imagestats . ImageStats ( img . astype ( np . float32 ) , fields = 'stddev,mode,mean,max,min' ) imgsum = img ... | Find the center of the peak of offsets |
35,702 | def plot_zeropoint ( pars ) : from matplotlib import pyplot as plt xp = pars [ 'xp' ] yp = pars [ 'yp' ] searchrad = int ( pars [ 'searchrad' ] + 0.5 ) plt . figure ( num = pars [ 'figure_id' ] ) plt . clf ( ) if pars [ 'interactive' ] : plt . ion ( ) else : plt . ioff ( ) plt . imshow ( pars [ 'data' ] , vmin = 0 , vm... | Plot 2d histogram . |
35,703 | def build_xy_zeropoint ( imgxy , refxy , searchrad = 3.0 , histplot = False , figure_id = 1 , plotname = None , interactive = True ) : print ( 'Computing initial guess for X and Y shifts...' ) zpmat = cdriz . arrxyzero ( imgxy . astype ( np . float32 ) , refxy . astype ( np . float32 ) , searchrad ) xp , yp , flux , zp... | Create a matrix which contains the delta between each XY position and each UV position . |
35,704 | def build_pos_grid ( start , end , nstep , mesh = False ) : dx = end [ 0 ] - start [ 0 ] if dx < 0 : nstart = end end = start start = nstart dx = - dx stepx = dx / nstep xarr = np . arange ( start [ 0 ] , end [ 0 ] + stepx / 2.0 , stepx ) yarr = np . interp ( xarr , [ start [ 0 ] , end [ 0 ] ] , [ start [ 1 ] , end [ 1... | Return a grid of positions starting at X Y given by start and ending at X Y given by end . The grid will be completely filled in X and Y by every step interval . |
35,705 | def doUnitConversions ( self ) : _handle = fileutil . openImage ( self . _filename , mode = 'readonly' , memmap = False ) for det in range ( 1 , self . _numchips + 1 ) : chip = self . _image [ self . scienceExt , det ] conversionFactor = 1.0 if 'D2IMFILE' in _handle [ 0 ] . header and _handle [ 0 ] . header [ 'D2IMFILE... | Apply unit conversions to all the chips ignoring the group parameter . This insures that all the chips get the same conversions when this gets done even if only 1 chip was specified to be processed . |
35,706 | def getdarkcurrent ( self , exten ) : darkrate = 0.005 if self . proc_unit == 'native' : darkrate = darkrate / self . getGain ( exten ) try : chip = self . _image [ 0 ] darkcurrent = chip . header [ 'DARKTIME' ] * darkrate except : msg = "#############################################\n" msg += "# ... | Return the dark current for the WFPC2 detector . This value will be contained within an instrument specific keyword . The value in the image header will be converted to units of electrons . |
35,707 | def generateCatalog ( wcs , mode = 'automatic' , catalog = None , src_find_filters = None , ** kwargs ) : if not isinstance ( catalog , Catalog ) : if mode == 'automatic' : catalog = ImageCatalog ( wcs , catalog , src_find_filters , ** kwargs ) else : catalog = UserCatalog ( wcs , catalog , ** kwargs ) return catalog | Function which determines what type of catalog object needs to be instantiated based on what type of source selection algorithm the user specified . |
35,708 | def generateRaDec ( self ) : self . prefix = self . PAR_PREFIX if not isinstance ( self . wcs , pywcs . WCS ) : print ( textutil . textbox ( 'WCS not a valid PyWCS object. ' 'Conversion of RA/Dec not possible...' ) , file = sys . stderr ) raise ValueError if self . xypos is None or len ( self . xypos [ 0 ] ) == 0 : sel... | Convert XY positions into sky coordinates using STWCS methods . |
35,709 | def apply_exclusions ( self , exclusions ) : exclusion_coords = tweakutils . parse_exclusions ( exclusions ) if exclusion_coords is None : return excluded_list = [ ] radec_indx = list ( range ( len ( self . radec [ 0 ] ) ) ) for ra , dec , indx in zip ( self . radec [ 0 ] , self . radec [ 1 ] , radec_indx ) : src_pos =... | Trim sky catalog to remove any sources within regions specified by exclusions file . |
35,710 | def buildCatalogs ( self , exclusions = None , ** kwargs ) : self . generateXY ( ** kwargs ) self . generateRaDec ( ) if exclusions : self . apply_exclusions ( exclusions ) self . apply_flux_limits ( ) | Primary interface to build catalogs based on user inputs . |
35,711 | def plotXYCatalog ( self , ** kwargs ) : try : from matplotlib import pyplot as pl except : pl = None if pl is not None : pl . clf ( ) pars = kwargs . copy ( ) if 'marker' not in pars : pars [ 'marker' ] = 'b+' if 'cmap' in pars : pl_cmap = pars [ 'cmap' ] del pars [ 'cmap' ] else : pl_cmap = 'summer' pl_vmin = None pl... | Method which displays the original image and overlays the positions of the detected sources from this image s catalog . |
35,712 | def writeXYCatalog ( self , filename ) : if self . xypos is None : warnstr = textutil . textbox ( 'WARNING: \n No X,Y source catalog to write to file. ' ) for line in warnstr . split ( '\n' ) : log . warning ( line ) print ( warnstr ) return f = open ( filename , 'w' ) f . write ( "# Source catalog derived for %s\n"... | Write out the X Y catalog to a file |
35,713 | def generateXY ( self , ** kwargs ) : self . num_objects = 0 xycols = self . _readCatalog ( ) if xycols is not None : self . xypos = xycols [ : 3 ] if self . numcols > 3 : self . xypos . append ( np . asarray ( xycols [ 3 ] , dtype = int ) ) if self . numcols > 4 : self . sharp = xycols [ 4 ] if self . numcols > 5 : se... | Method to interpret input catalog file as columns of positions and fluxes . |
35,714 | def do_blot ( source , source_wcs , blot_wcs , exptime , coeffs = True , interp = 'poly5' , sinscl = 1.0 , stepsize = 10 , wcsmap = None ) : _outsci = np . zeros ( blot_wcs . array_shape , dtype = np . float32 ) build = False misval = 0.0 kscale = 1.0 xmin = 1 ymin = 1 xmax , ymax = source_wcs . pixel_shape if coeffs :... | Core functionality of performing the blot operation to create a single blotted image from a single source image . All distortion information is assumed to be included in the WCS specification of the output blotted image given in blot_wcs . |
35,715 | def _lowerAsn ( asnfile ) : _indx = asnfile . find ( '_asn.fits' ) _new_asn = asnfile [ : _indx ] + '_pipeline' + asnfile [ _indx : ] if os . path . exists ( _new_asn ) : os . remove ( _new_asn ) shutil . copy ( asnfile , _new_asn ) fasn = fits . open ( _new_asn , mode = 'update' , memmap = False ) for i in range ( len... | Create a copy of the original asn file and change the case of all members to lower - case . |
35,716 | def _appendTrlFile ( trlfile , drizfile ) : if not os . path . exists ( drizfile ) : return ftrl = open ( trlfile , 'a' ) fdriz = open ( drizfile ) _dlines = fdriz . readlines ( ) ftrl . writelines ( _dlines ) ftrl . close ( ) fdriz . close ( ) os . remove ( drizfile ) | Append drizfile to already existing trlfile from CALXXX . |
35,717 | def _timestamp ( _process_name ) : _prefix = time . strftime ( "%Y%j%H%M%S-I-----" , time . localtime ( ) ) _lenstr = 60 - len ( _process_name ) return _prefix + _process_name + ( _lenstr * '-' ) + '\n' | Create formatted time string recognizable by OPUS . |
35,718 | def _createWorkingDir ( rootdir , input ) : rootname = input [ : input . find ( '_' ) ] newdir = os . path . join ( rootdir , rootname ) if not os . path . exists ( newdir ) : os . mkdir ( newdir ) return newdir | Create a working directory based on input name under the parent directory specified as rootdir |
35,719 | def _copyToNewWorkingDir ( newdir , input ) : flist = [ ] if '_asn.fits' in input : asndict = asnutil . readASNTable ( input , None ) flist . append ( input [ : input . find ( '_' ) ] ) flist . extend ( asndict [ 'order' ] ) flist . append ( asndict [ 'output' ] ) else : flist . append ( input [ : input . find ( '_' ) ... | Copy input file and all related files necessary for processing to the new working directory . |
35,720 | def median ( input = None , configObj = None , editpars = False , ** inputDict ) : if input is not None : inputDict [ "input" ] = input else : raise ValueError ( "Please supply an input image" ) configObj = util . getDefaultConfigObj ( __taskname__ , configObj , inputDict , loadOnly = ( not editpars ) ) if configObj is... | Create a median image from the seperately drizzled images . |
35,721 | def createMedian ( imgObjList , configObj , procSteps = None ) : if imgObjList is None : msg = "Please provide a list of imageObjects to the median step" print ( msg , file = sys . stderr ) raise ValueError ( msg ) if procSteps is not None : procSteps . addStep ( 'Create Median' ) step_name = util . getSectionName ( co... | Top - level interface to createMedian step called from top - level AstroDrizzle . |
35,722 | def _writeImage ( dataArray = None , inputHeader = None ) : prihdu = fits . PrimaryHDU ( data = dataArray , header = inputHeader ) pf = fits . HDUList ( ) pf . append ( prihdu ) return pf | Writes out the result of the combination step . The header of the first outsingle file in the association parlist is used as the header of the new image . |
35,723 | def fetch_uri_contents ( self , uri : str ) -> URI : address , pkg_name , pkg_version = parse_registry_uri ( uri ) self . w3 . enable_unstable_package_management_api ( ) self . w3 . pm . set_registry ( address ) _ , _ , manifest_uri = self . w3 . pm . get_release_data ( pkg_name , pkg_version ) return manifest_uri | Return content - addressed URI stored at registry URI . |
35,724 | def pin_assets ( self , file_or_dir_path : Path ) -> List [ Dict [ str , str ] ] : if file_or_dir_path . is_dir ( ) : asset_data = [ dummy_ipfs_pin ( path ) for path in file_or_dir_path . glob ( "*" ) ] elif file_or_dir_path . is_file ( ) : asset_data = [ dummy_ipfs_pin ( file_or_dir_path ) ] else : raise FileNotFoundE... | Return a dict containing the IPFS hash file name and size of a file . |
35,725 | async def _cleanup ( self ) : while True : await asyncio . sleep ( CLEANUP_INTERVAL_S ) self . _tasks = { t for t in self . _tasks if not t . done ( ) } | Periodically removes completed tasks from the collection allowing fire - and - forget tasks to be garbage collected . |
35,726 | async def create ( self , coro : Coroutine ) -> asyncio . Task : task = asyncio . get_event_loop ( ) . create_task ( coro ) self . _tasks . add ( task ) return task | Starts execution of a coroutine . |
35,727 | async def cancel ( self , task : asyncio . Task , wait_for : bool = True ) -> Any : if task is None : return task . cancel ( ) with suppress ( KeyError ) : self . _tasks . remove ( task ) with suppress ( Exception ) : return ( await task ) if wait_for else None | Cancels and waits for an asyncio . Task to finish . Removes it from the collection of managed tasks . |
35,728 | def is_supported_content_addressed_uri ( uri : URI ) -> bool : if not is_ipfs_uri ( uri ) and not is_valid_content_addressed_github_uri ( uri ) : return False return True | Returns a bool indicating whether provided uri is currently supported . Currently Py - EthPM only supports IPFS and Github blob content - addressed uris . |
35,729 | def update_w3 ( self , w3 : Web3 ) -> "Package" : validate_w3_instance ( w3 ) return Package ( self . manifest , w3 , self . uri ) | Returns a new instance of Package containing the same manifest but connected to a different web3 instance . |
35,730 | def from_file ( cls , file_path : Path , w3 : Web3 ) -> "Package" : if isinstance ( file_path , Path ) : raw_manifest = file_path . read_text ( ) validate_raw_manifest_format ( raw_manifest ) manifest = json . loads ( raw_manifest ) else : raise TypeError ( "The Package.from_file method expects a pathlib.Path instance.... | Returns a Package instantiated by a manifest located at the provided Path . file_path arg must be a pathlib . Path instance . A valid Web3 instance is required to instantiate a Package . |
35,731 | def get_contract_factory ( self , name : ContractName ) -> Contract : validate_contract_name ( name ) if "contract_types" not in self . manifest : raise InsufficientAssetsError ( "This package does not contain any contract type data." ) try : contract_data = self . manifest [ "contract_types" ] [ name ] except KeyError... | Return the contract factory for a given contract type generated from the data vailable in Package . manifest . Contract factories are accessible from the package class . |
35,732 | def get_contract_instance ( self , name : ContractName , address : Address ) -> Contract : validate_address ( address ) validate_contract_name ( name ) try : self . manifest [ "contract_types" ] [ name ] [ "abi" ] except KeyError : raise InsufficientAssetsError ( "Package does not have the ABI required to generate a co... | Will return a Web3 . contract instance generated from the contract type data available in Package . manifest and the provided address . The provided address must be valid on the connected chain available through Package . w3 . |
35,733 | def build_dependencies ( self ) -> "Dependencies" : validate_build_dependencies_are_present ( self . manifest ) dependencies = self . manifest [ "build_dependencies" ] dependency_packages = { } for name , uri in dependencies . items ( ) : try : validate_build_dependency ( name , uri ) dependency_package = Package . fro... | Return Dependencies instance containing the build dependencies available on this Package . The Package class should provide access to the full dependency tree . |
35,734 | def deployments ( self ) -> Union [ "Deployments" , Dict [ None , None ] ] : if not check_for_deployments ( self . manifest ) : return { } all_blockchain_uris = self . manifest [ "deployments" ] . keys ( ) matching_uri = validate_single_matching_uri ( all_blockchain_uris , self . w3 ) deployments = self . manifest [ "d... | Returns a Deployments object containing all the deployment data and contract factories of a Package s contract_types . Automatically filters deployments to only expose those available on the current Package . w3 instance . |
35,735 | def dummy_ipfs_pin ( path : Path ) -> Dict [ str , str ] : ipfs_return = { "Hash" : generate_file_hash ( path . read_bytes ( ) ) , "Name" : path . name , "Size" : str ( path . stat ( ) . st_size ) , } return ipfs_return | Return IPFS data as if file was pinned to an actual node . |
35,736 | def extract_ipfs_path_from_uri ( value : str ) -> str : parse_result = parse . urlparse ( value ) if parse_result . netloc : if parse_result . path : return "" . join ( ( parse_result . netloc , parse_result . path . rstrip ( "/" ) ) ) else : return parse_result . netloc else : return parse_result . path . strip ( "/" ... | Return the path from an IPFS URI . Path = IPFS hash & following path . |
35,737 | def is_ipfs_uri ( value : str ) -> bool : parse_result = parse . urlparse ( value ) if parse_result . scheme != "ipfs" : return False if not parse_result . netloc and not parse_result . path : return False return True | Return a bool indicating whether or not the value is a valid IPFS URI . |
35,738 | def get_instance ( self , contract_name : str ) -> None : self . _validate_name_and_references ( contract_name ) contract_type = self . deployment_data [ contract_name ] [ "contract_type" ] factory = self . contract_factories [ contract_type ] address = to_canonical_address ( self . deployment_data [ contract_name ] [ ... | Fetches a contract instance belonging to deployment after validating contract name . |
35,739 | def validate_address ( address : Any ) -> None : if not is_address ( address ) : raise ValidationError ( f"Expected an address, got: {address}" ) if not is_canonical_address ( address ) : raise ValidationError ( "Py-EthPM library only accepts canonicalized addresses. " f"{address} is not in the accepted format." ) | Raise a ValidationError if an address is not canonicalized . |
35,740 | def validate_package_name ( pkg_name : str ) -> None : if not bool ( re . match ( PACKAGE_NAME_REGEX , pkg_name ) ) : raise ValidationError ( f"{pkg_name} is not a valid package name." ) | Raise an exception if the value is not a valid package name as defined in the EthPM - Spec . |
35,741 | def validate_registry_uri ( uri : str ) -> None : parsed = parse . urlparse ( uri ) scheme , authority , pkg_name , query = ( parsed . scheme , parsed . netloc , parsed . path , parsed . query , ) validate_registry_uri_scheme ( scheme ) validate_registry_uri_authority ( authority ) if query : validate_registry_uri_vers... | Raise an exception if the URI does not conform to the registry URI scheme . |
35,742 | def validate_registry_uri_authority ( auth : str ) -> None : if is_ens_domain ( auth ) is False and not is_checksum_address ( auth ) : raise ValidationError ( f"{auth} is not a valid registry URI authority." ) | Raise an exception if the authority is not a valid ENS domain or a valid checksummed contract address . |
35,743 | def validate_registry_uri_version ( query : str ) -> None : query_dict = parse . parse_qs ( query , keep_blank_values = True ) if "version" not in query_dict : raise ValidationError ( f"{query} is not a correctly formatted version param." ) | Raise an exception if the version param is malformed . |
35,744 | def validate_meta_object ( meta : Dict [ str , Any ] , allow_extra_meta_fields : bool ) -> None : for key , value in meta . items ( ) : if key in META_FIELDS : if type ( value ) is not META_FIELDS [ key ] : raise ValidationError ( f"Values for {key} are expected to have the type {META_FIELDS[key]}, " f"instead got {typ... | Validates that every key is one of META_FIELDS and has a value of the expected type . |
35,745 | def validate_manifest_against_schema ( manifest : Dict [ str , Any ] ) -> None : schema_data = _load_schema_data ( ) try : validate ( manifest , schema_data ) except jsonValidationError as e : raise ValidationError ( f"Manifest invalid for schema version {schema_data['version']}. " f"Reason: {e.message}" ) | Load and validate manifest against schema located at MANIFEST_SCHEMA_PATH . |
35,746 | def validate_manifest_deployments ( manifest : Dict [ str , Any ] ) -> None : if set ( ( "contract_types" , "deployments" ) ) . issubset ( manifest ) : all_contract_types = list ( manifest [ "contract_types" ] . keys ( ) ) all_deployments = list ( manifest [ "deployments" ] . values ( ) ) all_deployment_names = extract... | Validate that a manifest s deployments contracts reference existing contract_types . |
35,747 | def build ( obj : Dict [ str , Any ] , * fns : Callable [ ... , Any ] ) -> Dict [ str , Any ] : return pipe ( obj , * fns ) | Wrapper function to pipe manifest through build functions . Does not validate the manifest by default . |
35,748 | def get_names_and_paths ( compiler_output : Dict [ str , Any ] ) -> Dict [ str , str ] : return { contract_name : make_path_relative ( path ) for path in compiler_output for contract_name in compiler_output [ path ] . keys ( ) } | Return a mapping of contract name to relative path as defined in compiler output . |
35,749 | def contract_type ( name : str , compiler_output : Dict [ str , Any ] , alias : Optional [ str ] = None , abi : Optional [ bool ] = False , compiler : Optional [ bool ] = False , contract_type : Optional [ bool ] = False , deployment_bytecode : Optional [ bool ] = False , natspec : Optional [ bool ] = False , runtime_b... | Returns a copy of manifest with added contract_data field as specified by kwargs . If no kwargs are present all available contract_data found in the compiler output will be included . |
35,750 | def filter_all_data_by_selected_fields ( all_type_data : Dict [ str , Any ] , selected_fields : List [ str ] ) -> Iterable [ Tuple [ str , Any ] ] : for field in selected_fields : if field in all_type_data : yield field , all_type_data [ field ] else : raise ManifestBuildingError ( f"Selected field: {field} not availab... | Raises exception if selected field data is not available in the contract type data automatically gathered by normalize_compiler_output . Otherwise returns the data . |
35,751 | def normalize_compiler_output ( compiler_output : Dict [ str , Any ] ) -> Dict [ str , Any ] : paths_and_names = [ ( path , contract_name ) for path in compiler_output for contract_name in compiler_output [ path ] . keys ( ) ] paths , names = zip ( * paths_and_names ) if len ( names ) != len ( set ( names ) ) : raise M... | Return compiler output with normalized fields for each contract type as specified in normalize_contract_type . |
35,752 | def normalize_contract_type ( contract_type_data : Dict [ str , Any ] ) -> Iterable [ Tuple [ str , Any ] ] : yield "abi" , contract_type_data [ "abi" ] if "evm" in contract_type_data : if "bytecode" in contract_type_data [ "evm" ] : yield "deployment_bytecode" , normalize_bytecode_object ( contract_type_data [ "evm" ]... | Serialize contract_data found in compiler output to the defined fields . |
35,753 | def process_bytecode ( link_refs : Dict [ str , Any ] , bytecode : bytes ) -> str : all_offsets = [ y for x in link_refs . values ( ) for y in x . values ( ) ] validate_link_ref_fns = ( validate_link_ref ( ref [ "start" ] * 2 , ref [ "length" ] * 2 ) for ref in concat ( all_offsets ) ) pipe ( bytecode , * validate_link... | Replace link_refs in bytecode with 0 s . |
35,754 | def deployment_type ( * , contract_instance : str , contract_type : str , deployment_bytecode : Dict [ str , Any ] = None , runtime_bytecode : Dict [ str , Any ] = None , compiler : Dict [ str , Any ] = None , ) -> Manifest : return _deployment_type ( contract_instance , contract_type , deployment_bytecode , runtime_by... | Returns a callable that allows the user to add deployments of the same type across multiple chains . |
35,755 | def deployment ( * , block_uri : URI , contract_instance : str , contract_type : str , address : HexStr , transaction : HexStr = None , block : HexStr = None , deployment_bytecode : Dict [ str , Any ] = None , runtime_bytecode : Dict [ str , Any ] = None , compiler : Dict [ str , Any ] = None , ) -> Manifest : return _... | Returns a manifest with the newly included deployment . Requires a valid blockchain URI however no validation is provided that this URI is unique amongst the other deployment URIs so the user must take care that each blockchain URI represents a unique blockchain . |
35,756 | def _build_deployments_object ( contract_type : str , deployment_bytecode : Dict [ str , Any ] , runtime_bytecode : Dict [ str , Any ] , compiler : Dict [ str , Any ] , address : HexStr , tx : HexStr , block : HexStr , manifest : Dict [ str , Any ] , ) -> Iterable [ Tuple [ str , Any ] ] : yield "contract_type" , contr... | Returns a dict with properly formatted deployment data . |
35,757 | def pin_to_ipfs ( manifest : Manifest , * , backend : BaseIPFSBackend , prettify : Optional [ bool ] = False ) -> List [ Dict [ str , str ] ] : contents = format_manifest ( manifest , prettify = prettify ) with tempfile . NamedTemporaryFile ( ) as temp : temp . write ( to_bytes ( text = contents ) ) temp . seek ( 0 ) r... | Returns the IPFS pin data after pinning the manifest to the provided IPFS Backend . |
35,758 | def create_parser ( default_name : str ) -> argparse . ArgumentParser : argparser = argparse . ArgumentParser ( fromfile_prefix_chars = '@' ) argparser . add_argument ( '-H' , '--host' , help = 'Host to which the app binds. [%(default)s]' , default = '0.0.0.0' ) argparser . add_argument ( '-p' , '--port' , help = 'Port... | Creates the default brewblox_service ArgumentParser . Service - agnostic arguments are added . |
35,759 | def create_app ( default_name : str = None , parser : argparse . ArgumentParser = None , raw_args : List [ str ] = None ) -> web . Application : if parser is None : assert default_name , 'Default service name is required' parser = create_parser ( default_name ) args = parser . parse_args ( raw_args ) _init_logging ( ar... | Creates and configures an Aiohttp application . |
35,760 | def furnish ( app : web . Application ) : app_name = app [ 'config' ] [ 'name' ] prefix = '/' + app_name . lstrip ( '/' ) app . router . add_routes ( routes ) cors_middleware . enable_cors ( app ) known_resources = set ( ) for route in list ( app . router . routes ( ) ) : if route . resource in known_resources : contin... | Configures Application routes readying it for running . |
35,761 | def run ( app : web . Application ) : host = app [ 'config' ] [ 'host' ] port = app [ 'config' ] [ 'port' ] web . run_app ( app , host = host , port = port ) | Runs the application in an async context . This function will block indefinitely until the application is shut down . |
35,762 | def get_linked_deployments ( deployments : Dict [ str , Any ] ) -> Dict [ str , Any ] : linked_deployments = { dep : data for dep , data in deployments . items ( ) if get_in ( ( "runtime_bytecode" , "link_dependencies" ) , data ) } for deployment , data in linked_deployments . items ( ) : if any ( link_dep [ "value" ] ... | Returns all deployments found in a chain URI s deployment data that contain link dependencies . |
35,763 | def apply_all_link_refs ( bytecode : bytes , link_refs : List [ Dict [ str , Any ] ] , attr_dict : Dict [ str , str ] ) -> bytes : if link_refs is None : return bytecode link_fns = ( apply_link_ref ( offset , ref [ "length" ] , attr_dict [ ref [ "name" ] ] ) for ref in link_refs for offset in ref [ "offsets" ] ) linked... | Applies all link references corresponding to a valid attr_dict to the bytecode . |
35,764 | def apply_link_ref ( offset : int , length : int , value : bytes , bytecode : bytes ) -> bytes : try : validate_empty_bytes ( offset , length , bytecode ) except ValidationError : raise BytecodeLinkingError ( "Link references cannot be applied to bytecode" ) new_bytes = ( bytecode [ : offset ] + value + bytecode [ offs... | Returns the new bytecode with value put into the location indicated by offset and length . |
35,765 | def validate_attr_dict ( self , attr_dict : Dict [ str , str ] ) -> None : attr_dict_names = list ( attr_dict . keys ( ) ) if not self . unlinked_references and not self . linked_references : raise BytecodeLinkingError ( "Unable to validate attr dict, this contract has no linked/unlinked references." ) unlinked_refs = ... | Validates that ContractType keys in attr_dict reference existing manifest ContractTypes . |
35,766 | def items ( self ) -> Tuple [ Tuple [ str , "Package" ] , ... ] : item_dict = { name : self . build_dependencies . get ( name ) for name in self . build_dependencies } return tuple ( item_dict . items ( ) ) | Return an iterable containing package name and corresponding Package instance that are available . |
35,767 | def values ( self ) -> List [ "Package" ] : values = [ self . build_dependencies . get ( name ) for name in self . build_dependencies ] return values | Return an iterable of the available Package instances . |
35,768 | def get_dependency_package ( self , package_name : str ) -> "Package" : self . _validate_name ( package_name ) return self . build_dependencies . get ( package_name ) | Return the dependency Package for a given package name . |
35,769 | def add ( app : web . Application , feature : Any , key : Hashable = None , exist_ok : bool = False ) : if FEATURES_KEY not in app : app [ FEATURES_KEY ] = dict ( ) key = key or type ( feature ) if key in app [ FEATURES_KEY ] : if exist_ok : return else : raise KeyError ( f'Feature "{key}" already registered' ) app [ F... | Adds a new feature to the app . |
35,770 | def get ( app : web . Application , feature_type : Type [ Any ] = None , key : Hashable = None ) -> Any : key = key or feature_type if not key : raise AssertionError ( 'No feature identifier provided' ) try : found = app [ FEATURES_KEY ] [ key ] except KeyError : raise KeyError ( f'No feature found for "{key}"' ) if fe... | Finds declared feature . Identification is done based on feature type and key . |
35,771 | def validate_minimal_contract_factory_data ( contract_data : Dict [ str , str ] ) -> None : if not all ( key in contract_data . keys ( ) for key in ( "abi" , "deployment_bytecode" ) ) : raise InsufficientAssetsError ( "Minimum required contract data to generate a deployable " "contract factory (abi & deployment_bytecod... | Validate that contract data in a package contains at least an abi and deployment_bytecode necessary to generate a deployable contract factory . |
35,772 | def generate_contract_factory_kwargs ( contract_data : Dict [ str , Any ] ) -> Generator [ Tuple [ str , Any ] , None , None ] : if "abi" in contract_data : yield "abi" , contract_data [ "abi" ] if "deployment_bytecode" in contract_data : yield "bytecode" , contract_data [ "deployment_bytecode" ] [ "bytecode" ] if "lin... | Build a dictionary of kwargs to be passed into contract factory . |
35,773 | async def _relay ( self , channel : aioamqp . channel . Channel , body : str , envelope : aioamqp . envelope . Envelope , properties : aioamqp . properties . Properties ) : try : await channel . basic_client_ack ( envelope . delivery_tag ) await self . on_message ( self , envelope . routing_key , json . loads ( body ) ... | Relays incoming messages between the queue and the user callback |
35,774 | def _lazy_listen ( self ) : if all ( [ self . _loop , not self . running , self . _subscriptions or ( self . _pending and not self . _pending . empty ( ) ) , ] ) : self . _task = self . _loop . create_task ( self . _listen ( ) ) | Ensures that the listener task only runs when actually needed . This function is a no - op if any of the preconditions is not met . |
35,775 | def subscribe ( self , exchange_name : str , routing : str , exchange_type : ExchangeType_ = 'topic' , on_message : EVENT_CALLBACK_ = None ) -> EventSubscription : sub = EventSubscription ( exchange_name , routing , exchange_type , on_message = on_message ) if self . _pending is not None : self . _pending . put_nowait ... | Adds a new event subscription to the listener . |
35,776 | async def publish ( self , exchange : str , routing : str , message : Union [ str , dict ] , exchange_type : ExchangeType_ = 'topic' ) : try : await self . _ensure_channel ( ) except Exception : await self . _ensure_channel ( ) data = json . dumps ( message ) . encode ( ) await self . _channel . exchange_declare ( exch... | Publish a new event message . |
35,777 | def is_ens_domain ( authority : str ) -> bool : if authority [ - 4 : ] != ".eth" or len ( authority . split ( "." ) ) not in [ 2 , 3 ] : return False return True | Return false if authority is not a valid ENS domain . |
35,778 | def exclude ( self , d , item ) : try : md = d . __metadata__ pmd = getattr ( md , '__print__' , None ) if pmd is None : return False excludes = getattr ( pmd , 'excludes' , [ ] ) return ( item [ 0 ] in excludes ) except : pass return False | check metadata for excluded items |
35,779 | def find ( self , name , resolved = True ) : qref = qualify ( name , self . schema . root , self . schema . tns ) query = BlindQuery ( qref ) result = query . execute ( self . schema ) if result is None : log . error ( '(%s) not-found' , name ) return None if resolved : result = result . resolve ( ) return result | Get the definition object for the schema object by name . |
35,780 | def getchild ( self , name , parent ) : if name . startswith ( '@' ) : return parent . get_attribute ( name [ 1 : ] ) else : return parent . get_child ( name ) | get a child by name |
35,781 | def find ( self , location ) : try : content = self . store [ location ] return StringIO ( content ) except : reason = 'location "%s" not in document store' % location raise Exception , reason | Find the specified location in the store . |
35,782 | def get_message ( self , method , args , kwargs , options = None ) : content = self . headercontent ( method , options = options ) header = self . header ( content ) content = self . bodycontent ( method , args , kwargs ) body = self . body ( content ) env = self . envelope ( header , body ) if self . options ( ) . pre... | Get the soap message for the specified method args and soapheaders . This is the entry point for creating the outbound soap message . |
35,783 | def send ( self , soapenv ) : result = None location = self . location ( ) binding = self . method . binding . input transport = self . options . transport retxml = self . options . retxml prettyxml = self . options . prettyxml log . debug ( 'sending to (%s)\nmessage:\n%s' , location , soapenv ) try : self . last_sent ... | Send soap message . |
35,784 | def succeeded ( self , binding , reply ) : log . debug ( 'http succeeded:\n%s' , reply ) plugins = PluginContainer ( self . options . plugins ) if len ( reply ) > 0 : with LocalTimer ( ) as lt : reply , result = binding . get_reply ( self . method , reply ) self . last_received ( reply ) metrics . log . debug ( "Callin... | Request succeeded process the reply |
35,785 | def failed ( self , binding , error ) : status , reason = ( error . httpcode , tostr ( error ) ) reply = error . fp . read ( ) log . debug ( 'http failed:\n%s' , reply ) if status == 500 : if len ( reply ) > 0 : r , p = binding . get_fault ( reply ) self . last_received ( r ) return ( status , p ) else : return ( statu... | Request failed process reply based on reason |
35,786 | def _get_line_no_from_comments ( py_line ) : matched = LINECOL_COMMENT_RE . match ( py_line ) if matched : return int ( matched . group ( 1 ) ) else : return 0 | Return the line number parsed from the comment or 0 . |
35,787 | def _find_fuzzy_line ( py_line_no , py_by_line_no , cheetah_by_line_no , prefer_first ) : stripped_line = _fuzz_py_line ( py_by_line_no [ py_line_no ] ) cheetah_lower_bound , cheetah_upper_bound = _find_bounds ( py_line_no , py_by_line_no , cheetah_by_line_no , ) sliced = list ( enumerate ( cheetah_by_line_no ) ) [ che... | Attempt to fuzzily find matching lines . |
35,788 | def perform_step ( file_contents , step ) : assert type ( file_contents ) is not bytes xmldoc = parse ( file_contents ) return step ( xmldoc ) | Performs a step of the transformation . |
35,789 | def _get_sender ( * sender_params , ** kwargs ) : notify_func = kwargs [ 'notify_func' ] with _sender_instances_lock : existing_sender = _sender_instances . get ( sender_params , None ) if existing_sender : sender = existing_sender sender . _notify = notify_func else : sender = _Sender ( * sender_params , notify = noti... | Utility function acting as a Sender factory - ensures senders don t get created twice of more for the same target server |
35,790 | def terminate ( ) : with _sender_instances_lock : for sender_key , sender in _sender_instances . items ( ) : sender . close ( ) _sender_instances . clear ( ) | Stops all the active Senders by flushing the buffers and closing the underlying sockets |
35,791 | def _send_batch ( self , batch ) : try : json_batch = '[' + ',' . join ( batch ) + ']' logger . debug ( consts . LOG_MSG_SENDING_BATCH , len ( batch ) , len ( json_batch ) , self . _rest_url ) res = self . _session . post ( self . _rest_url , data = json_batch , headers = consts . CONTENT_TYPE_JSON ) logger . debug ( c... | Sends a batch to the destination server via HTTP REST API |
35,792 | def __get_event ( self , block = True , timeout = 1 ) : while True : if self . _exceeding_event : event = self . _exceeding_event self . _exceeding_event = None else : event = self . _event_queue . get ( block , timeout ) event_size = len ( event ) if event_size - 2 >= self . _batch_max_size : self . _notify ( logging ... | Retrieves an event . If self . _exceeding_event is not None it ll be returned . Otherwise an event is dequeued from the event buffer . If The event which was retrieved is bigger than the permitted batch size it ll be omitted and the next event in the event buffer is returned |
35,793 | def get_links ( self , request = None ) : links = LinkNode ( ) paths = [ ] view_endpoints = [ ] for path , method , callback in self . endpoints : view = self . create_view ( callback , method , request ) if getattr ( view , 'exclude_from_schema' , False ) : continue path = self . coerce_path ( path , method , view ) p... | Return a dictionary containing all the links that should be included in the API schema . |
35,794 | def get_path_fields ( self , path , method , view ) : model = getattr ( getattr ( view , 'queryset' , None ) , 'model' , None ) fields = [ ] for variable in uritemplate . variables ( path ) : if variable == 'version' : continue title = '' description = '' schema_cls = coreschema . String kwargs = { } if model is not No... | Return a list of coreapi . Field instances corresponding to any templated path variables . |
35,795 | def get_serializer_class ( self , view , method_func ) : if hasattr ( method_func , 'request_serializer' ) : return getattr ( method_func , 'request_serializer' ) if hasattr ( view , 'serializer_class' ) : return getattr ( view , 'serializer_class' ) if hasattr ( view , 'get_serializer_class' ) : return getattr ( view ... | Try to get the serializer class from view method . If view method don t have request serializer fallback to serializer_class on view class |
35,796 | def fallback_schema_from_field ( self , field ) : title = force_text ( field . label ) if field . label else '' description = force_text ( field . help_text ) if field . help_text else '' if isinstance ( field , ( serializers . DictField , serializers . JSONField ) ) : return coreschema . Object ( properties = { } , ti... | Fallback schema for field that isn t inspected properly by DRF and probably won t land in upstream canon due to its hacky nature only for doc purposes |
35,797 | def update ( self , instance , validated_data ) : instance . title = validated_data . get ( 'title' , instance . title ) instance . code = validated_data . get ( 'code' , instance . code ) instance . linenos = validated_data . get ( 'linenos' , instance . linenos ) instance . language = validated_data . get ( 'language... | Update and return an existing Snippet instance given the validated data . |
35,798 | def _generate_openapi_object ( document ) : parsed_url = urlparse . urlparse ( document . url ) swagger = OrderedDict ( ) swagger [ 'swagger' ] = '2.0' swagger [ 'info' ] = OrderedDict ( ) swagger [ 'info' ] [ 'title' ] = document . title swagger [ 'info' ] [ 'description' ] = document . description swagger [ 'info' ] ... | Generates root of the Swagger spec . |
35,799 | def _get_responses ( link ) : template = link . response_schema template . update ( { 'description' : 'Success' } ) res = { 200 : template } res . update ( link . error_status_codes ) return res | Returns an OpenApi - compliant response |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.