sentence1 stringlengths 52 3.87M | sentence2 stringlengths 1 47.2k | label stringclasses 1
value |
|---|---|---|
def gauss(x, sigma):
""" Compute 1-D value of gaussian at position x relative to center."""
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. | entailment |
def make_vector_plot(coordfile, columns=[1, 2, 3, 4], data=None,
figure_id=None, title=None, axes=None, every=1,
labelsize=8, ylimit=None, limit=None, xlower=None,
ylower=None, output=None, headl=4, headw=3,
xsh=0.0, ysh=0.0, fit=None, ... | Convert a XYXYMATCH file into a vector plot or set of residuals plots.
This function provides a single interface for generating either a
vector plot of residuals or a set of 4 plots showing residuals.
The data being plotted can also be adjusted for a linear fit
on-the-fly.
Para... | entailment |
def find_xy_peak(img, center=None, sigma=3.0):
""" Find the center of the peak of offsets """
# find level of noise in histogram
istats = imagestats.ImageStats(img.astype(np.float32), nclip=1,
fields='stddev,mode,mean,max,min')
if istats.stddev == 0.0:
istats =... | Find the center of the peak of offsets | entailment |
def plot_zeropoint(pars):
""" Plot 2d histogram.
Pars will be a dictionary containing:
data, figure_id, vmax, title_str, xp,yp, searchrad
"""
from matplotlib import pyplot as plt
xp = pars['xp']
yp = pars['yp']
searchrad = int(pars['searchrad'] + 0.5)
plt.figure(num=pars['figu... | Plot 2d histogram.
Pars will be a dictionary containing:
data, figure_id, vmax, title_str, xp,yp, searchrad | entailment |
def build_xy_zeropoint(imgxy, refxy, searchrad=3.0, histplot=False,
figure_id=1, plotname=None, interactive=True):
""" Create a matrix which contains the delta between each XY position and
each UV position.
"""
print('Computing initial guess for X and Y shifts...')
# run ... | Create a matrix which contains the delta between each XY position and
each UV position. | entailment |
def build_pos_grid(start, end, nstep, mesh=False):
"""
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.
"""
# Build X and Y arrays
dx = end[0] - start[0]
if dx < 0:
... | 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. | entailment |
def find_DQ_extension(self):
""" Return the suffix for the data quality extension and the name of
the file which that DQ extension should be read from.
"""
dqfile = None
# Look for additional file with DQ array, primarily for WFPC2 data
indx = self._filename.find('.fits... | Return the suffix for the data quality extension and the name of
the file which that DQ extension should be read from. | entailment |
def setInstrumentParameters(self, instrpars):
""" This method overrides the superclass to set default values into
the parameter dictionary, in case empty entries are provided.
"""
pri_header = self._image[0].header
self.proc_unit = instrpars['proc_unit']
instrpars['gn... | This method overrides the superclass to set default values into
the parameter dictionary, in case empty entries are provided. | entailment |
def doUnitConversions(self):
""" 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.
"""
# Image information
_handl... | 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. | entailment |
def getdarkcurrent(self,exten):
"""
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.
Returns
-------
darkcurrent : f... | 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.
Returns
-------
darkcurrent : float
Dark current for the WFPC3 detector... | entailment |
def getReadNoise(self, exten):
"""
Method for returning the readnoise of a detector (in counts).
Returns
-------
readnoise : float
The readnoise of the detector in **units of counts/electrons**.
"""
rn = self._image[exten]._rdnoise
if self.pr... | Method for returning the readnoise of a detector (in counts).
Returns
-------
readnoise : float
The readnoise of the detector in **units of counts/electrons**. | entailment |
def buildMask(self, chip, bits=0, write=False):
""" Build masks as specified in the user parameters found in the
configObj object.
"""
sci_chip = self._image[self.scienceExt,chip]
### For WFPC2 Data, build mask files using:
maskname = sci_chip.dqrootname+'_dqmask.fits... | Build masks as specified in the user parameters found in the
configObj object. | entailment |
def generateCatalog(wcs, mode='automatic', catalog=None,
src_find_filters=None, **kwargs):
""" Function which determines what type of catalog object needs to be
instantiated based on what type of source selection algorithm the user
specified.
Parameters
----------
wcs : obj
... | Function which determines what type of catalog object needs to be
instantiated based on what type of source selection algorithm the user
specified.
Parameters
----------
wcs : obj
WCS object generated by STWCS or PyWCS
catalog : str or ndarray
Filename of existing catalog or nd... | entailment |
def generateRaDec(self):
""" Convert XY positions into sky coordinates using STWCS methods. """
self.prefix = self.PAR_PREFIX
if not isinstance(self.wcs,pywcs.WCS):
print(
textutil.textbox(
'WCS not a valid PyWCS object. '
'Con... | Convert XY positions into sky coordinates using STWCS methods. | entailment |
def apply_exclusions(self,exclusions):
""" Trim sky catalog to remove any sources within regions specified by
exclusions file.
"""
# parse exclusion file into list of positions and distances
exclusion_coords = tweakutils.parse_exclusions(exclusions)
if exclusion_coord... | Trim sky catalog to remove any sources within regions specified by
exclusions file. | entailment |
def apply_flux_limits(self):
""" Apply any user-specified limits on source selection
Limits based on fluxes.
"""
if not self._apply_flux_limits:
return
# only if limits are set should they be applied
if ((self.maxflux is None and self.minflux is None) or... | Apply any user-specified limits on source selection
Limits based on fluxes. | entailment |
def buildCatalogs(self, exclusions=None, **kwargs):
""" Primary interface to build catalogs based on user inputs.
"""
self.generateXY(**kwargs)
self.generateRaDec()
if exclusions:
self.apply_exclusions(exclusions)
# apply selection limits as specified by the ... | Primary interface to build catalogs based on user inputs. | entailment |
def plotXYCatalog(self, **kwargs):
"""
Method which displays the original image and overlays the positions
of the detected sources from this image's catalog.
Plotting `kwargs` that can be provided are:
vmin, vmax, cmap, marker
Default colormap is `summer`.
... | Method which displays the original image and overlays the positions
of the detected sources from this image's catalog.
Plotting `kwargs` that can be provided are:
vmin, vmax, cmap, marker
Default colormap is `summer`. | entailment |
def writeXYCatalog(self,filename):
""" Write out the X,Y catalog to a file
"""
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)
... | Write out the X,Y catalog to a file | entailment |
def generateXY(self, **kwargs):
""" Generate source catalog from input image using DAOFIND-style algorithm
"""
#x,y,flux,sharp,round = idlphot.find(array,self.pars['hmin'],self.pars['fwhm'],
# roundlim=self.pars['roundlim'], sharplim=self.pars['sharplim'])
prin... | Generate source catalog from input image using DAOFIND-style algorithm | entailment |
def generateXY(self, **kwargs):
"""
Method to interpret input catalog file as columns of positions and fluxes.
"""
self.num_objects = 0
xycols = self._readCatalog()
if xycols is not None:
# convert the catalog into attribute
self.xypos = xycols[:3... | Method to interpret input catalog file as columns of positions and fluxes. | entailment |
def plotXYCatalog(self, **kwargs):
"""
Plots the source catalog positions using matplotlib's `pyplot.plot()`
Plotting `kwargs` that can also be passed include any keywords understood
by matplotlib's `pyplot.plot()` function such as::
vmin, vmax, cmap, marker
"""
... | Plots the source catalog positions using matplotlib's `pyplot.plot()`
Plotting `kwargs` that can also be passed include any keywords understood
by matplotlib's `pyplot.plot()` function such as::
vmin, vmax, cmap, marker | entailment |
def run(configObj,wcsmap=None):
"""
Run the blot task based on parameters provided interactively by the user.
"""
# Insure all output filenames specified have .fits extensions
if configObj['outdata'][-5:] != '.fits': configObj['outdata'] += '.fits'
scale_pars = configObj['Data Scaling Paramet... | Run the blot task based on parameters provided interactively by the user. | entailment |
def runBlot(imageObjectList, output_wcs, configObj={},
wcsmap=wcs_functions.WCSMap, procSteps=None):
"""
runBlot(imageObjectList, output_wcs, configObj={},
wcsmap=wcs_functions.WCSMap, procSteps=None)
"""
if procSteps is not None:
procSteps.addStep('Blot')
blot_name ... | runBlot(imageObjectList, output_wcs, configObj={},
wcsmap=wcs_functions.WCSMap, procSteps=None) | entailment |
def run_blot(imageObjectList,output_wcs,paramDict,wcsmap=wcs_functions.WCSMap):
"""
run_blot(imageObjectList, output_wcs, paramDict, wcsmap=wcs_functions.WCSMap)
Perform the blot operation on the list of images.
"""
# Insure that input imageObject is a list
if not isinstance(imageObjectList, li... | run_blot(imageObjectList, output_wcs, paramDict, wcsmap=wcs_functions.WCSMap)
Perform the blot operation on the list of images. | entailment |
def do_blot(source, source_wcs, blot_wcs, exptime, coeffs = True,
interp='poly5', sinscl=1.0, stepsize=10, wcsmap=None):
""" 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 incl... | 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'.
This is the simplest interface that can be ... | entailment |
def process(inFile,force=False,newpath=None, inmemory=False, num_cores=None,
headerlets=True, align_to_gaia=True):
""" Run astrodrizzle on input file/ASN table
using default values for astrodrizzle parameters.
"""
# We only need to import this package if a user run the task
import dr... | Run astrodrizzle on input file/ASN table
using default values for astrodrizzle parameters. | entailment |
def _lowerAsn(asnfile):
""" Create a copy of the original asn file and change
the case of all members to lower-case.
"""
# Start by creating a new name for the ASN table
_indx = asnfile.find('_asn.fits')
_new_asn = asnfile[:_indx]+'_pipeline'+asnfile[_indx:]
if os.path.exists(_new_asn):
... | Create a copy of the original asn file and change
the case of all members to lower-case. | entailment |
def _appendTrlFile(trlfile,drizfile):
""" Append drizfile to already existing trlfile from CALXXX.
"""
if not os.path.exists(drizfile):
return
# Open already existing CALWF3 trailer file for appending
ftrl = open(trlfile,'a')
# Open astrodrizzle trailer file
fdriz = open(drizfile)
... | Append drizfile to already existing trlfile from CALXXX. | entailment |
def _timestamp(_process_name):
"""Create formatted time string recognizable by OPUS."""
_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. | entailment |
def _createWorkingDir(rootdir,input):
"""
Create a working directory based on input name under the parent directory specified as rootdir
"""
# extract rootname from input
rootname = input[:input.find('_')]
newdir = os.path.join(rootdir,rootname)
if not os.path.exists(newdir):
os.mkdi... | Create a working directory based on input name under the parent directory specified as rootdir | entailment |
def _copyToNewWorkingDir(newdir,input):
""" Copy input file and all related files necessary for processing to the new working directory.
This function works in a greedy manner, in that all files associated
with all inputs(have the same rootname) will be copied to the new
working directory.
... | Copy input file and all related files necessary for processing to the new working directory.
This function works in a greedy manner, in that all files associated
with all inputs(have the same rootname) will be copied to the new
working directory. | entailment |
def _restoreResults(newdir,origdir):
""" Move (not copy) all files from newdir back to the original directory
"""
for fname in glob.glob(os.path.join(newdir,'*')):
shutil.move(fname,os.path.join(origdir,os.path.basename(fname))) | Move (not copy) all files from newdir back to the original directory | entailment |
def median(input=None, configObj=None, editpars=False, **inputDict):
"""
Create a median image from the seperately drizzled images.
"""
if input is not None:
inputDict["input"] = input
else:
raise ValueError("Please supply an input image")
configObj = util.getDefaultConfigObj(__... | Create a median image from the seperately drizzled images. | entailment |
def createMedian(imgObjList, configObj, procSteps=None):
""" Top-level interface to createMedian step called from top-level
AstroDrizzle.
This function parses the input parameters then calls the `_median()`
function to median-combine the input images into a single image.
"""
if imgObjList is N... | Top-level interface to createMedian step called from top-level
AstroDrizzle.
This function parses the input parameters then calls the `_median()`
function to median-combine the input images into a single image. | entailment |
def _median(imageObjectList, paramDict):
"""Create a median image from the list of image Objects
that has been given.
"""
newmasks = paramDict['median_newmasks']
comb_type = paramDict['combine_type'].lower()
nlow = paramDict['combine_nlow']
nhigh = paramDict['combine_nhigh']
grow = pa... | Create a median image from the list of image Objects
that has been given. | entailment |
def _writeImage(dataArray=None, inputHeader=None):
""" 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.
Parameters
----------
dataArray : arr
Array o... | 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.
Parameters
----------
dataArray : arr
Array of data to be written to a fits.PrimaryHDU object
i... | entailment |
def tran(inimage,outimage,direction='forward',x=None,y=None,
coords=None, coordfile=None,colnames=None,separator=None,
precision=6, output=None,verbose=True):
""" Primary interface to perform coordinate transformations in pixel
coordinates between 2 images using STWCS and full distortion mod... | Primary interface to perform coordinate transformations in pixel
coordinates between 2 images using STWCS and full distortion models
read from each image's header. | entailment |
def fetch_uri_contents(self, uri: str) -> URI:
"""
Return content-addressed URI stored at registry URI.
"""
address, pkg_name, pkg_version = parse_registry_uri(uri)
self.w3.enable_unstable_package_management_api()
self.w3.pm.set_registry(address)
_, _, manifest_ur... | Return content-addressed URI stored at registry URI. | entailment |
def pin_assets(self, file_or_dir_path: Path) -> List[Dict[str, str]]:
"""
Return a dict containing the IPFS hash, file name, and size of a file.
"""
if file_or_dir_path.is_dir():
asset_data = [dummy_ipfs_pin(path) for path in file_or_dir_path.glob("*")]
elif file_or_d... | Return a dict containing the IPFS hash, file name, and size of a file. | entailment |
async def create_task(app: web.Application,
coro: Coroutine,
*args, **kwargs
) -> asyncio.Task:
"""
Convenience function for calling `TaskScheduler.create(coro)`
This will use the default `TaskScheduler` to create a new background task.
... | Convenience function for calling `TaskScheduler.create(coro)`
This will use the default `TaskScheduler` to create a new background task.
Example:
import asyncio
from datetime import datetime
from brewblox_service import scheduler, service
async def current_time(interval):
... | entailment |
async def cancel_task(app: web.Application,
task: asyncio.Task,
*args, **kwargs
) -> Any:
"""
Convenience function for calling `TaskScheduler.cancel(task)`
This will use the default `TaskScheduler` to cancel the given task.
Example:
... | Convenience function for calling `TaskScheduler.cancel(task)`
This will use the default `TaskScheduler` to cancel the given task.
Example:
import asyncio
from datetime import datetime
from brewblox_service import scheduler, service
async def current_time(interval):
... | entailment |
async def _cleanup(self):
"""
Periodically removes completed tasks from the collection,
allowing fire-and-forget tasks to be garbage collected.
This does not delete the task object, it merely removes the reference in the scheduler.
"""
while True:
await async... | Periodically removes completed tasks from the collection,
allowing fire-and-forget tasks to be garbage collected.
This does not delete the task object, it merely removes the reference in the scheduler. | entailment |
async def create(self, coro: Coroutine) -> asyncio.Task:
"""
Starts execution of a coroutine.
The created asyncio.Task is returned, and added to managed tasks.
The scheduler guarantees that it is cancelled during application shutdown,
regardless of whether it was already cancell... | Starts execution of a coroutine.
The created asyncio.Task is returned, and added to managed tasks.
The scheduler guarantees that it is cancelled during application shutdown,
regardless of whether it was already cancelled manually.
Args:
coro (Coroutine):
The... | entailment |
async def cancel(self, task: asyncio.Task, wait_for: bool = True) -> Any:
"""
Cancels and waits for an `asyncio.Task` to finish.
Removes it from the collection of managed tasks.
Args:
task (asyncio.Task):
The to be cancelled task.
It is not re... | Cancels and waits for an `asyncio.Task` to finish.
Removes it from the collection of managed tasks.
Args:
task (asyncio.Task):
The to be cancelled task.
It is not required that the task was was created with `TaskScheduler.create_task()`.
wait_for... | entailment |
def create_content_addressed_github_uri(uri: URI) -> URI:
"""
Returns a content-addressed Github "git_url" that conforms to this scheme.
https://api.github.com/repos/:owner/:repo/git/blobs/:file_sha
Accepts Github-defined "url" that conforms to this scheme
https://api.github.com/repos/:owner/:repo/... | Returns a content-addressed Github "git_url" that conforms to this scheme.
https://api.github.com/repos/:owner/:repo/git/blobs/:file_sha
Accepts Github-defined "url" that conforms to this scheme
https://api.github.com/repos/:owner/:repo/contents/:path/:to/manifest.json | entailment |
def is_valid_github_uri(uri: URI, expected_path_terms: Tuple[str, ...]) -> bool:
"""
Return a bool indicating whether or not the URI fulfills the following specs
Valid Github URIs *must*:
- Have 'https' scheme
- Have 'api.github.com' authority
- Have a path that contains all "expected_path_terms... | Return a bool indicating whether or not the URI fulfills the following specs
Valid Github URIs *must*:
- Have 'https' scheme
- Have 'api.github.com' authority
- Have a path that contains all "expected_path_terms" | entailment |
def validate_blob_uri_contents(contents: bytes, blob_uri: str) -> None:
"""
Raises an exception if the sha1 hash of the contents does not match the hash found in te
blob_uri. Formula for how git calculates the hash found here:
http://alblue.bandlem.com/2011/08/git-tip-of-week-objects.html
"""
bl... | Raises an exception if the sha1 hash of the contents does not match the hash found in te
blob_uri. Formula for how git calculates the hash found here:
http://alblue.bandlem.com/2011/08/git-tip-of-week-objects.html | entailment |
def parse_registry_uri(uri: str) -> RegistryURI:
"""
Validate and return (authority, pkg name, version) from a valid registry URI
"""
validate_registry_uri(uri)
parsed_uri = parse.urlparse(uri)
authority = parsed_uri.netloc
pkg_name = parsed_uri.path.strip("/")
pkg_version = parsed_uri.q... | Validate and return (authority, pkg name, version) from a valid registry URI | entailment |
def is_supported_content_addressed_uri(uri: URI) -> bool:
"""
Returns a bool indicating whether provided uri is currently supported.
Currently Py-EthPM only supports IPFS and Github blob content-addressed uris.
"""
if not is_ipfs_uri(uri) and not is_valid_content_addressed_github_uri(uri):
r... | Returns a bool indicating whether provided uri is currently supported.
Currently Py-EthPM only supports IPFS and Github blob content-addressed uris. | entailment |
def create_BIP122_uri(
chain_id: str, resource_type: str, resource_identifier: str
) -> URI:
"""
See: https://github.com/bitcoin/bips/blob/master/bip-0122.mediawiki
"""
if resource_type != BLOCK:
raise ValueError("Invalid resource_type. Must be one of 'block'")
elif not is_block_or_tran... | See: https://github.com/bitcoin/bips/blob/master/bip-0122.mediawiki | entailment |
def update_w3(self, w3: Web3) -> "Package":
"""
Returns a new instance of `Package` containing the same manifest,
but connected to a different web3 instance.
.. doctest::
>>> new_w3 = Web3(Web3.EthereumTesterProvider())
>>> NewPackage = OwnedPackage.update_w3(new_... | Returns a new instance of `Package` containing the same manifest,
but connected to a different web3 instance.
.. doctest::
>>> new_w3 = Web3(Web3.EthereumTesterProvider())
>>> NewPackage = OwnedPackage.update_w3(new_w3)
>>> assert NewPackage.w3 == new_w3
>>>... | entailment |
def from_file(cls, file_path: Path, w3: Web3) -> "Package":
"""
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``.
"""
if... | 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``. | entailment |
def from_uri(cls, uri: URI, w3: Web3) -> "Package":
"""
Returns a Package object instantiated by a manifest located at a content-addressed URI.
A valid ``Web3`` instance is also required.
URI schemes supported:
- IPFS `ipfs://Qm...`
- HTTP `https://api.g... | Returns a Package object instantiated by a manifest located at a content-addressed URI.
A valid ``Web3`` instance is also required.
URI schemes supported:
- IPFS `ipfs://Qm...`
- HTTP `https://api.github.com/repos/:owner/:repo/git/blobs/:file_sha`
- Registry ... | entailment |
def get_contract_factory(self, name: ContractName) -> Contract:
"""
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.
.. code:: python
Owned = OwnedPackag... | 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.
.. code:: python
Owned = OwnedPackage.get_contract_factory('owned')
In cases where a contract uses a library, t... | entailment |
def get_contract_instance(self, name: ContractName, address: Address) -> Contract:
"""
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 ch... | 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``. | entailment |
def build_dependencies(self) -> "Dependencies":
"""
Return `Dependencies` instance containing the build dependencies available on this Package.
The ``Package`` class should provide access to the full dependency tree.
.. code:: python
>>> owned_package.build_dependencies['zep... | Return `Dependencies` instance containing the build dependencies available on this Package.
The ``Package`` class should provide access to the full dependency tree.
.. code:: python
>>> owned_package.build_dependencies['zeppelin']
<ZeppelinPackage> | entailment |
def deployments(self) -> Union["Deployments", Dict[None, None]]:
"""
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.w... | 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.
.. code:: python
package.deployments.get_instance(... | entailment |
def dummy_ipfs_pin(path: Path) -> Dict[str, str]:
"""
Return IPFS data as if file was pinned to an actual node.
"""
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. | entailment |
def extract_ipfs_path_from_uri(value: str) -> str:
"""
Return the path from an IPFS URI.
Path = IPFS hash & following path.
"""
parse_result = parse.urlparse(value)
if parse_result.netloc:
if parse_result.path:
return "".join((parse_result.netloc, parse_result.path.rstrip("/... | Return the path from an IPFS URI.
Path = IPFS hash & following path. | entailment |
def is_ipfs_uri(value: str) -> bool:
"""
Return a bool indicating whether or not the value is a valid IPFS URI.
"""
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 T... | Return a bool indicating whether or not the value is a valid IPFS URI. | entailment |
def get_instance(self, contract_name: str) -> None:
"""
Fetches a contract instance belonging to deployment
after validating contract name.
"""
self._validate_name_and_references(contract_name)
# Use a deployment's "contract_type" to lookup contract factory
# in c... | Fetches a contract instance belonging to deployment
after validating contract name. | entailment |
def validate_address(address: Any) -> None:
"""
Raise a ValidationError if an address is not canonicalized.
"""
if not is_address(address):
raise ValidationError(f"Expected an address, got: {address}")
if not is_canonical_address(address):
raise ValidationError(
"Py-EthPM... | Raise a ValidationError if an address is not canonicalized. | entailment |
def validate_empty_bytes(offset: int, length: int, bytecode: bytes) -> None:
"""
Validates that segment [`offset`:`offset`+`length`] of
`bytecode` is comprised of empty bytes (b'\00').
"""
slot_length = offset + length
slot = bytecode[offset:slot_length]
if slot != bytearray(length):
... | Validates that segment [`offset`:`offset`+`length`] of
`bytecode` is comprised of empty bytes (b'\00'). | entailment |
def validate_package_name(pkg_name: str) -> None:
"""
Raise an exception if the value is not a valid package name
as defined in the EthPM-Spec.
"""
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. | entailment |
def validate_registry_uri(uri: str) -> None:
"""
Raise an exception if the URI does not conform to the registry URI scheme.
"""
parsed = parse.urlparse(uri)
scheme, authority, pkg_name, query = (
parsed.scheme,
parsed.netloc,
parsed.path,
parsed.query,
)
valid... | Raise an exception if the URI does not conform to the registry URI scheme. | entailment |
def validate_registry_uri_authority(auth: str) -> None:
"""
Raise an exception if the authority is not a valid ENS domain
or a valid checksummed contract address.
"""
if is_ens_domain(auth) is False and not is_checksum_address(auth):
raise ValidationError(f"{auth} is not a valid registry URI... | Raise an exception if the authority is not a valid ENS domain
or a valid checksummed contract address. | entailment |
def validate_registry_uri_version(query: str) -> None:
"""
Raise an exception if the version param is malformed.
"""
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. | entailment |
def validate_single_matching_uri(all_blockchain_uris: List[str], w3: Web3) -> str:
"""
Return a single block URI after validating that it is the *only* URI in
all_blockchain_uris that matches the w3 instance.
"""
matching_uris = [
uri for uri in all_blockchain_uris if check_if_chain_matches_... | Return a single block URI after validating that it is the *only* URI in
all_blockchain_uris that matches the w3 instance. | entailment |
def validate_meta_object(meta: Dict[str, Any], allow_extra_meta_fields: bool) -> None:
"""
Validates that every key is one of `META_FIELDS` and has a value of the expected type.
"""
for key, value in meta.items():
if key in META_FIELDS:
if type(value) is not META_FIELDS[key]:
... | Validates that every key is one of `META_FIELDS` and has a value of the expected type. | entailment |
def validate_manifest_against_schema(manifest: Dict[str, Any]) -> None:
"""
Load and validate manifest against schema
located at MANIFEST_SCHEMA_PATH.
"""
schema_data = _load_schema_data()
try:
validate(manifest, schema_data)
except jsonValidationError as e:
raise ValidationE... | Load and validate manifest against schema
located at MANIFEST_SCHEMA_PATH. | entailment |
def validate_manifest_deployments(manifest: Dict[str, Any]) -> None:
"""
Validate that a manifest's deployments contracts reference existing contract_types.
"""
if set(("contract_types", "deployments")).issubset(manifest):
all_contract_types = list(manifest["contract_types"].keys())
all_... | Validate that a manifest's deployments contracts reference existing contract_types. | entailment |
def validate_raw_manifest_format(raw_manifest: str) -> None:
"""
Raise a ValidationError if a manifest ...
- is not tightly packed (i.e. no linebreaks or extra whitespace)
- does not have alphabetically sorted keys
- has duplicate keys
- is not UTF-8 encoded
- has a trailing newline
"""
... | Raise a ValidationError if a manifest ...
- is not tightly packed (i.e. no linebreaks or extra whitespace)
- does not have alphabetically sorted keys
- has duplicate keys
- is not UTF-8 encoded
- has a trailing newline | entailment |
def build(obj: Dict[str, Any], *fns: Callable[..., Any]) -> Dict[str, Any]:
"""
Wrapper function to pipe manifest through build functions.
Does not validate the manifest by default.
"""
return pipe(obj, *fns) | Wrapper function to pipe manifest through build functions.
Does not validate the manifest by default. | entailment |
def get_names_and_paths(compiler_output: Dict[str, Any]) -> Dict[str, str]:
"""
Return a mapping of contract name to relative path as defined in compiler output.
"""
return {
contract_name: make_path_relative(path)
for path in compiler_output
for contract_name in compiler_output[... | Return a mapping of contract name to relative path as defined in compiler output. | entailment |
def make_path_relative(path: str) -> str:
"""
Returns the given path prefixed with "./" if the path
is not already relative in the compiler output.
"""
if "../" in path:
raise ManifestBuildingError(
f"Path: {path} appears to be outside of the virtual source tree. "
"P... | Returns the given path prefixed with "./" if the path
is not already relative in the compiler output. | entailment |
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_byte... | 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.
To include specific contract_data fields, add kwarg set to True (i.e. `abi=True`)
To alias a contract_type, include a kw... | entailment |
def filter_all_data_by_selected_fields(
all_type_data: Dict[str, Any], selected_fields: List[str]
) -> Iterable[Tuple[str, Any]]:
"""
Raises exception if selected field data is not available in the contract type data
automatically gathered by normalize_compiler_output. Otherwise, returns the data.
"... | Raises exception if selected field data is not available in the contract type data
automatically gathered by normalize_compiler_output. Otherwise, returns the data. | entailment |
def normalize_compiler_output(compiler_output: Dict[str, Any]) -> Dict[str, Any]:
"""
Return compiler output with normalized fields for each contract type,
as specified in `normalize_contract_type`.
"""
paths_and_names = [
(path, contract_name)
for path in compiler_output
for... | Return compiler output with normalized fields for each contract type,
as specified in `normalize_contract_type`. | entailment |
def normalize_contract_type(
contract_type_data: Dict[str, Any]
) -> Iterable[Tuple[str, Any]]:
"""
Serialize contract_data found in compiler output to the defined fields.
"""
yield "abi", contract_type_data["abi"]
if "evm" in contract_type_data:
if "bytecode" in contract_type_data["evm"... | Serialize contract_data found in compiler output to the defined fields. | entailment |
def process_bytecode(link_refs: Dict[str, Any], bytecode: bytes) -> str:
"""
Replace link_refs in bytecode with 0's.
"""
all_offsets = [y for x in link_refs.values() for y in x.values()]
# Link ref validation.
validate_link_ref_fns = (
validate_link_ref(ref["start"] * 2, ref["length"] * ... | Replace link_refs in bytecode with 0's. | entailment |
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:
"""
Returns a callable that allows the user to add deployments of the same type
acr... | Returns a callable that allows the user to add deployments of the same type
across multiple chains. | entailment |
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:
... | 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. | entailment |
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]]:
"""
Returns a dict with proper... | Returns a dict with properly formatted deployment data. | entailment |
def init_manifest(
package_name: str, version: str, manifest_version: Optional[str] = "2"
) -> Dict[str, Any]:
"""
Returns an initial dict with the minimal requried fields for a valid manifest.
Should only be used as the first fn to be piped into a `build()` pipeline.
"""
return {
"packa... | Returns an initial dict with the minimal requried fields for a valid manifest.
Should only be used as the first fn to be piped into a `build()` pipeline. | entailment |
def write_to_disk(
manifest_root_dir: Optional[Path] = None,
manifest_name: Optional[str] = None,
prettify: Optional[bool] = False,
) -> Manifest:
"""
Write the active manifest to disk
Defaults
- Writes manifest to cwd unless Path is provided as manifest_root_dir.
- Writes manifest with ... | Write the active manifest to disk
Defaults
- Writes manifest to cwd unless Path is provided as manifest_root_dir.
- Writes manifest with a filename of Manifest[version].json unless a desired
manifest name (which must end in json) is provided as manifest_name.
- Writes the minified manifest version t... | entailment |
def pin_to_ipfs(
manifest: Manifest, *, backend: BaseIPFSBackend, prettify: Optional[bool] = False
) -> List[Dict[str, str]]:
"""
Returns the IPFS pin data after pinning the manifest to the provided IPFS Backend.
`pin_to_ipfs()` Should *always* be the last argument in a builder, as it will return the p... | Returns the IPFS pin data after pinning the manifest to the provided IPFS Backend.
`pin_to_ipfs()` Should *always* be the last argument in a builder, as it will return the pin
data and not the manifest. | entailment |
def create_parser(default_name: str) -> argparse.ArgumentParser:
"""
Creates the default brewblox_service ArgumentParser.
Service-agnostic arguments are added.
The parser allows calling code to add additional arguments before using it in create_app()
Args:
default_name (str):
d... | Creates the default brewblox_service ArgumentParser.
Service-agnostic arguments are added.
The parser allows calling code to add additional arguments before using it in create_app()
Args:
default_name (str):
default value for the --name commandline argument.
Returns:
argpa... | entailment |
def create_app(
default_name: str = None,
parser: argparse.ArgumentParser = None,
raw_args: List[str] = None
) -> web.Application:
"""
Creates and configures an Aiohttp application.
Args:
default_name (str, optional):
Default value for the --name commandline argu... | Creates and configures an Aiohttp application.
Args:
default_name (str, optional):
Default value for the --name commandline argument.
This value is required if `parser` is not provided.
This value will be ignored if `parser` is provided.
parser (argparse.Argumen... | entailment |
def furnish(app: web.Application):
"""
Configures Application routes, readying it for running.
This function modifies routes and resources that were added by calling code,
and must be called immediately prior to `run(app)`.
Args:
app (web.Application):
The Aiohttp Application a... | Configures Application routes, readying it for running.
This function modifies routes and resources that were added by calling code,
and must be called immediately prior to `run(app)`.
Args:
app (web.Application):
The Aiohttp Application as created by `create_app()` | entailment |
def run(app: web.Application):
"""
Runs the application in an async context.
This function will block indefinitely until the application is shut down.
Args:
app (web.Application):
The Aiohttp Application as created by `create_app()`
"""
host = app['config']['host']
port ... | Runs the application in an async context.
This function will block indefinitely until the application is shut down.
Args:
app (web.Application):
The Aiohttp Application as created by `create_app()` | entailment |
def get_linked_deployments(deployments: Dict[str, Any]) -> Dict[str, Any]:
"""
Returns all deployments found in a chain URI's deployment data that contain link dependencies.
"""
linked_deployments = {
dep: data
for dep, data in deployments.items()
if get_in(("runtime_bytecode", "... | Returns all deployments found in a chain URI's deployment data that contain link dependencies. | entailment |
def validate_linked_references(
link_deps: Tuple[Tuple[int, bytes], ...], bytecode: bytes
) -> None:
"""
Validates that normalized linked_references (offset, expected_bytes)
match the corresponding bytecode.
"""
offsets, values = zip(*link_deps)
for idx, offset in enumerate(offsets):
... | Validates that normalized linked_references (offset, expected_bytes)
match the corresponding bytecode. | entailment |
def normalize_linked_references(
data: List[Dict[str, Any]]
) -> Generator[Tuple[int, str, str], None, None]:
"""
Return a tuple of information representing all insertions of a linked reference.
(offset, type, value)
"""
for deployment in data:
for offset in deployment["offsets"]:
... | Return a tuple of information representing all insertions of a linked reference.
(offset, type, value) | entailment |
def validate_deployments_tx_receipt(
deployments: Dict[str, Any], w3: Web3, allow_missing_data: bool = False
) -> None:
"""
Validate that address and block hash found in deployment data match what is found on-chain.
:allow_missing_data: by default, enforces validation of address and blockHash.
"""
... | Validate that address and block hash found in deployment data match what is found on-chain.
:allow_missing_data: by default, enforces validation of address and blockHash. | entailment |
def is_prelinked_bytecode(bytecode: bytes, link_refs: List[Dict[str, Any]]) -> bool:
"""
Returns False if all expected link_refs are unlinked, otherwise returns True.
todo support partially pre-linked bytecode (currently all or nothing)
"""
for link_ref in link_refs:
for offset in link_ref["... | Returns False if all expected link_refs are unlinked, otherwise returns True.
todo support partially pre-linked bytecode (currently all or nothing) | entailment |
def apply_all_link_refs(
bytecode: bytes, link_refs: List[Dict[str, Any]], attr_dict: Dict[str, str]
) -> bytes:
"""
Applies all link references corresponding to a valid attr_dict to the bytecode.
"""
if link_refs is None:
return bytecode
link_fns = (
apply_link_ref(offset, ref["... | Applies all link references corresponding to a valid attr_dict to the bytecode. | entailment |
def apply_link_ref(offset: int, length: int, value: bytes, bytecode: bytes) -> bytes:
"""
Returns the new bytecode with `value` put into the location indicated by `offset` and `length`.
"""
try:
validate_empty_bytes(offset, length, bytecode)
except ValidationError:
raise BytecodeLink... | Returns the new bytecode with `value` put into the location indicated by `offset` and `length`. | entailment |
def link_bytecode(cls, attr_dict: Dict[str, str]) -> Type["LinkableContract"]:
"""
Return a cloned contract factory with the deployment / runtime bytecode linked.
:attr_dict: Dict[`ContractType`: `Address`] for all deployment and runtime link references.
"""
if not cls.unlinked_... | Return a cloned contract factory with the deployment / runtime bytecode linked.
:attr_dict: Dict[`ContractType`: `Address`] for all deployment and runtime link references. | entailment |
def validate_attr_dict(self, attr_dict: Dict[str, str]) -> None:
"""
Validates that ContractType keys in attr_dict reference existing manifest ContractTypes.
"""
attr_dict_names = list(attr_dict.keys())
if not self.unlinked_references and not self.linked_references:
... | Validates that ContractType keys in attr_dict reference existing manifest ContractTypes. | entailment |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.