Instruction
stringlengths
362
7.83k
output_code
stringlengths
1
945
Given snippet: <|code_start|> """Read cloudtype and flag info from filename.""" ctth = CtthObj() ctype = CtypeObj() cma = CmaObj() ctth.height = patmosx_nc.variables['cld_height_acha'][0, :, :].astype(np.float) ctth.h_nodata = patmosx_nc.variables['cld_height_acha']._FillValue if np.ma.is_masked(ctth.height): ctth.height.data[ctth.height.mask] = ATRAIN_MATCH_NODATA ctth.height = ctth.height.data ctth.height = 1000*ctth.height cf = patmosx_nc.variables['cloud_fraction'][0, :, :].astype(np.float) cma.cma_ext = np.where(cf >= 0.5, 1, 0) if np.ma.is_masked(cf): cma.cma_ext[cf.mask] = 255 ctype.phaseflag = None ctype.ct_conditions = None return ctype, cma, ctth def read_patmosx_angobj(patmosx_nc): """Read angles info from filename.""" angle_obj = ImagerAngObj() angle_obj.satz.data = patmosx_nc.variables['sensor_zenith_angle'][0, :, :].astype(np.float) angle_obj.sunz.data = patmosx_nc.variables['solar_zenith_angle'][0, :, :].astype(np.float) angle_obj.azidiff.data = None return angle_obj def read_patmosx_geoobj(patmosx_nc, filename, cross, SETTINGS): """Read geolocation and time info from filename.""" <|code_end|> , continue by predicting the next line. Consider current file imports: import atrain_match.config as config import os import netCDF4 import numpy as np import calendar import logging from atrain_match.utils.runutils import do_some_geo_obj_logging from atrain_match.cloudproducts.read_pps import ( AllImagerData, CtypeObj, CtthObj, CmaObj, ImagerAngObj) from datetime import datetime from datetime import timedelta from pyhdf.SD import SD, SDC and context: # Path: atrain_match/utils/runutils.py # def do_some_geo_obj_logging(GeoObj): # import time # tim1 = time.strftime("%Y%m%d %H:%M", # time.gmtime(GeoObj.sec1970_start)) # tim2 = time.strftime("%Y%m%d %H:%M", # time.gmtime(GeoObj.sec1970_end)) # logger.debug("Starttime: %s, end time: %s", tim1, tim2) # logger.debug("Min lon: %f, max lon: %d", # np.min(np.where( # np.equal(GeoObj.longitude, GeoObj.nodata), # 99999, # GeoObj.longitude)), # np.max(GeoObj.longitude)) # logger.debug("Min lat: %d, max lat: %d", # np.min(np.where( # np.equal(GeoObj.latitude, GeoObj.nodata), # 99999, # GeoObj.latitude)), # np.max(GeoObj.latitude)) # # Path: atrain_match/cloudproducts/read_pps.py # class AllImagerData(object): # """Class to hold all imager cloudproduct data.""" # # def __init__(self, array_dict=None): # """Init with data from array_dict, or empty.""" # self.latitude = None # self.longitude = None # self.nodata = None # latlon nodata # self.sec1970_end = None # self.sec1970_start = None # self.time = None # self.num_of_lines = None # self.instrument = "imager" # # self.imager_geo = None # self.imager_angles = None # self.imager_channeldata = None # self.ctype = None # self.cma = None # self.ctth = None # self.aux = AuxiliaryObj({'surftemp': None}) # self.cpp = None # self.nwp_segments = None # if array_dict is not None: # self.__dict__.update(array_dict) # # class CtypeObj: # """Class to hold imager data for cloud type.""" # # def __init__(self): # """Init all datasets to None.""" # self.cloudtype = None # self.ct_statusflag = None # self.ct_quality = None # self.ct_conditions = None # self.phaseflag = None # v2012 # # class CtthObj: # """Class to hold imager data for CTTH.""" # # def __init__(self): # """Init all datasets to None.""" # self.height = None # self.height_corr = None # self.temperature = None # self.pressure = None # self.ctth_statusflag = None # # class CmaObj: # """Class to hold imager data for CMA and CMAPROB.""" # # def __init__(self): # """Init all datasets to None.""" # self.cma_ext = None # self.cma_quality = None # self.cma_bin = None # self.cma_prob = None # self.cma_aflag = None # self.cma_testlist0 = None # new in v2018 # self.cma_testlist1 = None # new in v2018 # self.cma_testlist2 = None # new in v2018 # self.cma_testlist3 = None # new in v2018 # self.cma_testlist4 = None # new in v2018 # self.cma_testlist5 = None # new in v2018 # # class ImagerAngObj(object): # """Class to hold imager angle data.""" # # def __init__(self): # self.satz = SmallDataObject() # self.sunz = SmallDataObject() # self.satazimuth = SmallDataObject() # self.sunazimuth = SmallDataObject() # self.azidiff = SmallDataObject() which might include code, classes, or functions. Output only the next line.
cloudproducts = AllImagerData()
Continue the code snippet: <|code_start|> if ".nc" in filename: return patmosx_read_all_nc(filename, cross, SETTINGS) else: return patmosx_read_all_hdf(filename, cross, SETTINGS) def patmosx_read_all_nc(filename, cross, SETTINGS): """Read geolocation, angles info, ctth, and cma.""" patmosx_nc = netCDF4.Dataset(filename, 'r', format='NETCDF4') logger.info("Opening file %s", filename) logger.info("Reading longitude, latitude and time ...") cloudproducts = read_patmosx_geoobj(patmosx_nc, filename, cross, SETTINGS) logger.info("Reading angles ...") cloudproducts.imager_angles = read_patmosx_angobj(patmosx_nc) logger.info("Reading cloud type ...") # , angle_obj) ctype, cma, ctth = read_patmosx_ctype_cmask_ctth(patmosx_nc) cloudproducts.cma = cma cloudproducts.ctth = ctth cloudproducts.ctype = ctype logger.info("Not reading surface temperature") logger.info("Not reading cloud microphysical properties") logger.info("Not reading channel data") return cloudproducts def read_patmosx_ctype_cmask_ctth(patmosx_nc): """Read cloudtype and flag info from filename.""" ctth = CtthObj() <|code_end|> . Use current file imports: import atrain_match.config as config import os import netCDF4 import numpy as np import calendar import logging from atrain_match.utils.runutils import do_some_geo_obj_logging from atrain_match.cloudproducts.read_pps import ( AllImagerData, CtypeObj, CtthObj, CmaObj, ImagerAngObj) from datetime import datetime from datetime import timedelta from pyhdf.SD import SD, SDC and context (classes, functions, or code) from other files: # Path: atrain_match/utils/runutils.py # def do_some_geo_obj_logging(GeoObj): # import time # tim1 = time.strftime("%Y%m%d %H:%M", # time.gmtime(GeoObj.sec1970_start)) # tim2 = time.strftime("%Y%m%d %H:%M", # time.gmtime(GeoObj.sec1970_end)) # logger.debug("Starttime: %s, end time: %s", tim1, tim2) # logger.debug("Min lon: %f, max lon: %d", # np.min(np.where( # np.equal(GeoObj.longitude, GeoObj.nodata), # 99999, # GeoObj.longitude)), # np.max(GeoObj.longitude)) # logger.debug("Min lat: %d, max lat: %d", # np.min(np.where( # np.equal(GeoObj.latitude, GeoObj.nodata), # 99999, # GeoObj.latitude)), # np.max(GeoObj.latitude)) # # Path: atrain_match/cloudproducts/read_pps.py # class AllImagerData(object): # """Class to hold all imager cloudproduct data.""" # # def __init__(self, array_dict=None): # """Init with data from array_dict, or empty.""" # self.latitude = None # self.longitude = None # self.nodata = None # latlon nodata # self.sec1970_end = None # self.sec1970_start = None # self.time = None # self.num_of_lines = None # self.instrument = "imager" # # self.imager_geo = None # self.imager_angles = None # self.imager_channeldata = None # self.ctype = None # self.cma = None # self.ctth = None # self.aux = AuxiliaryObj({'surftemp': None}) # self.cpp = None # self.nwp_segments = None # if array_dict is not None: # self.__dict__.update(array_dict) # # class CtypeObj: # """Class to hold imager data for cloud type.""" # # def __init__(self): # """Init all datasets to None.""" # self.cloudtype = None # self.ct_statusflag = None # self.ct_quality = None # self.ct_conditions = None # self.phaseflag = None # v2012 # # class CtthObj: # """Class to hold imager data for CTTH.""" # # def __init__(self): # """Init all datasets to None.""" # self.height = None # self.height_corr = None # self.temperature = None # self.pressure = None # self.ctth_statusflag = None # # class CmaObj: # """Class to hold imager data for CMA and CMAPROB.""" # # def __init__(self): # """Init all datasets to None.""" # self.cma_ext = None # self.cma_quality = None # self.cma_bin = None # self.cma_prob = None # self.cma_aflag = None # self.cma_testlist0 = None # new in v2018 # self.cma_testlist1 = None # new in v2018 # self.cma_testlist2 = None # new in v2018 # self.cma_testlist3 = None # new in v2018 # self.cma_testlist4 = None # new in v2018 # self.cma_testlist5 = None # new in v2018 # # class ImagerAngObj(object): # """Class to hold imager angle data.""" # # def __init__(self): # self.satz = SmallDataObject() # self.sunz = SmallDataObject() # self.satazimuth = SmallDataObject() # self.sunazimuth = SmallDataObject() # self.azidiff = SmallDataObject() . Output only the next line.
ctype = CtypeObj()
Based on the snippet: <|code_start|>def patmosx_read_all(filename, cross, SETTINGS): if ".nc" in filename: return patmosx_read_all_nc(filename, cross, SETTINGS) else: return patmosx_read_all_hdf(filename, cross, SETTINGS) def patmosx_read_all_nc(filename, cross, SETTINGS): """Read geolocation, angles info, ctth, and cma.""" patmosx_nc = netCDF4.Dataset(filename, 'r', format='NETCDF4') logger.info("Opening file %s", filename) logger.info("Reading longitude, latitude and time ...") cloudproducts = read_patmosx_geoobj(patmosx_nc, filename, cross, SETTINGS) logger.info("Reading angles ...") cloudproducts.imager_angles = read_patmosx_angobj(patmosx_nc) logger.info("Reading cloud type ...") # , angle_obj) ctype, cma, ctth = read_patmosx_ctype_cmask_ctth(patmosx_nc) cloudproducts.cma = cma cloudproducts.ctth = ctth cloudproducts.ctype = ctype logger.info("Not reading surface temperature") logger.info("Not reading cloud microphysical properties") logger.info("Not reading channel data") return cloudproducts def read_patmosx_ctype_cmask_ctth(patmosx_nc): """Read cloudtype and flag info from filename.""" <|code_end|> , predict the immediate next line with the help of imports: import atrain_match.config as config import os import netCDF4 import numpy as np import calendar import logging from atrain_match.utils.runutils import do_some_geo_obj_logging from atrain_match.cloudproducts.read_pps import ( AllImagerData, CtypeObj, CtthObj, CmaObj, ImagerAngObj) from datetime import datetime from datetime import timedelta from pyhdf.SD import SD, SDC and context (classes, functions, sometimes code) from other files: # Path: atrain_match/utils/runutils.py # def do_some_geo_obj_logging(GeoObj): # import time # tim1 = time.strftime("%Y%m%d %H:%M", # time.gmtime(GeoObj.sec1970_start)) # tim2 = time.strftime("%Y%m%d %H:%M", # time.gmtime(GeoObj.sec1970_end)) # logger.debug("Starttime: %s, end time: %s", tim1, tim2) # logger.debug("Min lon: %f, max lon: %d", # np.min(np.where( # np.equal(GeoObj.longitude, GeoObj.nodata), # 99999, # GeoObj.longitude)), # np.max(GeoObj.longitude)) # logger.debug("Min lat: %d, max lat: %d", # np.min(np.where( # np.equal(GeoObj.latitude, GeoObj.nodata), # 99999, # GeoObj.latitude)), # np.max(GeoObj.latitude)) # # Path: atrain_match/cloudproducts/read_pps.py # class AllImagerData(object): # """Class to hold all imager cloudproduct data.""" # # def __init__(self, array_dict=None): # """Init with data from array_dict, or empty.""" # self.latitude = None # self.longitude = None # self.nodata = None # latlon nodata # self.sec1970_end = None # self.sec1970_start = None # self.time = None # self.num_of_lines = None # self.instrument = "imager" # # self.imager_geo = None # self.imager_angles = None # self.imager_channeldata = None # self.ctype = None # self.cma = None # self.ctth = None # self.aux = AuxiliaryObj({'surftemp': None}) # self.cpp = None # self.nwp_segments = None # if array_dict is not None: # self.__dict__.update(array_dict) # # class CtypeObj: # """Class to hold imager data for cloud type.""" # # def __init__(self): # """Init all datasets to None.""" # self.cloudtype = None # self.ct_statusflag = None # self.ct_quality = None # self.ct_conditions = None # self.phaseflag = None # v2012 # # class CtthObj: # """Class to hold imager data for CTTH.""" # # def __init__(self): # """Init all datasets to None.""" # self.height = None # self.height_corr = None # self.temperature = None # self.pressure = None # self.ctth_statusflag = None # # class CmaObj: # """Class to hold imager data for CMA and CMAPROB.""" # # def __init__(self): # """Init all datasets to None.""" # self.cma_ext = None # self.cma_quality = None # self.cma_bin = None # self.cma_prob = None # self.cma_aflag = None # self.cma_testlist0 = None # new in v2018 # self.cma_testlist1 = None # new in v2018 # self.cma_testlist2 = None # new in v2018 # self.cma_testlist3 = None # new in v2018 # self.cma_testlist4 = None # new in v2018 # self.cma_testlist5 = None # new in v2018 # # class ImagerAngObj(object): # """Class to hold imager angle data.""" # # def __init__(self): # self.satz = SmallDataObject() # self.sunz = SmallDataObject() # self.satazimuth = SmallDataObject() # self.sunazimuth = SmallDataObject() # self.azidiff = SmallDataObject() . Output only the next line.
ctth = CtthObj()
Using the snippet: <|code_start|> return patmosx_read_all_nc(filename, cross, SETTINGS) else: return patmosx_read_all_hdf(filename, cross, SETTINGS) def patmosx_read_all_nc(filename, cross, SETTINGS): """Read geolocation, angles info, ctth, and cma.""" patmosx_nc = netCDF4.Dataset(filename, 'r', format='NETCDF4') logger.info("Opening file %s", filename) logger.info("Reading longitude, latitude and time ...") cloudproducts = read_patmosx_geoobj(patmosx_nc, filename, cross, SETTINGS) logger.info("Reading angles ...") cloudproducts.imager_angles = read_patmosx_angobj(patmosx_nc) logger.info("Reading cloud type ...") # , angle_obj) ctype, cma, ctth = read_patmosx_ctype_cmask_ctth(patmosx_nc) cloudproducts.cma = cma cloudproducts.ctth = ctth cloudproducts.ctype = ctype logger.info("Not reading surface temperature") logger.info("Not reading cloud microphysical properties") logger.info("Not reading channel data") return cloudproducts def read_patmosx_ctype_cmask_ctth(patmosx_nc): """Read cloudtype and flag info from filename.""" ctth = CtthObj() ctype = CtypeObj() <|code_end|> , determine the next line of code. You have imports: import atrain_match.config as config import os import netCDF4 import numpy as np import calendar import logging from atrain_match.utils.runutils import do_some_geo_obj_logging from atrain_match.cloudproducts.read_pps import ( AllImagerData, CtypeObj, CtthObj, CmaObj, ImagerAngObj) from datetime import datetime from datetime import timedelta from pyhdf.SD import SD, SDC and context (class names, function names, or code) available: # Path: atrain_match/utils/runutils.py # def do_some_geo_obj_logging(GeoObj): # import time # tim1 = time.strftime("%Y%m%d %H:%M", # time.gmtime(GeoObj.sec1970_start)) # tim2 = time.strftime("%Y%m%d %H:%M", # time.gmtime(GeoObj.sec1970_end)) # logger.debug("Starttime: %s, end time: %s", tim1, tim2) # logger.debug("Min lon: %f, max lon: %d", # np.min(np.where( # np.equal(GeoObj.longitude, GeoObj.nodata), # 99999, # GeoObj.longitude)), # np.max(GeoObj.longitude)) # logger.debug("Min lat: %d, max lat: %d", # np.min(np.where( # np.equal(GeoObj.latitude, GeoObj.nodata), # 99999, # GeoObj.latitude)), # np.max(GeoObj.latitude)) # # Path: atrain_match/cloudproducts/read_pps.py # class AllImagerData(object): # """Class to hold all imager cloudproduct data.""" # # def __init__(self, array_dict=None): # """Init with data from array_dict, or empty.""" # self.latitude = None # self.longitude = None # self.nodata = None # latlon nodata # self.sec1970_end = None # self.sec1970_start = None # self.time = None # self.num_of_lines = None # self.instrument = "imager" # # self.imager_geo = None # self.imager_angles = None # self.imager_channeldata = None # self.ctype = None # self.cma = None # self.ctth = None # self.aux = AuxiliaryObj({'surftemp': None}) # self.cpp = None # self.nwp_segments = None # if array_dict is not None: # self.__dict__.update(array_dict) # # class CtypeObj: # """Class to hold imager data for cloud type.""" # # def __init__(self): # """Init all datasets to None.""" # self.cloudtype = None # self.ct_statusflag = None # self.ct_quality = None # self.ct_conditions = None # self.phaseflag = None # v2012 # # class CtthObj: # """Class to hold imager data for CTTH.""" # # def __init__(self): # """Init all datasets to None.""" # self.height = None # self.height_corr = None # self.temperature = None # self.pressure = None # self.ctth_statusflag = None # # class CmaObj: # """Class to hold imager data for CMA and CMAPROB.""" # # def __init__(self): # """Init all datasets to None.""" # self.cma_ext = None # self.cma_quality = None # self.cma_bin = None # self.cma_prob = None # self.cma_aflag = None # self.cma_testlist0 = None # new in v2018 # self.cma_testlist1 = None # new in v2018 # self.cma_testlist2 = None # new in v2018 # self.cma_testlist3 = None # new in v2018 # self.cma_testlist4 = None # new in v2018 # self.cma_testlist5 = None # new in v2018 # # class ImagerAngObj(object): # """Class to hold imager angle data.""" # # def __init__(self): # self.satz = SmallDataObject() # self.sunz = SmallDataObject() # self.satazimuth = SmallDataObject() # self.sunazimuth = SmallDataObject() # self.azidiff = SmallDataObject() . Output only the next line.
cma = CmaObj()
Next line prediction: <|code_start|> cloudproducts.ctype = ctype logger.info("Not reading surface temperature") logger.info("Not reading cloud microphysical properties") logger.info("Not reading channel data") return cloudproducts def read_patmosx_ctype_cmask_ctth(patmosx_nc): """Read cloudtype and flag info from filename.""" ctth = CtthObj() ctype = CtypeObj() cma = CmaObj() ctth.height = patmosx_nc.variables['cld_height_acha'][0, :, :].astype(np.float) ctth.h_nodata = patmosx_nc.variables['cld_height_acha']._FillValue if np.ma.is_masked(ctth.height): ctth.height.data[ctth.height.mask] = ATRAIN_MATCH_NODATA ctth.height = ctth.height.data ctth.height = 1000*ctth.height cf = patmosx_nc.variables['cloud_fraction'][0, :, :].astype(np.float) cma.cma_ext = np.where(cf >= 0.5, 1, 0) if np.ma.is_masked(cf): cma.cma_ext[cf.mask] = 255 ctype.phaseflag = None ctype.ct_conditions = None return ctype, cma, ctth def read_patmosx_angobj(patmosx_nc): """Read angles info from filename.""" <|code_end|> . Use current file imports: (import atrain_match.config as config import os import netCDF4 import numpy as np import calendar import logging from atrain_match.utils.runutils import do_some_geo_obj_logging from atrain_match.cloudproducts.read_pps import ( AllImagerData, CtypeObj, CtthObj, CmaObj, ImagerAngObj) from datetime import datetime from datetime import timedelta from pyhdf.SD import SD, SDC) and context including class names, function names, or small code snippets from other files: # Path: atrain_match/utils/runutils.py # def do_some_geo_obj_logging(GeoObj): # import time # tim1 = time.strftime("%Y%m%d %H:%M", # time.gmtime(GeoObj.sec1970_start)) # tim2 = time.strftime("%Y%m%d %H:%M", # time.gmtime(GeoObj.sec1970_end)) # logger.debug("Starttime: %s, end time: %s", tim1, tim2) # logger.debug("Min lon: %f, max lon: %d", # np.min(np.where( # np.equal(GeoObj.longitude, GeoObj.nodata), # 99999, # GeoObj.longitude)), # np.max(GeoObj.longitude)) # logger.debug("Min lat: %d, max lat: %d", # np.min(np.where( # np.equal(GeoObj.latitude, GeoObj.nodata), # 99999, # GeoObj.latitude)), # np.max(GeoObj.latitude)) # # Path: atrain_match/cloudproducts/read_pps.py # class AllImagerData(object): # """Class to hold all imager cloudproduct data.""" # # def __init__(self, array_dict=None): # """Init with data from array_dict, or empty.""" # self.latitude = None # self.longitude = None # self.nodata = None # latlon nodata # self.sec1970_end = None # self.sec1970_start = None # self.time = None # self.num_of_lines = None # self.instrument = "imager" # # self.imager_geo = None # self.imager_angles = None # self.imager_channeldata = None # self.ctype = None # self.cma = None # self.ctth = None # self.aux = AuxiliaryObj({'surftemp': None}) # self.cpp = None # self.nwp_segments = None # if array_dict is not None: # self.__dict__.update(array_dict) # # class CtypeObj: # """Class to hold imager data for cloud type.""" # # def __init__(self): # """Init all datasets to None.""" # self.cloudtype = None # self.ct_statusflag = None # self.ct_quality = None # self.ct_conditions = None # self.phaseflag = None # v2012 # # class CtthObj: # """Class to hold imager data for CTTH.""" # # def __init__(self): # """Init all datasets to None.""" # self.height = None # self.height_corr = None # self.temperature = None # self.pressure = None # self.ctth_statusflag = None # # class CmaObj: # """Class to hold imager data for CMA and CMAPROB.""" # # def __init__(self): # """Init all datasets to None.""" # self.cma_ext = None # self.cma_quality = None # self.cma_bin = None # self.cma_prob = None # self.cma_aflag = None # self.cma_testlist0 = None # new in v2018 # self.cma_testlist1 = None # new in v2018 # self.cma_testlist2 = None # new in v2018 # self.cma_testlist3 = None # new in v2018 # self.cma_testlist4 = None # new in v2018 # self.cma_testlist5 = None # new in v2018 # # class ImagerAngObj(object): # """Class to hold imager angle data.""" # # def __init__(self): # self.satz = SmallDataObject() # self.sunz = SmallDataObject() # self.satazimuth = SmallDataObject() # self.sunazimuth = SmallDataObject() # self.azidiff = SmallDataObject() . Output only the next line.
angle_obj = ImagerAngObj()
Next line prediction: <|code_start|> @property def cols(self): # self._cols = np.array(self._cols, dtype=np.int64) return np.ma.array(self._cols, mask=self.mask, fill_value=-NODATA, hard_mask=True) @property def time_diff(self): """Time difference in seconds""" if self._time_diff is None: return None # Only use pixel mask return np.ma.array(self._time_diff, mask=self._pixel_mask, fill_value=np.inf, hard_mask=True) @time_diff.setter def time_diff(self, value): self._time_diff = value @property def mask(self): if None not in (self.time_diff, self.time_threshold): return (self._pixel_mask + (abs(self.time_diff) > self.time_threshold)) return self._pixel_mask def match_lonlat(source, target, <|code_end|> . Use current file imports: (import numpy as np import logging from atrain_match.config import RESOLUTION, NODATA from pyresample.geometry import SwathDefinition from pyresample.kd_tree import get_neighbour_info from pyresample.kd_tree import get_sample_from_neighbour_info) and context including class names, function names, or small code snippets from other files: # Path: atrain_match/config.py # RESOLUTION = int(os.environ.get('ATRAIN_RESOLUTION', 5)) # # NODATA = -9 . Output only the next line.
radius_of_influence=0.7*RESOLUTION*1000.0,
Predict the next line for this snippet: <|code_start|># along with atrain_match. If not, see <http://www.gnu.org/licenses/>. """Match TRUTH and IMAGER data.""" # from __future__ import with_statement logger = logging.getLogger(__name__) class MatchMapper(object): """ Map arrays from one swath to another. Note that MatchMapper always works with an extra dimension: neighbour """ def __init__(self, rows, cols, pixel_mask, time_diff=None, time_threshold=None): self._rows = np.array(rows).astype(np.int) self._cols = np.array(cols).astype(np.int) self._pixel_mask = pixel_mask self._time_diff = time_diff self.time_threshold = time_threshold def __call__(self, array): """Maps *array* to target swath.""" return np.ma.array(array[self.rows, self.cols], mask=self.mask) @property def rows(self): # self._rows = np.array(self._rows, dtype=np.int64) <|code_end|> with the help of current file imports: import numpy as np import logging from atrain_match.config import RESOLUTION, NODATA from pyresample.geometry import SwathDefinition from pyresample.kd_tree import get_neighbour_info from pyresample.kd_tree import get_sample_from_neighbour_info and context from other files: # Path: atrain_match/config.py # RESOLUTION = int(os.environ.get('ATRAIN_RESOLUTION', 5)) # # NODATA = -9 , which may contain function names, class names, or code. Output only the next line.
return np.ma.array(self._rows, mask=self.mask, fill_value=NODATA,
Continue the code snippet: <|code_start|> size=5, mode='constant', cval=-9999999999999) flat_index = np.array(flat_index, dtype=np.int) delta_row, delta_col = np.unravel_index(flat_index, (5, 5)) delta_row = delta_row - 2 delta_col = delta_col - 2 new_row = row + delta_row new_col = col + delta_col new_row_matched = np.array([new_row[matched['row'][idx], matched['col'][idx]] for idx in range(matched['row'].shape[0])]) new_col_matched = np.array([new_col[matched['row'][idx], matched['col'][idx]] for idx in range(matched['row'].shape[0])]) return new_row_matched, new_col_matched class test_prototyping_utils(unittest.TestCase): def setUp(self): self.t11 = np.array([[1, 43, 3, 4, 5, 6, 7, 8, 9, 35], [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], [1, 2, 3, 4, 25, 6, 7, 8, 9, 10], [1, 2, 3, 4, 5, 6, 7, 8, 9, 101], [11, 2, 3, 4, 5, 6, 7, 8, 9, 101]]) self.matched = {'row': np.array([0, 0, 1, 1, 2, 2, 3, 3, 4, 4]), 'col': np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])} def test_warmest(self): <|code_end|> . Use current file imports: import numpy as np import unittest from atrain_match.utils.pps_prototyping_util import (get_warmest_or_coldest_index) from atrain_match.utils import match from scipy.ndimage.filters import generic_filter from pyresample.geometry import SwathDefinition from pyresample.kd_tree import get_neighbour_info and context (classes, functions, or code) from other files: # Path: atrain_match/utils/pps_prototyping_util.py # def get_warmest_or_coldest_index(t11, matched, warmest=True): # """Get index for coldedest pixel in 5x5 neighbourhood.""" # FILL = 999999.9 # coldest # if warmest: # FILL = -99 # # steps = [(i, j) for i in [-2, -1, 0, 1, 2] for j in [-2, -1, 0, 1, 2]] # t11_neighbour_i = np.zeros((25, matched['row'].shape[0])) # for i, (step_r, step_c) in enumerate(steps): # new_row_col = {'row': matched['row'] + step_r, # 'col': matched['col'] + step_c} # t11_neighbour_i[i, :] = get_data_from_array_fill_outside(t11, # new_row_col, # Fill=FILL) # if warmest: # neigbour_index = np.argmax(t11_neighbour_i, axis=0) # else: # coldest # neigbour_index = np.argmin(t11_neighbour_i, axis=0) # new_row_matched = np.array( # [matched['row'][idx] + steps[neigbour_index[idx]][0] # for idx in range(matched['row'].shape[0])]) # new_col_matched = np.array( # [matched['col'][idx] + steps[neigbour_index[idx]][1] # for idx in range(matched['row'].shape[0])]) # new_row_col = {'row': new_row_matched, 'col': new_col_matched} # return new_row_col # # Path: atrain_match/utils/match.py # class MatchMapper(object): # def __init__(self, rows, cols, pixel_mask, time_diff=None, # time_threshold=None): # def __call__(self, array): # def rows(self): # def cols(self): # def time_diff(self): # def time_diff(self, value): # def mask(self): # def match_lonlat(source, target, # radius_of_influence=0.7*RESOLUTION*1000.0, # n_neighbours=1): . Output only the next line.
retv = get_warmest_or_coldest_index(self.t11, self.matched)
Predict the next line for this snippet: <|code_start|>class test_match_lon_lat(unittest.TestCase): def setUp(self): lon = np.array([[999, 10, 15], [-999, 20, 25]]).astype(np.float64) lat = np.array([[999, 10, 15], [-999, 20, 25]]).astype(np.float64) lon_t = np.array([31, 10, 15]).astype(np.float64) lat_t = np.array([89, 10, 15]).astype(np.float64) lon3 = np.array([[25, 10, 15], [10, 10, 15]]).astype(np.float64) lat3 = np.array([[10, 11, 16], [12, 10, 15]]).astype(np.float64) self.source = (lon, lat) self.source3 = (lon3, lat3) self.target = (lon_t, lat_t) self.RESOLUTION = 5 def test_match_integers(self): lon = np.array([0, 10, 25]) source_def = SwathDefinition(*(lon, lon)) target_def = SwathDefinition(*(lon, lon)) valid_in, valid_out, indices_int, distances = get_neighbour_info(source_def, target_def, 1000, neighbours=1) lon = np.array([0, 10, 25]).astype(np.float64) source_def = SwathDefinition(*(lon, lon)) target_def = SwathDefinition(*(lon, lon)) valid_in, valid_out, indices_float, distances = get_neighbour_info(source_def, target_def, 1000, neighbours=1) def test_match(self): <|code_end|> with the help of current file imports: import numpy as np import unittest from atrain_match.utils.pps_prototyping_util import (get_warmest_or_coldest_index) from atrain_match.utils import match from scipy.ndimage.filters import generic_filter from pyresample.geometry import SwathDefinition from pyresample.kd_tree import get_neighbour_info and context from other files: # Path: atrain_match/utils/pps_prototyping_util.py # def get_warmest_or_coldest_index(t11, matched, warmest=True): # """Get index for coldedest pixel in 5x5 neighbourhood.""" # FILL = 999999.9 # coldest # if warmest: # FILL = -99 # # steps = [(i, j) for i in [-2, -1, 0, 1, 2] for j in [-2, -1, 0, 1, 2]] # t11_neighbour_i = np.zeros((25, matched['row'].shape[0])) # for i, (step_r, step_c) in enumerate(steps): # new_row_col = {'row': matched['row'] + step_r, # 'col': matched['col'] + step_c} # t11_neighbour_i[i, :] = get_data_from_array_fill_outside(t11, # new_row_col, # Fill=FILL) # if warmest: # neigbour_index = np.argmax(t11_neighbour_i, axis=0) # else: # coldest # neigbour_index = np.argmin(t11_neighbour_i, axis=0) # new_row_matched = np.array( # [matched['row'][idx] + steps[neigbour_index[idx]][0] # for idx in range(matched['row'].shape[0])]) # new_col_matched = np.array( # [matched['col'][idx] + steps[neigbour_index[idx]][1] # for idx in range(matched['row'].shape[0])]) # new_row_col = {'row': new_row_matched, 'col': new_col_matched} # return new_row_col # # Path: atrain_match/utils/match.py # class MatchMapper(object): # def __init__(self, rows, cols, pixel_mask, time_diff=None, # time_threshold=None): # def __call__(self, array): # def rows(self): # def cols(self): # def time_diff(self): # def time_diff(self, value): # def mask(self): # def match_lonlat(source, target, # radius_of_influence=0.7*RESOLUTION*1000.0, # n_neighbours=1): , which may contain function names, class names, or code. Output only the next line.
mapper, _ = match.match_lonlat(self.source3, self.target,
Predict the next line after this snippet: <|code_start|> class MOD06Obj: # skeleton container for MODIS Level2 data def __init__(self): self.height = None self.temperature = None self.pressure = None self.cloud_emissivity = None self.cloud_phase = None self.lwp = None self.multilayer = None self.optical_depth = None def add_modis_06(ca_matchup, AM_PATHS, cross): mfile = find_modis_lvl2_file(AM_PATHS, cross) if mfile.endswith('.h5'): modis_06 = read_modis_h5(mfile) else: modis_06 = read_modis_hdf(mfile) ca_matchup_truth_sat = getattr(ca_matchup, ca_matchup.truth_sat) row_matched = ca_matchup_truth_sat.imager_linnum col_matched = ca_matchup_truth_sat.imager_pixnum index = {'row': row_matched, 'col': col_matched} index_5km = {'row': np.floor(row_matched/5).astype(np.int), 'col': np.floor(col_matched/5).astype(np.int)} <|code_end|> using the current file's imports: from atrain_match.libs.extract_imager_along_track import get_data_from_array from atrain_match.config import NODATA from atrain_match.libs.truth_imager_match import find_main_cloudproduct_file from pyhdf.SD import SD, SDC import numpy as np import os import h5py import logging and any relevant context from other files: # Path: atrain_match/libs/extract_imager_along_track.py # def get_data_from_array(array, matched): # if array is None: # return None # return np.array([array[matched['row'][idx], matched['col'][idx]] # for idx in range(matched['row'].shape[0])]) # # Path: atrain_match/config.py # NODATA = -9 . Output only the next line.
ca_matchup.modis_lvl2.height = get_data_from_array(modis_06.height, index)
Using the snippet: <|code_start|># # You should have received a copy of the GNU General Public License # along with atrain_match. If not, see <http://www.gnu.org/licenses/>. # -*- coding: utf-8 -*- # Program truth_imager_plot.py """Plotting functions to plot CALIOP, CPR (CloudSat) and colocated imager data along track.""" def plot_cal_clsat_geoprof_imager(match_clsat, match_calipso, imager_ctth_m_above_seasurface, plotpath, basename, mode, file_type='png', **options): """Plot imager co-located data on CALIOP and CPR (Cloudsat) track.""" instrument = 'imager' if 'instrument' in options: instrument = options['instrument'] MAXHEIGHT = None if 'MAXHEIGHT' in options: MAXHEIGHT = options["MAXHEIGHT"] caliop_height = match_calipso.calipso.layer_top_altitude * 1000 caliop_base = match_calipso.calipso.layer_base_altitude * 1000 calipso_val_h = match_calipso.calipso.validation_height caliop_base[caliop_base < 0] = -9 caliop_height[caliop_height < 0] = -9 <|code_end|> , determine the next line of code. You have imports: import numpy as np from atrain_match.config import RESOLUTION from matplotlib import pyplot as plt and context (class names, function names, or code) available: # Path: atrain_match/config.py # RESOLUTION = int(os.environ.get('ATRAIN_RESOLUTION', 5)) . Output only the next line.
if RESOLUTION == 5 and match_clsat is not None:
Predict the next line after this snippet: <|code_start|> MY_SATELLITES = options.satellites if options.years: MY_YEARS = options.years years_string = "_".join(MY_YEARS) satellites_string = "_".join(MY_SATELLITES) # get cases CASES = [] month_list = ["*"] day_list = ["*"] if "MONTH" in SETTINGS.keys() and len(SETTINGS["MONTHS"]) > 0: month_list = ["{:02d}".format(int(ind)) for ind in SETTINGS["MONTHS"]] if options.months: month_list = ["{:02d}".format(int(ind)) for ind in options.months] if "DAY" in SETTINGS.keys() and len(SETTINGS["DAYS"]) > 0: day_list = ["{:02d}".format(int(ind)) for ind in SETTINGS["DAYS"]] for sat in MY_SATELLITES: for year in MY_YEARS: for month in month_list: for day in day_list: CASES.append({'satname': sat, 'month': month, 'year': year, 'day': day}) if len(modes_dnt_list) == 0: logger.warning("No modes selected!") parser.print_help() # For each mode calcualte the statistics for process_mode_dnt in modes_dnt_list: <|code_end|> using the current file's imports: from atrain_match.config import (RESOLUTION, _validation_results_dir, SURFACES) from atrain_match.statistics import orrb_CFC_stat from atrain_match.statistics import orrb_CTH_stat from atrain_match.statistics import orrb_CTY_stat from atrain_match.statistics import orrb_CPH_stat from atrain_match.statistics import orrb_LWP_stat from glob import glob from atrain_match.utils.runutils import read_config_info import logging import os import argparse and any relevant context from other files: # Path: atrain_match/config.py # def str2bool(v): # RESOLUTION = int(os.environ.get('ATRAIN_RESOLUTION', 5)) # AREA_CONFIG_FILE = os.environ.get('AREA_CONFIG_FILE', './areas.def') # AREA_CONFIG_FILE_PLOTS_ON_AREA = os.environ.get('AREA_CONFIG_FILE_PLOTS_ON_AREA', './region_config_test.cfg') # ATRAIN_MATCH_CONFIG_PATH = os.environ.get('ATRAINMATCH_CONFIG_DIR', './etc') # ATRAIN_MATCH_CONFIG_FILE = os.environ.get('ATRAINMATCH_CONFIG_FILE', 'atrain_match.cfg') # INSTRUMENT = {'npp': 'viirs', # 'noaa18': 'avhrr', # 'meteosat8': 'seviri', # 'meteosat9': 'seviri', # 'meteosat10': 'seviri', # 'meteosat11': 'seviri', # 'fy3d': 'mersi2', # 'noaa20': 'viirs', # 'sga1': 'metimage', # 'epsga1': 'metimage', # 'metopsga1': 'metimage', # 'eos1': 'modis', # 'eos2': 'modis'} # ALLOWED_MODES = [] # MODES_NO_DNT = ['BASIC'] # PROCESS_SURFACES = [ # "ICE_COVER_SEA", "ICE_FREE_SEA", "SNOW_COVER_LAND", "SNOW_FREE_LAND", # "COASTAL_ZONE", # "TROPIC_ZONE", "TROPIC_ZONE_SNOW_FREE_LAND", "TROPIC_ZONE_ICE_FREE_SEA", # "SUB_TROPIC_ZONE", # "SUB_TROPIC_ZONE_SNOW_FREE_LAND", "SUB_TROPIC_ZONE_ICE_FREE_SEA", # "HIGH-LATITUDES", # "HIGH-LATITUDES_SNOW_FREE_LAND", "HIGH-LATITUDES_ICE_FREE_SEA", # "HIGH-LATITUDES_SNOW_COVER_LAND", "HIGH-LATITUDES_ICE_COVER_SEA", # "POLAR", "POLAR_SNOW_FREE_LAND", "POLAR_ICE_FREE_SEA", # "POLAR_SNOW_COVER_LAND", "POLAR_ICE_COVER_SEA"] # COMPRESS_LVL = 6 # : Compresssion level for generated matched files (h5) # NODATA = -9 # CLOUDSAT_CLOUDY_THR = 30.0 # CALIPSO_FILE_LENGTH = 60*60 # s calipso files are shorter 60 minutes # CLOUDSAT_FILE_LENGTH = 120*60 # s cloudsat files are shorter 120 minutes # ISS_FILE_LENGTH = 60*60 # s iss files are shorter 60 minutes # AMSR_FILE_LENGTH = 60*60 # AMSR-Es files are shorter 60 minutes # SYNOP_FILE_LENGTH = 24*60 # s Our synop data comes in 1 day files # MORA_FILE_LENGTH = 24*60 # s Our MORA data comes in 1 day files # PPS_FORMAT_2012_OR_EARLIER = False # SURFACES = PROCESS_SURFACES # DNT_FLAG = ['ALL', 'DAY', 'NIGHT', 'TWILIGHT'] . Output only the next line.
print(RESOLUTION)
Here is a snippet: <|code_start|> if "MONTH" in SETTINGS.keys() and len(SETTINGS["MONTHS"]) > 0: month_list = ["{:02d}".format(int(ind)) for ind in SETTINGS["MONTHS"]] if options.months: month_list = ["{:02d}".format(int(ind)) for ind in options.months] if "DAY" in SETTINGS.keys() and len(SETTINGS["DAYS"]) > 0: day_list = ["{:02d}".format(int(ind)) for ind in SETTINGS["DAYS"]] for sat in MY_SATELLITES: for year in MY_YEARS: for month in month_list: for day in day_list: CASES.append({'satname': sat, 'month': month, 'year': year, 'day': day}) if len(modes_dnt_list) == 0: logger.warning("No modes selected!") parser.print_help() # For each mode calcualte the statistics for process_mode_dnt in modes_dnt_list: print(RESOLUTION) # get result files for all cases for truth_sat in SETTINGS["COMPILE_STATISTICS_TRUTH"]: logger.info("PROCESS MODE %s, truth: %s", process_mode_dnt, truth_sat.upper()) print("Gathering statistics from all validation results files in the " "following directories:") results_files = [] for case in CASES: indata_dir = AM_PATHS['result_dir'].format( <|code_end|> . Write the next line using the current file imports: from atrain_match.config import (RESOLUTION, _validation_results_dir, SURFACES) from atrain_match.statistics import orrb_CFC_stat from atrain_match.statistics import orrb_CTH_stat from atrain_match.statistics import orrb_CTY_stat from atrain_match.statistics import orrb_CPH_stat from atrain_match.statistics import orrb_LWP_stat from glob import glob from atrain_match.utils.runutils import read_config_info import logging import os import argparse and context from other files: # Path: atrain_match/config.py # def str2bool(v): # RESOLUTION = int(os.environ.get('ATRAIN_RESOLUTION', 5)) # AREA_CONFIG_FILE = os.environ.get('AREA_CONFIG_FILE', './areas.def') # AREA_CONFIG_FILE_PLOTS_ON_AREA = os.environ.get('AREA_CONFIG_FILE_PLOTS_ON_AREA', './region_config_test.cfg') # ATRAIN_MATCH_CONFIG_PATH = os.environ.get('ATRAINMATCH_CONFIG_DIR', './etc') # ATRAIN_MATCH_CONFIG_FILE = os.environ.get('ATRAINMATCH_CONFIG_FILE', 'atrain_match.cfg') # INSTRUMENT = {'npp': 'viirs', # 'noaa18': 'avhrr', # 'meteosat8': 'seviri', # 'meteosat9': 'seviri', # 'meteosat10': 'seviri', # 'meteosat11': 'seviri', # 'fy3d': 'mersi2', # 'noaa20': 'viirs', # 'sga1': 'metimage', # 'epsga1': 'metimage', # 'metopsga1': 'metimage', # 'eos1': 'modis', # 'eos2': 'modis'} # ALLOWED_MODES = [] # MODES_NO_DNT = ['BASIC'] # PROCESS_SURFACES = [ # "ICE_COVER_SEA", "ICE_FREE_SEA", "SNOW_COVER_LAND", "SNOW_FREE_LAND", # "COASTAL_ZONE", # "TROPIC_ZONE", "TROPIC_ZONE_SNOW_FREE_LAND", "TROPIC_ZONE_ICE_FREE_SEA", # "SUB_TROPIC_ZONE", # "SUB_TROPIC_ZONE_SNOW_FREE_LAND", "SUB_TROPIC_ZONE_ICE_FREE_SEA", # "HIGH-LATITUDES", # "HIGH-LATITUDES_SNOW_FREE_LAND", "HIGH-LATITUDES_ICE_FREE_SEA", # "HIGH-LATITUDES_SNOW_COVER_LAND", "HIGH-LATITUDES_ICE_COVER_SEA", # "POLAR", "POLAR_SNOW_FREE_LAND", "POLAR_ICE_FREE_SEA", # "POLAR_SNOW_COVER_LAND", "POLAR_ICE_COVER_SEA"] # COMPRESS_LVL = 6 # : Compresssion level for generated matched files (h5) # NODATA = -9 # CLOUDSAT_CLOUDY_THR = 30.0 # CALIPSO_FILE_LENGTH = 60*60 # s calipso files are shorter 60 minutes # CLOUDSAT_FILE_LENGTH = 120*60 # s cloudsat files are shorter 120 minutes # ISS_FILE_LENGTH = 60*60 # s iss files are shorter 60 minutes # AMSR_FILE_LENGTH = 60*60 # AMSR-Es files are shorter 60 minutes # SYNOP_FILE_LENGTH = 24*60 # s Our synop data comes in 1 day files # MORA_FILE_LENGTH = 24*60 # s Our MORA data comes in 1 day files # PPS_FORMAT_2012_OR_EARLIER = False # SURFACES = PROCESS_SURFACES # DNT_FLAG = ['ALL', 'DAY', 'NIGHT', 'TWILIGHT'] , which may include functions, classes, or code. Output only the next line.
val_dir=_validation_results_dir,
Predict the next line after this snippet: <|code_start|> parser.add_argument('--years', '-y', metavar='YYYY', type=str, nargs='*', required=False, help='List of year to combine, ' 'overrides YEARS in atrain_match.cfg') parser.add_argument('--months', '-m', metavar='mm', type=str, nargs='*', required=False, help='List of year to combine, ' 'overrides YEARS in atrain_match.cfg') (options) = parser.parse_args() AM_PATHS, SETTINGS = read_config_info() # Find all wanted modes (dnt) modes_list = [] if options.nodnt: New_DNT_FLAG = [''] else: New_DNT_FLAG = ['', '_DAY', '_NIGHT', '_TWILIGHT'] if options.basic: modes_list.append('BASIC') if options.standard: modes_list.append('STANDARD') if options.satz: for mode in ['SATZ_LOW', 'SATZ_70', 'SATZ_HIGH', 'SATZ_0_20', 'SATZ_20_40', 'SATZ_40_60', 'SATZ_60_80', 'SATZ_80_100',]: modes_list.append(mode) if options.odticfilter: # I prefer this one! /KG print('Will calculate statistic for mode OPTICAL_DEPTH_THIN_IS_CLEAR') modes_list.append('OPTICAL_DEPTH_THIN_IS_CLEAR') if options.surface_new_way: print('Will calculate statistic for the different surfaces') <|code_end|> using the current file's imports: from atrain_match.config import (RESOLUTION, _validation_results_dir, SURFACES) from atrain_match.statistics import orrb_CFC_stat from atrain_match.statistics import orrb_CTH_stat from atrain_match.statistics import orrb_CTY_stat from atrain_match.statistics import orrb_CPH_stat from atrain_match.statistics import orrb_LWP_stat from glob import glob from atrain_match.utils.runutils import read_config_info import logging import os import argparse and any relevant context from other files: # Path: atrain_match/config.py # def str2bool(v): # RESOLUTION = int(os.environ.get('ATRAIN_RESOLUTION', 5)) # AREA_CONFIG_FILE = os.environ.get('AREA_CONFIG_FILE', './areas.def') # AREA_CONFIG_FILE_PLOTS_ON_AREA = os.environ.get('AREA_CONFIG_FILE_PLOTS_ON_AREA', './region_config_test.cfg') # ATRAIN_MATCH_CONFIG_PATH = os.environ.get('ATRAINMATCH_CONFIG_DIR', './etc') # ATRAIN_MATCH_CONFIG_FILE = os.environ.get('ATRAINMATCH_CONFIG_FILE', 'atrain_match.cfg') # INSTRUMENT = {'npp': 'viirs', # 'noaa18': 'avhrr', # 'meteosat8': 'seviri', # 'meteosat9': 'seviri', # 'meteosat10': 'seviri', # 'meteosat11': 'seviri', # 'fy3d': 'mersi2', # 'noaa20': 'viirs', # 'sga1': 'metimage', # 'epsga1': 'metimage', # 'metopsga1': 'metimage', # 'eos1': 'modis', # 'eos2': 'modis'} # ALLOWED_MODES = [] # MODES_NO_DNT = ['BASIC'] # PROCESS_SURFACES = [ # "ICE_COVER_SEA", "ICE_FREE_SEA", "SNOW_COVER_LAND", "SNOW_FREE_LAND", # "COASTAL_ZONE", # "TROPIC_ZONE", "TROPIC_ZONE_SNOW_FREE_LAND", "TROPIC_ZONE_ICE_FREE_SEA", # "SUB_TROPIC_ZONE", # "SUB_TROPIC_ZONE_SNOW_FREE_LAND", "SUB_TROPIC_ZONE_ICE_FREE_SEA", # "HIGH-LATITUDES", # "HIGH-LATITUDES_SNOW_FREE_LAND", "HIGH-LATITUDES_ICE_FREE_SEA", # "HIGH-LATITUDES_SNOW_COVER_LAND", "HIGH-LATITUDES_ICE_COVER_SEA", # "POLAR", "POLAR_SNOW_FREE_LAND", "POLAR_ICE_FREE_SEA", # "POLAR_SNOW_COVER_LAND", "POLAR_ICE_COVER_SEA"] # COMPRESS_LVL = 6 # : Compresssion level for generated matched files (h5) # NODATA = -9 # CLOUDSAT_CLOUDY_THR = 30.0 # CALIPSO_FILE_LENGTH = 60*60 # s calipso files are shorter 60 minutes # CLOUDSAT_FILE_LENGTH = 120*60 # s cloudsat files are shorter 120 minutes # ISS_FILE_LENGTH = 60*60 # s iss files are shorter 60 minutes # AMSR_FILE_LENGTH = 60*60 # AMSR-Es files are shorter 60 minutes # SYNOP_FILE_LENGTH = 24*60 # s Our synop data comes in 1 day files # MORA_FILE_LENGTH = 24*60 # s Our MORA data comes in 1 day files # PPS_FORMAT_2012_OR_EARLIER = False # SURFACES = PROCESS_SURFACES # DNT_FLAG = ['ALL', 'DAY', 'NIGHT', 'TWILIGHT'] . Output only the next line.
for surface in SURFACES:
Using the snippet: <|code_start|> data = _interpolate_height_and_temperature_from_pressure(obt.imager, 440) setattr(obt.imager, 'segment_nwp_h440', data) data = _interpolate_height_and_temperature_from_pressure(obt.imager, 680) setattr(obt.imager, 'segment_nwp_h680', data) return obt # --------------------------------------------------------------------------- def imager_track_from_matched(obt, SETTINGS, cloudproducts, extract_radiances=True, extract_cma=True, extract_ctth=True, extract_ctype=True, extract_cpp=True, extract_aux_segments=True, extract_aux=True, aux_params=None, extract_some_data_for_x_neighbours=False, find_mean_data_for_x_neighbours=False): aux_params_all = ["surftemp", "t500", "t700", "t850", "t950", "ttro", "ciwv", "t900", "t1000", "t800", "t250", "t2m", "ptro", "psur", "h2m", "u10m", "v10m", "t2m", "snowa", "snowd", "seaice", "landuse", "fractionofland", "elevation", "r37_sza_correction_done", <|code_end|> , determine the next line of code. You have imports: import numpy as np import logging import os from atrain_match.cloudproducts.read_oca import OCA_READ_EXTRA from atrain_match.utils.pps_prototyping_util import (get_coldest_values, get_darkest_values, get_warmest_values) from atrain_match.utils.pps_prototyping_util import add_cnn_features and context (class names, function names, or code) available: # Path: atrain_match/cloudproducts/read_oca.py # OCA_READ_EXTRA = OCA_READ_EXTRA_ONLY_OCA + ['flag_cm'] . Output only the next line.
] + OCA_READ_EXTRA # And NN-extra!
Here is a snippet: <|code_start|> seconds = np.float64(pps_nc.variables['time'][::]) # from PPS often 0 if 'seconds' in time_temp: if 'T' in time_temp: time_obj = time.strptime(time_temp, 'seconds since %Y-%m-%dT%H:%M:%S+00:00') elif time_temp == u'seconds since 1970-01-01': time_obj = time.strptime(time_temp, 'seconds since %Y-%m-%d') else: time_obj = time.strptime(time_temp, 'seconds since %Y-%m-%d %H:%M:%S.%f +00:00') sec_since_1970 = calendar.timegm(time_obj) all_imager_obj.sec1970_start = (sec_since_1970 + np.float64(np.min(pps_nc.variables['time_bnds'][::])) + seconds) all_imager_obj.sec1970_end = (sec_since_1970 + np.float64(np.max(pps_nc.variables['time_bnds'][::])) + seconds) else: try: all_imager_obj.sec1970_start = calendar.timegm(time.strptime(pps_nc.variables['lon'].start_time, '%Y-%m-%d %H:%M:%S.%f')) all_imager_obj.sec1970_end = calendar.timegm(time.strptime(pps_nc.variables['lon'].end_time, '%Y-%m-%d %H:%M:%S.%f')) except: all_imager_obj.sec1970_start = calendar.timegm(time.strptime(pps_nc.start_time, '%Y-%m-%d %H:%M:%S')) all_imager_obj.sec1970_end = calendar.timegm(time.strptime(pps_nc.end_time, '%Y-%m-%d %H:%M:%S')) # print type(all_imager_obj.sec1970_start) all_imager_obj.sec1970_start = np.float64(all_imager_obj.sec1970_start) all_imager_obj.sec1970_end = np.float64(all_imager_obj.sec1970_end) <|code_end|> . Write the next line using the current file imports: from atrain_match.utils.runutils import do_some_geo_obj_logging from datetime import datetime import atrain_match.config as config import numpy as np import os import netCDF4 import h5py import logging import time import calendar import h5py import h5py import h5py and context from other files: # Path: atrain_match/utils/runutils.py # def do_some_geo_obj_logging(GeoObj): # import time # tim1 = time.strftime("%Y%m%d %H:%M", # time.gmtime(GeoObj.sec1970_start)) # tim2 = time.strftime("%Y%m%d %H:%M", # time.gmtime(GeoObj.sec1970_end)) # logger.debug("Starttime: %s, end time: %s", tim1, tim2) # logger.debug("Min lon: %f, max lon: %d", # np.min(np.where( # np.equal(GeoObj.longitude, GeoObj.nodata), # 99999, # GeoObj.longitude)), # np.max(GeoObj.longitude)) # logger.debug("Min lat: %d, max lat: %d", # np.min(np.where( # np.equal(GeoObj.latitude, GeoObj.nodata), # 99999, # GeoObj.latitude)), # np.max(GeoObj.latitude)) , which may include functions, classes, or code. Output only the next line.
do_some_geo_obj_logging(all_imager_obj)
Next line prediction: <|code_start|> class ProvinceAdmin(admin.ModelAdmin): list_display = ('name', 'code', 'order', 'pk', 'enabled') class CityAdmin(admin.ModelAdmin): list_display = ('name', 'province', 'pk', 'enabled') <|code_end|> . Use current file imports: (from django.contrib.gis import admin from angkot.geo.models import Province, City) and context including class names, function names, or small code snippets from other files: # Path: angkot/geo/models.py # class Province(models.Model): # name = models.CharField(max_length=100) # code = models.CharField(max_length=5) # # order = models.IntegerField(default=0) # # # Internal # enabled = models.BooleanField(default=False) # updated = models.DateTimeField(default=timezone.now) # created = models.DateTimeField(default=timezone.now) # # def __str__(self): # return self.name # # def save(self): # self.updated = timezone.now() # super(Province, self).save() # # class Meta: # ordering = ('pk',) # # class City(models.Model): # name = models.CharField(max_length=100) # province = models.ForeignKey(Province) # # # Internal # enabled = models.BooleanField(default=False) # updated = models.DateTimeField(default=timezone.now) # created = models.DateTimeField(default=timezone.now) # # def __str__(self): # return '{}, {}'.format(self.name, self.province) # # def save(self): # self.updated = timezone.now() # super(City, self).save() # # class Meta: # ordering = ('province', 'name',) # verbose_name_plural = 'cities' . Output only the next line.
admin.site.register(Province, ProvinceAdmin)
Based on the snippet: <|code_start|> class ProvinceAdmin(admin.ModelAdmin): list_display = ('name', 'code', 'order', 'pk', 'enabled') class CityAdmin(admin.ModelAdmin): list_display = ('name', 'province', 'pk', 'enabled') admin.site.register(Province, ProvinceAdmin) <|code_end|> , predict the immediate next line with the help of imports: from django.contrib.gis import admin from angkot.geo.models import Province, City and context (classes, functions, sometimes code) from other files: # Path: angkot/geo/models.py # class Province(models.Model): # name = models.CharField(max_length=100) # code = models.CharField(max_length=5) # # order = models.IntegerField(default=0) # # # Internal # enabled = models.BooleanField(default=False) # updated = models.DateTimeField(default=timezone.now) # created = models.DateTimeField(default=timezone.now) # # def __str__(self): # return self.name # # def save(self): # self.updated = timezone.now() # super(Province, self).save() # # class Meta: # ordering = ('pk',) # # class City(models.Model): # name = models.CharField(max_length=100) # province = models.ForeignKey(Province) # # # Internal # enabled = models.BooleanField(default=False) # updated = models.DateTimeField(default=timezone.now) # created = models.DateTimeField(default=timezone.now) # # def __str__(self): # return '{}, {}'.format(self.name, self.province) # # def save(self): # self.updated = timezone.now() # super(City, self).save() # # class Meta: # ordering = ('province', 'name',) # verbose_name_plural = 'cities' . Output only the next line.
admin.site.register(City, CityAdmin)
Continue the code snippet: <|code_start|> class JSTORAPI: DEFAULT_DOI_PREFIX = "10.2307" """Main DOI prefix. Used for real DOIs and non registered pseudo-DOIs with the same format""" def __init__(self, http_service: HTTPService, url): self._jstor_pdf_url = url self._http = http_service @property def enabled(self): return bool(self._jstor_pdf_url) def jstor_pdf_stream(self, jstor_url: str, jstor_ip: str): doi = jstor_url.replace("jstor://", "") if not "/" in doi: doi = f"{self.DEFAULT_DOI_PREFIX}/{doi}" url = f"{self._jstor_pdf_url}/{doi}?ip={jstor_ip}" return self._http.stream( <|code_end|> . Use current file imports: from via.requests_tools.headers import add_request_headers from via.services import HTTPService and context (classes, functions, or code) from other files: # Path: via/requests_tools/headers.py # def add_request_headers(headers): # """Add headers for 3rd party providers which we access data from.""" # # # Pass our abuse policy in request headers for third-party site admins. # headers["X-Abuse-Policy"] = "https://web.hypothes.is/abuse-policy/" # headers["X-Complaints-To"] = "https://web.hypothes.is/report-abuse/" # # return headers # # Path: via/services/http.py # class HTTPService: # """Send HTTP requests with `requests` and receive the responses.""" # # def __init__(self, session=None, error_translator=None): # # A requests session is used so that cookies are persisted across # # requests and urllib3 connection pooling is used (which means that # # underlying TCP connections are re-used when making multiple requests # # to the same host, e.g. pagination). # # # # See https://docs.python-requests.org/en/latest/user/advanced/#session-objects # self._session = session or requests.Session() # self._error_translator = error_translator # # def get(self, *args, **kwargs): # return self.request("GET", *args, **kwargs) # # def put(self, *args, **kwargs): # return self.request("PUT", *args, **kwargs) # # def post(self, *args, **kwargs): # return self.request("POST", *args, **kwargs) # # def patch(self, *args, **kwargs): # return self.request("PATCH", *args, **kwargs) # # def delete(self, *args, **kwargs): # return self.request("DELETE", *args, **kwargs) # # def request(self, method, url, timeout=(10, 10), raise_for_status=True, **kwargs): # """Send a request with `requests` and return the requests.Response object. # # :param method: The HTTP method to use, one of "GET", "PUT", "POST", # "PATCH", "DELETE", "OPTIONS" or "HEAD" # :param url: The URL to request # :param timeout: How long (in seconds) to wait before raising an error. # This can be a (connect_timeout, read_timeout) 2-tuple or it can be # a single float that will be used as both the connect and read # timeout. # Good practice is to set this to slightly larger than a multiple of # 3, which is the default TCP packet retransmission window. See: # https://docs.python-requests.org/en/master/user/advanced/#timeouts # Note that the read_timeout is *not* a time limit on the entire # response download. It's a time limit on how long to wait *between # bytes from the server*. The entire download can take much longer. # :param raise_for_status: Optionally raise for 4xx & 5xx response statuses. # :param **kwargs: Any other keyword arguments will be passed directly to # requests.Session().request(): # https://docs.python-requests.org/en/latest/api/#requests.Session.request # :raise request.exceptions are mapped to via's exception on DEFAULT_ERROR_MAP # :raise UnhandledUpstreamException: For any non mapped exception raised by requests # :raise Exception: For any non requests exception raised # :returns: a request.Response # """ # response = None # # try: # pylint:disable=too-many-try-statements # response = self._session.request( # method, # url, # timeout=timeout, # **kwargs, # ) # if raise_for_status: # response.raise_for_status() # # except Exception as err: # if mapped_err := self._translate_exception(err): # raise mapped_err from err # pylint: disable=raising-bad-type # # raise # # return response # # def stream(self, url, method="GET", **kwargs): # response = self.request(method=method, url=url, stream=True, **kwargs) # try: # yield from self._stream_bytes(response) # except Exception as err: # if mapped_err := self._translate_exception(err): # raise mapped_err from err # pylint: disable=raising-bad-type # # raise # # def _translate_exception(self, err): # if self._error_translator and (mapped := self._error_translator(err)): # return mapped # # for (error_class, target_class) in DEFAULT_ERROR_MAP.items(): # if isinstance(err, error_class): # return target_class( # message=err.args[0] if err.args else None, # requests_err=err if hasattr(err, "request") else None, # ) # # return None # # @staticmethod # def _stream_bytes(response, min_chunk_size=64000): # """Stream content from a `requests.Response` object. # # The response must have been called with `stream=True` for this to be # effective. This will attempt to smooth over some of the variation of block # size to give a smoother output for upstream services calling us. # """ # buffer = b"" # # # The chunk_size appears to be a guide value at best. We often get more # # or just about 9 bytes, so we'll do some smoothing for our callers so we # # don't incur overhead with very short iterations of content # for chunk in response.iter_content(chunk_size=min_chunk_size): # buffer += chunk # if len(buffer) >= min_chunk_size: # yield buffer # buffer = b"" # # if buffer: # yield buffer . Output only the next line.
url, headers=add_request_headers({"Accept": "application/pdf"})
Next line prediction: <|code_start|> ( param( HTTPUnsupportedMediaType, HTTPUnsupportedMediaType.code, id="Pyramid error", ), param(BlockingIOError, 500, id="Unknown python error"), ), ) def test_values_are_copied_from_the_exception( self, exception_class, status_code, pyramid_request ): exception = exception_class("details string") values = other_exceptions(exception, pyramid_request) assert values == Any.dict.containing( { "exception": Any.dict.containing( {"class": exception.__class__.__name__, "details": "details string"} ), "status_code": status_code, } ) assert pyramid_request.response.status_int == status_code @pytest.mark.parametrize( "exception_class,mapped_exception", ( <|code_end|> . Use current file imports: (import json import pytest from io import BytesIO from unittest.mock import sentinel from h_matchers import Any from pyramid.httpexceptions import ( HTTPClientError, HTTPGatewayTimeout, HTTPNotFound, HTTPUnsupportedMediaType, ) from pyramid.testing import DummyRequest from pytest import param from requests import HTTPError, Request, Response from via.exceptions import ( BadURL, GoogleDriveServiceError, UnhandledUpstreamException, UpstreamServiceError, ) from via.views.exceptions import ( EXCEPTION_MAP, google_drive_exceptions, other_exceptions, )) and context including class names, function names, or small code snippets from other files: # Path: via/exceptions.py # class BadURL(RequestBasedException): # """An invalid URL was discovered.""" # # def __init__(self, message, requests_err=None, url=None): # super().__init__(message, requests_err) # self.url = url # # status_int = 400 # # class GoogleDriveServiceError(UpstreamServiceError): # """Something interesting happened in Google Drive. # # We often use the more generic versions, but if there's something of # particular interest, we might raise this error. # """ # # def __init__(self, message, status_int, requests_err=None): # super().__init__(message, requests_err=requests_err) # # self.status_int = status_int # # class UnhandledUpstreamException(UpstreamServiceError): # """Something we did not plan for went wrong.""" # # status_int = 417 # # class UpstreamServiceError(RequestBasedException): # """Something went wrong when calling an upstream service.""" # # status_int = 409 # # Path: via/views/exceptions.py # EXCEPTION_MAP = { # BadURL: { # "title": "The URL isn't valid", # "long_description": [ # "Parts of the URL could be missing or in the wrong format." # ], # "stage": "request", # "retryable": False, # }, # UpstreamTimeout: { # "title": "Timeout", # "long_description": ["The web page we tried to get took too long to respond."], # "stage": "upstream", # "retryable": True, # }, # UnhandledUpstreamException: { # "title": "Something went wrong", # "long_description": ["We experienced an unexpected error."], # "stage": "via", # "retryable": True, # }, # UpstreamServiceError: { # "title": "Could not get web page", # "long_description": [ # "Something went wrong when we tried to get the web page.", # "It might be missing or might have returned an error.", # ], # "stage": "upstream", # "retryable": True, # }, # HTTPNotFound: { # "title": "Page not found", # "long_description": [ # "The URL you asked for is not part of this service.", # "Please check the URL you have entered.", # ], # "stage": "request", # "retryable": False, # }, # HTTPClientError: { # "title": "Bad request", # "long_description": [ # "We can't process the request because we don't understand it." # ], # "stage": "request", # "retryable": False, # }, # } # # @exception_view_config(Exception, route_name="proxy_google_drive_file", renderer="json") # @exception_view_config( # Exception, route_name="proxy_google_drive_file:resource_key", renderer="json" # ) # def google_drive_exceptions(exc, request): # """Catch all errors for Google Drive and display an HTML page.""" # # # Don't log 404's as they aren't very interesting # if not isinstance(exc, HTTPNotFound): # h_pyramid_sentry.report_exception(exc) # # _set_status(exc, request) # # data = { # "exception": exc.__class__.__name__, # "message": str(exc.args[0]) if exc.args else None, # } # # if hasattr(exc, "response") and exc.response is not None: # data["upstream"] = _serialise_requests_info(exc.request, exc.response) # # return data # # @exception_view_config(Exception, renderer="via:templates/exception.html.jinja2") # def other_exceptions(exc, request): # """Catch all errors (Pyramid or Python) and display an HTML page.""" # # # We don't want to log errors from upstream services or things which are # # the user goofing about making bad queries. # if not isinstance(exc, (UpstreamServiceError, BadURL, HTTPClientError)): # h_pyramid_sentry.report_exception(exc) # # return _get_error_body(exc, request) . Output only the next line.
param(BadURL, BadURL, id="Mapped directly"),
Given the following code snippet before the placeholder: <|code_start|> if should_report: h_pyramid_sentry.report_exception.assert_called_once_with(exception) else: h_pyramid_sentry.report_exception.assert_not_called() @pytest.fixture def pyramid_request(self): return DummyRequest() @pytest.fixture(autouse=True) def get_original_url(self, patch): return patch("via.views.exceptions.get_original_url") @pytest.fixture(autouse=True) def h_pyramid_sentry(self, patch): return patch("via.views.exceptions.h_pyramid_sentry") class TestGoogleDriveExceptions: def test_it(self, pyramid_request): json_body = {"test": "info"} # Constructing requests exceptions is no fun... request = Request("GET", "http://example.com") response = Response() response.status_code = 502 response.raw = BytesIO(json.dumps(json_body).encode("utf-8")) response.headers["Content-Type"] = "mime/type" <|code_end|> , predict the next line using imports from the current file: import json import pytest from io import BytesIO from unittest.mock import sentinel from h_matchers import Any from pyramid.httpexceptions import ( HTTPClientError, HTTPGatewayTimeout, HTTPNotFound, HTTPUnsupportedMediaType, ) from pyramid.testing import DummyRequest from pytest import param from requests import HTTPError, Request, Response from via.exceptions import ( BadURL, GoogleDriveServiceError, UnhandledUpstreamException, UpstreamServiceError, ) from via.views.exceptions import ( EXCEPTION_MAP, google_drive_exceptions, other_exceptions, ) and context including class names, function names, and sometimes code from other files: # Path: via/exceptions.py # class BadURL(RequestBasedException): # """An invalid URL was discovered.""" # # def __init__(self, message, requests_err=None, url=None): # super().__init__(message, requests_err) # self.url = url # # status_int = 400 # # class GoogleDriveServiceError(UpstreamServiceError): # """Something interesting happened in Google Drive. # # We often use the more generic versions, but if there's something of # particular interest, we might raise this error. # """ # # def __init__(self, message, status_int, requests_err=None): # super().__init__(message, requests_err=requests_err) # # self.status_int = status_int # # class UnhandledUpstreamException(UpstreamServiceError): # """Something we did not plan for went wrong.""" # # status_int = 417 # # class UpstreamServiceError(RequestBasedException): # """Something went wrong when calling an upstream service.""" # # status_int = 409 # # Path: via/views/exceptions.py # EXCEPTION_MAP = { # BadURL: { # "title": "The URL isn't valid", # "long_description": [ # "Parts of the URL could be missing or in the wrong format." # ], # "stage": "request", # "retryable": False, # }, # UpstreamTimeout: { # "title": "Timeout", # "long_description": ["The web page we tried to get took too long to respond."], # "stage": "upstream", # "retryable": True, # }, # UnhandledUpstreamException: { # "title": "Something went wrong", # "long_description": ["We experienced an unexpected error."], # "stage": "via", # "retryable": True, # }, # UpstreamServiceError: { # "title": "Could not get web page", # "long_description": [ # "Something went wrong when we tried to get the web page.", # "It might be missing or might have returned an error.", # ], # "stage": "upstream", # "retryable": True, # }, # HTTPNotFound: { # "title": "Page not found", # "long_description": [ # "The URL you asked for is not part of this service.", # "Please check the URL you have entered.", # ], # "stage": "request", # "retryable": False, # }, # HTTPClientError: { # "title": "Bad request", # "long_description": [ # "We can't process the request because we don't understand it." # ], # "stage": "request", # "retryable": False, # }, # } # # @exception_view_config(Exception, route_name="proxy_google_drive_file", renderer="json") # @exception_view_config( # Exception, route_name="proxy_google_drive_file:resource_key", renderer="json" # ) # def google_drive_exceptions(exc, request): # """Catch all errors for Google Drive and display an HTML page.""" # # # Don't log 404's as they aren't very interesting # if not isinstance(exc, HTTPNotFound): # h_pyramid_sentry.report_exception(exc) # # _set_status(exc, request) # # data = { # "exception": exc.__class__.__name__, # "message": str(exc.args[0]) if exc.args else None, # } # # if hasattr(exc, "response") and exc.response is not None: # data["upstream"] = _serialise_requests_info(exc.request, exc.response) # # return data # # @exception_view_config(Exception, renderer="via:templates/exception.html.jinja2") # def other_exceptions(exc, request): # """Catch all errors (Pyramid or Python) and display an HTML page.""" # # # We don't want to log errors from upstream services or things which are # # the user goofing about making bad queries. # if not isinstance(exc, (UpstreamServiceError, BadURL, HTTPClientError)): # h_pyramid_sentry.report_exception(exc) # # return _get_error_body(exc, request) . Output only the next line.
exception = GoogleDriveServiceError(
Based on the snippet: <|code_start|> HTTPUnsupportedMediaType, HTTPUnsupportedMediaType.code, id="Pyramid error", ), param(BlockingIOError, 500, id="Unknown python error"), ), ) def test_values_are_copied_from_the_exception( self, exception_class, status_code, pyramid_request ): exception = exception_class("details string") values = other_exceptions(exception, pyramid_request) assert values == Any.dict.containing( { "exception": Any.dict.containing( {"class": exception.__class__.__name__, "details": "details string"} ), "status_code": status_code, } ) assert pyramid_request.response.status_int == status_code @pytest.mark.parametrize( "exception_class,mapped_exception", ( param(BadURL, BadURL, id="Mapped directly"), param(HTTPUnsupportedMediaType, HTTPClientError, id="Inherited"), <|code_end|> , predict the immediate next line with the help of imports: import json import pytest from io import BytesIO from unittest.mock import sentinel from h_matchers import Any from pyramid.httpexceptions import ( HTTPClientError, HTTPGatewayTimeout, HTTPNotFound, HTTPUnsupportedMediaType, ) from pyramid.testing import DummyRequest from pytest import param from requests import HTTPError, Request, Response from via.exceptions import ( BadURL, GoogleDriveServiceError, UnhandledUpstreamException, UpstreamServiceError, ) from via.views.exceptions import ( EXCEPTION_MAP, google_drive_exceptions, other_exceptions, ) and context (classes, functions, sometimes code) from other files: # Path: via/exceptions.py # class BadURL(RequestBasedException): # """An invalid URL was discovered.""" # # def __init__(self, message, requests_err=None, url=None): # super().__init__(message, requests_err) # self.url = url # # status_int = 400 # # class GoogleDriveServiceError(UpstreamServiceError): # """Something interesting happened in Google Drive. # # We often use the more generic versions, but if there's something of # particular interest, we might raise this error. # """ # # def __init__(self, message, status_int, requests_err=None): # super().__init__(message, requests_err=requests_err) # # self.status_int = status_int # # class UnhandledUpstreamException(UpstreamServiceError): # """Something we did not plan for went wrong.""" # # status_int = 417 # # class UpstreamServiceError(RequestBasedException): # """Something went wrong when calling an upstream service.""" # # status_int = 409 # # Path: via/views/exceptions.py # EXCEPTION_MAP = { # BadURL: { # "title": "The URL isn't valid", # "long_description": [ # "Parts of the URL could be missing or in the wrong format." # ], # "stage": "request", # "retryable": False, # }, # UpstreamTimeout: { # "title": "Timeout", # "long_description": ["The web page we tried to get took too long to respond."], # "stage": "upstream", # "retryable": True, # }, # UnhandledUpstreamException: { # "title": "Something went wrong", # "long_description": ["We experienced an unexpected error."], # "stage": "via", # "retryable": True, # }, # UpstreamServiceError: { # "title": "Could not get web page", # "long_description": [ # "Something went wrong when we tried to get the web page.", # "It might be missing or might have returned an error.", # ], # "stage": "upstream", # "retryable": True, # }, # HTTPNotFound: { # "title": "Page not found", # "long_description": [ # "The URL you asked for is not part of this service.", # "Please check the URL you have entered.", # ], # "stage": "request", # "retryable": False, # }, # HTTPClientError: { # "title": "Bad request", # "long_description": [ # "We can't process the request because we don't understand it." # ], # "stage": "request", # "retryable": False, # }, # } # # @exception_view_config(Exception, route_name="proxy_google_drive_file", renderer="json") # @exception_view_config( # Exception, route_name="proxy_google_drive_file:resource_key", renderer="json" # ) # def google_drive_exceptions(exc, request): # """Catch all errors for Google Drive and display an HTML page.""" # # # Don't log 404's as they aren't very interesting # if not isinstance(exc, HTTPNotFound): # h_pyramid_sentry.report_exception(exc) # # _set_status(exc, request) # # data = { # "exception": exc.__class__.__name__, # "message": str(exc.args[0]) if exc.args else None, # } # # if hasattr(exc, "response") and exc.response is not None: # data["upstream"] = _serialise_requests_info(exc.request, exc.response) # # return data # # @exception_view_config(Exception, renderer="via:templates/exception.html.jinja2") # def other_exceptions(exc, request): # """Catch all errors (Pyramid or Python) and display an HTML page.""" # # # We don't want to log errors from upstream services or things which are # # the user goofing about making bad queries. # if not isinstance(exc, (UpstreamServiceError, BadURL, HTTPClientError)): # h_pyramid_sentry.report_exception(exc) # # return _get_error_body(exc, request) . Output only the next line.
param(BlockingIOError, UnhandledUpstreamException, id="Unmapped"),
Given the code snippet: <|code_start|> ) def test_it_reads_the_urls_from_the_request( self, pyramid_request, get_original_url ): pyramid_request.url = sentinel.request_url values = other_exceptions(ValueError(), pyramid_request) get_original_url.assert_called_once_with(pyramid_request.context) assert values["url"] == { "original": get_original_url.return_value, "retry": sentinel.request_url, } def test_it_doesnt_read_the_url_if_the_request_has_no_context( self, pyramid_request, get_original_url ): # It seems we can get in the situation where Pyramid does not provide # a context attribute at all on the object delattr(pyramid_request, "context") values = other_exceptions(ValueError(), pyramid_request) get_original_url.assert_not_called() assert values["url"]["original"] is None @pytest.mark.parametrize( "exception_class,should_report", ( <|code_end|> , generate the next line using the imports in this file: import json import pytest from io import BytesIO from unittest.mock import sentinel from h_matchers import Any from pyramid.httpexceptions import ( HTTPClientError, HTTPGatewayTimeout, HTTPNotFound, HTTPUnsupportedMediaType, ) from pyramid.testing import DummyRequest from pytest import param from requests import HTTPError, Request, Response from via.exceptions import ( BadURL, GoogleDriveServiceError, UnhandledUpstreamException, UpstreamServiceError, ) from via.views.exceptions import ( EXCEPTION_MAP, google_drive_exceptions, other_exceptions, ) and context (functions, classes, or occasionally code) from other files: # Path: via/exceptions.py # class BadURL(RequestBasedException): # """An invalid URL was discovered.""" # # def __init__(self, message, requests_err=None, url=None): # super().__init__(message, requests_err) # self.url = url # # status_int = 400 # # class GoogleDriveServiceError(UpstreamServiceError): # """Something interesting happened in Google Drive. # # We often use the more generic versions, but if there's something of # particular interest, we might raise this error. # """ # # def __init__(self, message, status_int, requests_err=None): # super().__init__(message, requests_err=requests_err) # # self.status_int = status_int # # class UnhandledUpstreamException(UpstreamServiceError): # """Something we did not plan for went wrong.""" # # status_int = 417 # # class UpstreamServiceError(RequestBasedException): # """Something went wrong when calling an upstream service.""" # # status_int = 409 # # Path: via/views/exceptions.py # EXCEPTION_MAP = { # BadURL: { # "title": "The URL isn't valid", # "long_description": [ # "Parts of the URL could be missing or in the wrong format." # ], # "stage": "request", # "retryable": False, # }, # UpstreamTimeout: { # "title": "Timeout", # "long_description": ["The web page we tried to get took too long to respond."], # "stage": "upstream", # "retryable": True, # }, # UnhandledUpstreamException: { # "title": "Something went wrong", # "long_description": ["We experienced an unexpected error."], # "stage": "via", # "retryable": True, # }, # UpstreamServiceError: { # "title": "Could not get web page", # "long_description": [ # "Something went wrong when we tried to get the web page.", # "It might be missing or might have returned an error.", # ], # "stage": "upstream", # "retryable": True, # }, # HTTPNotFound: { # "title": "Page not found", # "long_description": [ # "The URL you asked for is not part of this service.", # "Please check the URL you have entered.", # ], # "stage": "request", # "retryable": False, # }, # HTTPClientError: { # "title": "Bad request", # "long_description": [ # "We can't process the request because we don't understand it." # ], # "stage": "request", # "retryable": False, # }, # } # # @exception_view_config(Exception, route_name="proxy_google_drive_file", renderer="json") # @exception_view_config( # Exception, route_name="proxy_google_drive_file:resource_key", renderer="json" # ) # def google_drive_exceptions(exc, request): # """Catch all errors for Google Drive and display an HTML page.""" # # # Don't log 404's as they aren't very interesting # if not isinstance(exc, HTTPNotFound): # h_pyramid_sentry.report_exception(exc) # # _set_status(exc, request) # # data = { # "exception": exc.__class__.__name__, # "message": str(exc.args[0]) if exc.args else None, # } # # if hasattr(exc, "response") and exc.response is not None: # data["upstream"] = _serialise_requests_info(exc.request, exc.response) # # return data # # @exception_view_config(Exception, renderer="via:templates/exception.html.jinja2") # def other_exceptions(exc, request): # """Catch all errors (Pyramid or Python) and display an HTML page.""" # # # We don't want to log errors from upstream services or things which are # # the user goofing about making bad queries. # if not isinstance(exc, (UpstreamServiceError, BadURL, HTTPClientError)): # h_pyramid_sentry.report_exception(exc) # # return _get_error_body(exc, request) . Output only the next line.
(UpstreamServiceError, False),
Predict the next line for this snippet: <|code_start|> values = other_exceptions(exception, pyramid_request) assert values == Any.dict.containing( { "exception": Any.dict.containing( {"class": exception.__class__.__name__, "details": "details string"} ), "status_code": status_code, } ) assert pyramid_request.response.status_int == status_code @pytest.mark.parametrize( "exception_class,mapped_exception", ( param(BadURL, BadURL, id="Mapped directly"), param(HTTPUnsupportedMediaType, HTTPClientError, id="Inherited"), param(BlockingIOError, UnhandledUpstreamException, id="Unmapped"), ), ) def test_we_fill_in_other_values_based_on_exception_lookup( self, exception_class, mapped_exception, pyramid_request ): exception = exception_class("details string") values = other_exceptions(exception, pyramid_request) assert values["exception"] == Any.dict.containing( <|code_end|> with the help of current file imports: import json import pytest from io import BytesIO from unittest.mock import sentinel from h_matchers import Any from pyramid.httpexceptions import ( HTTPClientError, HTTPGatewayTimeout, HTTPNotFound, HTTPUnsupportedMediaType, ) from pyramid.testing import DummyRequest from pytest import param from requests import HTTPError, Request, Response from via.exceptions import ( BadURL, GoogleDriveServiceError, UnhandledUpstreamException, UpstreamServiceError, ) from via.views.exceptions import ( EXCEPTION_MAP, google_drive_exceptions, other_exceptions, ) and context from other files: # Path: via/exceptions.py # class BadURL(RequestBasedException): # """An invalid URL was discovered.""" # # def __init__(self, message, requests_err=None, url=None): # super().__init__(message, requests_err) # self.url = url # # status_int = 400 # # class GoogleDriveServiceError(UpstreamServiceError): # """Something interesting happened in Google Drive. # # We often use the more generic versions, but if there's something of # particular interest, we might raise this error. # """ # # def __init__(self, message, status_int, requests_err=None): # super().__init__(message, requests_err=requests_err) # # self.status_int = status_int # # class UnhandledUpstreamException(UpstreamServiceError): # """Something we did not plan for went wrong.""" # # status_int = 417 # # class UpstreamServiceError(RequestBasedException): # """Something went wrong when calling an upstream service.""" # # status_int = 409 # # Path: via/views/exceptions.py # EXCEPTION_MAP = { # BadURL: { # "title": "The URL isn't valid", # "long_description": [ # "Parts of the URL could be missing or in the wrong format." # ], # "stage": "request", # "retryable": False, # }, # UpstreamTimeout: { # "title": "Timeout", # "long_description": ["The web page we tried to get took too long to respond."], # "stage": "upstream", # "retryable": True, # }, # UnhandledUpstreamException: { # "title": "Something went wrong", # "long_description": ["We experienced an unexpected error."], # "stage": "via", # "retryable": True, # }, # UpstreamServiceError: { # "title": "Could not get web page", # "long_description": [ # "Something went wrong when we tried to get the web page.", # "It might be missing or might have returned an error.", # ], # "stage": "upstream", # "retryable": True, # }, # HTTPNotFound: { # "title": "Page not found", # "long_description": [ # "The URL you asked for is not part of this service.", # "Please check the URL you have entered.", # ], # "stage": "request", # "retryable": False, # }, # HTTPClientError: { # "title": "Bad request", # "long_description": [ # "We can't process the request because we don't understand it." # ], # "stage": "request", # "retryable": False, # }, # } # # @exception_view_config(Exception, route_name="proxy_google_drive_file", renderer="json") # @exception_view_config( # Exception, route_name="proxy_google_drive_file:resource_key", renderer="json" # ) # def google_drive_exceptions(exc, request): # """Catch all errors for Google Drive and display an HTML page.""" # # # Don't log 404's as they aren't very interesting # if not isinstance(exc, HTTPNotFound): # h_pyramid_sentry.report_exception(exc) # # _set_status(exc, request) # # data = { # "exception": exc.__class__.__name__, # "message": str(exc.args[0]) if exc.args else None, # } # # if hasattr(exc, "response") and exc.response is not None: # data["upstream"] = _serialise_requests_info(exc.request, exc.response) # # return data # # @exception_view_config(Exception, renderer="via:templates/exception.html.jinja2") # def other_exceptions(exc, request): # """Catch all errors (Pyramid or Python) and display an HTML page.""" # # # We don't want to log errors from upstream services or things which are # # the user goofing about making bad queries. # if not isinstance(exc, (UpstreamServiceError, BadURL, HTTPClientError)): # h_pyramid_sentry.report_exception(exc) # # return _get_error_body(exc, request) , which may contain function names, class names, or code. Output only the next line.
EXCEPTION_MAP[mapped_exception]
Given the following code snippet before the placeholder: <|code_start|> ), ) def test_other_exceptions_reporting_to_sentry( self, pyramid_request, h_pyramid_sentry, exception_class, should_report ): exception = exception_class("Oh no") other_exceptions(exception, pyramid_request) if should_report: h_pyramid_sentry.report_exception.assert_called_once_with(exception) else: h_pyramid_sentry.report_exception.assert_not_called() @pytest.mark.parametrize( "exception_class,should_report", ( (HTTPNotFound, False), (UnhandledUpstreamException, True), (BadURL, True), (HTTPClientError, True), (ValueError, True), (HTTPGatewayTimeout, True), ), ) def test_google_drive_exceptions_reporting_to_sentry( self, pyramid_request, h_pyramid_sentry, exception_class, should_report ): exception = exception_class("Oh no") <|code_end|> , predict the next line using imports from the current file: import json import pytest from io import BytesIO from unittest.mock import sentinel from h_matchers import Any from pyramid.httpexceptions import ( HTTPClientError, HTTPGatewayTimeout, HTTPNotFound, HTTPUnsupportedMediaType, ) from pyramid.testing import DummyRequest from pytest import param from requests import HTTPError, Request, Response from via.exceptions import ( BadURL, GoogleDriveServiceError, UnhandledUpstreamException, UpstreamServiceError, ) from via.views.exceptions import ( EXCEPTION_MAP, google_drive_exceptions, other_exceptions, ) and context including class names, function names, and sometimes code from other files: # Path: via/exceptions.py # class BadURL(RequestBasedException): # """An invalid URL was discovered.""" # # def __init__(self, message, requests_err=None, url=None): # super().__init__(message, requests_err) # self.url = url # # status_int = 400 # # class GoogleDriveServiceError(UpstreamServiceError): # """Something interesting happened in Google Drive. # # We often use the more generic versions, but if there's something of # particular interest, we might raise this error. # """ # # def __init__(self, message, status_int, requests_err=None): # super().__init__(message, requests_err=requests_err) # # self.status_int = status_int # # class UnhandledUpstreamException(UpstreamServiceError): # """Something we did not plan for went wrong.""" # # status_int = 417 # # class UpstreamServiceError(RequestBasedException): # """Something went wrong when calling an upstream service.""" # # status_int = 409 # # Path: via/views/exceptions.py # EXCEPTION_MAP = { # BadURL: { # "title": "The URL isn't valid", # "long_description": [ # "Parts of the URL could be missing or in the wrong format." # ], # "stage": "request", # "retryable": False, # }, # UpstreamTimeout: { # "title": "Timeout", # "long_description": ["The web page we tried to get took too long to respond."], # "stage": "upstream", # "retryable": True, # }, # UnhandledUpstreamException: { # "title": "Something went wrong", # "long_description": ["We experienced an unexpected error."], # "stage": "via", # "retryable": True, # }, # UpstreamServiceError: { # "title": "Could not get web page", # "long_description": [ # "Something went wrong when we tried to get the web page.", # "It might be missing or might have returned an error.", # ], # "stage": "upstream", # "retryable": True, # }, # HTTPNotFound: { # "title": "Page not found", # "long_description": [ # "The URL you asked for is not part of this service.", # "Please check the URL you have entered.", # ], # "stage": "request", # "retryable": False, # }, # HTTPClientError: { # "title": "Bad request", # "long_description": [ # "We can't process the request because we don't understand it." # ], # "stage": "request", # "retryable": False, # }, # } # # @exception_view_config(Exception, route_name="proxy_google_drive_file", renderer="json") # @exception_view_config( # Exception, route_name="proxy_google_drive_file:resource_key", renderer="json" # ) # def google_drive_exceptions(exc, request): # """Catch all errors for Google Drive and display an HTML page.""" # # # Don't log 404's as they aren't very interesting # if not isinstance(exc, HTTPNotFound): # h_pyramid_sentry.report_exception(exc) # # _set_status(exc, request) # # data = { # "exception": exc.__class__.__name__, # "message": str(exc.args[0]) if exc.args else None, # } # # if hasattr(exc, "response") and exc.response is not None: # data["upstream"] = _serialise_requests_info(exc.request, exc.response) # # return data # # @exception_view_config(Exception, renderer="via:templates/exception.html.jinja2") # def other_exceptions(exc, request): # """Catch all errors (Pyramid or Python) and display an HTML page.""" # # # We don't want to log errors from upstream services or things which are # # the user goofing about making bad queries. # if not isinstance(exc, (UpstreamServiceError, BadURL, HTTPClientError)): # h_pyramid_sentry.report_exception(exc) # # return _get_error_body(exc, request) . Output only the next line.
google_drive_exceptions(exception, pyramid_request)
Given snippet: <|code_start|> class TestOtherExceptions: @pytest.mark.parametrize( "exception_class,status_code", ( param( HTTPUnsupportedMediaType, HTTPUnsupportedMediaType.code, id="Pyramid error", ), param(BlockingIOError, 500, id="Unknown python error"), ), ) def test_values_are_copied_from_the_exception( self, exception_class, status_code, pyramid_request ): exception = exception_class("details string") <|code_end|> , continue by predicting the next line. Consider current file imports: import json import pytest from io import BytesIO from unittest.mock import sentinel from h_matchers import Any from pyramid.httpexceptions import ( HTTPClientError, HTTPGatewayTimeout, HTTPNotFound, HTTPUnsupportedMediaType, ) from pyramid.testing import DummyRequest from pytest import param from requests import HTTPError, Request, Response from via.exceptions import ( BadURL, GoogleDriveServiceError, UnhandledUpstreamException, UpstreamServiceError, ) from via.views.exceptions import ( EXCEPTION_MAP, google_drive_exceptions, other_exceptions, ) and context: # Path: via/exceptions.py # class BadURL(RequestBasedException): # """An invalid URL was discovered.""" # # def __init__(self, message, requests_err=None, url=None): # super().__init__(message, requests_err) # self.url = url # # status_int = 400 # # class GoogleDriveServiceError(UpstreamServiceError): # """Something interesting happened in Google Drive. # # We often use the more generic versions, but if there's something of # particular interest, we might raise this error. # """ # # def __init__(self, message, status_int, requests_err=None): # super().__init__(message, requests_err=requests_err) # # self.status_int = status_int # # class UnhandledUpstreamException(UpstreamServiceError): # """Something we did not plan for went wrong.""" # # status_int = 417 # # class UpstreamServiceError(RequestBasedException): # """Something went wrong when calling an upstream service.""" # # status_int = 409 # # Path: via/views/exceptions.py # EXCEPTION_MAP = { # BadURL: { # "title": "The URL isn't valid", # "long_description": [ # "Parts of the URL could be missing or in the wrong format." # ], # "stage": "request", # "retryable": False, # }, # UpstreamTimeout: { # "title": "Timeout", # "long_description": ["The web page we tried to get took too long to respond."], # "stage": "upstream", # "retryable": True, # }, # UnhandledUpstreamException: { # "title": "Something went wrong", # "long_description": ["We experienced an unexpected error."], # "stage": "via", # "retryable": True, # }, # UpstreamServiceError: { # "title": "Could not get web page", # "long_description": [ # "Something went wrong when we tried to get the web page.", # "It might be missing or might have returned an error.", # ], # "stage": "upstream", # "retryable": True, # }, # HTTPNotFound: { # "title": "Page not found", # "long_description": [ # "The URL you asked for is not part of this service.", # "Please check the URL you have entered.", # ], # "stage": "request", # "retryable": False, # }, # HTTPClientError: { # "title": "Bad request", # "long_description": [ # "We can't process the request because we don't understand it." # ], # "stage": "request", # "retryable": False, # }, # } # # @exception_view_config(Exception, route_name="proxy_google_drive_file", renderer="json") # @exception_view_config( # Exception, route_name="proxy_google_drive_file:resource_key", renderer="json" # ) # def google_drive_exceptions(exc, request): # """Catch all errors for Google Drive and display an HTML page.""" # # # Don't log 404's as they aren't very interesting # if not isinstance(exc, HTTPNotFound): # h_pyramid_sentry.report_exception(exc) # # _set_status(exc, request) # # data = { # "exception": exc.__class__.__name__, # "message": str(exc.args[0]) if exc.args else None, # } # # if hasattr(exc, "response") and exc.response is not None: # data["upstream"] = _serialise_requests_info(exc.request, exc.response) # # return data # # @exception_view_config(Exception, renderer="via:templates/exception.html.jinja2") # def other_exceptions(exc, request): # """Catch all errors (Pyramid or Python) and display an HTML page.""" # # # We don't want to log errors from upstream services or things which are # # the user goofing about making bad queries. # if not isinstance(exc, (UpstreamServiceError, BadURL, HTTPClientError)): # h_pyramid_sentry.report_exception(exc) # # return _get_error_body(exc, request) which might include code, classes, or functions. Output only the next line.
values = other_exceptions(exception, pyramid_request)
Predict the next line for this snippet: <|code_start|> class TestDebugHeaders: def test_it(self, pyramid_request): pyramid_request.headers = {"Key": "Value"} <|code_end|> with the help of current file imports: from unittest.mock import create_autospec, sentinel from h_matchers import Any from pyramid.testing import DummyRequest from via.views.debug import debug_headers import pytest and context from other files: # Path: via/views/debug.py # @view.view_config(route_name="debug_headers") # def debug_headers(_context, request): # """Dump the headers as we receive them for debugging.""" # # if request.GET.get("raw"): # headers = OrderedDict(request.headers) # else: # headers = clean_headers(request.headers) # # self_url = request.route_url("debug_headers") # # return Response( # body=f""" # <h1>Instructions</h1> # <ol> # <li>Access the service directly (not thru *.hypothes.is) # <li>Enable Do-Not-Track if supported</li> # <li> # <a href="{self_url}"> # Click here to get referer # </a> # </li> # <li>Press F5 to get 'Cache-Control'</li> # </ol> # # <a href="{self_url}?raw=1">Show all headers</a> # # <hr> # # <h1>Headers received</h1> # <pre>{json.dumps(headers, indent=4)}</pre><br> # """, # status=200, # ) , which may contain function names, class names, or code. Output only the next line.
response = debug_headers(sentinel.context, pyramid_request)
Predict the next line after this snippet: <|code_start|> @pytest.mark.usefixtures("http_service") def test_it(self, call_view, jstor_api, pyramid_request): response = call_view( "jstor://DOI", view=proxy_jstor_pdf, params={"jstor.ip": "1.1.1.1"} ) assert response.status_code == 200 assert response.headers["Content-Disposition"] == "inline" assert response.headers["Content-Type"] == "application/pdf" assert ( response.headers["Cache-Control"] == "public, max-age=43200, stale-while-revalidate=86400" ) jstor_api.jstor_pdf_stream.assert_called_once_with( "jstor://DOI", pyramid_request.params["jstor.ip"] ) def test_when_not_enabled(self, call_view, jstor_api): jstor_api.enabled = False with pytest.raises(HTTPUnauthorized): call_view( "jstor://DOI", view=proxy_jstor_pdf, params={"jstor.ip": "1.1.1.1"} ) @pytest.fixture def call_view(pyramid_request): def call_view(url="http://example.com/name.pdf", params=None, view=view_pdf): pyramid_request.params = dict(params or {}, url=url) <|code_end|> using the current file's imports: from unittest.mock import sentinel from h_matchers import Any from pyramid.httpexceptions import HTTPNoContent, HTTPUnauthorized from via.resources import QueryURLResource from via.views.view_pdf import ( proxy_google_drive_file, proxy_jstor_pdf, proxy_onedrive_pdf, view_pdf, ) import pytest and any relevant context from other files: # Path: via/resources.py # class QueryURLResource(_URLResource): # """Resource for routes expecting urls from the query.""" # # def url_from_query(self): # """Get the 'url' parameter from the query. # # :return: The URL as a string # :raise HTTPBadRequest: If the URL is missing or empty # :raise BadURL: If the URL is malformed # """ # try: # url = self._request.params["url"].strip() # except KeyError as err: # raise HTTPBadRequest("Required parameter 'url' missing") from err # # if not url: # raise HTTPBadRequest("Required parameter 'url' is blank") # # return self._normalise_url(url) # # Path: via/views/view_pdf.py # @view_config(route_name="proxy_google_drive_file", decorator=(has_secure_url_token,)) # @view_config( # route_name="proxy_google_drive_file:resource_key", decorator=(has_secure_url_token,) # ) # def proxy_google_drive_file(request): # """Proxy a file from Google Drive.""" # # # Add an iterable to stream the content instead of holding it all in memory # content_iterable = request.find_service(GoogleDriveAPI).iter_file( # file_id=request.matchdict["file_id"], # resource_key=request.matchdict.get("resource_key"), # ) # # return _iter_pdf_response(request.response, content_iterable) # # @view_config(route_name="proxy_jstor_pdf", decorator=(has_secure_url_token,)) # def proxy_jstor_pdf(context, request): # jstor_api = request.find_service(JSTORAPI) # if not jstor_api.enabled: # raise HTTPUnauthorized("JSTOR integration not enabled in Via") # # content_iterable = jstor_api.jstor_pdf_stream( # context.url_from_query(), request.params["jstor.ip"] # ) # return _iter_pdf_response(request.response, content_iterable) # # @view_config(route_name="proxy_onedrive_pdf", decorator=(has_secure_url_token,)) # def proxy_onedrive_pdf(context, request): # url = context.url_from_query() # # content_iterable = request.find_service(HTTPService).stream( # url, headers=add_request_headers({}) # ) # # return _iter_pdf_response(request.response, content_iterable) # # @view_config( # renderer="via:templates/pdf_viewer.html.jinja2", # route_name="view_pdf", # # We have to keep the leash short here for caching so we can pick up new # # immutable assets when they are deployed # http_cache=0, # decorator=(has_secure_url_token,), # ) # def view_pdf(context, request): # """HTML page with client and the PDF embedded.""" # # url = context.url_from_query() # request.checkmate.raise_if_blocked(url) # # _, h_config = Configuration.extract_from_params(request.params) # # return { # # The upstream PDF URL that should be associated with any annotations. # "pdf_url": url, # # The CORS-proxied PDF URL which the viewer should actually load the # # PDF from. # "proxy_pdf_url": request.find_service(PDFURLBuilder).get_pdf_url(url), # "client_embed_url": request.registry.settings["client_embed_url"], # "static_url": request.static_url, # "hypothesis_config": h_config, # } . Output only the next line.
context = QueryURLResource(pyramid_request)
Next line prediction: <|code_start|> "hypothesis_config": sentinel.h_config, } def test_it_builds_the_url( self, call_view, google_drive_api, pdf_url_builder_service ): google_drive_api.parse_file_url.return_value = None call_view("https://example.com/foo/bar.pdf?q=s") pdf_url_builder_service.get_pdf_url.assert_called_once_with( "https://example.com/foo/bar.pdf?q=s" ) @pytest.fixture def Configuration(self, patch): Configuration = patch("via.views.view_pdf.Configuration") Configuration.extract_from_params.return_value = ( sentinel.via_config, sentinel.h_config, ) return Configuration @pytest.mark.usefixtures( "secure_link_service", "google_drive_api", "pdf_url_builder_service" ) class TestProxyGoogleDriveFile: def test_status_and_headers(self, pyramid_request): <|code_end|> . Use current file imports: (from unittest.mock import sentinel from h_matchers import Any from pyramid.httpexceptions import HTTPNoContent, HTTPUnauthorized from via.resources import QueryURLResource from via.views.view_pdf import ( proxy_google_drive_file, proxy_jstor_pdf, proxy_onedrive_pdf, view_pdf, ) import pytest) and context including class names, function names, or small code snippets from other files: # Path: via/resources.py # class QueryURLResource(_URLResource): # """Resource for routes expecting urls from the query.""" # # def url_from_query(self): # """Get the 'url' parameter from the query. # # :return: The URL as a string # :raise HTTPBadRequest: If the URL is missing or empty # :raise BadURL: If the URL is malformed # """ # try: # url = self._request.params["url"].strip() # except KeyError as err: # raise HTTPBadRequest("Required parameter 'url' missing") from err # # if not url: # raise HTTPBadRequest("Required parameter 'url' is blank") # # return self._normalise_url(url) # # Path: via/views/view_pdf.py # @view_config(route_name="proxy_google_drive_file", decorator=(has_secure_url_token,)) # @view_config( # route_name="proxy_google_drive_file:resource_key", decorator=(has_secure_url_token,) # ) # def proxy_google_drive_file(request): # """Proxy a file from Google Drive.""" # # # Add an iterable to stream the content instead of holding it all in memory # content_iterable = request.find_service(GoogleDriveAPI).iter_file( # file_id=request.matchdict["file_id"], # resource_key=request.matchdict.get("resource_key"), # ) # # return _iter_pdf_response(request.response, content_iterable) # # @view_config(route_name="proxy_jstor_pdf", decorator=(has_secure_url_token,)) # def proxy_jstor_pdf(context, request): # jstor_api = request.find_service(JSTORAPI) # if not jstor_api.enabled: # raise HTTPUnauthorized("JSTOR integration not enabled in Via") # # content_iterable = jstor_api.jstor_pdf_stream( # context.url_from_query(), request.params["jstor.ip"] # ) # return _iter_pdf_response(request.response, content_iterable) # # @view_config(route_name="proxy_onedrive_pdf", decorator=(has_secure_url_token,)) # def proxy_onedrive_pdf(context, request): # url = context.url_from_query() # # content_iterable = request.find_service(HTTPService).stream( # url, headers=add_request_headers({}) # ) # # return _iter_pdf_response(request.response, content_iterable) # # @view_config( # renderer="via:templates/pdf_viewer.html.jinja2", # route_name="view_pdf", # # We have to keep the leash short here for caching so we can pick up new # # immutable assets when they are deployed # http_cache=0, # decorator=(has_secure_url_token,), # ) # def view_pdf(context, request): # """HTML page with client and the PDF embedded.""" # # url = context.url_from_query() # request.checkmate.raise_if_blocked(url) # # _, h_config = Configuration.extract_from_params(request.params) # # return { # # The upstream PDF URL that should be associated with any annotations. # "pdf_url": url, # # The CORS-proxied PDF URL which the viewer should actually load the # # PDF from. # "proxy_pdf_url": request.find_service(PDFURLBuilder).get_pdf_url(url), # "client_embed_url": request.registry.settings["client_embed_url"], # "static_url": request.static_url, # "hypothesis_config": h_config, # } . Output only the next line.
response = proxy_google_drive_file(pyramid_request)
Next line prediction: <|code_start|> def test_it_streams_content(self, http_service, call_view): # Create a generator and a counter of how many times it's been accessed def count_access(i): count_access.value += 1 return i count_access.value = 0 http_service.stream.return_value = (count_access(i) for i in range(3)) response = call_view("https://one-drive.com", view=proxy_onedrive_pdf) # The first and only the first item has been reified from the generator assert count_access.value == 1 # And we still get everything if we iterate assert list(response.app_iter) == [0, 1, 2] def test_it_can_stream_an_empty_iterator(self, http_service, call_view): http_service.stream.return_value = iter([]) response = call_view("https://one-drive.com", view=proxy_onedrive_pdf) assert isinstance(response, HTTPNoContent) @pytest.mark.usefixtures("secure_link_service", "pdf_url_builder_service") class TestJSTORPDF: @pytest.mark.usefixtures("http_service") def test_it(self, call_view, jstor_api, pyramid_request): response = call_view( <|code_end|> . Use current file imports: (from unittest.mock import sentinel from h_matchers import Any from pyramid.httpexceptions import HTTPNoContent, HTTPUnauthorized from via.resources import QueryURLResource from via.views.view_pdf import ( proxy_google_drive_file, proxy_jstor_pdf, proxy_onedrive_pdf, view_pdf, ) import pytest) and context including class names, function names, or small code snippets from other files: # Path: via/resources.py # class QueryURLResource(_URLResource): # """Resource for routes expecting urls from the query.""" # # def url_from_query(self): # """Get the 'url' parameter from the query. # # :return: The URL as a string # :raise HTTPBadRequest: If the URL is missing or empty # :raise BadURL: If the URL is malformed # """ # try: # url = self._request.params["url"].strip() # except KeyError as err: # raise HTTPBadRequest("Required parameter 'url' missing") from err # # if not url: # raise HTTPBadRequest("Required parameter 'url' is blank") # # return self._normalise_url(url) # # Path: via/views/view_pdf.py # @view_config(route_name="proxy_google_drive_file", decorator=(has_secure_url_token,)) # @view_config( # route_name="proxy_google_drive_file:resource_key", decorator=(has_secure_url_token,) # ) # def proxy_google_drive_file(request): # """Proxy a file from Google Drive.""" # # # Add an iterable to stream the content instead of holding it all in memory # content_iterable = request.find_service(GoogleDriveAPI).iter_file( # file_id=request.matchdict["file_id"], # resource_key=request.matchdict.get("resource_key"), # ) # # return _iter_pdf_response(request.response, content_iterable) # # @view_config(route_name="proxy_jstor_pdf", decorator=(has_secure_url_token,)) # def proxy_jstor_pdf(context, request): # jstor_api = request.find_service(JSTORAPI) # if not jstor_api.enabled: # raise HTTPUnauthorized("JSTOR integration not enabled in Via") # # content_iterable = jstor_api.jstor_pdf_stream( # context.url_from_query(), request.params["jstor.ip"] # ) # return _iter_pdf_response(request.response, content_iterable) # # @view_config(route_name="proxy_onedrive_pdf", decorator=(has_secure_url_token,)) # def proxy_onedrive_pdf(context, request): # url = context.url_from_query() # # content_iterable = request.find_service(HTTPService).stream( # url, headers=add_request_headers({}) # ) # # return _iter_pdf_response(request.response, content_iterable) # # @view_config( # renderer="via:templates/pdf_viewer.html.jinja2", # route_name="view_pdf", # # We have to keep the leash short here for caching so we can pick up new # # immutable assets when they are deployed # http_cache=0, # decorator=(has_secure_url_token,), # ) # def view_pdf(context, request): # """HTML page with client and the PDF embedded.""" # # url = context.url_from_query() # request.checkmate.raise_if_blocked(url) # # _, h_config = Configuration.extract_from_params(request.params) # # return { # # The upstream PDF URL that should be associated with any annotations. # "pdf_url": url, # # The CORS-proxied PDF URL which the viewer should actually load the # # PDF from. # "proxy_pdf_url": request.find_service(PDFURLBuilder).get_pdf_url(url), # "client_embed_url": request.registry.settings["client_embed_url"], # "static_url": request.static_url, # "hypothesis_config": h_config, # } . Output only the next line.
"jstor://DOI", view=proxy_jstor_pdf, params={"jstor.ip": "1.1.1.1"}
Predict the next line after this snippet: <|code_start|> google_drive_api.iter_file.return_value = (count_access(i) for i in range(3)) response = proxy_google_drive_file(pyramid_request) # The first and only the first item has been reified from the generator assert count_access.value == 1 # And we still get everything if we iterate assert list(response.app_iter) == [0, 1, 2] def test_it_can_stream_an_empty_iterator(self, pyramid_request, google_drive_api): google_drive_api.iter_file.return_value = iter([]) response = proxy_google_drive_file(pyramid_request) assert isinstance(response, HTTPNoContent) @pytest.fixture def pyramid_request(self, pyramid_request): pyramid_request.matchdict.update( {"file_id": sentinel.file_id, "token": sentinel.token} ) return pyramid_request @pytest.mark.usefixtures("secure_link_service", "pdf_url_builder_service") class TestProxyOneDrivePDF: @pytest.mark.usefixtures("http_service") def test_status_and_headers(self, call_view): <|code_end|> using the current file's imports: from unittest.mock import sentinel from h_matchers import Any from pyramid.httpexceptions import HTTPNoContent, HTTPUnauthorized from via.resources import QueryURLResource from via.views.view_pdf import ( proxy_google_drive_file, proxy_jstor_pdf, proxy_onedrive_pdf, view_pdf, ) import pytest and any relevant context from other files: # Path: via/resources.py # class QueryURLResource(_URLResource): # """Resource for routes expecting urls from the query.""" # # def url_from_query(self): # """Get the 'url' parameter from the query. # # :return: The URL as a string # :raise HTTPBadRequest: If the URL is missing or empty # :raise BadURL: If the URL is malformed # """ # try: # url = self._request.params["url"].strip() # except KeyError as err: # raise HTTPBadRequest("Required parameter 'url' missing") from err # # if not url: # raise HTTPBadRequest("Required parameter 'url' is blank") # # return self._normalise_url(url) # # Path: via/views/view_pdf.py # @view_config(route_name="proxy_google_drive_file", decorator=(has_secure_url_token,)) # @view_config( # route_name="proxy_google_drive_file:resource_key", decorator=(has_secure_url_token,) # ) # def proxy_google_drive_file(request): # """Proxy a file from Google Drive.""" # # # Add an iterable to stream the content instead of holding it all in memory # content_iterable = request.find_service(GoogleDriveAPI).iter_file( # file_id=request.matchdict["file_id"], # resource_key=request.matchdict.get("resource_key"), # ) # # return _iter_pdf_response(request.response, content_iterable) # # @view_config(route_name="proxy_jstor_pdf", decorator=(has_secure_url_token,)) # def proxy_jstor_pdf(context, request): # jstor_api = request.find_service(JSTORAPI) # if not jstor_api.enabled: # raise HTTPUnauthorized("JSTOR integration not enabled in Via") # # content_iterable = jstor_api.jstor_pdf_stream( # context.url_from_query(), request.params["jstor.ip"] # ) # return _iter_pdf_response(request.response, content_iterable) # # @view_config(route_name="proxy_onedrive_pdf", decorator=(has_secure_url_token,)) # def proxy_onedrive_pdf(context, request): # url = context.url_from_query() # # content_iterable = request.find_service(HTTPService).stream( # url, headers=add_request_headers({}) # ) # # return _iter_pdf_response(request.response, content_iterable) # # @view_config( # renderer="via:templates/pdf_viewer.html.jinja2", # route_name="view_pdf", # # We have to keep the leash short here for caching so we can pick up new # # immutable assets when they are deployed # http_cache=0, # decorator=(has_secure_url_token,), # ) # def view_pdf(context, request): # """HTML page with client and the PDF embedded.""" # # url = context.url_from_query() # request.checkmate.raise_if_blocked(url) # # _, h_config = Configuration.extract_from_params(request.params) # # return { # # The upstream PDF URL that should be associated with any annotations. # "pdf_url": url, # # The CORS-proxied PDF URL which the viewer should actually load the # # PDF from. # "proxy_pdf_url": request.find_service(PDFURLBuilder).get_pdf_url(url), # "client_embed_url": request.registry.settings["client_embed_url"], # "static_url": request.static_url, # "hypothesis_config": h_config, # } . Output only the next line.
response = call_view("https://one-drive.com", view=proxy_onedrive_pdf)
Predict the next line after this snippet: <|code_start|>@pytest.mark.usefixtures("secure_link_service", "pdf_url_builder_service") class TestJSTORPDF: @pytest.mark.usefixtures("http_service") def test_it(self, call_view, jstor_api, pyramid_request): response = call_view( "jstor://DOI", view=proxy_jstor_pdf, params={"jstor.ip": "1.1.1.1"} ) assert response.status_code == 200 assert response.headers["Content-Disposition"] == "inline" assert response.headers["Content-Type"] == "application/pdf" assert ( response.headers["Cache-Control"] == "public, max-age=43200, stale-while-revalidate=86400" ) jstor_api.jstor_pdf_stream.assert_called_once_with( "jstor://DOI", pyramid_request.params["jstor.ip"] ) def test_when_not_enabled(self, call_view, jstor_api): jstor_api.enabled = False with pytest.raises(HTTPUnauthorized): call_view( "jstor://DOI", view=proxy_jstor_pdf, params={"jstor.ip": "1.1.1.1"} ) @pytest.fixture def call_view(pyramid_request): <|code_end|> using the current file's imports: from unittest.mock import sentinel from h_matchers import Any from pyramid.httpexceptions import HTTPNoContent, HTTPUnauthorized from via.resources import QueryURLResource from via.views.view_pdf import ( proxy_google_drive_file, proxy_jstor_pdf, proxy_onedrive_pdf, view_pdf, ) import pytest and any relevant context from other files: # Path: via/resources.py # class QueryURLResource(_URLResource): # """Resource for routes expecting urls from the query.""" # # def url_from_query(self): # """Get the 'url' parameter from the query. # # :return: The URL as a string # :raise HTTPBadRequest: If the URL is missing or empty # :raise BadURL: If the URL is malformed # """ # try: # url = self._request.params["url"].strip() # except KeyError as err: # raise HTTPBadRequest("Required parameter 'url' missing") from err # # if not url: # raise HTTPBadRequest("Required parameter 'url' is blank") # # return self._normalise_url(url) # # Path: via/views/view_pdf.py # @view_config(route_name="proxy_google_drive_file", decorator=(has_secure_url_token,)) # @view_config( # route_name="proxy_google_drive_file:resource_key", decorator=(has_secure_url_token,) # ) # def proxy_google_drive_file(request): # """Proxy a file from Google Drive.""" # # # Add an iterable to stream the content instead of holding it all in memory # content_iterable = request.find_service(GoogleDriveAPI).iter_file( # file_id=request.matchdict["file_id"], # resource_key=request.matchdict.get("resource_key"), # ) # # return _iter_pdf_response(request.response, content_iterable) # # @view_config(route_name="proxy_jstor_pdf", decorator=(has_secure_url_token,)) # def proxy_jstor_pdf(context, request): # jstor_api = request.find_service(JSTORAPI) # if not jstor_api.enabled: # raise HTTPUnauthorized("JSTOR integration not enabled in Via") # # content_iterable = jstor_api.jstor_pdf_stream( # context.url_from_query(), request.params["jstor.ip"] # ) # return _iter_pdf_response(request.response, content_iterable) # # @view_config(route_name="proxy_onedrive_pdf", decorator=(has_secure_url_token,)) # def proxy_onedrive_pdf(context, request): # url = context.url_from_query() # # content_iterable = request.find_service(HTTPService).stream( # url, headers=add_request_headers({}) # ) # # return _iter_pdf_response(request.response, content_iterable) # # @view_config( # renderer="via:templates/pdf_viewer.html.jinja2", # route_name="view_pdf", # # We have to keep the leash short here for caching so we can pick up new # # immutable assets when they are deployed # http_cache=0, # decorator=(has_secure_url_token,), # ) # def view_pdf(context, request): # """HTML page with client and the PDF embedded.""" # # url = context.url_from_query() # request.checkmate.raise_if_blocked(url) # # _, h_config = Configuration.extract_from_params(request.params) # # return { # # The upstream PDF URL that should be associated with any annotations. # "pdf_url": url, # # The CORS-proxied PDF URL which the viewer should actually load the # # PDF from. # "proxy_pdf_url": request.find_service(PDFURLBuilder).get_pdf_url(url), # "client_embed_url": request.registry.settings["client_embed_url"], # "static_url": request.static_url, # "hypothesis_config": h_config, # } . Output only the next line.
def call_view(url="http://example.com/name.pdf", params=None, view=view_pdf):
Based on the snippet: <|code_start|> ) def test_it( self, content_type, context, expected_cache_control_header, get_url_details, pyramid_request, status_code, via_client_service, http_service, ): pyramid_request.params = {"url": sentinel.url, "foo": "bar"} get_url_details.return_value = (sentinel.mime_type, status_code) via_client_service.is_pdf.return_value = content_type == "PDF" response = route_by_content(context, pyramid_request) url = context.url_from_query.return_value pyramid_request.checkmate.raise_if_blocked.assert_called_once_with(url) get_url_details.assert_called_once_with( http_service, url, pyramid_request.headers ) via_client_service.is_pdf.assert_called_once_with(sentinel.mime_type) via_client_service.url_for.assert_called_once_with( url, sentinel.mime_type, {"foo": "bar"} ) assert response == temporary_redirect_to( via_client_service.url_for.return_value ) <|code_end|> , predict the immediate next line with the help of imports: from unittest.mock import create_autospec, sentinel from tests.conftest import assert_cache_control from tests.unit.matchers import temporary_redirect_to from via.resources import QueryURLResource from via.views.route_by_content import route_by_content import pytest and context (classes, functions, sometimes code) from other files: # Path: tests/conftest.py # def assert_cache_control(headers, cache_parts): # """Assert that all parts of the Cache-Control header are present.""" # assert dict(headers) == Any.dict.containing({"Cache-Control": Any.string()}) # assert ( # headers["Cache-Control"].split(", ") == Any.list.containing(cache_parts).only() # ) # # Path: tests/unit/matchers.py # def temporary_redirect_to(location): # """Return a matcher for any `HTTP 302 Found` redirect to the given URL.""" # return Any.instance_of(Response).with_attrs( # {"status_code": 302, "location": location} # ) # # Path: via/resources.py # class QueryURLResource(_URLResource): # """Resource for routes expecting urls from the query.""" # # def url_from_query(self): # """Get the 'url' parameter from the query. # # :return: The URL as a string # :raise HTTPBadRequest: If the URL is missing or empty # :raise BadURL: If the URL is malformed # """ # try: # url = self._request.params["url"].strip() # except KeyError as err: # raise HTTPBadRequest("Required parameter 'url' missing") from err # # if not url: # raise HTTPBadRequest("Required parameter 'url' is blank") # # return self._normalise_url(url) # # Path: via/views/route_by_content.py # @view.view_config(route_name="route_by_content", decorator=(has_secure_url_token,)) # def route_by_content(context, request): # """Routes the request according to the Content-Type header.""" # url = context.url_from_query() # # request.checkmate.raise_if_blocked(url) # # mime_type, status_code = get_url_details( # request.find_service(HTTPService), url, request.headers # ) # via_client_svc = request.find_service(ViaClientService) # # if via_client_svc.is_pdf(mime_type): # caching_headers = _caching_headers(max_age=300) # else: # caching_headers = _cache_headers_for_http(status_code) # # params = dict(request.params) # params.pop("url", None) # # url = via_client_svc.url_for(url, mime_type, params) # # return exc.HTTPFound(url, headers=caching_headers) . Output only the next line.
assert_cache_control(
Given the code snippet: <|code_start|> ("HTML", 500, "no-cache"), ("HTML", 501, "no-cache"), ], ) def test_it( self, content_type, context, expected_cache_control_header, get_url_details, pyramid_request, status_code, via_client_service, http_service, ): pyramid_request.params = {"url": sentinel.url, "foo": "bar"} get_url_details.return_value = (sentinel.mime_type, status_code) via_client_service.is_pdf.return_value = content_type == "PDF" response = route_by_content(context, pyramid_request) url = context.url_from_query.return_value pyramid_request.checkmate.raise_if_blocked.assert_called_once_with(url) get_url_details.assert_called_once_with( http_service, url, pyramid_request.headers ) via_client_service.is_pdf.assert_called_once_with(sentinel.mime_type) via_client_service.url_for.assert_called_once_with( url, sentinel.mime_type, {"foo": "bar"} ) <|code_end|> , generate the next line using the imports in this file: from unittest.mock import create_autospec, sentinel from tests.conftest import assert_cache_control from tests.unit.matchers import temporary_redirect_to from via.resources import QueryURLResource from via.views.route_by_content import route_by_content import pytest and context (functions, classes, or occasionally code) from other files: # Path: tests/conftest.py # def assert_cache_control(headers, cache_parts): # """Assert that all parts of the Cache-Control header are present.""" # assert dict(headers) == Any.dict.containing({"Cache-Control": Any.string()}) # assert ( # headers["Cache-Control"].split(", ") == Any.list.containing(cache_parts).only() # ) # # Path: tests/unit/matchers.py # def temporary_redirect_to(location): # """Return a matcher for any `HTTP 302 Found` redirect to the given URL.""" # return Any.instance_of(Response).with_attrs( # {"status_code": 302, "location": location} # ) # # Path: via/resources.py # class QueryURLResource(_URLResource): # """Resource for routes expecting urls from the query.""" # # def url_from_query(self): # """Get the 'url' parameter from the query. # # :return: The URL as a string # :raise HTTPBadRequest: If the URL is missing or empty # :raise BadURL: If the URL is malformed # """ # try: # url = self._request.params["url"].strip() # except KeyError as err: # raise HTTPBadRequest("Required parameter 'url' missing") from err # # if not url: # raise HTTPBadRequest("Required parameter 'url' is blank") # # return self._normalise_url(url) # # Path: via/views/route_by_content.py # @view.view_config(route_name="route_by_content", decorator=(has_secure_url_token,)) # def route_by_content(context, request): # """Routes the request according to the Content-Type header.""" # url = context.url_from_query() # # request.checkmate.raise_if_blocked(url) # # mime_type, status_code = get_url_details( # request.find_service(HTTPService), url, request.headers # ) # via_client_svc = request.find_service(ViaClientService) # # if via_client_svc.is_pdf(mime_type): # caching_headers = _caching_headers(max_age=300) # else: # caching_headers = _cache_headers_for_http(status_code) # # params = dict(request.params) # params.pop("url", None) # # url = via_client_svc.url_for(url, mime_type, params) # # return exc.HTTPFound(url, headers=caching_headers) . Output only the next line.
assert response == temporary_redirect_to(
Next line prediction: <|code_start|> get_url_details, pyramid_request, status_code, via_client_service, http_service, ): pyramid_request.params = {"url": sentinel.url, "foo": "bar"} get_url_details.return_value = (sentinel.mime_type, status_code) via_client_service.is_pdf.return_value = content_type == "PDF" response = route_by_content(context, pyramid_request) url = context.url_from_query.return_value pyramid_request.checkmate.raise_if_blocked.assert_called_once_with(url) get_url_details.assert_called_once_with( http_service, url, pyramid_request.headers ) via_client_service.is_pdf.assert_called_once_with(sentinel.mime_type) via_client_service.url_for.assert_called_once_with( url, sentinel.mime_type, {"foo": "bar"} ) assert response == temporary_redirect_to( via_client_service.url_for.return_value ) assert_cache_control( response.headers, expected_cache_control_header.split(", ") ) @pytest.fixture def context(self): <|code_end|> . Use current file imports: (from unittest.mock import create_autospec, sentinel from tests.conftest import assert_cache_control from tests.unit.matchers import temporary_redirect_to from via.resources import QueryURLResource from via.views.route_by_content import route_by_content import pytest) and context including class names, function names, or small code snippets from other files: # Path: tests/conftest.py # def assert_cache_control(headers, cache_parts): # """Assert that all parts of the Cache-Control header are present.""" # assert dict(headers) == Any.dict.containing({"Cache-Control": Any.string()}) # assert ( # headers["Cache-Control"].split(", ") == Any.list.containing(cache_parts).only() # ) # # Path: tests/unit/matchers.py # def temporary_redirect_to(location): # """Return a matcher for any `HTTP 302 Found` redirect to the given URL.""" # return Any.instance_of(Response).with_attrs( # {"status_code": 302, "location": location} # ) # # Path: via/resources.py # class QueryURLResource(_URLResource): # """Resource for routes expecting urls from the query.""" # # def url_from_query(self): # """Get the 'url' parameter from the query. # # :return: The URL as a string # :raise HTTPBadRequest: If the URL is missing or empty # :raise BadURL: If the URL is malformed # """ # try: # url = self._request.params["url"].strip() # except KeyError as err: # raise HTTPBadRequest("Required parameter 'url' missing") from err # # if not url: # raise HTTPBadRequest("Required parameter 'url' is blank") # # return self._normalise_url(url) # # Path: via/views/route_by_content.py # @view.view_config(route_name="route_by_content", decorator=(has_secure_url_token,)) # def route_by_content(context, request): # """Routes the request according to the Content-Type header.""" # url = context.url_from_query() # # request.checkmate.raise_if_blocked(url) # # mime_type, status_code = get_url_details( # request.find_service(HTTPService), url, request.headers # ) # via_client_svc = request.find_service(ViaClientService) # # if via_client_svc.is_pdf(mime_type): # caching_headers = _caching_headers(max_age=300) # else: # caching_headers = _cache_headers_for_http(status_code) # # params = dict(request.params) # params.pop("url", None) # # url = via_client_svc.url_for(url, mime_type, params) # # return exc.HTTPFound(url, headers=caching_headers) . Output only the next line.
return create_autospec(QueryURLResource, spec_set=True, instance=True)
Next line prediction: <|code_start|> @pytest.mark.usefixtures("via_client_service") class TestRouteByContent: @pytest.mark.parametrize( "content_type,status_code,expected_cache_control_header", [ ("PDF", 200, "public, max-age=300, stale-while-revalidate=86400"), ("HTML", 200, "public, max-age=60, stale-while-revalidate=86400"), ("HTML", 401, "public, max-age=60, stale-while-revalidate=86400"), ("HTML", 404, "public, max-age=60, stale-while-revalidate=86400"), ("HTML", 500, "no-cache"), ("HTML", 501, "no-cache"), ], ) def test_it( self, content_type, context, expected_cache_control_header, get_url_details, pyramid_request, status_code, via_client_service, http_service, ): pyramid_request.params = {"url": sentinel.url, "foo": "bar"} get_url_details.return_value = (sentinel.mime_type, status_code) via_client_service.is_pdf.return_value = content_type == "PDF" <|code_end|> . Use current file imports: (from unittest.mock import create_autospec, sentinel from tests.conftest import assert_cache_control from tests.unit.matchers import temporary_redirect_to from via.resources import QueryURLResource from via.views.route_by_content import route_by_content import pytest) and context including class names, function names, or small code snippets from other files: # Path: tests/conftest.py # def assert_cache_control(headers, cache_parts): # """Assert that all parts of the Cache-Control header are present.""" # assert dict(headers) == Any.dict.containing({"Cache-Control": Any.string()}) # assert ( # headers["Cache-Control"].split(", ") == Any.list.containing(cache_parts).only() # ) # # Path: tests/unit/matchers.py # def temporary_redirect_to(location): # """Return a matcher for any `HTTP 302 Found` redirect to the given URL.""" # return Any.instance_of(Response).with_attrs( # {"status_code": 302, "location": location} # ) # # Path: via/resources.py # class QueryURLResource(_URLResource): # """Resource for routes expecting urls from the query.""" # # def url_from_query(self): # """Get the 'url' parameter from the query. # # :return: The URL as a string # :raise HTTPBadRequest: If the URL is missing or empty # :raise BadURL: If the URL is malformed # """ # try: # url = self._request.params["url"].strip() # except KeyError as err: # raise HTTPBadRequest("Required parameter 'url' missing") from err # # if not url: # raise HTTPBadRequest("Required parameter 'url' is blank") # # return self._normalise_url(url) # # Path: via/views/route_by_content.py # @view.view_config(route_name="route_by_content", decorator=(has_secure_url_token,)) # def route_by_content(context, request): # """Routes the request according to the Content-Type header.""" # url = context.url_from_query() # # request.checkmate.raise_if_blocked(url) # # mime_type, status_code = get_url_details( # request.find_service(HTTPService), url, request.headers # ) # via_client_svc = request.find_service(ViaClientService) # # if via_client_svc.is_pdf(mime_type): # caching_headers = _caching_headers(max_age=300) # else: # caching_headers = _cache_headers_for_http(status_code) # # params = dict(request.params) # params.pop("url", None) # # url = via_client_svc.url_for(url, mime_type, params) # # return exc.HTTPFound(url, headers=caching_headers) . Output only the next line.
response = route_by_content(context, pyramid_request)
Given snippet: <|code_start|> pyramid_request.registry.settings = { "checkmate_allow_all": sentinel.checkmate_allow_all, "checkmate_ignore_reasons": sentinel.checkmate_ignore_reasons, } pyramid_request.params["via.blocked_for"] = sentinel.via_blocked_for client.raise_if_blocked(sentinel.url) check_url.assert_called_once_with( sentinel.url, allow_all=sentinel.checkmate_allow_all, blocked_for=sentinel.via_blocked_for, ignore_reasons=sentinel.checkmate_ignore_reasons, ) def test_raise_if_blocked_can_block(self, client, check_url, block_response): check_url.return_value = block_response with pytest.raises(HTTPTemporaryRedirect) as exc: client.raise_if_blocked(sentinel.url) assert exc.value.location == block_response.presentation_url def test_raise_if_blocked_ignores_CheckmateExceptions(self, client, check_url): check_url.side_effect = CheckmateException client.raise_if_blocked(sentinel.url) @pytest.fixture def client(self, pyramid_request): <|code_end|> , continue by predicting the next line. Consider current file imports: from unittest.mock import create_autospec, patch, sentinel from checkmatelib import CheckmateException from checkmatelib.client import BlockResponse from pyramid.httpexceptions import HTTPTemporaryRedirect from via.checkmate import ViaCheckmateClient import pytest and context: # Path: via/checkmate.py # class ViaCheckmateClient(CheckmateClient): # def __init__(self, request): # super().__init__( # host=request.registry.settings["checkmate_url"], # api_key=request.registry.settings["checkmate_api_key"], # ) # self._request = request # # def raise_if_blocked(self, url): # """Raise a redirect to Checkmate if the URL is blocked. # # This will sensibly apply all ignore reasons and other configuration for # Checkmate. # # :param url: The URL to check # :raise HTTPTemporaryRedirect: If the URL is blocked # """ # try: # blocked = self.check_url( # url, # allow_all=self._request.registry.settings["checkmate_allow_all"], # blocked_for=self._request.params.get("via.blocked_for"), # ignore_reasons=self._request.registry.settings[ # "checkmate_ignore_reasons" # ], # ) # # except CheckmateException: # blocked = None # # if blocked: # raise HTTPTemporaryRedirect(location=blocked.presentation_url) which might include code, classes, or functions. Output only the next line.
return ViaCheckmateClient(pyramid_request)
Using the snippet: <|code_start|>"""Error views to handle when things go wrong in the app.""" EXCEPTION_MAP = { BadURL: { "title": "The URL isn't valid", "long_description": [ "Parts of the URL could be missing or in the wrong format." ], "stage": "request", "retryable": False, }, UpstreamTimeout: { "title": "Timeout", "long_description": ["The web page we tried to get took too long to respond."], "stage": "upstream", "retryable": True, }, <|code_end|> , determine the next line of code. You have imports: import h_pyramid_sentry from pyramid.httpexceptions import HTTPClientError, HTTPNotFound from pyramid.view import exception_view_config from via.exceptions import ( BadURL, UnhandledUpstreamException, UpstreamServiceError, UpstreamTimeout, ) from via.resources import get_original_url and context (class names, function names, or code) available: # Path: via/exceptions.py # class BadURL(RequestBasedException): # """An invalid URL was discovered.""" # # def __init__(self, message, requests_err=None, url=None): # super().__init__(message, requests_err) # self.url = url # # status_int = 400 # # class UnhandledUpstreamException(UpstreamServiceError): # """Something we did not plan for went wrong.""" # # status_int = 417 # # class UpstreamServiceError(RequestBasedException): # """Something went wrong when calling an upstream service.""" # # status_int = 409 # # class UpstreamTimeout(UpstreamServiceError): # """We timed out waiting for an upstream service.""" # # # "504 - Gateway Timeout" is the correct thing to raise, but this # # will cause Cloudflare to intercept it: # # https://support.cloudflare.com/hc/en-us/articles/115003011431-Troubleshooting-Cloudflare-5XX-errors#502504error # # We're using "408 - Request Timeout" which is technically # # incorrect as it implies the user took too long, but has good semantics # status_int = 408 # # Path: via/resources.py # def get_original_url(context): # """Get the original URL from a provided context object (if any).""" # # if isinstance(context, QueryURLResource): # getter = context.url_from_query # elif isinstance(context, PathURLResource): # getter = context.url_from_path # else: # return None # # try: # return getter() # except BadURL as err: # return err.url # except HTTPBadRequest: # return None . Output only the next line.
UnhandledUpstreamException: {
Given the code snippet: <|code_start|>"""Error views to handle when things go wrong in the app.""" EXCEPTION_MAP = { BadURL: { "title": "The URL isn't valid", "long_description": [ "Parts of the URL could be missing or in the wrong format." ], "stage": "request", "retryable": False, }, UpstreamTimeout: { "title": "Timeout", "long_description": ["The web page we tried to get took too long to respond."], "stage": "upstream", "retryable": True, }, UnhandledUpstreamException: { "title": "Something went wrong", "long_description": ["We experienced an unexpected error."], "stage": "via", "retryable": True, }, <|code_end|> , generate the next line using the imports in this file: import h_pyramid_sentry from pyramid.httpexceptions import HTTPClientError, HTTPNotFound from pyramid.view import exception_view_config from via.exceptions import ( BadURL, UnhandledUpstreamException, UpstreamServiceError, UpstreamTimeout, ) from via.resources import get_original_url and context (functions, classes, or occasionally code) from other files: # Path: via/exceptions.py # class BadURL(RequestBasedException): # """An invalid URL was discovered.""" # # def __init__(self, message, requests_err=None, url=None): # super().__init__(message, requests_err) # self.url = url # # status_int = 400 # # class UnhandledUpstreamException(UpstreamServiceError): # """Something we did not plan for went wrong.""" # # status_int = 417 # # class UpstreamServiceError(RequestBasedException): # """Something went wrong when calling an upstream service.""" # # status_int = 409 # # class UpstreamTimeout(UpstreamServiceError): # """We timed out waiting for an upstream service.""" # # # "504 - Gateway Timeout" is the correct thing to raise, but this # # will cause Cloudflare to intercept it: # # https://support.cloudflare.com/hc/en-us/articles/115003011431-Troubleshooting-Cloudflare-5XX-errors#502504error # # We're using "408 - Request Timeout" which is technically # # incorrect as it implies the user took too long, but has good semantics # status_int = 408 # # Path: via/resources.py # def get_original_url(context): # """Get the original URL from a provided context object (if any).""" # # if isinstance(context, QueryURLResource): # getter = context.url_from_query # elif isinstance(context, PathURLResource): # getter = context.url_from_path # else: # return None # # try: # return getter() # except BadURL as err: # return err.url # except HTTPBadRequest: # return None . Output only the next line.
UpstreamServiceError: {
Predict the next line after this snippet: <|code_start|>"""Error views to handle when things go wrong in the app.""" EXCEPTION_MAP = { BadURL: { "title": "The URL isn't valid", "long_description": [ "Parts of the URL could be missing or in the wrong format." ], "stage": "request", "retryable": False, }, <|code_end|> using the current file's imports: import h_pyramid_sentry from pyramid.httpexceptions import HTTPClientError, HTTPNotFound from pyramid.view import exception_view_config from via.exceptions import ( BadURL, UnhandledUpstreamException, UpstreamServiceError, UpstreamTimeout, ) from via.resources import get_original_url and any relevant context from other files: # Path: via/exceptions.py # class BadURL(RequestBasedException): # """An invalid URL was discovered.""" # # def __init__(self, message, requests_err=None, url=None): # super().__init__(message, requests_err) # self.url = url # # status_int = 400 # # class UnhandledUpstreamException(UpstreamServiceError): # """Something we did not plan for went wrong.""" # # status_int = 417 # # class UpstreamServiceError(RequestBasedException): # """Something went wrong when calling an upstream service.""" # # status_int = 409 # # class UpstreamTimeout(UpstreamServiceError): # """We timed out waiting for an upstream service.""" # # # "504 - Gateway Timeout" is the correct thing to raise, but this # # will cause Cloudflare to intercept it: # # https://support.cloudflare.com/hc/en-us/articles/115003011431-Troubleshooting-Cloudflare-5XX-errors#502504error # # We're using "408 - Request Timeout" which is technically # # incorrect as it implies the user took too long, but has good semantics # status_int = 408 # # Path: via/resources.py # def get_original_url(context): # """Get the original URL from a provided context object (if any).""" # # if isinstance(context, QueryURLResource): # getter = context.url_from_query # elif isinstance(context, PathURLResource): # getter = context.url_from_path # else: # return None # # try: # return getter() # except BadURL as err: # return err.url # except HTTPBadRequest: # return None . Output only the next line.
UpstreamTimeout: {
Predict the next line after this snippet: <|code_start|> except Exception: # pylint: disable=broad-except # Use super broad exceptions so we can't fail here data["text"] = "... cannot retrieve ..." return data @exception_view_config(Exception, renderer="via:templates/exception.html.jinja2") def other_exceptions(exc, request): """Catch all errors (Pyramid or Python) and display an HTML page.""" # We don't want to log errors from upstream services or things which are # the user goofing about making bad queries. if not isinstance(exc, (UpstreamServiceError, BadURL, HTTPClientError)): h_pyramid_sentry.report_exception(exc) return _get_error_body(exc, request) def _get_error_body(exc, request): status_code = _set_status(exc, request) exception_meta = _get_meta(exc) exception_meta.update({"class": exc.__class__.__name__, "details": str(exc)}) return { "status_code": status_code, "exception": exception_meta, "url": { <|code_end|> using the current file's imports: import h_pyramid_sentry from pyramid.httpexceptions import HTTPClientError, HTTPNotFound from pyramid.view import exception_view_config from via.exceptions import ( BadURL, UnhandledUpstreamException, UpstreamServiceError, UpstreamTimeout, ) from via.resources import get_original_url and any relevant context from other files: # Path: via/exceptions.py # class BadURL(RequestBasedException): # """An invalid URL was discovered.""" # # def __init__(self, message, requests_err=None, url=None): # super().__init__(message, requests_err) # self.url = url # # status_int = 400 # # class UnhandledUpstreamException(UpstreamServiceError): # """Something we did not plan for went wrong.""" # # status_int = 417 # # class UpstreamServiceError(RequestBasedException): # """Something went wrong when calling an upstream service.""" # # status_int = 409 # # class UpstreamTimeout(UpstreamServiceError): # """We timed out waiting for an upstream service.""" # # # "504 - Gateway Timeout" is the correct thing to raise, but this # # will cause Cloudflare to intercept it: # # https://support.cloudflare.com/hc/en-us/articles/115003011431-Troubleshooting-Cloudflare-5XX-errors#502504error # # We're using "408 - Request Timeout" which is technically # # incorrect as it implies the user took too long, but has good semantics # status_int = 408 # # Path: via/resources.py # def get_original_url(context): # """Get the original URL from a provided context object (if any).""" # # if isinstance(context, QueryURLResource): # getter = context.url_from_query # elif isinstance(context, PathURLResource): # getter = context.url_from_path # else: # return None # # try: # return getter() # except BadURL as err: # return err.url # except HTTPBadRequest: # return None . Output only the next line.
"original": get_original_url(request.context)
Given the following code snippet before the placeholder: <|code_start|> "http://example.com/%D0%BA%D0%B0%D0%BB%D0%BE%D1%88%D0%B8", "http://example.com/%D0%BA%D0%B0%D0%BB%D0%BE%D1%88%D0%B8", ), ] BAD_URLS = ("https://]", "https://%5D") class TestQueryURLResource: @pytest.mark.parametrize("url,expected", NORMALISED_URLS) def test_url_from_query_returns_url(self, context, pyramid_request, url, expected): pyramid_request.params["url"] = url assert context.url_from_query() == expected @pytest.mark.parametrize("params", ({}, {"urk": "foo"}, {"url": ""})) def test_url_from_query_raises_HTTPBadRequest_for_bad_urls( self, context, pyramid_request, params ): pyramid_request.params = params with pytest.raises(HTTPBadRequest): context.url_from_query() @pytest.mark.parametrize("bad_url", BAD_URLS) def test_url_from_raises_BadURL_for_malformed_urls( self, context, pyramid_request, bad_url ): pyramid_request.params["url"] = bad_url <|code_end|> , predict the next line using imports from the current file: from unittest.mock import create_autospec from pyramid.httpexceptions import HTTPBadRequest from via.exceptions import BadURL from via.resources import PathURLResource, QueryURLResource, get_original_url import pytest and context including class names, function names, and sometimes code from other files: # Path: via/exceptions.py # class BadURL(RequestBasedException): # """An invalid URL was discovered.""" # # def __init__(self, message, requests_err=None, url=None): # super().__init__(message, requests_err) # self.url = url # # status_int = 400 # # Path: via/resources.py # class PathURLResource(_URLResource): # """Resource for routes expecting urls from the path.""" # # def url_from_path(self): # """Get the 'url' parameter from the path. # # :return: The URL as a string # :raise HTTPBadRequest: If the URL is missing or empty # :raise BadURL: If the URL is malformed # """ # # url = self._request.path_qs[1:].strip() # if not url: # raise HTTPBadRequest("Required path part 'url` is missing") # # return self._normalise_url(url) # # class QueryURLResource(_URLResource): # """Resource for routes expecting urls from the query.""" # # def url_from_query(self): # """Get the 'url' parameter from the query. # # :return: The URL as a string # :raise HTTPBadRequest: If the URL is missing or empty # :raise BadURL: If the URL is malformed # """ # try: # url = self._request.params["url"].strip() # except KeyError as err: # raise HTTPBadRequest("Required parameter 'url' missing") from err # # if not url: # raise HTTPBadRequest("Required parameter 'url' is blank") # # return self._normalise_url(url) # # def get_original_url(context): # """Get the original URL from a provided context object (if any).""" # # if isinstance(context, QueryURLResource): # getter = context.url_from_query # elif isinstance(context, PathURLResource): # getter = context.url_from_path # else: # return None # # try: # return getter() # except BadURL as err: # return err.url # except HTTPBadRequest: # return None . Output only the next line.
with pytest.raises(BadURL):
Based on the snippet: <|code_start|> return QueryURLResource(pyramid_request) class TestPathURLResource: @pytest.mark.parametrize("url,expected", NORMALISED_URLS) def test_url_from_path_returns_url(self, context, pyramid_request, url, expected): pyramid_request.path_qs = f"/{url}" assert context.url_from_path() == expected @pytest.mark.parametrize("bad_path", ("/", "/ ")) def test_url_from_path_raises_HTTPBadRequest_for_missing_urls( self, context, pyramid_request, bad_path ): pyramid_request.path_qs = bad_path with pytest.raises(HTTPBadRequest): context.url_from_path() @pytest.mark.parametrize("bad_url", BAD_URLS) def test_url_from_path_BadURL_for_malformed_urls( self, context, pyramid_request, bad_url ): pyramid_request.path_qs = f"/{bad_url}" with pytest.raises(BadURL): context.url_from_path() @pytest.fixture def context(self, pyramid_request): <|code_end|> , predict the immediate next line with the help of imports: from unittest.mock import create_autospec from pyramid.httpexceptions import HTTPBadRequest from via.exceptions import BadURL from via.resources import PathURLResource, QueryURLResource, get_original_url import pytest and context (classes, functions, sometimes code) from other files: # Path: via/exceptions.py # class BadURL(RequestBasedException): # """An invalid URL was discovered.""" # # def __init__(self, message, requests_err=None, url=None): # super().__init__(message, requests_err) # self.url = url # # status_int = 400 # # Path: via/resources.py # class PathURLResource(_URLResource): # """Resource for routes expecting urls from the path.""" # # def url_from_path(self): # """Get the 'url' parameter from the path. # # :return: The URL as a string # :raise HTTPBadRequest: If the URL is missing or empty # :raise BadURL: If the URL is malformed # """ # # url = self._request.path_qs[1:].strip() # if not url: # raise HTTPBadRequest("Required path part 'url` is missing") # # return self._normalise_url(url) # # class QueryURLResource(_URLResource): # """Resource for routes expecting urls from the query.""" # # def url_from_query(self): # """Get the 'url' parameter from the query. # # :return: The URL as a string # :raise HTTPBadRequest: If the URL is missing or empty # :raise BadURL: If the URL is malformed # """ # try: # url = self._request.params["url"].strip() # except KeyError as err: # raise HTTPBadRequest("Required parameter 'url' missing") from err # # if not url: # raise HTTPBadRequest("Required parameter 'url' is blank") # # return self._normalise_url(url) # # def get_original_url(context): # """Get the original URL from a provided context object (if any).""" # # if isinstance(context, QueryURLResource): # getter = context.url_from_query # elif isinstance(context, PathURLResource): # getter = context.url_from_path # else: # return None # # try: # return getter() # except BadURL as err: # return err.url # except HTTPBadRequest: # return None . Output only the next line.
return PathURLResource(pyramid_request)
Given the following code snippet before the placeholder: <|code_start|>BAD_URLS = ("https://]", "https://%5D") class TestQueryURLResource: @pytest.mark.parametrize("url,expected", NORMALISED_URLS) def test_url_from_query_returns_url(self, context, pyramid_request, url, expected): pyramid_request.params["url"] = url assert context.url_from_query() == expected @pytest.mark.parametrize("params", ({}, {"urk": "foo"}, {"url": ""})) def test_url_from_query_raises_HTTPBadRequest_for_bad_urls( self, context, pyramid_request, params ): pyramid_request.params = params with pytest.raises(HTTPBadRequest): context.url_from_query() @pytest.mark.parametrize("bad_url", BAD_URLS) def test_url_from_raises_BadURL_for_malformed_urls( self, context, pyramid_request, bad_url ): pyramid_request.params["url"] = bad_url with pytest.raises(BadURL): context.url_from_query() @pytest.fixture def context(self, pyramid_request): <|code_end|> , predict the next line using imports from the current file: from unittest.mock import create_autospec from pyramid.httpexceptions import HTTPBadRequest from via.exceptions import BadURL from via.resources import PathURLResource, QueryURLResource, get_original_url import pytest and context including class names, function names, and sometimes code from other files: # Path: via/exceptions.py # class BadURL(RequestBasedException): # """An invalid URL was discovered.""" # # def __init__(self, message, requests_err=None, url=None): # super().__init__(message, requests_err) # self.url = url # # status_int = 400 # # Path: via/resources.py # class PathURLResource(_URLResource): # """Resource for routes expecting urls from the path.""" # # def url_from_path(self): # """Get the 'url' parameter from the path. # # :return: The URL as a string # :raise HTTPBadRequest: If the URL is missing or empty # :raise BadURL: If the URL is malformed # """ # # url = self._request.path_qs[1:].strip() # if not url: # raise HTTPBadRequest("Required path part 'url` is missing") # # return self._normalise_url(url) # # class QueryURLResource(_URLResource): # """Resource for routes expecting urls from the query.""" # # def url_from_query(self): # """Get the 'url' parameter from the query. # # :return: The URL as a string # :raise HTTPBadRequest: If the URL is missing or empty # :raise BadURL: If the URL is malformed # """ # try: # url = self._request.params["url"].strip() # except KeyError as err: # raise HTTPBadRequest("Required parameter 'url' missing") from err # # if not url: # raise HTTPBadRequest("Required parameter 'url' is blank") # # return self._normalise_url(url) # # def get_original_url(context): # """Get the original URL from a provided context object (if any).""" # # if isinstance(context, QueryURLResource): # getter = context.url_from_query # elif isinstance(context, PathURLResource): # getter = context.url_from_path # else: # return None # # try: # return getter() # except BadURL as err: # return err.url # except HTTPBadRequest: # return None . Output only the next line.
return QueryURLResource(pyramid_request)
Using the snippet: <|code_start|> pyramid_request.path_qs = f"/{url}" assert context.url_from_path() == expected @pytest.mark.parametrize("bad_path", ("/", "/ ")) def test_url_from_path_raises_HTTPBadRequest_for_missing_urls( self, context, pyramid_request, bad_path ): pyramid_request.path_qs = bad_path with pytest.raises(HTTPBadRequest): context.url_from_path() @pytest.mark.parametrize("bad_url", BAD_URLS) def test_url_from_path_BadURL_for_malformed_urls( self, context, pyramid_request, bad_url ): pyramid_request.path_qs = f"/{bad_url}" with pytest.raises(BadURL): context.url_from_path() @pytest.fixture def context(self, pyramid_request): return PathURLResource(pyramid_request) class TestGetOriginalURL: def test_it_with_paths(self, path_url_resource): assert ( <|code_end|> , determine the next line of code. You have imports: from unittest.mock import create_autospec from pyramid.httpexceptions import HTTPBadRequest from via.exceptions import BadURL from via.resources import PathURLResource, QueryURLResource, get_original_url import pytest and context (class names, function names, or code) available: # Path: via/exceptions.py # class BadURL(RequestBasedException): # """An invalid URL was discovered.""" # # def __init__(self, message, requests_err=None, url=None): # super().__init__(message, requests_err) # self.url = url # # status_int = 400 # # Path: via/resources.py # class PathURLResource(_URLResource): # """Resource for routes expecting urls from the path.""" # # def url_from_path(self): # """Get the 'url' parameter from the path. # # :return: The URL as a string # :raise HTTPBadRequest: If the URL is missing or empty # :raise BadURL: If the URL is malformed # """ # # url = self._request.path_qs[1:].strip() # if not url: # raise HTTPBadRequest("Required path part 'url` is missing") # # return self._normalise_url(url) # # class QueryURLResource(_URLResource): # """Resource for routes expecting urls from the query.""" # # def url_from_query(self): # """Get the 'url' parameter from the query. # # :return: The URL as a string # :raise HTTPBadRequest: If the URL is missing or empty # :raise BadURL: If the URL is malformed # """ # try: # url = self._request.params["url"].strip() # except KeyError as err: # raise HTTPBadRequest("Required parameter 'url' missing") from err # # if not url: # raise HTTPBadRequest("Required parameter 'url' is blank") # # return self._normalise_url(url) # # def get_original_url(context): # """Get the original URL from a provided context object (if any).""" # # if isinstance(context, QueryURLResource): # getter = context.url_from_query # elif isinstance(context, PathURLResource): # getter = context.url_from_path # else: # return None # # try: # return getter() # except BadURL as err: # return err.url # except HTTPBadRequest: # return None . Output only the next line.
get_original_url(path_url_resource)
Given snippet: <|code_start|> class TestJSTORAPI: @pytest.mark.parametrize( "url,expected", [(None, False), ("http://jstor-api.com", True)] ) def test_enabled(self, url, expected): assert JSTORAPI(sentinel.http, url).enabled == expected @pytest.mark.parametrize( "url,expected", [ ("jstor://ARTICLE_ID", "http://jstor-api.com/10.2307/ARTICLE_ID?ip=IP"), ("jstor://PREFIX/SUFFIX", "http://jstor-api.com/PREFIX/SUFFIX?ip=IP"), ], ) def test_pdf_stream(self, http_service, url, expected): stream = JSTORAPI(http_service, "http://jstor-api.com").jstor_pdf_stream( url, "IP" ) http_service.stream.assert_called_once_with( <|code_end|> , continue by predicting the next line. Consider current file imports: from unittest.mock import sentinel from via.requests_tools.headers import add_request_headers from via.services.jstor import JSTORAPI, factory import pytest and context: # Path: via/requests_tools/headers.py # def add_request_headers(headers): # """Add headers for 3rd party providers which we access data from.""" # # # Pass our abuse policy in request headers for third-party site admins. # headers["X-Abuse-Policy"] = "https://web.hypothes.is/abuse-policy/" # headers["X-Complaints-To"] = "https://web.hypothes.is/report-abuse/" # # return headers # # Path: via/services/jstor.py # class JSTORAPI: # DEFAULT_DOI_PREFIX = "10.2307" # """Main DOI prefix. Used for real DOIs and non registered pseudo-DOIs with the same format""" # # def __init__(self, http_service: HTTPService, url): # self._jstor_pdf_url = url # self._http = http_service # # @property # def enabled(self): # return bool(self._jstor_pdf_url) # # def jstor_pdf_stream(self, jstor_url: str, jstor_ip: str): # doi = jstor_url.replace("jstor://", "") # if not "/" in doi: # doi = f"{self.DEFAULT_DOI_PREFIX}/{doi}" # # url = f"{self._jstor_pdf_url}/{doi}?ip={jstor_ip}" # return self._http.stream( # url, headers=add_request_headers({"Accept": "application/pdf"}) # ) # # def factory(_context, request): # return JSTORAPI( # http_service=request.find_service(HTTPService), # url=request.registry.settings.get("jstor_pdf_url", None), # ) which might include code, classes, or functions. Output only the next line.
expected, headers=add_request_headers({"Accept": "application/pdf"})
Next line prediction: <|code_start|> class TestJSTORAPI: @pytest.mark.parametrize( "url,expected", [(None, False), ("http://jstor-api.com", True)] ) def test_enabled(self, url, expected): <|code_end|> . Use current file imports: (from unittest.mock import sentinel from via.requests_tools.headers import add_request_headers from via.services.jstor import JSTORAPI, factory import pytest) and context including class names, function names, or small code snippets from other files: # Path: via/requests_tools/headers.py # def add_request_headers(headers): # """Add headers for 3rd party providers which we access data from.""" # # # Pass our abuse policy in request headers for third-party site admins. # headers["X-Abuse-Policy"] = "https://web.hypothes.is/abuse-policy/" # headers["X-Complaints-To"] = "https://web.hypothes.is/report-abuse/" # # return headers # # Path: via/services/jstor.py # class JSTORAPI: # DEFAULT_DOI_PREFIX = "10.2307" # """Main DOI prefix. Used for real DOIs and non registered pseudo-DOIs with the same format""" # # def __init__(self, http_service: HTTPService, url): # self._jstor_pdf_url = url # self._http = http_service # # @property # def enabled(self): # return bool(self._jstor_pdf_url) # # def jstor_pdf_stream(self, jstor_url: str, jstor_ip: str): # doi = jstor_url.replace("jstor://", "") # if not "/" in doi: # doi = f"{self.DEFAULT_DOI_PREFIX}/{doi}" # # url = f"{self._jstor_pdf_url}/{doi}?ip={jstor_ip}" # return self._http.stream( # url, headers=add_request_headers({"Accept": "application/pdf"}) # ) # # def factory(_context, request): # return JSTORAPI( # http_service=request.find_service(HTTPService), # url=request.registry.settings.get("jstor_pdf_url", None), # ) . Output only the next line.
assert JSTORAPI(sentinel.http, url).enabled == expected
Here is a snippet: <|code_start|> class TestJSTORAPI: @pytest.mark.parametrize( "url,expected", [(None, False), ("http://jstor-api.com", True)] ) def test_enabled(self, url, expected): assert JSTORAPI(sentinel.http, url).enabled == expected @pytest.mark.parametrize( "url,expected", [ ("jstor://ARTICLE_ID", "http://jstor-api.com/10.2307/ARTICLE_ID?ip=IP"), ("jstor://PREFIX/SUFFIX", "http://jstor-api.com/PREFIX/SUFFIX?ip=IP"), ], ) def test_pdf_stream(self, http_service, url, expected): stream = JSTORAPI(http_service, "http://jstor-api.com").jstor_pdf_stream( url, "IP" ) http_service.stream.assert_called_once_with( expected, headers=add_request_headers({"Accept": "application/pdf"}) ) assert stream == http_service.stream.return_value class TestFactory: @pytest.mark.usefixtures("http_service") def test_it(self, pyramid_request): <|code_end|> . Write the next line using the current file imports: from unittest.mock import sentinel from via.requests_tools.headers import add_request_headers from via.services.jstor import JSTORAPI, factory import pytest and context from other files: # Path: via/requests_tools/headers.py # def add_request_headers(headers): # """Add headers for 3rd party providers which we access data from.""" # # # Pass our abuse policy in request headers for third-party site admins. # headers["X-Abuse-Policy"] = "https://web.hypothes.is/abuse-policy/" # headers["X-Complaints-To"] = "https://web.hypothes.is/report-abuse/" # # return headers # # Path: via/services/jstor.py # class JSTORAPI: # DEFAULT_DOI_PREFIX = "10.2307" # """Main DOI prefix. Used for real DOIs and non registered pseudo-DOIs with the same format""" # # def __init__(self, http_service: HTTPService, url): # self._jstor_pdf_url = url # self._http = http_service # # @property # def enabled(self): # return bool(self._jstor_pdf_url) # # def jstor_pdf_stream(self, jstor_url: str, jstor_ip: str): # doi = jstor_url.replace("jstor://", "") # if not "/" in doi: # doi = f"{self.DEFAULT_DOI_PREFIX}/{doi}" # # url = f"{self._jstor_pdf_url}/{doi}?ip={jstor_ip}" # return self._http.stream( # url, headers=add_request_headers({"Accept": "application/pdf"}) # ) # # def factory(_context, request): # return JSTORAPI( # http_service=request.find_service(HTTPService), # url=request.registry.settings.get("jstor_pdf_url", None), # ) , which may include functions, classes, or code. Output only the next line.
assert isinstance(factory(sentinel.context, pyramid_request), JSTORAPI)
Next line prediction: <|code_start|>"""Test that content is correctly served via Whitenoise.""" # pylint: disable=no-value-for-parameter # Pylint doesn't seem to understand h_matchers here for some reason class TestStaticContent: @pytest.mark.parametrize( "url,mime_type", ( ("/favicon.ico", "image/x-icon"), ("/js/pdfjs-init.js", "text/javascript"), ), ) def test_get_static_content(self, url, mime_type, test_app): response = test_app.get(url) assert dict(response.headers) == Any.dict.containing( {"Content-Type": Any.string.containing(mime_type), "ETag": Any.string()} ) <|code_end|> . Use current file imports: (import re import pytest from h_matchers import Any from tests.conftest import assert_cache_control) and context including class names, function names, or small code snippets from other files: # Path: tests/conftest.py # def assert_cache_control(headers, cache_parts): # """Assert that all parts of the Cache-Control header are present.""" # assert dict(headers) == Any.dict.containing({"Cache-Control": Any.string()}) # assert ( # headers["Cache-Control"].split(", ") == Any.list.containing(cache_parts).only() # ) . Output only the next line.
assert_cache_control(response.headers, ["public", "max-age=60"])
Next line prediction: <|code_start|> @pytest.mark.parametrize( "existing_header,expected_header", [ (None, "noindex, nofollow"), ("all", "all"), ], ) def test_it( self, existing_header, expected_header, handler, pyramid_request, tween ): if existing_header: handler.return_value.headers = {"X-Robots-Tag": existing_header} else: handler.return_value.headers = {} response = tween(pyramid_request) handler.assert_called_once_with(pyramid_request) assert response == handler.return_value assert response.headers["X-Robots-Tag"] == expected_header @pytest.fixture def handler(self): def handler_spec(request): """Spec for mock handler function.""" return create_autospec(handler_spec) @pytest.fixture def tween(self, handler, pyramid_request): <|code_end|> . Use current file imports: (from unittest.mock import create_autospec from via.tweens import robots_tween_factory import pytest) and context including class names, function names, or small code snippets from other files: # Path: via/tweens.py # def robots_tween_factory(handler, _registry): # def robots_tween(request): # response = handler(request) # # # If the view hasn't set its own X-Robots-Tag header then set one that # # tells Google (and most other crawlers) not to index the page and not # # to follow links on the page. # # # # https://developers.google.com/search/reference/robots_meta_tag # if "X-Robots-Tag" not in response.headers: # response.headers["X-Robots-Tag"] = "noindex, nofollow" # # return response # # return robots_tween . Output only the next line.
return robots_tween_factory(handler, pyramid_request.registry)
Given the code snippet: <|code_start|> def test_settings_raise_value_error_if_environment_variable_is_not_set(): with pytest.raises(ValueError): load_settings({}) def test_settings_are_configured_from_environment_variables(os, pyramid_settings): expected_settings = pyramid_settings expected_settings["data_directory"] = Path(pyramid_settings["data_directory"]) settings = load_settings({}) for key, value in expected_settings.items(): assert settings[key] == value def test_app(configurator, pyramid, os, pyramid_settings): <|code_end|> , generate the next line using the imports in this file: from pathlib import Path from via.app import create_app, load_settings from via.sentry_filters import SENTRY_FILTERS import pytest and context (functions, classes, or occasionally code) from other files: # Path: via/app.py # def create_app(_=None, **settings): # """Configure and return the WSGI app.""" # config = pyramid.config.Configurator(settings=load_settings(settings)) # # config.include("pyramid_exclog") # config.include("pyramid_jinja2") # config.include("pyramid_services") # config.include("h_pyramid_sentry") # # config.include("via.views") # config.include("via.services") # # # Configure Pyramid so we can generate static URLs # static_path = str(importlib_resources.files("via") / "static") # cache_buster = PathCacheBuster(static_path) # print(f"Cache buster salt: {cache_buster.salt}") # # config.add_static_view(name="static", path="via:static") # config.add_cache_buster("via:static", cachebust=cache_buster) # # # Make the CheckmateClient object available as request.checkmate. # config.add_request_method(ViaCheckmateClient, reify=True, name="checkmate") # # config.add_tween("via.tweens.robots_tween_factory") # # # Add this as near to the end of your config as possible: # config.include("pyramid_sanity") # # app = WhiteNoise( # config.make_wsgi_app(), # index_file=True, # # Config for serving files at static/<salt>/path which are marked # # as immutable # root=static_path, # prefix=cache_buster.immutable_path, # immutable_file_test=cache_buster.get_immutable_file_test(), # ) # # app.add_files( # # Config for serving files at / which are marked as mutable. This is # # for / -> index.html # root=static_path, # prefix="/", # ) # # return app # # def load_settings(settings): # """Load application settings from a dict or environment variables. # # Checks that the required parameters are either filled out in the provided # dict, or that the required values can be loaded from the environment. # # :param settings: Settings dict # :raise ValueError: If a required parameter is not filled # :return: A dict of settings # """ # for param, options in PARAMETERS.items(): # formatter = options.get("formatter", lambda v: v) # # value = settings[param] = formatter( # settings.get(param, os.environ.get(param.upper())) # ) # # if value is None and options.get("required"): # raise ValueError(f"Param {param} must be provided.") # # # Configure sentry # settings["h_pyramid_sentry.filters"] = SENTRY_FILTERS # # return settings # # Path: via/sentry_filters.py # SENTRY_FILTERS = [] . Output only the next line.
create_app()
Using the snippet: <|code_start|> def test_settings_raise_value_error_if_environment_variable_is_not_set(): with pytest.raises(ValueError): load_settings({}) def test_settings_are_configured_from_environment_variables(os, pyramid_settings): expected_settings = pyramid_settings expected_settings["data_directory"] = Path(pyramid_settings["data_directory"]) settings = load_settings({}) for key, value in expected_settings.items(): assert settings[key] == value def test_app(configurator, pyramid, os, pyramid_settings): create_app() expected_settings = dict( <|code_end|> , determine the next line of code. You have imports: from pathlib import Path from via.app import create_app, load_settings from via.sentry_filters import SENTRY_FILTERS import pytest and context (class names, function names, or code) available: # Path: via/app.py # def create_app(_=None, **settings): # """Configure and return the WSGI app.""" # config = pyramid.config.Configurator(settings=load_settings(settings)) # # config.include("pyramid_exclog") # config.include("pyramid_jinja2") # config.include("pyramid_services") # config.include("h_pyramid_sentry") # # config.include("via.views") # config.include("via.services") # # # Configure Pyramid so we can generate static URLs # static_path = str(importlib_resources.files("via") / "static") # cache_buster = PathCacheBuster(static_path) # print(f"Cache buster salt: {cache_buster.salt}") # # config.add_static_view(name="static", path="via:static") # config.add_cache_buster("via:static", cachebust=cache_buster) # # # Make the CheckmateClient object available as request.checkmate. # config.add_request_method(ViaCheckmateClient, reify=True, name="checkmate") # # config.add_tween("via.tweens.robots_tween_factory") # # # Add this as near to the end of your config as possible: # config.include("pyramid_sanity") # # app = WhiteNoise( # config.make_wsgi_app(), # index_file=True, # # Config for serving files at static/<salt>/path which are marked # # as immutable # root=static_path, # prefix=cache_buster.immutable_path, # immutable_file_test=cache_buster.get_immutable_file_test(), # ) # # app.add_files( # # Config for serving files at / which are marked as mutable. This is # # for / -> index.html # root=static_path, # prefix="/", # ) # # return app # # def load_settings(settings): # """Load application settings from a dict or environment variables. # # Checks that the required parameters are either filled out in the provided # dict, or that the required values can be loaded from the environment. # # :param settings: Settings dict # :raise ValueError: If a required parameter is not filled # :return: A dict of settings # """ # for param, options in PARAMETERS.items(): # formatter = options.get("formatter", lambda v: v) # # value = settings[param] = formatter( # settings.get(param, os.environ.get(param.upper())) # ) # # if value is None and options.get("required"): # raise ValueError(f"Param {param} must be provided.") # # # Configure sentry # settings["h_pyramid_sentry.filters"] = SENTRY_FILTERS # # return settings # # Path: via/sentry_filters.py # SENTRY_FILTERS = [] . Output only the next line.
{"h_pyramid_sentry.filters": SENTRY_FILTERS}, **pyramid_settings
Given the code snippet: <|code_start|> class TestGetURLDetails: @pytest.mark.parametrize( "content_type,mime_type,status_code", ( ("text/html", "text/html", 501), ("application/pdf", "application/pdf", 200), ("application/pdf; qs=0.001", "application/pdf", 201), (None, None, 301), ), ) def test_it_calls_get_for_normal_urls( # pylint: disable=too-many-arguments self, response, content_type, mime_type, status_code, http_service, ): if content_type: response.headers = {"Content-Type": content_type} else: response.headers = {} response.status_code = status_code url = "http://example.com" <|code_end|> , generate the next line using the imports in this file: from io import BytesIO from unittest.mock import sentinel from h_matchers import Any from requests import Response from via.get_url import get_url_details import pytest and context (functions, classes, or occasionally code) from other files: # Path: via/get_url.py # def get_url_details(http_service, url, headers=None): # """Get the content type and status code for a given URL. # # :param http_service: Instance of HTTPService to make the request with # :param url: URL to retrieve # :param headers: The original headers the request was made with # :return: 2-tuple of (mime type, status code) # # :raise BadURL: When the URL is malformed # :raise UpstreamServiceError: If we server gives us errors # :raise UnhandledException: For all other request based errors # """ # if headers is None: # headers = OrderedDict() # # if GoogleDriveAPI.parse_file_url(url): # return "application/pdf", 200 # # headers = add_request_headers(clean_headers(headers)) # # with http_service.get( # url, # stream=True, # allow_redirects=True, # headers=headers, # timeout=10, # raise_for_status=False, # ) as rsp: # content_type = rsp.headers.get("Content-Type") # if content_type: # mime_type, _ = cgi.parse_header(content_type) # else: # mime_type = None # # return mime_type, rsp.status_code . Output only the next line.
result = get_url_details(http_service, url, headers=sentinel.headers)
Predict the next line after this snippet: <|code_start|> def test_request_is_valid_can_fail(self, service, pyramid_request): service._via_secure_url.verify.side_effect = TokenException assert not service.request_is_valid(pyramid_request) @pytest.mark.usefixtures("with_signed_urls_not_required") def test_request_is_valid_if_signatures_not_required( self, service, pyramid_request ): assert service.request_is_valid(pyramid_request) service._via_secure_url.verify.assert_not_called() def test_sign_url(self, service): result = service.sign_url(sentinel.url) service._via_secure_url.create.assert_called_once_with( sentinel.url, max_age=timedelta(hours=25) ) assert result == service._via_secure_url.create.return_value @pytest.mark.usefixtures("with_signed_urls_not_required") def test_sign_url_if_signatures_not_required(self, service): result = service.sign_url(sentinel.url) assert result == sentinel.url @pytest.fixture def service(self): <|code_end|> using the current file's imports: from datetime import timedelta from unittest.mock import create_autospec, sentinel from h_vialib.exceptions import TokenException from pyramid.httpexceptions import HTTPUnauthorized from via.services.secure_link import SecureLinkService, factory, has_secure_url_token import pytest and any relevant context from other files: # Path: via/services/secure_link.py # class SecureLinkService: # """A service for signing and checking URLs have been signed.""" # # def __init__(self, secret, signed_urls_required): # """Initialise the service. # # :param secret: Shared secret to sign and verify URLs with # :param signed_urls_required: Enable or disable URL signing # """ # self._via_secure_url = ViaSecureURL(secret) # self._signed_urls_required = signed_urls_required # # def request_is_valid(self, request) -> bool: # """Check whether a request has been signed. # # This will also pass if signing is disabled. # """ # if not self._signed_urls_required: # return True # # try: # self._via_secure_url.verify(request.url) # except TokenException: # return False # # return True # # def sign_url(self, url): # """Get a signed URL (if URL signing is enabled).""" # # if self._signed_urls_required: # return self._via_secure_url.create(url, max_age=timedelta(hours=25)) # # return url # # def factory(_context, request): # return SecureLinkService( # secret=request.registry.settings["via_secret"], # signed_urls_required=request.registry.settings["signed_urls_required"], # ) # # def has_secure_url_token(view): # """Require the request to have a valid signature.""" # # def view_wrapper(context, request): # if not request.find_service(SecureLinkService).request_is_valid(request): # return HTTPUnauthorized() # # return view(context, request) # # return view_wrapper . Output only the next line.
return SecureLinkService(secret="not_a_secret", signed_urls_required=True)
Predict the next line after this snippet: <|code_start|> def test_sign_url(self, service): result = service.sign_url(sentinel.url) service._via_secure_url.create.assert_called_once_with( sentinel.url, max_age=timedelta(hours=25) ) assert result == service._via_secure_url.create.return_value @pytest.mark.usefixtures("with_signed_urls_not_required") def test_sign_url_if_signatures_not_required(self, service): result = service.sign_url(sentinel.url) assert result == sentinel.url @pytest.fixture def service(self): return SecureLinkService(secret="not_a_secret", signed_urls_required=True) @pytest.fixture def with_signed_urls_not_required(self, service): service._signed_urls_required = False @pytest.fixture(autouse=True) def ViaSecureURL(self, patch): return patch("via.services.secure_link.ViaSecureURL") class TestFactory: def test_it(self, pyramid_request, SecureLinkService): <|code_end|> using the current file's imports: from datetime import timedelta from unittest.mock import create_autospec, sentinel from h_vialib.exceptions import TokenException from pyramid.httpexceptions import HTTPUnauthorized from via.services.secure_link import SecureLinkService, factory, has_secure_url_token import pytest and any relevant context from other files: # Path: via/services/secure_link.py # class SecureLinkService: # """A service for signing and checking URLs have been signed.""" # # def __init__(self, secret, signed_urls_required): # """Initialise the service. # # :param secret: Shared secret to sign and verify URLs with # :param signed_urls_required: Enable or disable URL signing # """ # self._via_secure_url = ViaSecureURL(secret) # self._signed_urls_required = signed_urls_required # # def request_is_valid(self, request) -> bool: # """Check whether a request has been signed. # # This will also pass if signing is disabled. # """ # if not self._signed_urls_required: # return True # # try: # self._via_secure_url.verify(request.url) # except TokenException: # return False # # return True # # def sign_url(self, url): # """Get a signed URL (if URL signing is enabled).""" # # if self._signed_urls_required: # return self._via_secure_url.create(url, max_age=timedelta(hours=25)) # # return url # # def factory(_context, request): # return SecureLinkService( # secret=request.registry.settings["via_secret"], # signed_urls_required=request.registry.settings["signed_urls_required"], # ) # # def has_secure_url_token(view): # """Require the request to have a valid signature.""" # # def view_wrapper(context, request): # if not request.find_service(SecureLinkService).request_is_valid(request): # return HTTPUnauthorized() # # return view(context, request) # # return view_wrapper . Output only the next line.
service = factory(sentinel.context, pyramid_request)
Next line prediction: <|code_start|> # pylint: disable=protected-access class TestHasSecureURLToken: def test_it_with_valid_token(self, view, pyramid_request, secure_link_service): secure_link_service.request_is_valid.return_value = True <|code_end|> . Use current file imports: (from datetime import timedelta from unittest.mock import create_autospec, sentinel from h_vialib.exceptions import TokenException from pyramid.httpexceptions import HTTPUnauthorized from via.services.secure_link import SecureLinkService, factory, has_secure_url_token import pytest) and context including class names, function names, or small code snippets from other files: # Path: via/services/secure_link.py # class SecureLinkService: # """A service for signing and checking URLs have been signed.""" # # def __init__(self, secret, signed_urls_required): # """Initialise the service. # # :param secret: Shared secret to sign and verify URLs with # :param signed_urls_required: Enable or disable URL signing # """ # self._via_secure_url = ViaSecureURL(secret) # self._signed_urls_required = signed_urls_required # # def request_is_valid(self, request) -> bool: # """Check whether a request has been signed. # # This will also pass if signing is disabled. # """ # if not self._signed_urls_required: # return True # # try: # self._via_secure_url.verify(request.url) # except TokenException: # return False # # return True # # def sign_url(self, url): # """Get a signed URL (if URL signing is enabled).""" # # if self._signed_urls_required: # return self._via_secure_url.create(url, max_age=timedelta(hours=25)) # # return url # # def factory(_context, request): # return SecureLinkService( # secret=request.registry.settings["via_secret"], # signed_urls_required=request.registry.settings["signed_urls_required"], # ) # # def has_secure_url_token(view): # """Require the request to have a valid signature.""" # # def view_wrapper(context, request): # if not request.find_service(SecureLinkService).request_is_valid(request): # return HTTPUnauthorized() # # return view(context, request) # # return view_wrapper . Output only the next line.
result = has_secure_url_token(view)(sentinel.context, pyramid_request)
Given the following code snippet before the placeholder: <|code_start|> "mime_type,is_pdf", [ ("application/x-pdf", True), ("application/pdf", True), ("text/html", False), ], ) def test_is_pdf(self, mime_type, is_pdf, svc): assert svc.is_pdf(mime_type) == is_pdf @pytest.mark.parametrize( "mime_type,expected_content_type", [ ("application/pdf", "pdf"), ("text/html", "html"), (None, "html"), ], ) def test_url_for(self, mime_type, expected_content_type, svc, via_client): params = {"foo": "bar"} url = svc.url_for(sentinel.url, mime_type, params) via_client.url_for.assert_called_once_with( sentinel.url, expected_content_type, params ) assert url == via_client.url_for.return_value @pytest.fixture def svc(self, via_client): <|code_end|> , predict the next line using imports from the current file: from unittest.mock import sentinel from via.services.via_client import ViaClientService, factory import pytest and context including class names, function names, and sometimes code from other files: # Path: via/services/via_client.py # class ViaClientService: # """A wrapper service for h_vialib.ViaClient.""" # # def __init__(self, via_client): # self.via_client = via_client # # @staticmethod # def is_pdf(mime_type): # """Return True if the given MIME type is a PDF one.""" # return mime_type in ("application/x-pdf", "application/pdf") # # def url_for(self, url, mime_type, params): # """Return a Via URL for the given `url`.""" # return self.via_client.url_for( # url, # content_type="pdf" if self.is_pdf(mime_type) else "html", # options=params, # ) # # def factory(_context, request): # return ViaClientService( # via_client=ViaClient( # service_url=request.host_url, # html_service_url=request.registry.settings["via_html_url"], # secret=request.registry.settings["via_secret"], # ) # ) . Output only the next line.
return ViaClientService(via_client)
Based on the snippet: <|code_start|> @pytest.mark.parametrize( "mime_type,expected_content_type", [ ("application/pdf", "pdf"), ("text/html", "html"), (None, "html"), ], ) def test_url_for(self, mime_type, expected_content_type, svc, via_client): params = {"foo": "bar"} url = svc.url_for(sentinel.url, mime_type, params) via_client.url_for.assert_called_once_with( sentinel.url, expected_content_type, params ) assert url == via_client.url_for.return_value @pytest.fixture def svc(self, via_client): return ViaClientService(via_client) class TestFactory: def test_it(self, pyramid_request, ViaClient, ViaClientService): pyramid_request.registry.settings = { "via_html_url": sentinel.via_html_url, "via_secret": sentinel.via_secret, } <|code_end|> , predict the immediate next line with the help of imports: from unittest.mock import sentinel from via.services.via_client import ViaClientService, factory import pytest and context (classes, functions, sometimes code) from other files: # Path: via/services/via_client.py # class ViaClientService: # """A wrapper service for h_vialib.ViaClient.""" # # def __init__(self, via_client): # self.via_client = via_client # # @staticmethod # def is_pdf(mime_type): # """Return True if the given MIME type is a PDF one.""" # return mime_type in ("application/x-pdf", "application/pdf") # # def url_for(self, url, mime_type, params): # """Return a Via URL for the given `url`.""" # return self.via_client.url_for( # url, # content_type="pdf" if self.is_pdf(mime_type) else "html", # options=params, # ) # # def factory(_context, request): # return ViaClientService( # via_client=ViaClient( # service_url=request.host_url, # html_service_url=request.registry.settings["via_html_url"], # secret=request.registry.settings["via_secret"], # ) # ) . Output only the next line.
service = factory(sentinel.context, pyramid_request)
Predict the next line for this snippet: <|code_start|> class TestStatusRoute: @pytest.mark.parametrize( "include_checkmate,checkmate_fails,expected_status,expected_body", [ (False, False, 200, {"status": "okay"}), (False, True, 200, {"status": "okay"}), (True, False, 200, {"status": "okay", "okay": ["checkmate"]}), (True, True, 500, {"status": "down", "down": ["checkmate"]}), ], ) def test_status_returns_200_response( self, pyramid_request, include_checkmate, checkmate_fails, expected_status, expected_body, ): if include_checkmate: pyramid_request.params["include-checkmate"] = "" if checkmate_fails: pyramid_request.checkmate.check_url.side_effect = CheckmateException <|code_end|> with the help of current file imports: import pytest from checkmatelib import CheckmateException from via.views.status import get_status and context from other files: # Path: via/views/status.py # @view.view_config(route_name="get_status", renderer="json", http_cache=0) # def get_status(request): # """Status endpoint.""" # # body = {"status": "okay"} # # if "include-checkmate" in request.params: # try: # request.checkmate.check_url("https://example.com/") # except CheckmateException: # body["down"] = ["checkmate"] # else: # body["okay"] = ["checkmate"] # # # If any of the components checked above were down then report the # # status check as a whole as being down. # if body.get("down"): # request.response.status_int = 500 # body["status"] = "down" # # return body , which may contain function names, class names, or code. Output only the next line.
result = get_status(pyramid_request)
Next line prediction: <|code_start|> @classmethod def _normalise_url(cls, url): """Return a normalized URL from user input. Take a URL from user input (eg. a URL input field or path parameter) and convert it to a normalized form. """ return Configuration.strip_from_url(cls._parse_url(url).geturl()) @classmethod def _parse_url(cls, url): parsed = cls._repeated_decode(url) if not parsed.scheme: if not parsed.netloc: # Without a scheme urlparse often assumes the domain is the # path. To prevent this add a fake scheme and try again parsed = cls._parse_url("https://" + url.lstrip(".")) else: parsed = parsed._replace(scheme="https") return parsed @classmethod def _repeated_decode(cls, url): try: parsed = urlparse(url) except ValueError as exc: <|code_end|> . Use current file imports: (from urllib.parse import unquote, urlparse from h_vialib import Configuration from pyramid.httpexceptions import HTTPBadRequest from via.exceptions import BadURL) and context including class names, function names, or small code snippets from other files: # Path: via/exceptions.py # class BadURL(RequestBasedException): # """An invalid URL was discovered.""" # # def __init__(self, message, requests_err=None, url=None): # super().__init__(message, requests_err) # self.url = url # # status_int = 400 . Output only the next line.
raise BadURL(str(exc), url=url) from exc
Based on the snippet: <|code_start|> for param, options in PARAMETERS.items(): formatter = options.get("formatter", lambda v: v) value = settings[param] = formatter( settings.get(param, os.environ.get(param.upper())) ) if value is None and options.get("required"): raise ValueError(f"Param {param} must be provided.") # Configure sentry settings["h_pyramid_sentry.filters"] = SENTRY_FILTERS return settings def create_app(_=None, **settings): """Configure and return the WSGI app.""" config = pyramid.config.Configurator(settings=load_settings(settings)) config.include("pyramid_exclog") config.include("pyramid_jinja2") config.include("pyramid_services") config.include("h_pyramid_sentry") config.include("via.views") config.include("via.services") # Configure Pyramid so we can generate static URLs static_path = str(importlib_resources.files("via") / "static") <|code_end|> , predict the immediate next line with the help of imports: import os import importlib_resources import pyramid.config from pathlib import Path from pyramid.settings import asbool from whitenoise import WhiteNoise from via.cache_buster import PathCacheBuster from via.checkmate import ViaCheckmateClient from via.sentry_filters import SENTRY_FILTERS and context (classes, functions, sometimes code) from other files: # Path: via/cache_buster.py # class PathCacheBuster: # """A cache buster which modifies paths to enable immutable caching. # # Implements `pyramid.interfaces.ICacheBuster` and can be used with # `config.add_cache_buster()` to enable rewriting of URLs to a version # which contains the last modified time. # # This allows assets to be statically cached until at least one of them has # changed. This is achieved by generating a salt value from a hash of the # files which is applied to the input URL. # # :param path: Path to static for generating the salt value # """ # # def __init__(self, path): # self.salt = self._generate_salt(path) # # def __call__(self, request, subpath, kw): # pylint: disable=invalid-name # """Prepend the salt to the path. # # Implements the ICacheBuster interface. # """ # return f"{self.salt}/{subpath}", kw # # @property # def immutable_path(self): # """Return the external URL where immutable content is accessible.""" # return f"/static/{self.salt}" # # def get_immutable_file_test(self): # """Return an immutability test for use with Whitenoise.""" # immutable_path = self.immutable_path # # def _test(_, url): # return url.startswith(immutable_path) # # return _test # # @staticmethod # def _generate_salt(path): # """Generate salt based on the last hash of all files. # # This ensures we only change salt when at least one file has changed. # """ # hasher = hashlib.md5() # # for base_dir, dirs, file_names in os.walk(path, topdown=True): # # os.walk will respect our order as long as topdown=True. This # # ensures the same iteration through the files each time # dirs.sort() # # for file_name in sorted(file_names): # with open(os.path.join(base_dir, file_name), "rb") as handle: # hasher.update(handle.read()) # # return hasher.hexdigest() # # Path: via/checkmate.py # class ViaCheckmateClient(CheckmateClient): # def __init__(self, request): # super().__init__( # host=request.registry.settings["checkmate_url"], # api_key=request.registry.settings["checkmate_api_key"], # ) # self._request = request # # def raise_if_blocked(self, url): # """Raise a redirect to Checkmate if the URL is blocked. # # This will sensibly apply all ignore reasons and other configuration for # Checkmate. # # :param url: The URL to check # :raise HTTPTemporaryRedirect: If the URL is blocked # """ # try: # blocked = self.check_url( # url, # allow_all=self._request.registry.settings["checkmate_allow_all"], # blocked_for=self._request.params.get("via.blocked_for"), # ignore_reasons=self._request.registry.settings[ # "checkmate_ignore_reasons" # ], # ) # # except CheckmateException: # blocked = None # # if blocked: # raise HTTPTemporaryRedirect(location=blocked.presentation_url) # # Path: via/sentry_filters.py # SENTRY_FILTERS = [] . Output only the next line.
cache_buster = PathCacheBuster(static_path)
Here is a snippet: <|code_start|> if value is None and options.get("required"): raise ValueError(f"Param {param} must be provided.") # Configure sentry settings["h_pyramid_sentry.filters"] = SENTRY_FILTERS return settings def create_app(_=None, **settings): """Configure and return the WSGI app.""" config = pyramid.config.Configurator(settings=load_settings(settings)) config.include("pyramid_exclog") config.include("pyramid_jinja2") config.include("pyramid_services") config.include("h_pyramid_sentry") config.include("via.views") config.include("via.services") # Configure Pyramid so we can generate static URLs static_path = str(importlib_resources.files("via") / "static") cache_buster = PathCacheBuster(static_path) print(f"Cache buster salt: {cache_buster.salt}") config.add_static_view(name="static", path="via:static") config.add_cache_buster("via:static", cachebust=cache_buster) # Make the CheckmateClient object available as request.checkmate. <|code_end|> . Write the next line using the current file imports: import os import importlib_resources import pyramid.config from pathlib import Path from pyramid.settings import asbool from whitenoise import WhiteNoise from via.cache_buster import PathCacheBuster from via.checkmate import ViaCheckmateClient from via.sentry_filters import SENTRY_FILTERS and context from other files: # Path: via/cache_buster.py # class PathCacheBuster: # """A cache buster which modifies paths to enable immutable caching. # # Implements `pyramid.interfaces.ICacheBuster` and can be used with # `config.add_cache_buster()` to enable rewriting of URLs to a version # which contains the last modified time. # # This allows assets to be statically cached until at least one of them has # changed. This is achieved by generating a salt value from a hash of the # files which is applied to the input URL. # # :param path: Path to static for generating the salt value # """ # # def __init__(self, path): # self.salt = self._generate_salt(path) # # def __call__(self, request, subpath, kw): # pylint: disable=invalid-name # """Prepend the salt to the path. # # Implements the ICacheBuster interface. # """ # return f"{self.salt}/{subpath}", kw # # @property # def immutable_path(self): # """Return the external URL where immutable content is accessible.""" # return f"/static/{self.salt}" # # def get_immutable_file_test(self): # """Return an immutability test for use with Whitenoise.""" # immutable_path = self.immutable_path # # def _test(_, url): # return url.startswith(immutable_path) # # return _test # # @staticmethod # def _generate_salt(path): # """Generate salt based on the last hash of all files. # # This ensures we only change salt when at least one file has changed. # """ # hasher = hashlib.md5() # # for base_dir, dirs, file_names in os.walk(path, topdown=True): # # os.walk will respect our order as long as topdown=True. This # # ensures the same iteration through the files each time # dirs.sort() # # for file_name in sorted(file_names): # with open(os.path.join(base_dir, file_name), "rb") as handle: # hasher.update(handle.read()) # # return hasher.hexdigest() # # Path: via/checkmate.py # class ViaCheckmateClient(CheckmateClient): # def __init__(self, request): # super().__init__( # host=request.registry.settings["checkmate_url"], # api_key=request.registry.settings["checkmate_api_key"], # ) # self._request = request # # def raise_if_blocked(self, url): # """Raise a redirect to Checkmate if the URL is blocked. # # This will sensibly apply all ignore reasons and other configuration for # Checkmate. # # :param url: The URL to check # :raise HTTPTemporaryRedirect: If the URL is blocked # """ # try: # blocked = self.check_url( # url, # allow_all=self._request.registry.settings["checkmate_allow_all"], # blocked_for=self._request.params.get("via.blocked_for"), # ignore_reasons=self._request.registry.settings[ # "checkmate_ignore_reasons" # ], # ) # # except CheckmateException: # blocked = None # # if blocked: # raise HTTPTemporaryRedirect(location=blocked.presentation_url) # # Path: via/sentry_filters.py # SENTRY_FILTERS = [] , which may include functions, classes, or code. Output only the next line.
config.add_request_method(ViaCheckmateClient, reify=True, name="checkmate")
Continue the code snippet: <|code_start|> "checkmate_ignore_reasons": {}, "checkmate_allow_all": {"formatter": asbool}, "data_directory": {"required": True, "formatter": Path}, "signed_urls_required": {"formatter": asbool}, "enable_front_page": {"formatter": asbool}, "jstor_pdf_url": {}, } def load_settings(settings): """Load application settings from a dict or environment variables. Checks that the required parameters are either filled out in the provided dict, or that the required values can be loaded from the environment. :param settings: Settings dict :raise ValueError: If a required parameter is not filled :return: A dict of settings """ for param, options in PARAMETERS.items(): formatter = options.get("formatter", lambda v: v) value = settings[param] = formatter( settings.get(param, os.environ.get(param.upper())) ) if value is None and options.get("required"): raise ValueError(f"Param {param} must be provided.") # Configure sentry <|code_end|> . Use current file imports: import os import importlib_resources import pyramid.config from pathlib import Path from pyramid.settings import asbool from whitenoise import WhiteNoise from via.cache_buster import PathCacheBuster from via.checkmate import ViaCheckmateClient from via.sentry_filters import SENTRY_FILTERS and context (classes, functions, or code) from other files: # Path: via/cache_buster.py # class PathCacheBuster: # """A cache buster which modifies paths to enable immutable caching. # # Implements `pyramid.interfaces.ICacheBuster` and can be used with # `config.add_cache_buster()` to enable rewriting of URLs to a version # which contains the last modified time. # # This allows assets to be statically cached until at least one of them has # changed. This is achieved by generating a salt value from a hash of the # files which is applied to the input URL. # # :param path: Path to static for generating the salt value # """ # # def __init__(self, path): # self.salt = self._generate_salt(path) # # def __call__(self, request, subpath, kw): # pylint: disable=invalid-name # """Prepend the salt to the path. # # Implements the ICacheBuster interface. # """ # return f"{self.salt}/{subpath}", kw # # @property # def immutable_path(self): # """Return the external URL where immutable content is accessible.""" # return f"/static/{self.salt}" # # def get_immutable_file_test(self): # """Return an immutability test for use with Whitenoise.""" # immutable_path = self.immutable_path # # def _test(_, url): # return url.startswith(immutable_path) # # return _test # # @staticmethod # def _generate_salt(path): # """Generate salt based on the last hash of all files. # # This ensures we only change salt when at least one file has changed. # """ # hasher = hashlib.md5() # # for base_dir, dirs, file_names in os.walk(path, topdown=True): # # os.walk will respect our order as long as topdown=True. This # # ensures the same iteration through the files each time # dirs.sort() # # for file_name in sorted(file_names): # with open(os.path.join(base_dir, file_name), "rb") as handle: # hasher.update(handle.read()) # # return hasher.hexdigest() # # Path: via/checkmate.py # class ViaCheckmateClient(CheckmateClient): # def __init__(self, request): # super().__init__( # host=request.registry.settings["checkmate_url"], # api_key=request.registry.settings["checkmate_api_key"], # ) # self._request = request # # def raise_if_blocked(self, url): # """Raise a redirect to Checkmate if the URL is blocked. # # This will sensibly apply all ignore reasons and other configuration for # Checkmate. # # :param url: The URL to check # :raise HTTPTemporaryRedirect: If the URL is blocked # """ # try: # blocked = self.check_url( # url, # allow_all=self._request.registry.settings["checkmate_allow_all"], # blocked_for=self._request.params.get("via.blocked_for"), # ignore_reasons=self._request.registry.settings[ # "checkmate_ignore_reasons" # ], # ) # # except CheckmateException: # blocked = None # # if blocked: # raise HTTPTemporaryRedirect(location=blocked.presentation_url) # # Path: via/sentry_filters.py # SENTRY_FILTERS = [] . Output only the next line.
settings["h_pyramid_sentry.filters"] = SENTRY_FILTERS
Given the following code snippet before the placeholder: <|code_start|> class TestViewPDFAPI: @pytest.mark.usefixtures("checkmate_pass") def test_caching_is_disabled(self, test_app): response = test_app.get("/pdf?url=http://example.com/foo.pdf") <|code_end|> , predict the next line using imports from the current file: import pytest from tests.conftest import assert_cache_control and context including class names, function names, and sometimes code from other files: # Path: tests/conftest.py # def assert_cache_control(headers, cache_parts): # """Assert that all parts of the Cache-Control header are present.""" # assert dict(headers) == Any.dict.containing({"Cache-Control": Any.string()}) # assert ( # headers["Cache-Control"].split(", ") == Any.list.containing(cache_parts).only() # ) . Output only the next line.
assert_cache_control(
Based on the snippet: <|code_start|> class TestCleanHeaders: def test_basics(self): headers = {"Most-Headers": "are passed through", "Preserving": "order"} result = clean_headers(headers) assert result == headers assert list(result.keys()) == ["Most-Headers", "Preserving"] assert isinstance(result, OrderedDict) # For the following tests we are going to lean heavily on the defined lists # of headers, and just test that the function applies them correctly. Other # wise we just end-up copy pasting them here to no real benefit <|code_end|> , predict the immediate next line with the help of imports: from collections import OrderedDict from via.requests_tools.headers import ( BANNED_HEADERS, HEADER_DEFAULTS, HEADER_MAP, add_request_headers, clean_headers, ) import pytest and context (classes, functions, sometimes code) from other files: # Path: via/requests_tools/headers.py # BANNED_HEADERS = { # # Requests needs to set Host to the right thing for us # "Host", # # Don't pass Cookies # "Cookie", # # AWS things # "X-Amzn-Trace-Id", # # AWS NGINX / NGINX things # "X-Real-Ip", # "X-Forwarded-Proto", # "X-Forwarded-Port", # # Cloudflare things # "Cf-Request-Id", # "Cf-Connecting-Ip", # "Cf-Ipcountry", # "Cf-Ray", # "Cf-Visitor", # "Cdn-Loop", # } # # HEADER_DEFAULTS = { # # Mimic what it looks like if you got here from a Google search # "Referer": "https://www.google.com", # "Sec-Fetch-Dest": "document", # "Sec-Fetch-Mode": "navigate", # "Sec-Fetch-Site": "cross-site", # "Sec-Fetch-User": "?1", # # This gets overwritten by AWS NGINX # "Connection": "keep-alive", # } # # HEADER_MAP = {"Dnt": "DNT"} # # def add_request_headers(headers): # """Add headers for 3rd party providers which we access data from.""" # # # Pass our abuse policy in request headers for third-party site admins. # headers["X-Abuse-Policy"] = "https://web.hypothes.is/abuse-policy/" # headers["X-Complaints-To"] = "https://web.hypothes.is/report-abuse/" # # return headers # # def clean_headers(headers): # """Remove Cloudflare and other cruft from the headers. # # This will attempt to present a clean version of the headers which can be # used to make a request to the 3rd party site. # # Also: # # * Map the headers as if we had come from a Google Search # * Remove things added by AWS and Cloudflare etc. # * Fix some header names # # This is intended to return a list of headers that can be passed on to the # upstream service. # # :param headers: A mapping of header values # :return: An OrderedDict of cleaned headers # """ # clean = OrderedDict() # # for header_name, value in headers.items(): # if header_name in BANNED_HEADERS: # continue # # # Map to standard names for things # header_name = HEADER_MAP.get(header_name, header_name) # # # Add in defaults for certain fields # value = HEADER_DEFAULTS.get(header_name, value) # # clean[header_name] = value # # return clean . Output only the next line.
@pytest.mark.parametrize("header_name", BANNED_HEADERS)
Using the snippet: <|code_start|> class TestCleanHeaders: def test_basics(self): headers = {"Most-Headers": "are passed through", "Preserving": "order"} result = clean_headers(headers) assert result == headers assert list(result.keys()) == ["Most-Headers", "Preserving"] assert isinstance(result, OrderedDict) # For the following tests we are going to lean heavily on the defined lists # of headers, and just test that the function applies them correctly. Other # wise we just end-up copy pasting them here to no real benefit @pytest.mark.parametrize("header_name", BANNED_HEADERS) def test_we_remove_banned_headers(self, header_name): result = clean_headers({header_name: "value"}) assert header_name not in result <|code_end|> , determine the next line of code. You have imports: from collections import OrderedDict from via.requests_tools.headers import ( BANNED_HEADERS, HEADER_DEFAULTS, HEADER_MAP, add_request_headers, clean_headers, ) import pytest and context (class names, function names, or code) available: # Path: via/requests_tools/headers.py # BANNED_HEADERS = { # # Requests needs to set Host to the right thing for us # "Host", # # Don't pass Cookies # "Cookie", # # AWS things # "X-Amzn-Trace-Id", # # AWS NGINX / NGINX things # "X-Real-Ip", # "X-Forwarded-Proto", # "X-Forwarded-Port", # # Cloudflare things # "Cf-Request-Id", # "Cf-Connecting-Ip", # "Cf-Ipcountry", # "Cf-Ray", # "Cf-Visitor", # "Cdn-Loop", # } # # HEADER_DEFAULTS = { # # Mimic what it looks like if you got here from a Google search # "Referer": "https://www.google.com", # "Sec-Fetch-Dest": "document", # "Sec-Fetch-Mode": "navigate", # "Sec-Fetch-Site": "cross-site", # "Sec-Fetch-User": "?1", # # This gets overwritten by AWS NGINX # "Connection": "keep-alive", # } # # HEADER_MAP = {"Dnt": "DNT"} # # def add_request_headers(headers): # """Add headers for 3rd party providers which we access data from.""" # # # Pass our abuse policy in request headers for third-party site admins. # headers["X-Abuse-Policy"] = "https://web.hypothes.is/abuse-policy/" # headers["X-Complaints-To"] = "https://web.hypothes.is/report-abuse/" # # return headers # # def clean_headers(headers): # """Remove Cloudflare and other cruft from the headers. # # This will attempt to present a clean version of the headers which can be # used to make a request to the 3rd party site. # # Also: # # * Map the headers as if we had come from a Google Search # * Remove things added by AWS and Cloudflare etc. # * Fix some header names # # This is intended to return a list of headers that can be passed on to the # upstream service. # # :param headers: A mapping of header values # :return: An OrderedDict of cleaned headers # """ # clean = OrderedDict() # # for header_name, value in headers.items(): # if header_name in BANNED_HEADERS: # continue # # # Map to standard names for things # header_name = HEADER_MAP.get(header_name, header_name) # # # Add in defaults for certain fields # value = HEADER_DEFAULTS.get(header_name, value) # # clean[header_name] = value # # return clean . Output only the next line.
@pytest.mark.parametrize("header_name,default_value", HEADER_DEFAULTS.items())
Using the snippet: <|code_start|> headers = {"Most-Headers": "are passed through", "Preserving": "order"} result = clean_headers(headers) assert result == headers assert list(result.keys()) == ["Most-Headers", "Preserving"] assert isinstance(result, OrderedDict) # For the following tests we are going to lean heavily on the defined lists # of headers, and just test that the function applies them correctly. Other # wise we just end-up copy pasting them here to no real benefit @pytest.mark.parametrize("header_name", BANNED_HEADERS) def test_we_remove_banned_headers(self, header_name): result = clean_headers({header_name: "value"}) assert header_name not in result @pytest.mark.parametrize("header_name,default_value", HEADER_DEFAULTS.items()) def test_we_assign_to_defaults_if_present(self, header_name, default_value): result = clean_headers({header_name: "some custom default"}) assert result[header_name] == default_value @pytest.mark.parametrize("header_name", HEADER_DEFAULTS.keys()) def test_we_do_not_assign_to_defaults_if_absent(self, header_name): result = clean_headers({}) assert header_name not in result <|code_end|> , determine the next line of code. You have imports: from collections import OrderedDict from via.requests_tools.headers import ( BANNED_HEADERS, HEADER_DEFAULTS, HEADER_MAP, add_request_headers, clean_headers, ) import pytest and context (class names, function names, or code) available: # Path: via/requests_tools/headers.py # BANNED_HEADERS = { # # Requests needs to set Host to the right thing for us # "Host", # # Don't pass Cookies # "Cookie", # # AWS things # "X-Amzn-Trace-Id", # # AWS NGINX / NGINX things # "X-Real-Ip", # "X-Forwarded-Proto", # "X-Forwarded-Port", # # Cloudflare things # "Cf-Request-Id", # "Cf-Connecting-Ip", # "Cf-Ipcountry", # "Cf-Ray", # "Cf-Visitor", # "Cdn-Loop", # } # # HEADER_DEFAULTS = { # # Mimic what it looks like if you got here from a Google search # "Referer": "https://www.google.com", # "Sec-Fetch-Dest": "document", # "Sec-Fetch-Mode": "navigate", # "Sec-Fetch-Site": "cross-site", # "Sec-Fetch-User": "?1", # # This gets overwritten by AWS NGINX # "Connection": "keep-alive", # } # # HEADER_MAP = {"Dnt": "DNT"} # # def add_request_headers(headers): # """Add headers for 3rd party providers which we access data from.""" # # # Pass our abuse policy in request headers for third-party site admins. # headers["X-Abuse-Policy"] = "https://web.hypothes.is/abuse-policy/" # headers["X-Complaints-To"] = "https://web.hypothes.is/report-abuse/" # # return headers # # def clean_headers(headers): # """Remove Cloudflare and other cruft from the headers. # # This will attempt to present a clean version of the headers which can be # used to make a request to the 3rd party site. # # Also: # # * Map the headers as if we had come from a Google Search # * Remove things added by AWS and Cloudflare etc. # * Fix some header names # # This is intended to return a list of headers that can be passed on to the # upstream service. # # :param headers: A mapping of header values # :return: An OrderedDict of cleaned headers # """ # clean = OrderedDict() # # for header_name, value in headers.items(): # if header_name in BANNED_HEADERS: # continue # # # Map to standard names for things # header_name = HEADER_MAP.get(header_name, header_name) # # # Add in defaults for certain fields # value = HEADER_DEFAULTS.get(header_name, value) # # clean[header_name] = value # # return clean . Output only the next line.
@pytest.mark.parametrize("header_name,mapped_name", HEADER_MAP.items())
Predict the next line for this snippet: <|code_start|> # wise we just end-up copy pasting them here to no real benefit @pytest.mark.parametrize("header_name", BANNED_HEADERS) def test_we_remove_banned_headers(self, header_name): result = clean_headers({header_name: "value"}) assert header_name not in result @pytest.mark.parametrize("header_name,default_value", HEADER_DEFAULTS.items()) def test_we_assign_to_defaults_if_present(self, header_name, default_value): result = clean_headers({header_name: "some custom default"}) assert result[header_name] == default_value @pytest.mark.parametrize("header_name", HEADER_DEFAULTS.keys()) def test_we_do_not_assign_to_defaults_if_absent(self, header_name): result = clean_headers({}) assert header_name not in result @pytest.mark.parametrize("header_name,mapped_name", HEADER_MAP.items()) def test_we_map_mangled_header_names(self, header_name, mapped_name): result = clean_headers({header_name: "value"}) assert result[mapped_name] == "value" assert header_name not in result class TestAddHeaders: def test_it(self): <|code_end|> with the help of current file imports: from collections import OrderedDict from via.requests_tools.headers import ( BANNED_HEADERS, HEADER_DEFAULTS, HEADER_MAP, add_request_headers, clean_headers, ) import pytest and context from other files: # Path: via/requests_tools/headers.py # BANNED_HEADERS = { # # Requests needs to set Host to the right thing for us # "Host", # # Don't pass Cookies # "Cookie", # # AWS things # "X-Amzn-Trace-Id", # # AWS NGINX / NGINX things # "X-Real-Ip", # "X-Forwarded-Proto", # "X-Forwarded-Port", # # Cloudflare things # "Cf-Request-Id", # "Cf-Connecting-Ip", # "Cf-Ipcountry", # "Cf-Ray", # "Cf-Visitor", # "Cdn-Loop", # } # # HEADER_DEFAULTS = { # # Mimic what it looks like if you got here from a Google search # "Referer": "https://www.google.com", # "Sec-Fetch-Dest": "document", # "Sec-Fetch-Mode": "navigate", # "Sec-Fetch-Site": "cross-site", # "Sec-Fetch-User": "?1", # # This gets overwritten by AWS NGINX # "Connection": "keep-alive", # } # # HEADER_MAP = {"Dnt": "DNT"} # # def add_request_headers(headers): # """Add headers for 3rd party providers which we access data from.""" # # # Pass our abuse policy in request headers for third-party site admins. # headers["X-Abuse-Policy"] = "https://web.hypothes.is/abuse-policy/" # headers["X-Complaints-To"] = "https://web.hypothes.is/report-abuse/" # # return headers # # def clean_headers(headers): # """Remove Cloudflare and other cruft from the headers. # # This will attempt to present a clean version of the headers which can be # used to make a request to the 3rd party site. # # Also: # # * Map the headers as if we had come from a Google Search # * Remove things added by AWS and Cloudflare etc. # * Fix some header names # # This is intended to return a list of headers that can be passed on to the # upstream service. # # :param headers: A mapping of header values # :return: An OrderedDict of cleaned headers # """ # clean = OrderedDict() # # for header_name, value in headers.items(): # if header_name in BANNED_HEADERS: # continue # # # Map to standard names for things # header_name = HEADER_MAP.get(header_name, header_name) # # # Add in defaults for certain fields # value = HEADER_DEFAULTS.get(header_name, value) # # clean[header_name] = value # # return clean , which may contain function names, class names, or code. Output only the next line.
headers = add_request_headers({"X-Existing": "existing"})
Based on the snippet: <|code_start|> class TestCleanHeaders: def test_basics(self): headers = {"Most-Headers": "are passed through", "Preserving": "order"} <|code_end|> , predict the immediate next line with the help of imports: from collections import OrderedDict from via.requests_tools.headers import ( BANNED_HEADERS, HEADER_DEFAULTS, HEADER_MAP, add_request_headers, clean_headers, ) import pytest and context (classes, functions, sometimes code) from other files: # Path: via/requests_tools/headers.py # BANNED_HEADERS = { # # Requests needs to set Host to the right thing for us # "Host", # # Don't pass Cookies # "Cookie", # # AWS things # "X-Amzn-Trace-Id", # # AWS NGINX / NGINX things # "X-Real-Ip", # "X-Forwarded-Proto", # "X-Forwarded-Port", # # Cloudflare things # "Cf-Request-Id", # "Cf-Connecting-Ip", # "Cf-Ipcountry", # "Cf-Ray", # "Cf-Visitor", # "Cdn-Loop", # } # # HEADER_DEFAULTS = { # # Mimic what it looks like if you got here from a Google search # "Referer": "https://www.google.com", # "Sec-Fetch-Dest": "document", # "Sec-Fetch-Mode": "navigate", # "Sec-Fetch-Site": "cross-site", # "Sec-Fetch-User": "?1", # # This gets overwritten by AWS NGINX # "Connection": "keep-alive", # } # # HEADER_MAP = {"Dnt": "DNT"} # # def add_request_headers(headers): # """Add headers for 3rd party providers which we access data from.""" # # # Pass our abuse policy in request headers for third-party site admins. # headers["X-Abuse-Policy"] = "https://web.hypothes.is/abuse-policy/" # headers["X-Complaints-To"] = "https://web.hypothes.is/report-abuse/" # # return headers # # def clean_headers(headers): # """Remove Cloudflare and other cruft from the headers. # # This will attempt to present a clean version of the headers which can be # used to make a request to the 3rd party site. # # Also: # # * Map the headers as if we had come from a Google Search # * Remove things added by AWS and Cloudflare etc. # * Fix some header names # # This is intended to return a list of headers that can be passed on to the # upstream service. # # :param headers: A mapping of header values # :return: An OrderedDict of cleaned headers # """ # clean = OrderedDict() # # for header_name, value in headers.items(): # if header_name in BANNED_HEADERS: # continue # # # Map to standard names for things # header_name = HEADER_MAP.get(header_name, header_name) # # # Add in defaults for certain fields # value = HEADER_DEFAULTS.get(header_name, value) # # clean[header_name] = value # # return clean . Output only the next line.
result = clean_headers(headers)
Given the code snippet: <|code_start|>"""Views for debugging.""" @view.view_config(route_name="debug_headers") def debug_headers(_context, request): """Dump the headers as we receive them for debugging.""" if request.GET.get("raw"): headers = OrderedDict(request.headers) else: <|code_end|> , generate the next line using the imports in this file: import json from collections import OrderedDict from pyramid import view from pyramid.response import Response from via.get_url import clean_headers and context (functions, classes, or occasionally code) from other files: # Path: via/get_url.py # def get_url_details(http_service, url, headers=None): . Output only the next line.
headers = clean_headers(request.headers)
Using the snippet: <|code_start|> class TestProxy: def test_it( self, context, pyramid_request, get_url_details, via_client_service, http_service, ): url = context.url_from_path.return_value = "/https://example.org?a=1" result = proxy(context, pyramid_request) pyramid_request.checkmate.raise_if_blocked.assert_called_once_with(url) get_url_details.assert_called_once_with(http_service, url) via_client_service.url_for.assert_called_once_with( url, sentinel.mime_type, pyramid_request.params ) assert result == {"src": via_client_service.url_for.return_value} @pytest.fixture def context(self): <|code_end|> , determine the next line of code. You have imports: from unittest.mock import create_autospec, sentinel from via.resources import PathURLResource from via.views.proxy import proxy import pytest and context (class names, function names, or code) available: # Path: via/resources.py # class PathURLResource(_URLResource): # """Resource for routes expecting urls from the path.""" # # def url_from_path(self): # """Get the 'url' parameter from the path. # # :return: The URL as a string # :raise HTTPBadRequest: If the URL is missing or empty # :raise BadURL: If the URL is malformed # """ # # url = self._request.path_qs[1:].strip() # if not url: # raise HTTPBadRequest("Required path part 'url` is missing") # # return self._normalise_url(url) # # Path: via/views/proxy.py # @view_config(route_name="proxy", renderer="via:templates/proxy.html.jinja2") # def proxy(context, request): # url = context.url_from_path() # request.checkmate.raise_if_blocked(url) # # mime_type, _status_code = get_url_details(request.find_service(HTTPService), url) # # return { # "src": request.find_service(ViaClientService).url_for( # url, mime_type, request.params # ) # } . Output only the next line.
return create_autospec(PathURLResource, spec_set=True, instance=True)
Based on the snippet: <|code_start|> class TestProxy: def test_it( self, context, pyramid_request, get_url_details, via_client_service, http_service, ): url = context.url_from_path.return_value = "/https://example.org?a=1" <|code_end|> , predict the immediate next line with the help of imports: from unittest.mock import create_autospec, sentinel from via.resources import PathURLResource from via.views.proxy import proxy import pytest and context (classes, functions, sometimes code) from other files: # Path: via/resources.py # class PathURLResource(_URLResource): # """Resource for routes expecting urls from the path.""" # # def url_from_path(self): # """Get the 'url' parameter from the path. # # :return: The URL as a string # :raise HTTPBadRequest: If the URL is missing or empty # :raise BadURL: If the URL is malformed # """ # # url = self._request.path_qs[1:].strip() # if not url: # raise HTTPBadRequest("Required path part 'url` is missing") # # return self._normalise_url(url) # # Path: via/views/proxy.py # @view_config(route_name="proxy", renderer="via:templates/proxy.html.jinja2") # def proxy(context, request): # url = context.url_from_path() # request.checkmate.raise_if_blocked(url) # # mime_type, _status_code = get_url_details(request.find_service(HTTPService), url) # # return { # "src": request.find_service(ViaClientService).url_for( # url, mime_type, request.params # ) # } . Output only the next line.
result = proxy(context, pyramid_request)
Given snippet: <|code_start|> "via.client.ignoreOtherConfiguration": "1", "via.client.openSidebar": "1", "via.external_link_mode": "new-tab", } @pytest.mark.usefixtures("html_response", "checkmate_pass") def test_proxy_html(self, test_app): target_url = "http://example.com" response = test_app.get(f"/route?url={target_url}") assert response.status_code == 302 query = dict(self.DEFAULT_OPTIONS) assert response.location == Any.url.matching( f"https://viahtml.hypothes.is/proxy/{target_url}/" ).with_query(query) @pytest.mark.usefixtures("pdf_response", "checkmate_pass") def test_proxy_pdf(self, test_app): target_url = "http://example.com" response = test_app.get(f"/route?url={target_url}") assert response.status_code == 302 query = dict(self.DEFAULT_OPTIONS) query["via.sec"] = Any.string() query["url"] = target_url assert response.location == Any.url.matching( f"http://localhost/pdf?url={quote_plus(target_url)}" ).with_query(query) <|code_end|> , continue by predicting the next line. Consider current file imports: from urllib.parse import quote_plus from h_matchers import Any from tests.conftest import assert_cache_control import httpretty import pytest and context: # Path: tests/conftest.py # def assert_cache_control(headers, cache_parts): # """Assert that all parts of the Cache-Control header are present.""" # assert dict(headers) == Any.dict.containing({"Cache-Control": Any.string()}) # assert ( # headers["Cache-Control"].split(", ") == Any.list.containing(cache_parts).only() # ) which might include code, classes, or functions. Output only the next line.
assert_cache_control(
Given the following code snippet before the placeholder: <|code_start|> ): google_drive_api.parse_file_url.return_value = None pyramid_request.params["jstor.ip"] = "1.1.1.1" pdf_url = svc.get_pdf_url("jstor://DOI") secure_link_service.sign_url.assert_called_once_with( "http://example.com/jstor/proxied.pdf?url=jstor%3A%2F%2FDOI&jstor.ip=1.1.1.1" ) assert pdf_url == secure_link_service.sign_url.return_value def test_nginx_file_url(self, google_drive_api, svc): google_drive_api.parse_file_url.return_value = None pdf_url = svc.get_pdf_url("http://nginx/document.pdf") svc.nginx_signer.sign_url.assert_called_once_with( "http://nginx/document.pdf", nginx_path="/proxy/static/" ) assert pdf_url == svc.nginx_signer.sign_url.return_value @pytest.fixture def svc( self, google_drive_api, secure_link_service, pyramid_request, PatchedNGINXSigner, jstor_api, ): <|code_end|> , predict the next line using imports from the current file: from datetime import datetime, timedelta, timezone from unittest.mock import sentinel from via.services.pdf_url import PDFURLBuilder, _NGINXSigner, factory import pytest and context including class names, function names, and sometimes code from other files: # Path: via/services/pdf_url.py # class PDFURLBuilder: # request: Request # google_drive_api: GoogleDriveAPI # jstor_api: JSTORAPI # secure_link_service: SecureLinkService # route_url: Callable # nginx_signer: _NGINXSigner # # _MS_ONEDRIVE_URL = ( # re.compile(r"^https://.*\.sharepoint.com/.*download=1"), # re.compile(r"^https://api.onedrive.com/v1.0/.*/root/content"), # ) # # def get_pdf_url(self, url): # """Build a signed URL to the corresponding Via route for proxing the PDF at `url`. # # By default PDFs will be proxied by Nginx but we'll dispatch based on the URL # to other routes responsible of proxing PDFs from Google Drive or MS OneDrive. # """ # if file_details := self.google_drive_api.parse_file_url(url): # return self._google_file_url(file_details, url) # # if self._is_onedrive_url(url): # return self._proxy_onedrive_pdf(url) # # if url.startswith("jstor://"): # return self._proxy_jstor_pdf(url) # # return self.nginx_signer.sign_url(url, nginx_path="/proxy/static/") # # @classmethod # def _is_onedrive_url(cls, url): # return any(regexp.match(url) for regexp in cls._MS_ONEDRIVE_URL) # # def _proxy_onedrive_pdf(self, url): # url = self.secure_link_service.sign_url( # self.route_url( # "proxy_onedrive_pdf", # _query={"url": url}, # ) # ) # return url # # def _proxy_jstor_pdf(self, url): # return self.secure_link_service.sign_url( # self.route_url( # "proxy_jstor_pdf", # _query={"url": url, "jstor.ip": self.request.params.get("jstor.ip")}, # ) # ) # # def _google_file_url(self, file_details, url): # route = "proxy_google_drive_file" # if file_details.get("resource_key"): # route += ":resource_key" # # return self.secure_link_service.sign_url( # self.route_url( # route, # # Pass the original URL along so it will show up nicely in # # error messages. This isn't useful for users as they don't # # see this directly, but it's handy for us. # _query={"url": url}, # **file_details, # ) # ) # # class _NGINXSigner: # nginx_server: str # secret: str # # def sign_url(self, url, nginx_path): # """Return the URL from which the PDF viewer should load the PDF.""" # # # Compute the expiry time to put into the URL. # exp = int(quantized_expiry(max_age=timedelta(hours=25)).timestamp()) # # # The expression to be hashed. # # # # This matches the hash expression that we tell the NGINX secure link # # module to use with the secure_link_md5 setting in our NGINX config file. # # # # http://nginx.org/en/docs/http/ngx_http_secure_link_module.html#secure_link_md5 # hash_expression = f"{nginx_path}{exp}/{url} {self.secret}" # # # Compute the hash value to put into the URL. # # # # This implements the NGINX secure link module's hashing algorithm: # # # # http://nginx.org/en/docs/http/ngx_http_secure_link_module.html#secure_link_md5 # hash_ = hashlib.md5() # hash_.update(hash_expression.encode("utf-8")) # sec = hash_.digest() # sec = b64encode(sec) # sec = sec.replace(b"+", b"-") # sec = sec.replace(b"/", b"_") # sec = sec.replace(b"=", b"") # sec = sec.decode() # # # Construct the URL, inserting sec and exp where our NGINX config file # # expects to find them. # return f"{self.nginx_server}{nginx_path}{sec}/{exp}/{url}" # # def factory(_context, request): # return PDFURLBuilder( # request=request, # google_drive_api=request.find_service(GoogleDriveAPI), # jstor_api=request.find_service(JSTORAPI), # secure_link_service=request.find_service(SecureLinkService), # route_url=request.route_url, # nginx_signer=_NGINXSigner( # nginx_server=request.registry.settings["nginx_server"], # secret=request.registry.settings["nginx_secure_link_secret"], # ), # ) . Output only the next line.
return PDFURLBuilder(
Predict the next line for this snippet: <|code_start|> class TestNGINXSigner: def test_it( self, svc, quantized_expiry, ): signed_url = svc.sign_url( "https://example.com/foo/bar.pdf?q=s", "/proxy/static/" ) quantized_expiry.assert_called_once_with(max_age=timedelta(hours=25)) signed_url_parts = signed_url.split("/") signature = signed_url_parts[5] expiry = signed_url_parts[6] assert signature == "qTq65RXvm6P2Y4bfzWdPzg" assert expiry == "1581183021" @pytest.fixture def svc(self, pyramid_settings): <|code_end|> with the help of current file imports: from datetime import datetime, timedelta, timezone from unittest.mock import sentinel from via.services.pdf_url import PDFURLBuilder, _NGINXSigner, factory import pytest and context from other files: # Path: via/services/pdf_url.py # class PDFURLBuilder: # request: Request # google_drive_api: GoogleDriveAPI # jstor_api: JSTORAPI # secure_link_service: SecureLinkService # route_url: Callable # nginx_signer: _NGINXSigner # # _MS_ONEDRIVE_URL = ( # re.compile(r"^https://.*\.sharepoint.com/.*download=1"), # re.compile(r"^https://api.onedrive.com/v1.0/.*/root/content"), # ) # # def get_pdf_url(self, url): # """Build a signed URL to the corresponding Via route for proxing the PDF at `url`. # # By default PDFs will be proxied by Nginx but we'll dispatch based on the URL # to other routes responsible of proxing PDFs from Google Drive or MS OneDrive. # """ # if file_details := self.google_drive_api.parse_file_url(url): # return self._google_file_url(file_details, url) # # if self._is_onedrive_url(url): # return self._proxy_onedrive_pdf(url) # # if url.startswith("jstor://"): # return self._proxy_jstor_pdf(url) # # return self.nginx_signer.sign_url(url, nginx_path="/proxy/static/") # # @classmethod # def _is_onedrive_url(cls, url): # return any(regexp.match(url) for regexp in cls._MS_ONEDRIVE_URL) # # def _proxy_onedrive_pdf(self, url): # url = self.secure_link_service.sign_url( # self.route_url( # "proxy_onedrive_pdf", # _query={"url": url}, # ) # ) # return url # # def _proxy_jstor_pdf(self, url): # return self.secure_link_service.sign_url( # self.route_url( # "proxy_jstor_pdf", # _query={"url": url, "jstor.ip": self.request.params.get("jstor.ip")}, # ) # ) # # def _google_file_url(self, file_details, url): # route = "proxy_google_drive_file" # if file_details.get("resource_key"): # route += ":resource_key" # # return self.secure_link_service.sign_url( # self.route_url( # route, # # Pass the original URL along so it will show up nicely in # # error messages. This isn't useful for users as they don't # # see this directly, but it's handy for us. # _query={"url": url}, # **file_details, # ) # ) # # class _NGINXSigner: # nginx_server: str # secret: str # # def sign_url(self, url, nginx_path): # """Return the URL from which the PDF viewer should load the PDF.""" # # # Compute the expiry time to put into the URL. # exp = int(quantized_expiry(max_age=timedelta(hours=25)).timestamp()) # # # The expression to be hashed. # # # # This matches the hash expression that we tell the NGINX secure link # # module to use with the secure_link_md5 setting in our NGINX config file. # # # # http://nginx.org/en/docs/http/ngx_http_secure_link_module.html#secure_link_md5 # hash_expression = f"{nginx_path}{exp}/{url} {self.secret}" # # # Compute the hash value to put into the URL. # # # # This implements the NGINX secure link module's hashing algorithm: # # # # http://nginx.org/en/docs/http/ngx_http_secure_link_module.html#secure_link_md5 # hash_ = hashlib.md5() # hash_.update(hash_expression.encode("utf-8")) # sec = hash_.digest() # sec = b64encode(sec) # sec = sec.replace(b"+", b"-") # sec = sec.replace(b"/", b"_") # sec = sec.replace(b"=", b"") # sec = sec.decode() # # # Construct the URL, inserting sec and exp where our NGINX config file # # expects to find them. # return f"{self.nginx_server}{nginx_path}{sec}/{exp}/{url}" # # def factory(_context, request): # return PDFURLBuilder( # request=request, # google_drive_api=request.find_service(GoogleDriveAPI), # jstor_api=request.find_service(JSTORAPI), # secure_link_service=request.find_service(SecureLinkService), # route_url=request.route_url, # nginx_signer=_NGINXSigner( # nginx_server=request.registry.settings["nginx_server"], # secret=request.registry.settings["nginx_secure_link_secret"], # ), # ) , which may contain function names, class names, or code. Output only the next line.
return _NGINXSigner(
Based on the snippet: <|code_start|> @pytest.fixture def svc( self, google_drive_api, secure_link_service, pyramid_request, PatchedNGINXSigner, jstor_api, ): return PDFURLBuilder( pyramid_request, google_drive_api, jstor_api, secure_link_service, pyramid_request.route_url, PatchedNGINXSigner.return_value, ) class TestFactory: def test_it( self, pyramid_request, pyramid_settings, PDFURLBuilder, PatchedNGINXSigner, google_drive_api, secure_link_service, jstor_api, ): <|code_end|> , predict the immediate next line with the help of imports: from datetime import datetime, timedelta, timezone from unittest.mock import sentinel from via.services.pdf_url import PDFURLBuilder, _NGINXSigner, factory import pytest and context (classes, functions, sometimes code) from other files: # Path: via/services/pdf_url.py # class PDFURLBuilder: # request: Request # google_drive_api: GoogleDriveAPI # jstor_api: JSTORAPI # secure_link_service: SecureLinkService # route_url: Callable # nginx_signer: _NGINXSigner # # _MS_ONEDRIVE_URL = ( # re.compile(r"^https://.*\.sharepoint.com/.*download=1"), # re.compile(r"^https://api.onedrive.com/v1.0/.*/root/content"), # ) # # def get_pdf_url(self, url): # """Build a signed URL to the corresponding Via route for proxing the PDF at `url`. # # By default PDFs will be proxied by Nginx but we'll dispatch based on the URL # to other routes responsible of proxing PDFs from Google Drive or MS OneDrive. # """ # if file_details := self.google_drive_api.parse_file_url(url): # return self._google_file_url(file_details, url) # # if self._is_onedrive_url(url): # return self._proxy_onedrive_pdf(url) # # if url.startswith("jstor://"): # return self._proxy_jstor_pdf(url) # # return self.nginx_signer.sign_url(url, nginx_path="/proxy/static/") # # @classmethod # def _is_onedrive_url(cls, url): # return any(regexp.match(url) for regexp in cls._MS_ONEDRIVE_URL) # # def _proxy_onedrive_pdf(self, url): # url = self.secure_link_service.sign_url( # self.route_url( # "proxy_onedrive_pdf", # _query={"url": url}, # ) # ) # return url # # def _proxy_jstor_pdf(self, url): # return self.secure_link_service.sign_url( # self.route_url( # "proxy_jstor_pdf", # _query={"url": url, "jstor.ip": self.request.params.get("jstor.ip")}, # ) # ) # # def _google_file_url(self, file_details, url): # route = "proxy_google_drive_file" # if file_details.get("resource_key"): # route += ":resource_key" # # return self.secure_link_service.sign_url( # self.route_url( # route, # # Pass the original URL along so it will show up nicely in # # error messages. This isn't useful for users as they don't # # see this directly, but it's handy for us. # _query={"url": url}, # **file_details, # ) # ) # # class _NGINXSigner: # nginx_server: str # secret: str # # def sign_url(self, url, nginx_path): # """Return the URL from which the PDF viewer should load the PDF.""" # # # Compute the expiry time to put into the URL. # exp = int(quantized_expiry(max_age=timedelta(hours=25)).timestamp()) # # # The expression to be hashed. # # # # This matches the hash expression that we tell the NGINX secure link # # module to use with the secure_link_md5 setting in our NGINX config file. # # # # http://nginx.org/en/docs/http/ngx_http_secure_link_module.html#secure_link_md5 # hash_expression = f"{nginx_path}{exp}/{url} {self.secret}" # # # Compute the hash value to put into the URL. # # # # This implements the NGINX secure link module's hashing algorithm: # # # # http://nginx.org/en/docs/http/ngx_http_secure_link_module.html#secure_link_md5 # hash_ = hashlib.md5() # hash_.update(hash_expression.encode("utf-8")) # sec = hash_.digest() # sec = b64encode(sec) # sec = sec.replace(b"+", b"-") # sec = sec.replace(b"/", b"_") # sec = sec.replace(b"=", b"") # sec = sec.decode() # # # Construct the URL, inserting sec and exp where our NGINX config file # # expects to find them. # return f"{self.nginx_server}{nginx_path}{sec}/{exp}/{url}" # # def factory(_context, request): # return PDFURLBuilder( # request=request, # google_drive_api=request.find_service(GoogleDriveAPI), # jstor_api=request.find_service(JSTORAPI), # secure_link_service=request.find_service(SecureLinkService), # route_url=request.route_url, # nginx_signer=_NGINXSigner( # nginx_server=request.registry.settings["nginx_server"], # secret=request.registry.settings["nginx_secure_link_secret"], # ), # ) . Output only the next line.
svc = factory(sentinel.context, pyramid_request)
Here is a snippet: <|code_start|> class TestPathCacheBuster: EXPECTED_HASH = "606e8d07c0af18c736c272a592038742" def test_salt_is_generated_from_dir_hash(self, cache_buster): assert cache_buster.salt == self.EXPECTED_HASH def test_salt_changes_on_new_file(self, static_dir): new_file = static_dir / "new_file.txt" new_file.write_text("NEW") <|code_end|> . Write the next line using the current file imports: from unittest.mock import sentinel from via.cache_buster import PathCacheBuster import pytest and context from other files: # Path: via/cache_buster.py # class PathCacheBuster: # """A cache buster which modifies paths to enable immutable caching. # # Implements `pyramid.interfaces.ICacheBuster` and can be used with # `config.add_cache_buster()` to enable rewriting of URLs to a version # which contains the last modified time. # # This allows assets to be statically cached until at least one of them has # changed. This is achieved by generating a salt value from a hash of the # files which is applied to the input URL. # # :param path: Path to static for generating the salt value # """ # # def __init__(self, path): # self.salt = self._generate_salt(path) # # def __call__(self, request, subpath, kw): # pylint: disable=invalid-name # """Prepend the salt to the path. # # Implements the ICacheBuster interface. # """ # return f"{self.salt}/{subpath}", kw # # @property # def immutable_path(self): # """Return the external URL where immutable content is accessible.""" # return f"/static/{self.salt}" # # def get_immutable_file_test(self): # """Return an immutability test for use with Whitenoise.""" # immutable_path = self.immutable_path # # def _test(_, url): # return url.startswith(immutable_path) # # return _test # # @staticmethod # def _generate_salt(path): # """Generate salt based on the last hash of all files. # # This ensures we only change salt when at least one file has changed. # """ # hasher = hashlib.md5() # # for base_dir, dirs, file_names in os.walk(path, topdown=True): # # os.walk will respect our order as long as topdown=True. This # # ensures the same iteration through the files each time # dirs.sort() # # for file_name in sorted(file_names): # with open(os.path.join(base_dir, file_name), "rb") as handle: # hasher.update(handle.read()) # # return hasher.hexdigest() , which may include functions, classes, or code. Output only the next line.
assert PathCacheBuster(static_dir).salt != self.EXPECTED_HASH
Here is a snippet: <|code_start|> class TestRequestBasedException: @pytest.mark.parametrize( "error_params,expected_string", ( ( { "status_code": 400, "reason": "Bad request", "json_data": {"test": "data", "more": "data"}, }, 'message: 400 Bad request {"test": "data", "more": "data"}', ), ( { "status_code": 401, "raw_data": "<html>HTML response text!</html>", }, "message: 401 <html>HTML response text!</html>", ), ( { "status_code": 402, }, "message: 402", ), ), ) def test_it(self, error_params, expected_string): exception = RequestBasedException( <|code_end|> . Write the next line using the current file imports: import pytest from requests.exceptions import HTTPError from tests.common.requests_exceptions import make_requests_exception from via.exceptions import RequestBasedException and context from other files: # Path: tests/common/requests_exceptions.py # def make_requests_exception( # error_class, status_code, json_data=None, raw_data=None, **response_kwargs # ): # response = Response() # response.status_code = status_code # # for key, value in response_kwargs.items(): # setattr(response, key, value) # # if raw_data: # response.raw = BytesIO(raw_data.encode("utf-8")) # # elif json_data: # response.raw = BytesIO(json.dumps(json_data).encode("utf-8")) # # return error_class(response=response) # # Path: via/exceptions.py # class RequestBasedException(Exception): # """An exception based on a requests error.""" # # def __init__(self, message, requests_err=None): # super().__init__(message) # # self.request = requests_err.request if requests_err else None # self.response = requests_err.response if requests_err else None # # def __str__(self): # string = super().__str__() # # if self.response is None: # return string # # # Log the details of the response. This goes to both Sentry and the # # application's logs. It's helpful for debugging to know how the # # external service responded. # # return " ".join( # [ # part # for part in [ # f"{string}:", # str(self.response.status_code or ""), # self.response.reason, # self.response.text, # ] # if part # ] # ) , which may include functions, classes, or code. Output only the next line.
"message", requests_err=make_requests_exception(HTTPError, **error_params)
Continue the code snippet: <|code_start|> class TestRequestBasedException: @pytest.mark.parametrize( "error_params,expected_string", ( ( { "status_code": 400, "reason": "Bad request", "json_data": {"test": "data", "more": "data"}, }, 'message: 400 Bad request {"test": "data", "more": "data"}', ), ( { "status_code": 401, "raw_data": "<html>HTML response text!</html>", }, "message: 401 <html>HTML response text!</html>", ), ( { "status_code": 402, }, "message: 402", ), ), ) def test_it(self, error_params, expected_string): <|code_end|> . Use current file imports: import pytest from requests.exceptions import HTTPError from tests.common.requests_exceptions import make_requests_exception from via.exceptions import RequestBasedException and context (classes, functions, or code) from other files: # Path: tests/common/requests_exceptions.py # def make_requests_exception( # error_class, status_code, json_data=None, raw_data=None, **response_kwargs # ): # response = Response() # response.status_code = status_code # # for key, value in response_kwargs.items(): # setattr(response, key, value) # # if raw_data: # response.raw = BytesIO(raw_data.encode("utf-8")) # # elif json_data: # response.raw = BytesIO(json.dumps(json_data).encode("utf-8")) # # return error_class(response=response) # # Path: via/exceptions.py # class RequestBasedException(Exception): # """An exception based on a requests error.""" # # def __init__(self, message, requests_err=None): # super().__init__(message) # # self.request = requests_err.request if requests_err else None # self.response = requests_err.response if requests_err else None # # def __str__(self): # string = super().__str__() # # if self.response is None: # return string # # # Log the details of the response. This goes to both Sentry and the # # application's logs. It's helpful for debugging to know how the # # external service responded. # # return " ".join( # [ # part # for part in [ # f"{string}:", # str(self.response.status_code or ""), # self.response.reason, # self.response.text, # ] # if part # ] # ) . Output only the next line.
exception = RequestBasedException(
Here is a snippet: <|code_start|> class TestIndexViews: def test_get(self, views): assert views.get() == {} def test_post(self, views, pyramid_request): pyramid_request.params["url"] = "//site.org?q1=value1&q2=value2" redirect = views.post() assert isinstance(redirect, HTTPFound) assert ( redirect.location == "http://example.com/https://site.org?q1=value1&q2=value2" ) def test_post_with_no_url(self, views, pyramid_request): assert "url" not in pyramid_request.params redirect = views.post() <|code_end|> . Write the next line using the current file imports: import pytest from pyramid.httpexceptions import HTTPFound, HTTPNotFound from tests.unit.matchers import temporary_redirect_to from via.resources import QueryURLResource from via.views.exceptions import BadURL from via.views.index import IndexViews and context from other files: # Path: tests/unit/matchers.py # def temporary_redirect_to(location): # """Return a matcher for any `HTTP 302 Found` redirect to the given URL.""" # return Any.instance_of(Response).with_attrs( # {"status_code": 302, "location": location} # ) # # Path: via/resources.py # class QueryURLResource(_URLResource): # """Resource for routes expecting urls from the query.""" # # def url_from_query(self): # """Get the 'url' parameter from the query. # # :return: The URL as a string # :raise HTTPBadRequest: If the URL is missing or empty # :raise BadURL: If the URL is malformed # """ # try: # url = self._request.params["url"].strip() # except KeyError as err: # raise HTTPBadRequest("Required parameter 'url' missing") from err # # if not url: # raise HTTPBadRequest("Required parameter 'url' is blank") # # return self._normalise_url(url) # # Path: via/views/exceptions.py # EXCEPTION_MAP = { # BadURL: { # "title": "The URL isn't valid", # "long_description": [ # "Parts of the URL could be missing or in the wrong format." # ], # "stage": "request", # "retryable": False, # }, # UpstreamTimeout: { # "title": "Timeout", # "long_description": ["The web page we tried to get took too long to respond."], # "stage": "upstream", # "retryable": True, # }, # UnhandledUpstreamException: { # "title": "Something went wrong", # "long_description": ["We experienced an unexpected error."], # "stage": "via", # "retryable": True, # }, # UpstreamServiceError: { # "title": "Could not get web page", # "long_description": [ # "Something went wrong when we tried to get the web page.", # "It might be missing or might have returned an error.", # ], # "stage": "upstream", # "retryable": True, # }, # HTTPNotFound: { # "title": "Page not found", # "long_description": [ # "The URL you asked for is not part of this service.", # "Please check the URL you have entered.", # ], # "stage": "request", # "retryable": False, # }, # HTTPClientError: { # "title": "Bad request", # "long_description": [ # "We can't process the request because we don't understand it." # ], # "stage": "request", # "retryable": False, # }, # } # def _get_meta(exception): # def google_drive_exceptions(exc, request): # def _serialise_requests_info(request, response): # def other_exceptions(exc, request): # def _get_error_body(exc, request): # def _set_status(exc, request): # # Path: via/views/index.py # class IndexViews: # def __init__(self, context, request): # self.context = context # self.request = request # self.enabled = request.registry.settings["enable_front_page"] # # @view_config(request_method="GET", renderer="via:templates/index.html.jinja2") # def get(self): # if not self.enabled: # return HTTPNotFound() # # self.request.response.headers["X-Robots-Tag"] = "all" # # return {} # # @view_config(request_method="POST") # def post(self): # if not self.enabled: # return HTTPNotFound() # # try: # url = self.context.url_from_query() # except HTTPBadRequest: # # If we don't get a URL redirect the user to the index page # return HTTPFound(self.request.route_url(route_name="index")) # # # In order to replicate the URL structure from original Via we need to # # create a path like this: # # http://via.host/http://proxied.site?query=1 # # This means we need to pop off the query string and then add it # # separately from the URL, otherwise we'll get the query string encoded # # inside the URL portion of the path. # # # `context.url_from_query` protects us from parsing failing # parsed = urlparse(url) # url_without_query = parsed._replace(query="", fragment="").geturl() # # return HTTPFound( # self.request.route_url( # route_name="proxy", url=url_without_query, _query=parsed.query # ) # ) , which may include functions, classes, or code. Output only the next line.
assert redirect == temporary_redirect_to(
Given the code snippet: <|code_start|> assert redirect == temporary_redirect_to( pyramid_request.route_url(route_name="index") ) def test_post_raises_if_url_invalid(self, views, pyramid_request): # Set a `url` that causes `urlparse` to throw. pyramid_request.params["url"] = "http://::12.34.56.78]/" with pytest.raises(BadURL): views.post() @pytest.mark.usefixtures("disable_front_page") @pytest.mark.parametrize("view", ["get", "post"]) def test_it_404s_if_the_front_page_isnt_enabled(self, view, views, pyramid_request): view = getattr(views, view) response = view() assert isinstance(response, HTTPNotFound) @pytest.fixture def disable_front_page(self, pyramid_settings): pyramid_settings["enable_front_page"] = False @pytest.fixture def views(self, context, pyramid_request): return IndexViews(context, pyramid_request) @pytest.fixture def context(self, pyramid_request): <|code_end|> , generate the next line using the imports in this file: import pytest from pyramid.httpexceptions import HTTPFound, HTTPNotFound from tests.unit.matchers import temporary_redirect_to from via.resources import QueryURLResource from via.views.exceptions import BadURL from via.views.index import IndexViews and context (functions, classes, or occasionally code) from other files: # Path: tests/unit/matchers.py # def temporary_redirect_to(location): # """Return a matcher for any `HTTP 302 Found` redirect to the given URL.""" # return Any.instance_of(Response).with_attrs( # {"status_code": 302, "location": location} # ) # # Path: via/resources.py # class QueryURLResource(_URLResource): # """Resource for routes expecting urls from the query.""" # # def url_from_query(self): # """Get the 'url' parameter from the query. # # :return: The URL as a string # :raise HTTPBadRequest: If the URL is missing or empty # :raise BadURL: If the URL is malformed # """ # try: # url = self._request.params["url"].strip() # except KeyError as err: # raise HTTPBadRequest("Required parameter 'url' missing") from err # # if not url: # raise HTTPBadRequest("Required parameter 'url' is blank") # # return self._normalise_url(url) # # Path: via/views/exceptions.py # EXCEPTION_MAP = { # BadURL: { # "title": "The URL isn't valid", # "long_description": [ # "Parts of the URL could be missing or in the wrong format." # ], # "stage": "request", # "retryable": False, # }, # UpstreamTimeout: { # "title": "Timeout", # "long_description": ["The web page we tried to get took too long to respond."], # "stage": "upstream", # "retryable": True, # }, # UnhandledUpstreamException: { # "title": "Something went wrong", # "long_description": ["We experienced an unexpected error."], # "stage": "via", # "retryable": True, # }, # UpstreamServiceError: { # "title": "Could not get web page", # "long_description": [ # "Something went wrong when we tried to get the web page.", # "It might be missing or might have returned an error.", # ], # "stage": "upstream", # "retryable": True, # }, # HTTPNotFound: { # "title": "Page not found", # "long_description": [ # "The URL you asked for is not part of this service.", # "Please check the URL you have entered.", # ], # "stage": "request", # "retryable": False, # }, # HTTPClientError: { # "title": "Bad request", # "long_description": [ # "We can't process the request because we don't understand it." # ], # "stage": "request", # "retryable": False, # }, # } # def _get_meta(exception): # def google_drive_exceptions(exc, request): # def _serialise_requests_info(request, response): # def other_exceptions(exc, request): # def _get_error_body(exc, request): # def _set_status(exc, request): # # Path: via/views/index.py # class IndexViews: # def __init__(self, context, request): # self.context = context # self.request = request # self.enabled = request.registry.settings["enable_front_page"] # # @view_config(request_method="GET", renderer="via:templates/index.html.jinja2") # def get(self): # if not self.enabled: # return HTTPNotFound() # # self.request.response.headers["X-Robots-Tag"] = "all" # # return {} # # @view_config(request_method="POST") # def post(self): # if not self.enabled: # return HTTPNotFound() # # try: # url = self.context.url_from_query() # except HTTPBadRequest: # # If we don't get a URL redirect the user to the index page # return HTTPFound(self.request.route_url(route_name="index")) # # # In order to replicate the URL structure from original Via we need to # # create a path like this: # # http://via.host/http://proxied.site?query=1 # # This means we need to pop off the query string and then add it # # separately from the URL, otherwise we'll get the query string encoded # # inside the URL portion of the path. # # # `context.url_from_query` protects us from parsing failing # parsed = urlparse(url) # url_without_query = parsed._replace(query="", fragment="").geturl() # # return HTTPFound( # self.request.route_url( # route_name="proxy", url=url_without_query, _query=parsed.query # ) # ) . Output only the next line.
return QueryURLResource(pyramid_request)
Based on the snippet: <|code_start|> class TestIndexViews: def test_get(self, views): assert views.get() == {} def test_post(self, views, pyramid_request): pyramid_request.params["url"] = "//site.org?q1=value1&q2=value2" redirect = views.post() assert isinstance(redirect, HTTPFound) assert ( redirect.location == "http://example.com/https://site.org?q1=value1&q2=value2" ) def test_post_with_no_url(self, views, pyramid_request): assert "url" not in pyramid_request.params redirect = views.post() assert redirect == temporary_redirect_to( pyramid_request.route_url(route_name="index") ) def test_post_raises_if_url_invalid(self, views, pyramid_request): # Set a `url` that causes `urlparse` to throw. pyramid_request.params["url"] = "http://::12.34.56.78]/" <|code_end|> , predict the immediate next line with the help of imports: import pytest from pyramid.httpexceptions import HTTPFound, HTTPNotFound from tests.unit.matchers import temporary_redirect_to from via.resources import QueryURLResource from via.views.exceptions import BadURL from via.views.index import IndexViews and context (classes, functions, sometimes code) from other files: # Path: tests/unit/matchers.py # def temporary_redirect_to(location): # """Return a matcher for any `HTTP 302 Found` redirect to the given URL.""" # return Any.instance_of(Response).with_attrs( # {"status_code": 302, "location": location} # ) # # Path: via/resources.py # class QueryURLResource(_URLResource): # """Resource for routes expecting urls from the query.""" # # def url_from_query(self): # """Get the 'url' parameter from the query. # # :return: The URL as a string # :raise HTTPBadRequest: If the URL is missing or empty # :raise BadURL: If the URL is malformed # """ # try: # url = self._request.params["url"].strip() # except KeyError as err: # raise HTTPBadRequest("Required parameter 'url' missing") from err # # if not url: # raise HTTPBadRequest("Required parameter 'url' is blank") # # return self._normalise_url(url) # # Path: via/views/exceptions.py # EXCEPTION_MAP = { # BadURL: { # "title": "The URL isn't valid", # "long_description": [ # "Parts of the URL could be missing or in the wrong format." # ], # "stage": "request", # "retryable": False, # }, # UpstreamTimeout: { # "title": "Timeout", # "long_description": ["The web page we tried to get took too long to respond."], # "stage": "upstream", # "retryable": True, # }, # UnhandledUpstreamException: { # "title": "Something went wrong", # "long_description": ["We experienced an unexpected error."], # "stage": "via", # "retryable": True, # }, # UpstreamServiceError: { # "title": "Could not get web page", # "long_description": [ # "Something went wrong when we tried to get the web page.", # "It might be missing or might have returned an error.", # ], # "stage": "upstream", # "retryable": True, # }, # HTTPNotFound: { # "title": "Page not found", # "long_description": [ # "The URL you asked for is not part of this service.", # "Please check the URL you have entered.", # ], # "stage": "request", # "retryable": False, # }, # HTTPClientError: { # "title": "Bad request", # "long_description": [ # "We can't process the request because we don't understand it." # ], # "stage": "request", # "retryable": False, # }, # } # def _get_meta(exception): # def google_drive_exceptions(exc, request): # def _serialise_requests_info(request, response): # def other_exceptions(exc, request): # def _get_error_body(exc, request): # def _set_status(exc, request): # # Path: via/views/index.py # class IndexViews: # def __init__(self, context, request): # self.context = context # self.request = request # self.enabled = request.registry.settings["enable_front_page"] # # @view_config(request_method="GET", renderer="via:templates/index.html.jinja2") # def get(self): # if not self.enabled: # return HTTPNotFound() # # self.request.response.headers["X-Robots-Tag"] = "all" # # return {} # # @view_config(request_method="POST") # def post(self): # if not self.enabled: # return HTTPNotFound() # # try: # url = self.context.url_from_query() # except HTTPBadRequest: # # If we don't get a URL redirect the user to the index page # return HTTPFound(self.request.route_url(route_name="index")) # # # In order to replicate the URL structure from original Via we need to # # create a path like this: # # http://via.host/http://proxied.site?query=1 # # This means we need to pop off the query string and then add it # # separately from the URL, otherwise we'll get the query string encoded # # inside the URL portion of the path. # # # `context.url_from_query` protects us from parsing failing # parsed = urlparse(url) # url_without_query = parsed._replace(query="", fragment="").geturl() # # return HTTPFound( # self.request.route_url( # route_name="proxy", url=url_without_query, _query=parsed.query # ) # ) . Output only the next line.
with pytest.raises(BadURL):
Using the snippet: <|code_start|> assert "url" not in pyramid_request.params redirect = views.post() assert redirect == temporary_redirect_to( pyramid_request.route_url(route_name="index") ) def test_post_raises_if_url_invalid(self, views, pyramid_request): # Set a `url` that causes `urlparse` to throw. pyramid_request.params["url"] = "http://::12.34.56.78]/" with pytest.raises(BadURL): views.post() @pytest.mark.usefixtures("disable_front_page") @pytest.mark.parametrize("view", ["get", "post"]) def test_it_404s_if_the_front_page_isnt_enabled(self, view, views, pyramid_request): view = getattr(views, view) response = view() assert isinstance(response, HTTPNotFound) @pytest.fixture def disable_front_page(self, pyramid_settings): pyramid_settings["enable_front_page"] = False @pytest.fixture def views(self, context, pyramid_request): <|code_end|> , determine the next line of code. You have imports: import pytest from pyramid.httpexceptions import HTTPFound, HTTPNotFound from tests.unit.matchers import temporary_redirect_to from via.resources import QueryURLResource from via.views.exceptions import BadURL from via.views.index import IndexViews and context (class names, function names, or code) available: # Path: tests/unit/matchers.py # def temporary_redirect_to(location): # """Return a matcher for any `HTTP 302 Found` redirect to the given URL.""" # return Any.instance_of(Response).with_attrs( # {"status_code": 302, "location": location} # ) # # Path: via/resources.py # class QueryURLResource(_URLResource): # """Resource for routes expecting urls from the query.""" # # def url_from_query(self): # """Get the 'url' parameter from the query. # # :return: The URL as a string # :raise HTTPBadRequest: If the URL is missing or empty # :raise BadURL: If the URL is malformed # """ # try: # url = self._request.params["url"].strip() # except KeyError as err: # raise HTTPBadRequest("Required parameter 'url' missing") from err # # if not url: # raise HTTPBadRequest("Required parameter 'url' is blank") # # return self._normalise_url(url) # # Path: via/views/exceptions.py # EXCEPTION_MAP = { # BadURL: { # "title": "The URL isn't valid", # "long_description": [ # "Parts of the URL could be missing or in the wrong format." # ], # "stage": "request", # "retryable": False, # }, # UpstreamTimeout: { # "title": "Timeout", # "long_description": ["The web page we tried to get took too long to respond."], # "stage": "upstream", # "retryable": True, # }, # UnhandledUpstreamException: { # "title": "Something went wrong", # "long_description": ["We experienced an unexpected error."], # "stage": "via", # "retryable": True, # }, # UpstreamServiceError: { # "title": "Could not get web page", # "long_description": [ # "Something went wrong when we tried to get the web page.", # "It might be missing or might have returned an error.", # ], # "stage": "upstream", # "retryable": True, # }, # HTTPNotFound: { # "title": "Page not found", # "long_description": [ # "The URL you asked for is not part of this service.", # "Please check the URL you have entered.", # ], # "stage": "request", # "retryable": False, # }, # HTTPClientError: { # "title": "Bad request", # "long_description": [ # "We can't process the request because we don't understand it." # ], # "stage": "request", # "retryable": False, # }, # } # def _get_meta(exception): # def google_drive_exceptions(exc, request): # def _serialise_requests_info(request, response): # def other_exceptions(exc, request): # def _get_error_body(exc, request): # def _set_status(exc, request): # # Path: via/views/index.py # class IndexViews: # def __init__(self, context, request): # self.context = context # self.request = request # self.enabled = request.registry.settings["enable_front_page"] # # @view_config(request_method="GET", renderer="via:templates/index.html.jinja2") # def get(self): # if not self.enabled: # return HTTPNotFound() # # self.request.response.headers["X-Robots-Tag"] = "all" # # return {} # # @view_config(request_method="POST") # def post(self): # if not self.enabled: # return HTTPNotFound() # # try: # url = self.context.url_from_query() # except HTTPBadRequest: # # If we don't get a URL redirect the user to the index page # return HTTPFound(self.request.route_url(route_name="index")) # # # In order to replicate the URL structure from original Via we need to # # create a path like this: # # http://via.host/http://proxied.site?query=1 # # This means we need to pop off the query string and then add it # # separately from the URL, otherwise we'll get the query string encoded # # inside the URL portion of the path. # # # `context.url_from_query` protects us from parsing failing # parsed = urlparse(url) # url_without_query = parsed._replace(query="", fragment="").geturl() # # return HTTPFound( # self.request.route_url( # route_name="proxy", url=url_without_query, _query=parsed.query # ) # ) . Output only the next line.
return IndexViews(context, pyramid_request)
Predict the next line after this snippet: <|code_start|> @pytest.mark.parametrize( "url,expected_redirect_location", [ # When you submit the form on the front page it redirects you to the # page that will proxy the URL that you entered. ( "https://example.com/foo/", "http://localhost/https://example.com/foo/", ), ( "http://example.com/foo/", "http://localhost/http://example.com/foo/", ), # The submitted URL is normalized to strip leading/trailing spaces and # add a protocol. ( "example.com/foo/", "http://localhost/https://example.com/foo/", ), # If you submit an empty form it just reloads the front page again. ("", "http://localhost/"), ], ) def test_index(test_app, url, expected_redirect_location): form = test_app.get("/").form form.set("url", url) response = form.submit() <|code_end|> using the current file's imports: import pytest from tests.functional.matchers import temporary_redirect_to and any relevant context from other files: # Path: tests/functional/matchers.py # def temporary_redirect_to(location): # """Return a matcher for any `HTTP 302 Found` redirect to the given URL.""" # return Any.instance_of(TestResponse).with_attrs( # {"status_code": 302, "location": location} # ) . Output only the next line.
assert response == temporary_redirect_to(expected_redirect_location)
Here is a snippet: <|code_start|> DEFAULT_ERROR_MAP = { exceptions.MissingSchema: BadURL, exceptions.InvalidSchema: BadURL, exceptions.InvalidURL: BadURL, exceptions.URLRequired: BadURL, exceptions.Timeout: UpstreamTimeout, exceptions.ConnectionError: UpstreamServiceError, exceptions.TooManyRedirects: UpstreamServiceError, exceptions.SSLError: UpstreamServiceError, <|code_end|> . Write the next line using the current file imports: import requests from requests import RequestException, exceptions from via.exceptions import ( BadURL, UnhandledUpstreamException, UpstreamServiceError, UpstreamTimeout, ) and context from other files: # Path: via/exceptions.py # class BadURL(RequestBasedException): # """An invalid URL was discovered.""" # # def __init__(self, message, requests_err=None, url=None): # super().__init__(message, requests_err) # self.url = url # # status_int = 400 # # class UnhandledUpstreamException(UpstreamServiceError): # """Something we did not plan for went wrong.""" # # status_int = 417 # # class UpstreamServiceError(RequestBasedException): # """Something went wrong when calling an upstream service.""" # # status_int = 409 # # class UpstreamTimeout(UpstreamServiceError): # """We timed out waiting for an upstream service.""" # # # "504 - Gateway Timeout" is the correct thing to raise, but this # # will cause Cloudflare to intercept it: # # https://support.cloudflare.com/hc/en-us/articles/115003011431-Troubleshooting-Cloudflare-5XX-errors#502504error # # We're using "408 - Request Timeout" which is technically # # incorrect as it implies the user took too long, but has good semantics # status_int = 408 , which may include functions, classes, or code. Output only the next line.
RequestException: UnhandledUpstreamException,
Continue the code snippet: <|code_start|> DEFAULT_ERROR_MAP = { exceptions.MissingSchema: BadURL, exceptions.InvalidSchema: BadURL, exceptions.InvalidURL: BadURL, exceptions.URLRequired: BadURL, exceptions.Timeout: UpstreamTimeout, <|code_end|> . Use current file imports: import requests from requests import RequestException, exceptions from via.exceptions import ( BadURL, UnhandledUpstreamException, UpstreamServiceError, UpstreamTimeout, ) and context (classes, functions, or code) from other files: # Path: via/exceptions.py # class BadURL(RequestBasedException): # """An invalid URL was discovered.""" # # def __init__(self, message, requests_err=None, url=None): # super().__init__(message, requests_err) # self.url = url # # status_int = 400 # # class UnhandledUpstreamException(UpstreamServiceError): # """Something we did not plan for went wrong.""" # # status_int = 417 # # class UpstreamServiceError(RequestBasedException): # """Something went wrong when calling an upstream service.""" # # status_int = 409 # # class UpstreamTimeout(UpstreamServiceError): # """We timed out waiting for an upstream service.""" # # # "504 - Gateway Timeout" is the correct thing to raise, but this # # will cause Cloudflare to intercept it: # # https://support.cloudflare.com/hc/en-us/articles/115003011431-Troubleshooting-Cloudflare-5XX-errors#502504error # # We're using "408 - Request Timeout" which is technically # # incorrect as it implies the user took too long, but has good semantics # status_int = 408 . Output only the next line.
exceptions.ConnectionError: UpstreamServiceError,
Given the code snippet: <|code_start|> DEFAULT_ERROR_MAP = { exceptions.MissingSchema: BadURL, exceptions.InvalidSchema: BadURL, exceptions.InvalidURL: BadURL, exceptions.URLRequired: BadURL, <|code_end|> , generate the next line using the imports in this file: import requests from requests import RequestException, exceptions from via.exceptions import ( BadURL, UnhandledUpstreamException, UpstreamServiceError, UpstreamTimeout, ) and context (functions, classes, or occasionally code) from other files: # Path: via/exceptions.py # class BadURL(RequestBasedException): # """An invalid URL was discovered.""" # # def __init__(self, message, requests_err=None, url=None): # super().__init__(message, requests_err) # self.url = url # # status_int = 400 # # class UnhandledUpstreamException(UpstreamServiceError): # """Something we did not plan for went wrong.""" # # status_int = 417 # # class UpstreamServiceError(RequestBasedException): # """Something went wrong when calling an upstream service.""" # # status_int = 409 # # class UpstreamTimeout(UpstreamServiceError): # """We timed out waiting for an upstream service.""" # # # "504 - Gateway Timeout" is the correct thing to raise, but this # # will cause Cloudflare to intercept it: # # https://support.cloudflare.com/hc/en-us/articles/115003011431-Troubleshooting-Cloudflare-5XX-errors#502504error # # We're using "408 - Request Timeout" which is technically # # incorrect as it implies the user took too long, but has good semantics # status_int = 408 . Output only the next line.
exceptions.Timeout: UpstreamTimeout,
Given the following code snippet before the placeholder: <|code_start|> sids : list of values representing simulated internal sids start : start date delta : timedelta between internal events filter : filter to remove the sids """ def __init__(self, data, **kwargs): """ Data must be a DataFrame formatted like this: ################################################################################################# # # GS # TW # # # N10 # H10 # G14 # H14 # # # Price # Volume # Price # Volume # Price # Metric3 # Price # Metric3 # # 2013-12-20 00:09:15 # 101.00 # 1000 # 60.34 # 2500 # 400.00 # -0.0034 # Price # -5.0 # # 2013-12-20 00:09:17 # 201.00 # 2000 # 20.34 # 2500 # 200.00 # -2.0034 # Price # -2.0 # # etc... # ################################################################################################# """ assert isinstance(data.index, pd.tseries.index.DatetimeIndex) self.data = data # Unpack config dictionary with default values. self.sids = kwargs.get('sids', list(set(['.'.join(tup[:2]) for tup in data.columns]))) self.start = kwargs.get('start', data.index[0]) self.end = kwargs.get('end', data.index[-1]) # Hash_value for downstream sorting. <|code_end|> , predict the next line using imports from the current file: import pandas as pd from alephnull.gens.utils import hash_args from alephnull.sources.data_source import DataSource and context including class names, function names, and sometimes code from other files: # Path: alephnull/gens/utils.py # def hash_args(*args, **kwargs): # """Define a unique string for any set of representable args.""" # arg_string = '_'.join([str(arg) for arg in args]) # kwarg_string = '_'.join([str(key) + '=' + str(value) # for key, value in kwargs.iteritems()]) # combined = ':'.join([arg_string, kwarg_string]) # # hasher = md5() # hasher.update(combined) # return hasher.hexdigest() # # Path: alephnull/sources/data_source.py # class DataSource(object): # # __metaclass__ = ABCMeta # # @property # def event_type(self): # return DATASOURCE_TYPE.TRADE # # @property # def mapping(self): # """ # Mappings of the form: # target_key: (mapping_function, source_key) # """ # return {} # # @abstractproperty # def raw_data(self): # """ # An iterator that yields the raw datasource, # in chronological order of data, one event at a time. # """ # NotImplemented # # @abstractproperty # def instance_hash(self): # """ # A hash that represents the unique args to the source. # """ # pass # # def get_hash(self): # return self.__class__.__name__ + "-" + self.instance_hash # # def apply_mapping(self, raw_row): # """ # Override this to hand craft conversion of row. # """ # row = {target: mapping_func(raw_row[source_key]) # for target, (mapping_func, source_key) # in self.mapping.items()} # row.update({'source_id': self.get_hash()}) # row.update({'type': self.event_type}) # return row # # @property # def mapped_data(self): # for row in self.raw_data: # yield Event(self.apply_mapping(row)) # # def __iter__(self): # return self # # def next(self): # return self.mapped_data.next() . Output only the next line.
self.arg_string = hash_args(data, **kwargs)
Based on the snippet: <|code_start|> class DataSource(object): __metaclass__ = ABCMeta @property def event_type(self): <|code_end|> , predict the immediate next line with the help of imports: from abc import ( ABCMeta, abstractproperty ) from alephnull.protocol import DATASOURCE_TYPE from alephnull.protocol import Event and context (classes, functions, sometimes code) from other files: # Path: alephnull/protocol.py # DATASOURCE_TYPE = Enum( # 'AS_TRADED_EQUITY', # 'MERGER', # 'SPLIT', # 'DIVIDEND', # 'TRADE', # 'TRANSACTION', # 'ORDER', # 'EMPTY', # 'DONE', # 'CUSTOM', # 'BENCHMARK', # 'COMMISSION' # ) # # Path: alephnull/protocol.py # class Event(object): # # def __init__(self, initial_values=None): # if initial_values: # self.__dict__ = initial_values # # def __getitem__(self, name): # return getattr(self, name) # # def __setitem__(self, name, value): # setattr(self, name, value) # # def __delitem__(self, name): # delattr(self, name) # # def keys(self): # return self.__dict__.keys() # # def __eq__(self, other): # return self.__dict__ == other.__dict__ # # def __contains__(self, name): # return name in self.__dict__ # # def __repr__(self): # return "Event({0})".format(self.__dict__) . Output only the next line.
return DATASOURCE_TYPE.TRADE
Using the snippet: <|code_start|> """ An iterator that yields the raw datasource, in chronological order of data, one event at a time. """ NotImplemented @abstractproperty def instance_hash(self): """ A hash that represents the unique args to the source. """ pass def get_hash(self): return self.__class__.__name__ + "-" + self.instance_hash def apply_mapping(self, raw_row): """ Override this to hand craft conversion of row. """ row = {target: mapping_func(raw_row[source_key]) for target, (mapping_func, source_key) in self.mapping.items()} row.update({'source_id': self.get_hash()}) row.update({'type': self.event_type}) return row @property def mapped_data(self): for row in self.raw_data: <|code_end|> , determine the next line of code. You have imports: from abc import ( ABCMeta, abstractproperty ) from alephnull.protocol import DATASOURCE_TYPE from alephnull.protocol import Event and context (class names, function names, or code) available: # Path: alephnull/protocol.py # DATASOURCE_TYPE = Enum( # 'AS_TRADED_EQUITY', # 'MERGER', # 'SPLIT', # 'DIVIDEND', # 'TRADE', # 'TRANSACTION', # 'ORDER', # 'EMPTY', # 'DONE', # 'CUSTOM', # 'BENCHMARK', # 'COMMISSION' # ) # # Path: alephnull/protocol.py # class Event(object): # # def __init__(self, initial_values=None): # if initial_values: # self.__dict__ = initial_values # # def __getitem__(self, name): # return getattr(self, name) # # def __setitem__(self, name, value): # setattr(self, name, value) # # def __delitem__(self, name): # delattr(self, name) # # def keys(self): # return self.__dict__.keys() # # def __eq__(self, other): # return self.__dict__ == other.__dict__ # # def __contains__(self, name): # return name in self.__dict__ # # def __repr__(self): # return "Event({0})".format(self.__dict__) . Output only the next line.
yield Event(self.apply_mapping(row))
Predict the next line for this snippet: <|code_start|># # Copyright 2013 Quantopian, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ A source to be used in testing. """ def create_trade(sid, price, amount, datetime, source_id="test_factory"): trade = Event() trade.source_id = source_id <|code_end|> with the help of current file imports: import pytz import numpy as np from itertools import cycle, ifilter, izip from datetime import datetime, timedelta from alephnull.protocol import ( Event, DATASOURCE_TYPE ) from alephnull.gens.utils import hash_args from alephnull.utils.tradingcalendar import trading_days and context from other files: # Path: alephnull/protocol.py # class Event(object): # # def __init__(self, initial_values=None): # if initial_values: # self.__dict__ = initial_values # # def __getitem__(self, name): # return getattr(self, name) # # def __setitem__(self, name, value): # setattr(self, name, value) # # def __delitem__(self, name): # delattr(self, name) # # def keys(self): # return self.__dict__.keys() # # def __eq__(self, other): # return self.__dict__ == other.__dict__ # # def __contains__(self, name): # return name in self.__dict__ # # def __repr__(self): # return "Event({0})".format(self.__dict__) # # DATASOURCE_TYPE = Enum( # 'AS_TRADED_EQUITY', # 'MERGER', # 'SPLIT', # 'DIVIDEND', # 'TRADE', # 'TRANSACTION', # 'ORDER', # 'EMPTY', # 'DONE', # 'CUSTOM', # 'BENCHMARK', # 'COMMISSION' # ) # # Path: alephnull/gens/utils.py # def hash_args(*args, **kwargs): # """Define a unique string for any set of representable args.""" # arg_string = '_'.join([str(arg) for arg in args]) # kwarg_string = '_'.join([str(key) + '=' + str(value) # for key, value in kwargs.iteritems()]) # combined = ':'.join([arg_string, kwarg_string]) # # hasher = md5() # hasher.update(combined) # return hasher.hexdigest() , which may contain function names, class names, or code. Output only the next line.
trade.type = DATASOURCE_TYPE.TRADE
Given snippet: <|code_start|> if self.event_list is not None: # If event_list is provided, extract parameters from there # This isn't really clean and ultimately I think this # class should serve a single purpose (either take an # event_list or autocreate events). self.count = kwargs.get('count', len(self.event_list)) self.sids = kwargs.get( 'sids', np.unique([event.sid for event in self.event_list]).tolist()) self.start = kwargs.get('start', self.event_list[0].dt) self.end = kwargs.get('start', self.event_list[-1].dt) self.delta = kwargs.get( 'delta', self.event_list[1].dt - self.event_list[0].dt) self.concurrent = kwargs.get('concurrent', False) else: # Unpack config dictionary with default values. self.count = kwargs.get('count', 500) self.sids = kwargs.get('sids', [1, 2]) self.start = kwargs.get( 'start', datetime(2008, 6, 6, 15, tzinfo=pytz.utc)) self.delta = kwargs.get( 'delta', timedelta(minutes=1)) self.concurrent = kwargs.get('concurrent', False) # Hash_value for downstream sorting. <|code_end|> , continue by predicting the next line. Consider current file imports: import pytz import numpy as np from itertools import cycle, ifilter, izip from datetime import datetime, timedelta from alephnull.protocol import ( Event, DATASOURCE_TYPE ) from alephnull.gens.utils import hash_args from alephnull.utils.tradingcalendar import trading_days and context: # Path: alephnull/protocol.py # class Event(object): # # def __init__(self, initial_values=None): # if initial_values: # self.__dict__ = initial_values # # def __getitem__(self, name): # return getattr(self, name) # # def __setitem__(self, name, value): # setattr(self, name, value) # # def __delitem__(self, name): # delattr(self, name) # # def keys(self): # return self.__dict__.keys() # # def __eq__(self, other): # return self.__dict__ == other.__dict__ # # def __contains__(self, name): # return name in self.__dict__ # # def __repr__(self): # return "Event({0})".format(self.__dict__) # # DATASOURCE_TYPE = Enum( # 'AS_TRADED_EQUITY', # 'MERGER', # 'SPLIT', # 'DIVIDEND', # 'TRADE', # 'TRANSACTION', # 'ORDER', # 'EMPTY', # 'DONE', # 'CUSTOM', # 'BENCHMARK', # 'COMMISSION' # ) # # Path: alephnull/gens/utils.py # def hash_args(*args, **kwargs): # """Define a unique string for any set of representable args.""" # arg_string = '_'.join([str(arg) for arg in args]) # kwarg_string = '_'.join([str(key) + '=' + str(value) # for key, value in kwargs.iteritems()]) # combined = ':'.join([arg_string, kwarg_string]) # # hasher = md5() # hasher.update(combined) # return hasher.hexdigest() which might include code, classes, or functions. Output only the next line.
self.arg_string = hash_args(*args, **kwargs)
Given the following code snippet before the placeholder: <|code_start|> Factory method for self.sid_windows. """ return MovingStandardDevWindow( self.market_aware, self.window_length, self.delta ) def update(self, event): """ Update the event window for this event's sid. Return a dict from tracked fields to moving averages. """ # This will create a new EventWindow if this is the first # message for this sid. window = self.sid_windows[event.sid] window.update(event) return window.get_stddev() def assert_required_fields(self, event): """ We only allow events with a price field to be run through the returns transform. """ if 'price' not in event: raise WrongDataForTransform( transform="StdDevEventWindow", fields='price') <|code_end|> , predict the next line using imports from the current file: from collections import defaultdict from math import sqrt from alephnull.errors import WrongDataForTransform from alephnull.transforms.utils import EventWindow, TransformMeta import alephnull.utils.math_utils as zp_math and context including class names, function names, and sometimes code from other files: # Path: alephnull/transforms/utils.py # class EventWindow(object): # """ # Abstract base class for transform classes that calculate iterative # metrics on events within a given timedelta. Maintains a list of # events that are within a certain timedelta of the most recent # tick. Calls self.handle_add(event) for each event added to the # window. Calls self.handle_remove(event) for each event removed # from the window. Subclass these methods along with init(*args, # **kwargs) to calculate metrics over the window. # # If the market_aware flag is True, the EventWindow drops old events # based on the number of elapsed trading days between newest and oldest. # Otherwise old events are dropped based on a raw timedelta. # # See zipline/transforms/mavg.py and zipline/transforms/vwap.py for example # implementations of moving average and volume-weighted average # price. # """ # # Mark this as an abstract base class. # __metaclass__ = ABCMeta # # def __init__(self, market_aware=True, window_length=None, delta=None): # # check_window_length(window_length) # self.window_length = window_length # # self.ticks = deque() # # # Only Market-aware mode is now supported. # if not market_aware: # raise UnsupportedEventWindowFlagValue( # "Non-'market aware' mode is no longer supported." # ) # if delta: # raise UnsupportedEventWindowFlagValue( # "delta values are no longer supported." # ) # # Set the behavior for dropping events from the back of the # # event window. # self.drop_condition = self.out_of_market_window # # @abstractmethod # def handle_add(self, event): # raise NotImplementedError() # # @abstractmethod # def handle_remove(self, event): # raise NotImplementedError() # # def __len__(self): # return len(self.ticks) # # def update(self, event): # # if (hasattr(event, 'type') # and event.type not in ( # DATASOURCE_TYPE.TRADE, # DATASOURCE_TYPE.CUSTOM)): # return # # self.assert_well_formed(event) # # Add new event and increment totals. # self.ticks.append(event) # # # Subclasses should override handle_add to define behavior for # # adding new ticks. # self.handle_add(event) # # Clear out any expired events. # # # # oldest newest # # | | # # V V # while self.drop_condition(self.ticks[0].dt, self.ticks[-1].dt): # # # popleft removes and returns the oldest tick in self.ticks # popped = self.ticks.popleft() # # # Subclasses should override handle_remove to define # # behavior for removing ticks. # self.handle_remove(popped) # # def out_of_market_window(self, oldest, newest): # oldest_index = \ # trading.environment.trading_days.searchsorted(oldest) # newest_index = \ # trading.environment.trading_days.searchsorted(newest) # # trading_days_between = newest_index - oldest_index # # # "Put back" a day if oldest is earlier in its day than newest, # # reflecting the fact that we haven't yet completed the last # # day in the window. # if oldest.time() > newest.time(): # trading_days_between -= 1 # # return trading_days_between >= self.window_length # # # All event windows expect to receive events with datetime fields # # that arrive in sorted order. # def assert_well_formed(self, event): # assert isinstance(event.dt, datetime), \ # "Bad dt in EventWindow:%s" % event # if len(self.ticks) > 0: # # Something is wrong if new event is older than previous. # assert event.dt >= self.ticks[-1].dt, \ # "Events arrived out of order in EventWindow: %s -> %s" % \ # (event, self.ticks[0]) # # class TransformMeta(type): # """ # Metaclass that automatically packages a class inside of # StatefulTransform on initialization. Specifically, if Foo is a # class with its __metaclass__ attribute set to TransformMeta, then # calling Foo(*args, **kwargs) will return StatefulTransform(Foo, # *args, **kwargs) instead of an instance of Foo. (Note that you can # still recover an instance of a "raw" Foo by introspecting the # resulting StatefulTransform's 'state' field.) # """ # # def __call__(cls, *args, **kwargs): # return StatefulTransform(cls, *args, **kwargs) . Output only the next line.
class MovingStandardDevWindow(EventWindow):
Based on the snippet: <|code_start|># # Copyright 2013 Quantopian, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. class MovingStandardDev(object): """ Class that maintains a dictionary from sids to MovingStandardDevWindows. For each sid, we maintain a the standard deviation of all events falling within the specified window. """ <|code_end|> , predict the immediate next line with the help of imports: from collections import defaultdict from math import sqrt from alephnull.errors import WrongDataForTransform from alephnull.transforms.utils import EventWindow, TransformMeta import alephnull.utils.math_utils as zp_math and context (classes, functions, sometimes code) from other files: # Path: alephnull/transforms/utils.py # class EventWindow(object): # """ # Abstract base class for transform classes that calculate iterative # metrics on events within a given timedelta. Maintains a list of # events that are within a certain timedelta of the most recent # tick. Calls self.handle_add(event) for each event added to the # window. Calls self.handle_remove(event) for each event removed # from the window. Subclass these methods along with init(*args, # **kwargs) to calculate metrics over the window. # # If the market_aware flag is True, the EventWindow drops old events # based on the number of elapsed trading days between newest and oldest. # Otherwise old events are dropped based on a raw timedelta. # # See zipline/transforms/mavg.py and zipline/transforms/vwap.py for example # implementations of moving average and volume-weighted average # price. # """ # # Mark this as an abstract base class. # __metaclass__ = ABCMeta # # def __init__(self, market_aware=True, window_length=None, delta=None): # # check_window_length(window_length) # self.window_length = window_length # # self.ticks = deque() # # # Only Market-aware mode is now supported. # if not market_aware: # raise UnsupportedEventWindowFlagValue( # "Non-'market aware' mode is no longer supported." # ) # if delta: # raise UnsupportedEventWindowFlagValue( # "delta values are no longer supported." # ) # # Set the behavior for dropping events from the back of the # # event window. # self.drop_condition = self.out_of_market_window # # @abstractmethod # def handle_add(self, event): # raise NotImplementedError() # # @abstractmethod # def handle_remove(self, event): # raise NotImplementedError() # # def __len__(self): # return len(self.ticks) # # def update(self, event): # # if (hasattr(event, 'type') # and event.type not in ( # DATASOURCE_TYPE.TRADE, # DATASOURCE_TYPE.CUSTOM)): # return # # self.assert_well_formed(event) # # Add new event and increment totals. # self.ticks.append(event) # # # Subclasses should override handle_add to define behavior for # # adding new ticks. # self.handle_add(event) # # Clear out any expired events. # # # # oldest newest # # | | # # V V # while self.drop_condition(self.ticks[0].dt, self.ticks[-1].dt): # # # popleft removes and returns the oldest tick in self.ticks # popped = self.ticks.popleft() # # # Subclasses should override handle_remove to define # # behavior for removing ticks. # self.handle_remove(popped) # # def out_of_market_window(self, oldest, newest): # oldest_index = \ # trading.environment.trading_days.searchsorted(oldest) # newest_index = \ # trading.environment.trading_days.searchsorted(newest) # # trading_days_between = newest_index - oldest_index # # # "Put back" a day if oldest is earlier in its day than newest, # # reflecting the fact that we haven't yet completed the last # # day in the window. # if oldest.time() > newest.time(): # trading_days_between -= 1 # # return trading_days_between >= self.window_length # # # All event windows expect to receive events with datetime fields # # that arrive in sorted order. # def assert_well_formed(self, event): # assert isinstance(event.dt, datetime), \ # "Bad dt in EventWindow:%s" % event # if len(self.ticks) > 0: # # Something is wrong if new event is older than previous. # assert event.dt >= self.ticks[-1].dt, \ # "Events arrived out of order in EventWindow: %s -> %s" % \ # (event, self.ticks[0]) # # class TransformMeta(type): # """ # Metaclass that automatically packages a class inside of # StatefulTransform on initialization. Specifically, if Foo is a # class with its __metaclass__ attribute set to TransformMeta, then # calling Foo(*args, **kwargs) will return StatefulTransform(Foo, # *args, **kwargs) instead of an instance of Foo. (Note that you can # still recover an instance of a "raw" Foo by introspecting the # resulting StatefulTransform's 'state' field.) # """ # # def __call__(cls, *args, **kwargs): # return StatefulTransform(cls, *args, **kwargs) . Output only the next line.
__metaclass__ = TransformMeta
Based on the snippet: <|code_start|> This is intended to be wrapped in a partial, so that the slippage and commission models can be enclosed. """ for order, transaction in slippage(event, open_orders): if ( transaction and not zp_math.tolerant_equals(transaction.amount, 0) ): direction = math.copysign(1, transaction.amount) per_share, total_commission = commission.calculate(transaction) transaction.price = transaction.price + (per_share * direction) transaction.commission = total_commission yield order, transaction def transact_partial(slippage, commission): return partial(transact_stub, slippage, commission) class Transaction(object): def __init__(self, sid, amount, dt, price, order_id=None, commission=None, contract=None): self.sid = sid if contract is not None: self.contract = contract self.amount = amount self.dt = dt self.price = price self.order_id = order_id self.commission = commission <|code_end|> , predict the immediate next line with the help of imports: import abc import math import alephnull.utils.math_utils as zp_math from copy import copy from functools import partial from alephnull.protocol import DATASOURCE_TYPE and context (classes, functions, sometimes code) from other files: # Path: alephnull/protocol.py # DATASOURCE_TYPE = Enum( # 'AS_TRADED_EQUITY', # 'MERGER', # 'SPLIT', # 'DIVIDEND', # 'TRADE', # 'TRANSACTION', # 'ORDER', # 'EMPTY', # 'DONE', # 'CUSTOM', # 'BENCHMARK', # 'COMMISSION' # ) . Output only the next line.
self.type = DATASOURCE_TYPE.TRANSACTION
Using the snippet: <|code_start|># you can use a TradingEnvironment in a with clause: # lse = TradingEnvironment(bm_index="^FTSE", exchange_tz="Europe/London") # with lse: # # the code here will have lse as the global trading.environment # algo.run(start, end) # # User code will not normally need to use TradingEnvironment # directly. If you are extending zipline's core financial # compponents and need to use the environment, you must import the module # NOT the variable. If you import the module, you will get a # reference to the environment at import time, which will prevent # your code from responding to user code that changes the global # state. environment = None class TradingEnvironment(object): def __init__( self, load=None, bm_symbol='^GSPC', exchange_tz="US/Eastern", max_date=None, extra_dates=None ): self.prev_environment = self self.bm_symbol = bm_symbol if not load: <|code_end|> , determine the next line of code. You have imports: import bisect import logbook import datetime import pandas as pd from alephnull.data.loader import load_market_data from alephnull.utils import tradingcalendar from alephnull.utils.tradingcalendar import get_early_closes and context (class names, function names, or code) available: # Path: alephnull/data/loader.py # def load_market_data(bm_symbol='^GSPC'): # try: # fp_bm = get_datafile(get_benchmark_filename(bm_symbol), "rb") # except IOError: # print(""" # data files aren't distributed with source. # Fetching data from Yahoo Finance. # """).strip() # dump_benchmarks(bm_symbol) # fp_bm = get_datafile(get_benchmark_filename(bm_symbol), "rb") # # saved_benchmarks = pd.Series.from_csv(fp_bm) # saved_benchmarks = saved_benchmarks.tz_localize('UTC') # fp_bm.close() # # most_recent = pd.Timestamp('today', tz='UTC') - trading_day # most_recent_index = trading_days.searchsorted(most_recent) # days_up_to_now = trading_days[:most_recent_index + 1] # # # Find the offset of the last date for which we have trading data in our # # list of valid trading days # last_bm_date = saved_benchmarks.index[-1] # last_bm_date_offset = days_up_to_now.searchsorted( # last_bm_date.strftime('%Y/%m/%d')) # # # If more than 1 trading days has elapsed since the last day where # # we have data,then we need to update # if len(days_up_to_now) - last_bm_date_offset > 1: # benchmark_returns = update_benchmarks(bm_symbol, last_bm_date) # if ( # benchmark_returns.index.tz is None # or # benchmark_returns.index.tz.zone != 'UTC' # ): # benchmark_returns = benchmark_returns.tz_localize('UTC') # else: # benchmark_returns = saved_benchmarks # if ( # benchmark_returns.index.tz is None # or # benchmark_returns.index.tz.zone != 'UTC' # ): # benchmark_returns = benchmark_returns.tz_localize('UTC') # # #Get treasury curve module, filename & source from mapping. # #Default to USA. # module, filename, source = INDEX_MAPPING.get( # bm_symbol, INDEX_MAPPING['^GSPC']) # # try: # fp_tr = get_datafile(filename, "rb") # except IOError: # print(""" # data files aren't distributed with source. # Fetching data from {0} # """).format(source).strip() # dump_treasury_curves(module, filename) # fp_tr = get_datafile(filename, "rb") # # saved_curves = pd.DataFrame.from_csv(fp_tr) # # # Find the offset of the last date for which we have trading data in our # # list of valid trading days # last_tr_date = saved_curves.index[-1] # last_tr_date_offset = days_up_to_now.searchsorted( # last_tr_date.strftime('%Y/%m/%d')) # # # If more than 1 trading days has elapsed since the last day where # # we have data,then we need to update # if len(days_up_to_now) - last_tr_date_offset > 1: # treasury_curves = dump_treasury_curves(module, filename) # else: # treasury_curves = saved_curves.tz_localize('UTC') # # tr_curves = {} # for tr_dt, curve in treasury_curves.T.iterkv(): # # tr_dt = tr_dt.replace(hour=0, minute=0, second=0, microsecond=0, # # tzinfo=pytz.utc) # tr_curves[tr_dt] = curve.to_dict() # # fp_tr.close() # # tr_curves = OrderedDict(sorted( # ((dt, c) for dt, c in tr_curves.iteritems()), # key=lambda t: t[0])) # # return benchmark_returns, tr_curves . Output only the next line.
load = load_market_data
Predict the next line for this snippet: <|code_start|> self.fields, self.market_aware, self.window_length, self.delta ) def update(self, event): """ Update the event window for this event's sid. Return a dict from tracked fields to moving averages. """ # This will create a new EventWindow if this is the first # message for this sid. window = self.sid_windows[event.sid] window.update(event) return window.get_averages() class Averages(object): """ Container for averages. """ def __getitem__(self, name): """ Allow dictionary lookup. """ return self.__dict__[name] <|code_end|> with the help of current file imports: from collections import defaultdict from alephnull.transforms.utils import EventWindow, TransformMeta from alephnull.errors import WrongDataForTransform and context from other files: # Path: alephnull/transforms/utils.py # class EventWindow(object): # """ # Abstract base class for transform classes that calculate iterative # metrics on events within a given timedelta. Maintains a list of # events that are within a certain timedelta of the most recent # tick. Calls self.handle_add(event) for each event added to the # window. Calls self.handle_remove(event) for each event removed # from the window. Subclass these methods along with init(*args, # **kwargs) to calculate metrics over the window. # # If the market_aware flag is True, the EventWindow drops old events # based on the number of elapsed trading days between newest and oldest. # Otherwise old events are dropped based on a raw timedelta. # # See zipline/transforms/mavg.py and zipline/transforms/vwap.py for example # implementations of moving average and volume-weighted average # price. # """ # # Mark this as an abstract base class. # __metaclass__ = ABCMeta # # def __init__(self, market_aware=True, window_length=None, delta=None): # # check_window_length(window_length) # self.window_length = window_length # # self.ticks = deque() # # # Only Market-aware mode is now supported. # if not market_aware: # raise UnsupportedEventWindowFlagValue( # "Non-'market aware' mode is no longer supported." # ) # if delta: # raise UnsupportedEventWindowFlagValue( # "delta values are no longer supported." # ) # # Set the behavior for dropping events from the back of the # # event window. # self.drop_condition = self.out_of_market_window # # @abstractmethod # def handle_add(self, event): # raise NotImplementedError() # # @abstractmethod # def handle_remove(self, event): # raise NotImplementedError() # # def __len__(self): # return len(self.ticks) # # def update(self, event): # # if (hasattr(event, 'type') # and event.type not in ( # DATASOURCE_TYPE.TRADE, # DATASOURCE_TYPE.CUSTOM)): # return # # self.assert_well_formed(event) # # Add new event and increment totals. # self.ticks.append(event) # # # Subclasses should override handle_add to define behavior for # # adding new ticks. # self.handle_add(event) # # Clear out any expired events. # # # # oldest newest # # | | # # V V # while self.drop_condition(self.ticks[0].dt, self.ticks[-1].dt): # # # popleft removes and returns the oldest tick in self.ticks # popped = self.ticks.popleft() # # # Subclasses should override handle_remove to define # # behavior for removing ticks. # self.handle_remove(popped) # # def out_of_market_window(self, oldest, newest): # oldest_index = \ # trading.environment.trading_days.searchsorted(oldest) # newest_index = \ # trading.environment.trading_days.searchsorted(newest) # # trading_days_between = newest_index - oldest_index # # # "Put back" a day if oldest is earlier in its day than newest, # # reflecting the fact that we haven't yet completed the last # # day in the window. # if oldest.time() > newest.time(): # trading_days_between -= 1 # # return trading_days_between >= self.window_length # # # All event windows expect to receive events with datetime fields # # that arrive in sorted order. # def assert_well_formed(self, event): # assert isinstance(event.dt, datetime), \ # "Bad dt in EventWindow:%s" % event # if len(self.ticks) > 0: # # Something is wrong if new event is older than previous. # assert event.dt >= self.ticks[-1].dt, \ # "Events arrived out of order in EventWindow: %s -> %s" % \ # (event, self.ticks[0]) # # class TransformMeta(type): # """ # Metaclass that automatically packages a class inside of # StatefulTransform on initialization. Specifically, if Foo is a # class with its __metaclass__ attribute set to TransformMeta, then # calling Foo(*args, **kwargs) will return StatefulTransform(Foo, # *args, **kwargs) instead of an instance of Foo. (Note that you can # still recover an instance of a "raw" Foo by introspecting the # resulting StatefulTransform's 'state' field.) # """ # # def __call__(cls, *args, **kwargs): # return StatefulTransform(cls, *args, **kwargs) , which may contain function names, class names, or code. Output only the next line.
class MovingAverageEventWindow(EventWindow):
Given the following code snippet before the placeholder: <|code_start|># # Copyright 2013 Quantopian, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. class MovingAverage(object): """ Class that maintains a dictionary from sids to MovingAverageEventWindows. For each sid, we maintain moving averages over any number of distinct fields (For example, we can maintain a sid's average volume as well as its average price.) """ <|code_end|> , predict the next line using imports from the current file: from collections import defaultdict from alephnull.transforms.utils import EventWindow, TransformMeta from alephnull.errors import WrongDataForTransform and context including class names, function names, and sometimes code from other files: # Path: alephnull/transforms/utils.py # class EventWindow(object): # """ # Abstract base class for transform classes that calculate iterative # metrics on events within a given timedelta. Maintains a list of # events that are within a certain timedelta of the most recent # tick. Calls self.handle_add(event) for each event added to the # window. Calls self.handle_remove(event) for each event removed # from the window. Subclass these methods along with init(*args, # **kwargs) to calculate metrics over the window. # # If the market_aware flag is True, the EventWindow drops old events # based on the number of elapsed trading days between newest and oldest. # Otherwise old events are dropped based on a raw timedelta. # # See zipline/transforms/mavg.py and zipline/transforms/vwap.py for example # implementations of moving average and volume-weighted average # price. # """ # # Mark this as an abstract base class. # __metaclass__ = ABCMeta # # def __init__(self, market_aware=True, window_length=None, delta=None): # # check_window_length(window_length) # self.window_length = window_length # # self.ticks = deque() # # # Only Market-aware mode is now supported. # if not market_aware: # raise UnsupportedEventWindowFlagValue( # "Non-'market aware' mode is no longer supported." # ) # if delta: # raise UnsupportedEventWindowFlagValue( # "delta values are no longer supported." # ) # # Set the behavior for dropping events from the back of the # # event window. # self.drop_condition = self.out_of_market_window # # @abstractmethod # def handle_add(self, event): # raise NotImplementedError() # # @abstractmethod # def handle_remove(self, event): # raise NotImplementedError() # # def __len__(self): # return len(self.ticks) # # def update(self, event): # # if (hasattr(event, 'type') # and event.type not in ( # DATASOURCE_TYPE.TRADE, # DATASOURCE_TYPE.CUSTOM)): # return # # self.assert_well_formed(event) # # Add new event and increment totals. # self.ticks.append(event) # # # Subclasses should override handle_add to define behavior for # # adding new ticks. # self.handle_add(event) # # Clear out any expired events. # # # # oldest newest # # | | # # V V # while self.drop_condition(self.ticks[0].dt, self.ticks[-1].dt): # # # popleft removes and returns the oldest tick in self.ticks # popped = self.ticks.popleft() # # # Subclasses should override handle_remove to define # # behavior for removing ticks. # self.handle_remove(popped) # # def out_of_market_window(self, oldest, newest): # oldest_index = \ # trading.environment.trading_days.searchsorted(oldest) # newest_index = \ # trading.environment.trading_days.searchsorted(newest) # # trading_days_between = newest_index - oldest_index # # # "Put back" a day if oldest is earlier in its day than newest, # # reflecting the fact that we haven't yet completed the last # # day in the window. # if oldest.time() > newest.time(): # trading_days_between -= 1 # # return trading_days_between >= self.window_length # # # All event windows expect to receive events with datetime fields # # that arrive in sorted order. # def assert_well_formed(self, event): # assert isinstance(event.dt, datetime), \ # "Bad dt in EventWindow:%s" % event # if len(self.ticks) > 0: # # Something is wrong if new event is older than previous. # assert event.dt >= self.ticks[-1].dt, \ # "Events arrived out of order in EventWindow: %s -> %s" % \ # (event, self.ticks[0]) # # class TransformMeta(type): # """ # Metaclass that automatically packages a class inside of # StatefulTransform on initialization. Specifically, if Foo is a # class with its __metaclass__ attribute set to TransformMeta, then # calling Foo(*args, **kwargs) will return StatefulTransform(Foo, # *args, **kwargs) instead of an instance of Foo. (Note that you can # still recover an instance of a "raw" Foo by introspecting the # resulting StatefulTransform's 'state' field.) # """ # # def __call__(cls, *args, **kwargs): # return StatefulTransform(cls, *args, **kwargs) . Output only the next line.
__metaclass__ = TransformMeta
Next line prediction: <|code_start|># # Copyright 2013 Quantopian, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. log = logbook.Logger('Risk Period') choose_treasury = functools.partial(risk.choose_treasury, risk.select_treasury_duration) class RiskMetricsPeriod(object): def __init__(self, start_date, end_date, returns, benchmark_returns=None): <|code_end|> . Use current file imports: (import functools import logbook import math import numpy as np import numpy.linalg as la import pandas as pd import risk from alephnull.finance import trading from . risk import ( alpha, check_entry, information_ratio, sharpe_ratio, sortino_ratio, )) and context including class names, function names, or small code snippets from other files: # Path: alephnull/finance/trading.py # class TradingEnvironment(object): # class SimulationParameters(object): # def __init__( # self, # load=None, # bm_symbol='^GSPC', # exchange_tz="US/Eastern", # max_date=None, # extra_dates=None # ): # def __enter__(self, *args, **kwargs): # def __exit__(self, exc_type, exc_val, exc_tb): # def normalize_date(self, test_date): # def utc_dt_in_exchange(self, dt): # def exchange_dt_in_utc(self, dt): # def is_market_hours(self, test_date): # def is_trading_day(self, test_date): # def next_trading_day(self, test_date): # def days_in_range(self, start, end): # def next_open_and_close(self, start_date): # def get_open_and_close(self, day): # def market_minutes_for_day(self, midnight): # def trading_day_distance(self, first_date, second_date): # def get_index(self, dt): # def __init__(self, period_start, period_end, # capital_base=10e3, # emission_rate='daily', # data_frequency='daily'): # def calculate_first_open(self): # def calculate_last_close(self): # def days_in_period(self): # def __repr__(self): . Output only the next line.
treasury_curves = trading.environment.treasury_curves
Continue the code snippet: <|code_start|>try: except: #Replace this with source to multiplier get_multiplier = lambda x: 25 log = logbook.Logger('Performance') class FuturesPerformancePeriod(object): def __init__( self, starting_cash, period_open=None, period_close=None, keep_transactions=True, keep_orders=False, serialize_positions=True): # * # self.starting_mav = starting_cash self.ending_mav = starting_cash self.cash_adjustment = 0 self.ending_total_value = 0.0 self.pnl = 0.0 # ** # self.period_open = period_open self.period_close = period_close # sid => position object <|code_end|> . Use current file imports: import math import logbook import numpy as np import pandas as pd import alephnull.protocol as zp from collections import OrderedDict, defaultdict from .position import positiondict from alephtools.connection import get_multiplier and context (classes, functions, or code) from other files: # Path: alephnull/finance/performance/position.py # class positiondict(dict): # # def __missing__(self, key): # if type(key) is tuple: # pos = Position(key[0], contract=key[1]) # else: # pos = Position(key) # self[key] = pos # return pos . Output only the next line.
self.positions = positiondict()