idx
int64
0
63k
question
stringlengths
53
5.28k
target
stringlengths
5
805
29,200
def _getsatname ( self ) : if self . platform_name . startswith ( "Meteosat" ) : return self . platform_name else : raise NotImplementedError ( 'Platform {0} not yet supported...' . format ( self . platform_name ) )
Get the satellite name used in the rsr - reader from the platform and number
29,201
def make_tb2rad_lut ( self , filepath , normalized = True ) : tb_ = np . arange ( TB_MIN , TB_MAX , self . tb_resolution ) retv = self . tb2radiance ( tb_ , normalized = normalized ) rad = retv [ 'radiance' ] np . savez ( filepath , tb = tb_ , radiance = rad )
Generate a Tb to radiance look - up table
29,202
def radiance2tb ( self , rad ) : return radiance2tb ( rad , self . rsr [ self . bandname ] [ self . detector ] [ 'central_wavelength' ] * 1e-6 )
Get the Tb from the radiance using the Planck function and the central wavelength of the band
29,203
def radiance2tb ( self , rad ) : c_1 = 2 * H_PLANCK * C_SPEED ** 2 c_2 = H_PLANCK * C_SPEED / K_BOLTZMANN vc_ = SEVIRI [ self . bandname ] [ self . platform_name ] [ 0 ] vc_ *= 100.0 alpha = SEVIRI [ self . bandname ] [ self . platform_name ] [ 1 ] beta = SEVIRI [ self . bandname ] [ self . platform_name ] [ 2 ] tb_ = ...
Get the Tb from the radiance using the simple non - linear regression method .
29,204
def tb2radiance ( self , tb_ , ** kwargs ) : lut = kwargs . get ( 'lut' , None ) normalized = kwargs . get ( 'normalized' , True ) if lut is not None : raise NotImplementedError ( 'Using a tb-radiance LUT is not yet supported' ) if not normalized : raise NotImplementedError ( 'Deriving the band integrated radiance is n...
Get the radiance from the Tb using the simple non - linear regression method . SI units of course!
29,205
def _get_rsr_data_version ( self ) : rsr_data_version_path = os . path . join ( self . rsr_dir , RSR_DATA_VERSION_FILENAME ) if not os . path . exists ( rsr_data_version_path ) : return "v0.0.0" with open ( rsr_data_version_path , 'r' ) as fpt : return fpt . readline ( ) . strip ( )
Check the version of the RSR data from the version file in the RSR directory
29,206
def _check_instrument ( self ) : instr = INSTRUMENTS . get ( self . platform_name , self . instrument . lower ( ) ) if instr != self . instrument . lower ( ) : self . instrument = instr LOG . warning ( "Inconsistent instrument/satellite input - " + "instrument set to %s" , self . instrument ) self . instrument = self ....
Check and try fix instrument name if needed
29,207
def _get_filename ( self ) : self . filename = expanduser ( os . path . join ( self . rsr_dir , 'rsr_{0}_{1}.h5' . format ( self . instrument , self . platform_name ) ) ) LOG . debug ( 'Filename: %s' , str ( self . filename ) ) if not os . path . exists ( self . filename ) or not os . path . isfile ( self . filename ) ...
Get the rsr filname from platform and instrument names and download if not available .
29,208
def load ( self ) : import h5py no_detectors_message = False with h5py . File ( self . filename , 'r' ) as h5f : self . band_names = [ b . decode ( 'utf-8' ) for b in h5f . attrs [ 'band_names' ] . tolist ( ) ] self . description = h5f . attrs [ 'description' ] . decode ( 'utf-8' ) if not self . platform_name : try : s...
Read the internally formatet hdf5 relative spectral response data
29,209
def integral ( self , bandname ) : intg = { } for det in self . rsr [ bandname ] . keys ( ) : wvl = self . rsr [ bandname ] [ det ] [ 'wavelength' ] resp = self . rsr [ bandname ] [ det ] [ 'response' ] intg [ det ] = np . trapz ( resp , wvl ) return intg
Calculate the integral of the spectral response function for each detector .
29,210
def convert ( self ) : from pyspectral . utils import ( convert2wavenumber , get_central_wave ) if self . _wavespace == WAVE_LENGTH : rsr , info = convert2wavenumber ( self . rsr ) for band in rsr . keys ( ) : for det in rsr [ band ] . keys ( ) : self . rsr [ band ] [ det ] [ WAVE_NUMBER ] = rsr [ band ] [ det ] [ WAVE...
Convert spectral response functions from wavelength to wavenumber
29,211
def _get_options_from_config ( self ) : options = get_config ( ) self . output_dir = options . get ( 'rsr_dir' , './' ) self . path = options [ self . platform_name + '-' + self . instrument ] [ 'path' ] self . options = options
Get configuration settings from configuration file
29,212
def _get_bandfilenames ( self ) : for band in self . bandnames : LOG . debug ( "Band = %s" , str ( band ) ) self . filenames [ band ] = os . path . join ( self . path , self . options [ self . platform_name + '-' + self . instrument ] [ band ] ) LOG . debug ( self . filenames [ band ] ) if not os . path . exists ( self...
Get the instrument rsr filenames
29,213
def blackbody_rad2temp ( wavelength , radiance ) : mask = False if np . isscalar ( radiance ) : rad = np . array ( [ radiance , ] , dtype = 'float64' ) else : rad = np . array ( radiance , dtype = 'float64' ) if np . ma . is_masked ( radiance ) : mask = radiance . mask rad = np . ma . masked_array ( rad , mask = mask )...
Derive brightness temperatures from radiance using the Planck function . Wavelength space . Assumes SI units as input and returns temperature in Kelvin
29,214
def blackbody_wn_rad2temp ( wavenumber , radiance ) : if np . isscalar ( radiance ) : rad = np . array ( [ radiance , ] , dtype = 'float64' ) else : rad = np . array ( radiance , dtype = 'float64' ) if np . isscalar ( wavenumber ) : wavnum = np . array ( [ wavenumber , ] , dtype = 'float64' ) else : wavnum = np . array...
Derive brightness temperatures from radiance using the Planck function . Wavenumber space
29,215
def get_central_wave ( wavl , resp ) : return np . trapz ( resp * wavl , wavl ) / np . trapz ( resp , wavl )
Calculate the central wavelength or the central wavenumber depending on what is input
29,216
def generate_seviri_file ( seviri , platform_name ) : import h5py filename = os . path . join ( seviri . output_dir , "rsr_seviri_{0}.h5" . format ( platform_name ) ) sat_name = platform_name with h5py . File ( filename , "w" ) as h5f : h5f . attrs [ 'description' ] = 'Relative Spectral Responses for SEVIRI' h5f . attr...
Generate the pyspectral internal common format relative response function file for one SEVIRI
29,217
def convert2wavenumber ( self ) : for chname in self . rsr . keys ( ) : elems = [ k for k in self . rsr [ chname ] . keys ( ) ] for sat in elems : if sat == "wavelength" : LOG . debug ( "Get the wavenumber from the wavelength: sat=%s chname=%s" , sat , chname ) wnum = 1. / ( 1e-4 * self . rsr [ chname ] [ sat ] [ : ] )...
Convert from wavelengths to wavenumber
29,218
def get_centrals ( self ) : result = { } for chname in self . rsr . keys ( ) : result [ chname ] = { } if self . wavespace == "wavelength" : x__ = self . rsr [ chname ] [ "wavelength" ] else : x__ = self . rsr [ chname ] [ "wavenumber" ] for sat in self . rsr [ chname ] . keys ( ) : if sat in [ "wavelength" , "wavenumb...
Get the central wavenumbers or central wavelengths of all channels depending on the given wavespace
29,219
def _load ( self , scale = 1.0 ) : LOG . debug ( "File: %s" , str ( self . requested_band_filename ) ) data = np . genfromtxt ( self . requested_band_filename , unpack = True , names = [ 'wavelength' , 'wavenumber' , 'response' ] , skip_header = 2 ) wvl = data [ 'wavelength' ] * scale resp = data [ 'response' ] self . ...
Load the ABI relative spectral responses
29,220
def convert2wavenumber ( self ) : self . wavenumber = 1. / ( 1e-4 * self . wavelength [ : : - 1 ] ) self . irradiance = ( self . irradiance [ : : - 1 ] * self . wavelength [ : : - 1 ] * self . wavelength [ : : - 1 ] * 0.1 ) self . wavelength = None
Convert from wavelengths to wavenumber .
29,221
def _load ( self ) : self . wavelength , self . irradiance = np . genfromtxt ( self . filename , unpack = True )
Read the tabulated spectral irradiance data from file
29,222
def solar_constant ( self ) : if self . wavenumber is not None : return np . trapz ( self . irradiance , self . wavenumber ) elif self . wavelength is not None : return np . trapz ( self . irradiance , self . wavelength ) else : raise TypeError ( 'Neither wavelengths nor wavenumbers available!' )
Calculate the solar constant
29,223
def inband_solarflux ( self , rsr , scale = 1.0 , ** options ) : return self . _band_calculations ( rsr , True , scale , ** options )
Derive the inband solar flux for a given instrument relative spectral response valid for an earth - sun distance of one AU .
29,224
def inband_solarirradiance ( self , rsr , scale = 1.0 , ** options ) : return self . _band_calculations ( rsr , False , scale , ** options )
Derive the inband solar irradiance for a given instrument relative spectral response valid for an earth - sun distance of one AU .
29,225
def _band_calculations ( self , rsr , flux , scale , ** options ) : from scipy . interpolate import InterpolatedUnivariateSpline if 'detector' in options : detector = options [ 'detector' ] else : detector = 1 if self . wavespace == 'wavelength' : if 'response' in rsr : wvl = rsr [ 'wavelength' ] * scale resp = rsr [ '...
Derive the inband solar flux or inband solar irradiance for a given instrument relative spectral response valid for an earth - sun distance of one AU .
29,226
def _load ( self , filename = None ) : if not filename : filename = self . filename wb_ = open_workbook ( filename ) self . rsr = { } sheet_names = [ ] for sheet in wb_ . sheets ( ) : if sheet . name in [ 'Title' , ] : continue ch_name = AHI_BAND_NAMES . get ( sheet . name . strip ( ) , sheet . name . strip ( ) ) sheet...
Load the Himawari AHI RSR data for the band requested
29,227
def plot_band ( plt_in , band_name , rsr_obj , ** kwargs ) : if 'platform_name_in_legend' in kwargs : platform_name_in_legend = kwargs [ 'platform_name_in_legend' ] else : platform_name_in_legend = False detectors = rsr_obj . rsr [ band_name ] . keys ( ) det = sorted ( detectors ) [ 0 ] resp = rsr_obj . rsr [ band_name...
Do the plotting of one band
29,228
def convert2wavenumber ( rsr ) : retv = { } for chname in rsr . keys ( ) : retv [ chname ] = { } for det in rsr [ chname ] . keys ( ) : retv [ chname ] [ det ] = { } if 'wavenumber' in rsr [ chname ] [ det ] . keys ( ) : retv [ chname ] [ det ] = rsr [ chname ] [ det ] . copy ( ) LOG . debug ( "RSR data already in wave...
Take rsr data set with all channels and detectors for an instrument each with a set of wavelengths and normalised responses and convert to wavenumbers and responses
29,229
def get_bandname_from_wavelength ( sensor , wavelength , rsr , epsilon = 0.1 , multiple_bands = False ) : chdist_min = 2.0 chfound = [ ] for channel in rsr : chdist = abs ( rsr [ channel ] [ 'det-1' ] [ 'central_wavelength' ] - wavelength ) if chdist < chdist_min and chdist < epsilon : chfound . append ( BANDNAMES . ge...
Get the bandname from h5 rsr provided the approximate wavelength .
29,230
def download_rsr ( ** kwargs ) : import tarfile import requests TQDM_LOADED = True try : from tqdm import tqdm except ImportError : TQDM_LOADED = False dest_dir = kwargs . get ( 'dest_dir' , LOCAL_RSR_DIR ) dry_run = kwargs . get ( 'dry_run' , False ) LOG . info ( "Download RSR files and store in directory %s" , dest_d...
Download the pre - compiled hdf5 formatet relative spectral response functions from the internet
29,231
def download_luts ( ** kwargs ) : import tarfile import requests TQDM_LOADED = True try : from tqdm import tqdm except ImportError : TQDM_LOADED = False dry_run = kwargs . get ( 'dry_run' , False ) if 'aerosol_type' in kwargs : if isinstance ( kwargs [ 'aerosol_type' ] , ( list , tuple , set ) ) : aerosol_types = kwarg...
Download the luts from internet .
29,232
def get_logger ( name ) : log = logging . getLogger ( name ) if not log . handlers : log . addHandler ( NullHandler ( ) ) return log
Return logger with null handle
29,233
def _load ( self , filename = None ) : if not filename : filename = self . aatsr_path wb_ = open_workbook ( filename ) for sheet in wb_ . sheets ( ) : ch_name = sheet . name . strip ( ) if ch_name == 'aatsr_' + self . bandname : data = np . array ( [ s . split ( ) for s in sheet . col_values ( 0 , start_rowx = 3 , end_...
Read the AATSR rsr data
29,234
def _load ( self , scale = 0.001 ) : with open_workbook ( self . path ) as wb_ : for sheet in wb_ . sheets ( ) : if sheet . name in [ 'Plot of AllBands' , ] : continue ch_name = OLI_BAND_NAMES . get ( sheet . name . strip ( ) ) if ch_name != self . bandname : continue wvl = sheet . col_values ( 0 , 2 ) resp = sheet . c...
Load the Landsat OLI relative spectral responses
29,235
def _load ( self , scale = 1.0 ) : data = np . genfromtxt ( self . requested_band_filename , unpack = True , names = [ 'wavenumber' , 'response' ] , skip_header = 4 ) wavelength = 1. / data [ 'wavenumber' ] * 10000. response = data [ 'response' ] detectors = { } detectors [ 'det-1' ] = { 'wavelength' : wavelength , 're...
Load the MetImage RSR data for the band requested
29,236
def emissive_part_3x ( self , tb = True ) : try : self . _e3x = self . _rad3x_t11 * ( 1 - self . _r3x ) except TypeError : LOG . warning ( "Couldn't derive the emissive part \n" + "Please derive the relfectance prior to requesting the emissive part" ) if tb : return self . radiance2tb ( self . _e3x ) else : return self...
Get the emissive part of the 3 . x band
29,237
def _load ( self , scale = 0.001 ) : ncf = Dataset ( self . path , 'r' ) bandnum = OLCI_BAND_NAMES . index ( self . bandname ) resp = ncf . variables [ 'mean_spectral_response_function' ] [ bandnum , : ] wvl = ncf . variables [ 'mean_spectral_response_function_wavelength' ] [ bandnum , : ] * scale self . rsr = { 'wavel...
Load the OLCI relative spectral responses
29,238
def _get_bandfilenames ( self ) : path = self . path for band in MODIS_BAND_NAMES : bnum = int ( band ) LOG . debug ( "Band = %s" , str ( band ) ) if self . platform_name == 'EOS-Terra' : filename = os . path . join ( path , "rsr.{0:d}.inb.final" . format ( bnum ) ) else : if bnum in [ 5 , 6 , 7 ] + range ( 20 , 37 ) :...
Get the MODIS rsr filenames
29,239
def _load ( self ) : if self . is_sw or self . platform_name == 'EOS-Aqua' : scale = 0.001 else : scale = 1.0 detector = read_modis_response ( self . requested_band_filename , scale ) self . rsr = detector if self . _sort : self . sort ( )
Load the MODIS RSR data for the band requested
29,240
def _get_bandfilenames ( self , ** options ) : conf = options [ self . platform_name + '-viirs' ] rootdir = conf [ 'rootdir' ] for section in conf : if not section . startswith ( 'section' ) : continue bandnames = conf [ section ] [ 'bands' ] for band in bandnames : filename = os . path . join ( rootdir , conf [ sectio...
Get filename for each band
29,241
def _get_bandfile ( self , ** options ) : path = self . bandfilenames [ self . bandname ] if not os . path . exists ( path ) : raise IOError ( "Couldn't find an existing file for this band ({band}): {path}" . format ( band = self . bandname , path = path ) ) self . filename = path return
Get the VIIRS rsr filename
29,242
def _load ( self , scale = 0.001 ) : if self . bandname == 'DNB' : header_lines_to_skip = N_HEADER_LINES_DNB [ self . platform_name ] else : header_lines_to_skip = N_HEADER_LINES [ self . platform_name ] try : data = np . genfromtxt ( self . filename , unpack = True , skip_header = header_lines_to_skip , names = NAMES1...
Load the VIIRS RSR data for the band requested
29,243
def _load ( self , scale = 0.001 ) : with open_workbook ( self . path ) as wb_ : for sheet in wb_ . sheets ( ) : if sheet . name not in SHEET_HEADERS . keys ( ) : continue plt_short_name = PLATFORM_SHORT_NAME . get ( self . platform_name ) if plt_short_name != SHEET_HEADERS . get ( sheet . name ) : continue wvl = sheet...
Load the Sentinel - 2 MSI relative spectral responses
29,244
def _load ( self , scale = 1.0 ) : LOG . debug ( "File: %s" , str ( self . requested_band_filename ) ) ncf = Dataset ( self . requested_band_filename , 'r' ) wvl = ncf . variables [ 'wavelength' ] [ : ] * scale resp = ncf . variables [ 'response' ] [ : ] self . rsr = { 'wavelength' : wvl , 'response' : resp }
Load the SLSTR relative spectral responses
29,245
def get_config ( ) : if CONFIG_FILE is not None : configfile = CONFIG_FILE else : configfile = BUILTIN_CONFIG_FILE config = { } with open ( configfile , 'r' ) as fp_ : config = recursive_dict_update ( config , yaml . load ( fp_ , Loader = UnsafeLoader ) ) app_dirs = AppDirs ( 'pyspectral' , 'pytroll' ) user_datadir = a...
Get the configuration from file
29,246
def _get_lutfiles_version ( self ) : basedir = RAYLEIGH_LUT_DIRS [ self . _aerosol_type ] lutfiles_version_path = os . path . join ( basedir , ATM_CORRECTION_LUT_VERSION [ self . _aerosol_type ] [ 'filename' ] ) if not os . path . exists ( lutfiles_version_path ) : return "v0.0.0" with open ( lutfiles_version_path , 'r...
Check the version of the atm correction luts from the version file in the specific aerosol correction directory
29,247
def get_effective_wavelength ( self , bandname ) : try : rsr = RelativeSpectralResponse ( self . platform_name , self . sensor ) except ( IOError , OSError ) : LOG . exception ( "No spectral responses for this platform and sensor: %s %s" , self . platform_name , self . sensor ) if isinstance ( bandname , ( float , inte...
Get the effective wavelength with Rayleigh scattering in mind
29,248
def griditer ( x , y , ncol , nrow = None , step = 1 ) : if nrow is None : nrow = ncol yield from itertools . product ( range ( x , x + ncol , step ) , range ( y , y + nrow , step ) )
Iterate through a grid of tiles .
29,249
def bboxiter ( tile_bounds , tiles_per_row_per_region = 1 ) : x_lower = math . floor ( tile_bounds . min . x / tiles_per_row_per_region ) y_lower = math . floor ( tile_bounds . min . y / tiles_per_row_per_region ) ncol = math . ceil ( tile_bounds . max . x / tiles_per_row_per_region ) - x_lower nrow = math . ceil ( til...
Iterate through a grid of regions defined by a TileBB .
29,250
def resolution ( self ) : geo_coords = self . to_geographic ( ) resolution = abs ( _initialresolution * math . cos ( geo_coords . lat * _pi_180 ) / ( 2 ** self . zoom ) ) return resolution
Get the tile resolution at the current position .
29,251
def get_tiles ( self ) : for x , y in griditer ( self . root_tile . x , self . root_tile . y , ncol = self . tiles_per_row ) : yield TileCoordinate ( self . root_tile . zoom , x , y )
Get all TileCoordinates contained in the region
29,252
def maps_json ( ) : map_sources = { id : { "id" : map_source . id , "name" : map_source . name , "folder" : map_source . folder , "min_zoom" : map_source . min_zoom , "max_zoom" : map_source . max_zoom , "layers" : [ { "min_zoom" : layer . min_zoom , "max_zoom" : layer . max_zoom , "tile_url" : layer . tile_url . repla...
Generates a json object which serves as bridge between the web interface and the map source collection .
29,253
def map_to_pdf ( map_source , zoom , x , y , width , height ) : map_source = app . config [ "mapsources" ] [ map_source ] pdf_file = print_map ( map_source , x = float ( x ) , y = float ( y ) , zoom = int ( zoom ) , width = float ( width ) , height = float ( height ) , format = 'pdf' ) return send_file ( pdf_file , att...
Generate a PDF at the given position .
29,254
def kml_master ( ) : kml_doc = KMLMaster ( app . config [ "url_formatter" ] , app . config [ "mapsources" ] . values ( ) ) return kml_response ( kml_doc )
KML master document for loading all maps in Google Earth
29,255
def kml_map_root ( map_source ) : map = app . config [ "mapsources" ] [ map_source ] kml_doc = KMLMapRoot ( app . config [ "url_formatter" ] , map , app . config [ "LOG_TILES_PER_ROW" ] ) return kml_response ( kml_doc )
KML for a given map
29,256
def kml_region ( map_source , z , x , y ) : map = app . config [ "mapsources" ] [ map_source ] kml_doc = KMLRegion ( app . config [ "url_formatter" ] , map , app . config [ "LOG_TILES_PER_ROW" ] , z , x , y ) return kml_response ( kml_doc )
KML region fetched by a Google Earth network link .
29,257
def count_elements ( doc ) : "Counts the number of times each element is used in a document" summary = { } for el in doc . iter ( ) : try : namespace , element_name = re . search ( '^{(.+)}(.+)$' , el . tag ) . groups ( ) except : namespace = None element_name = el . tag if not summary . has_key ( namespace ) : summary...
Counts the number of times each element is used in a document
29,258
def get_factory_object_name ( namespace ) : "Returns the correct factory object for a given namespace" factory_map = { 'http://www.opengis.net/kml/2.2' : 'KML' , 'http://www.w3.org/2005/Atom' : 'ATOM' , 'http://www.google.com/kml/ext/2.2' : 'GX' } if namespace : if factory_map . has_key ( namespace ) : factory_object_n...
Returns the correct factory object for a given namespace
29,259
def kml_element_name ( grid_coords , elem_id = "KML" ) : return "_" . join ( str ( x ) for x in [ elem_id , grid_coords . zoom , grid_coords . x , grid_coords . y ] )
Create a unique element name for KML
29,260
def get_abs_url ( self , rel_url ) : rel_url = rel_url . lstrip ( "/" ) return "{}://{}:{}/{}" . format ( self . url_scheme , self . host , self . port , rel_url )
Create an absolute url from a relative one .
29,261
def get_map_url ( self , mapsource , grid_coords ) : return self . get_abs_url ( "/maps/{}/{}/{}/{}.kml" . format ( mapsource . id , grid_coords . zoom , grid_coords . x , grid_coords . y ) )
Get URL to a map region .
29,262
def add_maps ( self , parent , root_path = "" ) : for mapsource in self . map_folders [ root_path ] [ 'maps' ] : parent . append ( self . get_network_link ( mapsource ) ) for folder in self . map_folders [ root_path ] [ 'folders' ] : kml_folder_obj = kml_folder ( folder ) parent . append ( kml_folder_obj ) self . add_m...
Recursively add maps in a folder hierarchy .
29,263
def separate_namespace ( qname ) : "Separates the namespace from the element" import re try : namespace , element_name = re . search ( '^{(.+)}(.+)$' , qname ) . groups ( ) except : namespace = None element_name = qname return namespace , element_name
Separates the namespace from the element
29,264
def print_map ( map_source , x , y , zoom = 14 , width = 297 , height = 210 , dpi = 300 , format = "pdf" ) : bbox = get_print_bbox ( x , y , zoom , width , height , dpi ) tiles = [ get_tiles ( tile_layer , bbox ) for tile_layer in map_source . layers if tile_layer . min_zoom <= zoom <= tile_layer . max_zoom ] img = sti...
Download map tiles and stitch them together in a single image ready for printing .
29,265
def get_print_bbox ( x , y , zoom , width , height , dpi ) : tiles_h = width * dpi_to_dpmm ( dpi ) / TILE_SIZE tiles_v = height * dpi_to_dpmm ( dpi ) / TILE_SIZE mercator_coords = MercatorCoordinate ( x , y ) tile_coords = mercator_coords . to_tile ( zoom ) tile_bb = GridBB ( zoom , min_x = tile_coords . x - math . cei...
Calculate the tile bounding box based on position map size and resolution .
29,266
def download_tile ( map_layer , zoom , x , y ) : try : tile_url = map_layer . get_tile_url ( zoom , x , y ) tmp_file , headers = urllib . request . urlretrieve ( tile_url ) return ( x , y ) , tmp_file except URLError as e : app . logger . info ( "Error downloading tile x={}, y={}, z={} for layer {}: {}" . format ( x , ...
Download a given tile from the tile server .
29,267
def get_tiles ( map_layer , bbox , n_workers = N_DOWNLOAD_WORKERS ) : p = Pool ( n_workers ) tiles = { } for ( x , y ) , tmp_file in p . imap_unordered ( _download_tile_wrapper , zip ( itertools . repeat ( map_layer ) , itertools . repeat ( bbox . zoom ) , * zip ( * bboxiter ( bbox ) ) ) ) : app . logger . info ( "Down...
Download tiles .
29,268
def stitch_map ( tiles , width , height , bbox , dpi ) : size = ( int ( width * dpi_to_dpmm ( dpi ) ) , int ( height * dpi_to_dpmm ( dpi ) ) ) background = Image . new ( 'RGBA' , size , ( 255 , 255 , 255 ) ) for layer in tiles : layer_img = Image . new ( "RGBA" , size ) for ( x , y ) , tile_path in layer . items ( ) : ...
Merge tiles together into one image .
29,269
def add_scales_bar ( img , bbox ) : tc = TileCoordinate ( bbox . min . zoom , bbox . min . x , bbox . min . y ) meters_per_pixel = tc . resolution ( ) one_km_bar = int ( 1000 * ( 1 / meters_per_pixel ) ) col_black = ( 0 , 0 , 0 ) line_start = ( 100 , img . size [ 1 ] - 100 ) line_end = ( line_start [ 0 ] + one_km_bar ,...
Add a scales bar to the map .
29,270
def fromstring ( text , schema = None ) : if schema : parser = objectify . makeparser ( schema = schema . schema ) return objectify . fromstring ( text , parser = parser ) else : return objectify . fromstring ( text )
Parses a KML text string This function parses a KML text string and optionally validates it against a provided schema object
29,271
def parse ( fileobject , schema = None ) : if schema : parser = objectify . makeparser ( schema = schema . schema , strip_cdata = False ) return objectify . parse ( fileobject , parser = parser ) else : return objectify . parse ( fileobject )
Parses a file object This functon parses a KML file object and optionally validates it against a provided schema .
29,272
def load_maps ( maps_dir ) : maps_dir = os . path . abspath ( maps_dir ) maps = { } for root , dirnames , filenames in os . walk ( maps_dir ) : for filename in filenames : if filename . endswith ( ".xml" ) : xml_file = os . path . join ( root , filename ) map = MapSource . from_xml ( xml_file , maps_dir ) if map . id i...
Load all xml map sources from a given directory .
29,273
def walk_mapsources ( mapsources , root = "" ) : def get_first_folder ( path ) : path = path [ len ( root ) : ] path = path . lstrip ( F_SEP ) return path . split ( F_SEP ) [ 0 ] path_tuples = sorted ( ( ( get_first_folder ( m . folder ) , m ) for m in mapsources ) , key = lambda x : x [ 0 ] ) groups = { k : [ x for x ...
recursively walk through foldernames of mapsources .
29,274
def get_tile_url ( self , zoom , x , y ) : return self . tile_url . format ( ** { "$z" : zoom , "$x" : x , "$y" : y } )
Fill the placeholders of the tile url with zoom x and y .
29,275
def min_zoom ( self ) : zoom_levels = [ map_layer . min_zoom for map_layer in self . layers ] return min ( zoom_levels )
Get the minimal zoom level of all layers .
29,276
def max_zoom ( self ) : zoom_levels = [ map_layer . max_zoom for map_layer in self . layers ] return max ( zoom_levels )
Get the maximal zoom level of all layers .
29,277
def parse_xml_boundary ( xml_region ) : try : bounds = { } for boundary in xml_region . getchildren ( ) : bounds [ boundary . tag ] = float ( boundary . text ) bbox = GeographicBB ( min_lon = bounds [ "west" ] , max_lon = bounds [ "east" ] , min_lat = bounds [ "south" ] , max_lat = bounds [ "north" ] ) return bbox exce...
Get the geographic bounds from an XML element
29,278
def parse_xml_layers ( xml_layers ) : layers = [ ] for custom_map_source in xml_layers . getchildren ( ) : layers . append ( MapSource . parse_xml_layer ( custom_map_source ) ) return layers
Get the MapLayers from an XML element
29,279
def parse_xml_layer ( xml_custom_map_source ) : map_layer = MapLayer ( ) try : for elem in xml_custom_map_source . getchildren ( ) : if elem . tag == 'url' : map_layer . tile_url = elem . text elif elem . tag == 'minZoom' : map_layer . min_zoom = int ( elem . text ) elif elem . tag == 'maxZoom' : map_layer . max_zoom =...
Get one MapLayer from an XML element
29,280
def from_xml ( xml_path , mapsource_prefix = "" ) : xmldoc = xml . etree . ElementTree . parse ( xml_path ) . getroot ( ) map_id = os . path . splitext ( os . path . basename ( xml_path ) ) [ 0 ] map_name = map_id map_folder = re . sub ( "^" + re . escape ( mapsource_prefix ) , "" , os . path . dirname ( xml_path ) ) b...
Create a MapSource object from a MOBAC mapsource xml .
29,281
def get_saml_slos ( cls , logout_request ) : try : root = etree . fromstring ( logout_request ) return root . xpath ( "//samlp:SessionIndex" , namespaces = { 'samlp' : "urn:oasis:names:tc:SAML:2.0:protocol" } ) except etree . XMLSyntaxError : return None
returns saml logout ticket info
29,282
def verify_logout_request ( cls , logout_request , ticket ) : try : session_index = cls . get_saml_slos ( logout_request ) session_index = session_index [ 0 ] . text if session_index == ticket : return True else : return False except ( AttributeError , IndexError ) : return False
verifies the single logout request came from the CAS server returns True if the logout_request is valid False otherwise
29,283
def verify_ticket ( self , ticket , ** kwargs ) : try : from xml . etree import ElementTree except ImportError : from elementtree import ElementTree page = self . fetch_saml_validation ( ticket ) try : user = None attributes = { } response = page . content tree = ElementTree . fromstring ( response ) success = tree . f...
Verifies CAS 3 . 0 + XML - based authentication ticket and returns extended attributes .
29,284
def get_field_value ( self , instance , field_name ) : if field_name == 'percent' : field_name = 'id' value = getattr ( instance , field_name ) if callable ( value ) : value = value ( ) return value
Given an instance and the name of an attribute returns the value of that attribute on the instance .
29,285
def has_active_condition ( self , conditions , instances ) : return_value = None for instance in itertools . chain ( instances , [ None ] ) : if not self . can_execute ( instance ) : continue result = self . is_active ( instance , conditions ) if result is False : return False elif result is True : return_value = True ...
Given a list of instances and the conditions active for this switch returns a boolean reprsenting if any conditional is met including a non - instance default .
29,286
def is_active ( self , instance , conditions ) : return_value = None for name , field in self . fields . iteritems ( ) : field_conditions = conditions . get ( self . get_namespace ( ) , { } ) . get ( name ) if field_conditions : value = self . get_field_value ( instance , name ) for status , condition in field_conditio...
Given an instance and the conditions active for this switch returns a boolean representing if the feature is active .
29,287
def json ( func ) : "Decorator to make JSON views simpler" def wrapper ( self , request , * args , ** kwargs ) : try : response = { "success" : True , "data" : func ( self , request , * args , ** kwargs ) } except GargoyleException , exc : response = { "success" : False , "data" : exc . message } except Switch . DoesNo...
Decorator to make JSON views simpler
29,288
def is_active ( self , instance , conditions ) : if isinstance ( instance , User ) : return super ( UserConditionSet , self ) . is_active ( instance , conditions ) condition = conditions . get ( self . get_namespace ( ) , { } ) . get ( 'is_anonymous' ) if condition is not None : return bool ( condition ) return None
value is the current value of the switch instance is the instance of our type
29,289
def autodiscover ( ) : import copy from django . conf import settings from django . utils . importlib import import_module for app in settings . INSTALLED_APPS : before_import_registry = copy . copy ( gargoyle . _registry ) try : import_module ( '%s.gargoyle' % app ) except : gargoyle . _registry = before_import_regist...
Auto - discover INSTALLED_APPS admin . py modules and fail silently when not present . This forces an import on them to register any admin bits they may want .
29,290
def add_condition ( self , manager , condition_set , field_name , condition , exclude = False , commit = True ) : condition_set = manager . get_condition_set_by_id ( condition_set ) assert isinstance ( condition , basestring ) , 'conditions must be strings' namespace = condition_set . get_namespace ( ) if namespace not...
Adds a new condition and registers it in the global gargoyle switch manager .
29,291
def clear_conditions ( self , manager , condition_set , field_name = None , commit = True ) : condition_set = manager . get_condition_set_by_id ( condition_set ) namespace = condition_set . get_namespace ( ) if namespace not in self . value : return if not field_name : del self . value [ namespace ] elif field_name not...
Clears conditions given a set of parameters .
29,292
def add_term_facet ( self , * args , ** kwargs ) : self . facets . append ( TermFacet ( * args , ** kwargs ) )
Add a term factory facet
29,293
def add_date_facet ( self , * args , ** kwargs ) : self . facets . append ( DateHistogramFacet ( * args , ** kwargs ) )
Add a date factory facet
29,294
def add_geo_facet ( self , * args , ** kwargs ) : self . facets . append ( GeoDistanceFacet ( * args , ** kwargs ) )
Add a geo factory facet
29,295
def symbol_by_name ( name , aliases = { } , imp = None , package = None , sep = '.' , default = None , ** kwargs ) : if imp is None : imp = importlib . import_module if not isinstance ( name , six . string_types ) : return name name = aliases . get ( name ) or name sep = ':' if ':' in name else sep module_name , _ , cl...
Get symbol by qualified name .
29,296
def import_from_cwd ( module , imp = None , package = None ) : if imp is None : imp = importlib . import_module with cwd_in_path ( ) : return imp ( module , package = package )
Import module but make sure it finds modules located in the current directory .
29,297
def file_to_attachment ( filename , filehandler = None ) : if filehandler : return { '_name' : filename , 'content' : base64 . b64encode ( filehandler . read ( ) ) } with open ( filename , 'rb' ) as _file : return { '_name' : filename , 'content' : base64 . b64encode ( _file . read ( ) ) }
Convert a file to attachment
29,298
def string_to_datetime ( self , obj ) : if isinstance ( obj , six . string_types ) and len ( obj ) == 19 : try : return datetime . strptime ( obj , "%Y-%m-%dT%H:%M:%S" ) except ValueError : pass if isinstance ( obj , six . string_types ) and len ( obj ) > 19 : try : return datetime . strptime ( obj , "%Y-%m-%dT%H:%M:%S...
Decode a datetime string to a datetime object
29,299
def dict_to_object ( self , d ) : for k , v in list ( d . items ( ) ) : if isinstance ( v , six . string_types ) and len ( v ) == 19 : try : d [ k ] = datetime . strptime ( v , "%Y-%m-%dT%H:%M:%S" ) except ValueError : pass elif isinstance ( v , six . string_types ) and len ( v ) > 20 : try : d [ k ] = datetime . strpt...
Decode datetime value from string to datetime