idx
int64
0
63k
question
stringlengths
53
5.28k
target
stringlengths
5
805
26,600
def output_folder ( self , value ) : self . _output_folder = value if not os . path . exists ( self . _output_folder ) : os . makedirs ( self . _output_folder )
Output folder path for the rendering .
26,601
def _check_layer_count ( self , layer ) : if layer : if not layer . isValid ( ) : raise ImpactReport . LayerException ( 'Layer is not valid' ) if isinstance ( layer , QgsRasterLayer ) : return feature_count = len ( [ f for f in layer . getFeatures ( ) ] ) if feature_count == 0 : raise ImpactReport . LayerException ( 'L...
Check for the validity of the layer .
26,602
def map_title ( self ) : try : title = self . _keyword_io . read_keywords ( self . impact , 'map_title' ) return title except KeywordNotFoundError : return None except Exception : return None
Get the map title from the layer keywords if possible .
26,603
def map_legend_attributes ( self ) : LOGGER . debug ( 'InaSAFE Map getMapLegendAttributes called' ) legend_attribute_list = [ 'legend_notes' , 'legend_units' , 'legend_title' ] legend_attribute_dict = { } for legend_attribute in legend_attribute_list : try : legend_attribute_dict [ legend_attribute ] = self . _keyword_...
Get the map legend attribute from the layer keywords if possible .
26,604
def _vector_layers ( self ) : layers = [ ] vector_datasource = self . vector_driver . Open ( self . uri . absoluteFilePath ( ) ) if vector_datasource : for i in range ( vector_datasource . GetLayerCount ( ) ) : layers . append ( vector_datasource . GetLayer ( i ) . GetName ( ) ) return layers
Return a list of vector layers available .
26,605
def _raster_layers ( self ) : layers = [ ] raster_datasource = gdal . Open ( self . uri . absoluteFilePath ( ) ) if raster_datasource : subdatasets = raster_datasource . GetSubDatasets ( ) if len ( subdatasets ) == 0 : metadata = raster_datasource . GetMetadata ( ) layers . append ( metadata [ 'IDENTIFIER' ] ) else : f...
Return a list of raster layers available .
26,606
def _add_vector_layer ( self , vector_layer , layer_name , save_style = False ) : geometry = QGIS_OGR_GEOMETRY_MAP [ vector_layer . wkbType ( ) ] spatial_reference = osr . SpatialReference ( ) qgis_spatial_reference = vector_layer . crs ( ) . authid ( ) epsg = 4326 epsg_string = qgis_spatial_reference if epsg_string : ...
Add a vector layer to the geopackage .
26,607
def _add_tabular_layer ( self , tabular_layer , layer_name , save_style = False ) : return self . _add_vector_layer ( tabular_layer , layer_name , save_style )
Add a tabular layer to the geopackage .
26,608
def selected_canvas_hazlayer ( self ) : if self . lstCanvasHazLayers . selectedItems ( ) : item = self . lstCanvasHazLayers . currentItem ( ) else : return None try : layer_id = item . data ( Qt . UserRole ) except ( AttributeError , NameError ) : layer_id = None layer = QgsProject . instance ( ) . mapLayer ( layer_id ...
Obtain the canvas layer selected by user .
26,609
def list_compatible_canvas_layers ( self ) : italic_font = QFont ( ) italic_font . setItalic ( True ) list_widget = self . lstCanvasHazLayers list_widget . clear ( ) for layer in self . parent . get_compatible_canvas_layers ( 'hazard' ) : item = QListWidgetItem ( layer [ 'name' ] , list_widget ) item . setData ( Qt . U...
Fill the list widget with compatible layers .
26,610
def set_widgets ( self ) : last_layer = self . parent . layer and self . parent . layer . id ( ) or None self . lblDescribeCanvasHazLayer . clear ( ) self . list_compatible_canvas_layers ( ) self . auto_select_one_item ( self . lstCanvasHazLayers ) if last_layer : layers = [ ] for index in range ( self . lstCanvasHazLa...
Set widgets on the Hazard Layer From TOC tab .
26,611
def performance_log_message ( self ) : message = m . Message ( ) table = m . Table ( style_class = 'table table-condensed table-striped' ) row = m . Row ( ) row . add ( m . Cell ( tr ( 'Function' ) , header = True ) ) row . add ( m . Cell ( tr ( 'Time' ) , header = True ) ) if setting ( key = 'memory_profile' , expecte...
Return the profiling log as a message .
26,612
def requested_extent ( self , extent ) : if isinstance ( extent , QgsRectangle ) : self . _requested_extent = extent self . _is_ready = False else : raise InvalidExtentError ( '%s is not a valid extent.' % extent )
Setter for extent property .
26,613
def crs ( self , crs ) : if isinstance ( crs , QgsCoordinateReferenceSystem ) : self . _crs = crs self . _is_ready = False else : raise InvalidExtentError ( '%s is not a valid CRS object.' % crs )
Setter for extent_crs property .
26,614
def datastore ( self , datastore ) : if isinstance ( datastore , DataStore ) : self . _datastore = datastore else : raise Exception ( '%s is not a valid datastore.' % datastore )
Setter for the datastore .
26,615
def duration ( self ) : if self . end_datetime is None or self . start_datetime is None : return 0 return ( self . end_datetime - self . start_datetime ) . total_seconds ( )
The duration of running the impact function in seconds .
26,616
def console_progress_callback ( current , maximum , message = None ) : if maximum > 1000 and current % 1000 != 0 and current != maximum : return if message is not None : LOGGER . info ( message [ 'description' ] ) LOGGER . info ( 'Task progress: %i of %i' % ( current , maximum ) )
Simple console based callback implementation for tests .
26,617
def set_state_process ( self , context , process ) : LOGGER . info ( '%s: %s' % ( context , process ) ) self . state [ context ] [ "process" ] . append ( process )
Method to append process for a context in the IF state .
26,618
def set_state_info ( self , context , key , value ) : LOGGER . info ( '%s: %s: %s' % ( context , key , value ) ) self . state [ context ] [ "info" ] [ key ] = value
Method to add information for a context in the IF state .
26,619
def debug_layer ( self , layer , check_fields = True , add_to_datastore = None ) : check_layer ( layer , has_geometry = None ) if isinstance ( layer , QgsVectorLayer ) and check_fields : is_geojson = '.geojson' in layer . source ( ) . lower ( ) if layer . featureCount ( ) == 0 and is_geojson : pass else : check_inasafe...
Write the layer produced to the datastore if debug mode is on .
26,620
def pre_process ( self ) : LOGGER . info ( 'ANALYSIS : Pre processing' ) for pre_processor in self . _preprocessors : layer = pre_processor [ 'process' ] [ 'function' ] ( self ) purpose = pre_processor [ 'output' ] . get ( 'value' ) [ 'key' ] save_style = pre_processor [ 'output' ] . get ( 'save_style' , False ) result...
Run every pre - processors .
26,621
def hazard_preparation ( self ) : LOGGER . info ( 'ANALYSIS : Hazard preparation' ) use_same_projection = ( self . hazard . crs ( ) . authid ( ) == self . _crs . authid ( ) ) self . set_state_info ( 'hazard' , 'use_same_projection_as_aggregation' , use_same_projection ) if is_raster_layer ( self . hazard ) : extent = s...
This function is doing the hazard preparation .
26,622
def aggregate_hazard_preparation ( self ) : LOGGER . info ( 'ANALYSIS : Aggregate hazard preparation' ) self . set_state_process ( 'hazard' , 'Make hazard layer valid' ) self . hazard = clean_layer ( self . hazard ) self . debug_layer ( self . hazard ) self . set_state_process ( 'aggregation' , 'Union hazard polygons w...
This function is doing the aggregate hazard layer .
26,623
def exposure_preparation ( self ) : LOGGER . info ( 'ANALYSIS : Exposure preparation' ) use_same_projection = ( self . exposure . crs ( ) . authid ( ) == self . _crs . authid ( ) ) self . set_state_info ( 'exposure' , 'use_same_projection_as_aggregation' , use_same_projection ) if is_raster_layer ( self . exposure ) : ...
This function is doing the exposure preparation .
26,624
def intersect_exposure_and_aggregate_hazard ( self ) : LOGGER . info ( 'ANALYSIS : Intersect Exposure and Aggregate Hazard' ) if is_raster_layer ( self . exposure ) : self . set_state_process ( 'impact function' , 'Zonal stats between exposure and aggregate hazard' ) self . _aggregate_hazard_impacted = zonal_stats ( se...
This function intersects the exposure with the aggregate hazard .
26,625
def post_process ( self , layer ) : LOGGER . info ( 'ANALYSIS : Post processing' ) purpose = layer . keywords [ 'layer_purpose' ] if purpose != layer_purpose_aggregation_summary [ 'key' ] : layer_title ( layer ) for post_processor in post_processors : run , run_message = should_run ( layer . keywords , post_processor )...
More process after getting the impact layer with data .
26,626
def summary_calculation ( self ) : LOGGER . info ( 'ANALYSIS : Summary calculation' ) if is_vector_layer ( self . _exposure_summary ) : self . set_state_process ( 'impact function' , 'Aggregate the impact summary' ) self . _aggregate_hazard_impacted = aggregate_hazard_summary ( self . exposure_summary , self . _aggrega...
Do the summary calculation .
26,627
def style ( self ) : LOGGER . info ( 'ANALYSIS : Styling' ) classes = generate_classified_legend ( self . analysis_impacted , self . exposure , self . hazard , self . use_rounding , self . debug_mode ) hazard_class = hazard_class_field [ 'key' ] for layer in self . _outputs ( ) : without_geometries = [ QgsWkbTypes . Nu...
Function to apply some styles to the layers .
26,628
def exposure_notes ( self ) : notes = [ ] exposure = definition ( self . exposure . keywords . get ( 'exposure' ) ) if 'notes' in exposure : notes += exposure [ 'notes' ] if self . exposure . keywords [ 'layer_mode' ] == 'classified' : if 'classified_notes' in exposure : notes += exposure [ 'classified_notes' ] if self...
Get the exposure specific notes defined in definitions .
26,629
def hazard_notes ( self ) : notes = [ ] hazard = definition ( self . hazard . keywords . get ( 'hazard' ) ) if 'notes' in hazard : notes += hazard [ 'notes' ] if self . hazard . keywords [ 'layer_mode' ] == 'classified' : if 'classified_notes' in hazard : notes += hazard [ 'classified_notes' ] if self . hazard . keywor...
Get the hazard specific notes defined in definitions .
26,630
def notes ( self ) : fields = [ ] fields = fields + self . exposure_notes ( ) fields = fields + self . hazard_notes ( ) exposure = definition ( self . exposure . keywords . get ( 'exposure' ) ) hazard = definition ( self . hazard . keywords . get ( 'hazard' ) ) fields . extend ( specific_notes ( hazard , exposure ) ) i...
Return the notes section of the report .
26,631
def action_checklist ( self ) : actions = [ ] exposure = definition ( self . exposure . keywords . get ( 'exposure' ) ) actions . extend ( exposure . get ( 'actions' ) ) hazard = definition ( self . hazard . keywords . get ( 'hazard' ) ) actions . extend ( hazard . get ( 'actions' ) ) actions . extend ( specific_action...
Return the list of action check list dictionary .
26,632
def memory_error ( ) : warning_heading = m . Heading ( tr ( 'Memory issue' ) , ** WARNING_STYLE ) warning_message = tr ( 'There is not enough free memory to run this analysis.' ) suggestion_heading = m . Heading ( tr ( 'Suggestion' ) , ** SUGGESTION_STYLE ) suggestion = tr ( 'Try zooming in to a smaller area or using a...
Display an error when there is not enough memory .
26,633
def create_top_level_index_entry ( title , max_depth , subtitles ) : return_text = title + '\n' dash = '-' * len ( title ) + '\n' return_text += dash + '\n' return_text += '.. toctree::' + '\n' return_text += ' :maxdepth: ' + str ( max_depth ) + '\n\n' for subtitle in subtitles : return_text += ' ' + subtitle + '\n...
Function for creating a text entry in index . rst for its content .
26,634
def create_package_level_rst_index_file ( package_name , max_depth , modules , inner_packages = None ) : if inner_packages is None : inner_packages = [ ] return_text = 'Package::' + package_name dash = '=' * len ( return_text ) return_text += '\n' + dash + '\n\n' return_text += '.. toctree::' + '\n' return_text += ' ...
Function for creating text for index for a package .
26,635
def create_module_rst_file ( module_name ) : return_text = 'Module: ' + module_name dash = '=' * len ( return_text ) return_text += '\n' + dash + '\n\n' return_text += '.. automodule:: ' + module_name + '\n' return_text += ' :members:\n\n' return return_text
Function for creating content in each . rst file for a module .
26,636
def write_rst_file ( file_directory , file_name , content ) : create_dirs ( os . path . split ( os . path . join ( file_directory , file_name ) ) [ 0 ] ) try : fl = open ( os . path . join ( file_directory , file_name + '.rst' ) , 'w+' ) fl . write ( content ) fl . close ( ) except Exception as e : print ( ( 'Creating ...
Shorter procedure for creating rst file .
26,637
def get_python_files_from_list ( files , excluded_files = None ) : if excluded_files is None : excluded_files = [ '__init__.py' ] python_files = [ ] for fl in files : if ( fl . endswith ( '.py' ) and fl not in excluded_files and not fl . startswith ( 'test' ) ) : python_files . append ( fl ) return python_files
Return list of python file from files without excluded files .
26,638
def get_inasafe_code_path ( custom_inasafe_path = None ) : inasafe_code_path = os . path . abspath ( os . path . join ( os . path . dirname ( __file__ ) , '..' ) ) if custom_inasafe_path is not None : inasafe_code_path = custom_inasafe_path return inasafe_code_path
Determine the path to inasafe location .
26,639
def clean_api_docs_dirs ( ) : inasafe_docs_path = os . path . abspath ( os . path . join ( os . path . dirname ( __file__ ) , '..' , 'docs' , 'api-docs' ) ) if os . path . exists ( inasafe_docs_path ) : rmtree ( inasafe_docs_path ) create_dirs ( inasafe_docs_path ) return inasafe_docs_path
Empty previous api - docs directory .
26,640
def create_api_docs ( code_path , api_docs_path , max_depth = 2 ) : base_path = os . path . split ( code_path ) [ 0 ] for package , subpackages , candidate_files in os . walk ( code_path ) : if '__init__.py' not in candidate_files : continue package_relative_path = package . replace ( base_path + os . sep , '' ) index_...
Function for generating . rst file for all . py file in dir_path folder .
26,641
def get_inasafe_fields ( self ) : inasafe_fields = { } parameters = self . parameter_container . get_parameters ( True ) for parameter in parameters : if not parameter . value == no_field : inasafe_fields [ parameter . guid ] = parameter . value return inasafe_fields
Return inasafe fields from the current wizard state .
26,642
def get_inasafe_default_values ( self ) : inasafe_default_values = { } parameters = self . parameter_container . get_parameters ( True ) for parameter in parameters : if parameter . default is not None : inasafe_default_values [ parameter . guid ] = parameter . default return inasafe_default_values
Return inasafe default from the current wizard state .
26,643
def function_options_help ( ) : message = m . Message ( ) message . add ( m . Brand ( ) ) message . add ( heading ( ) ) message . add ( content ( ) ) return message
Help message for Function options Dialog .
26,644
def format_number ( x , use_rounding = True , is_population = False , coefficient = 1 ) : if use_rounding : x = rounding ( x , is_population ) x //= coefficient number = add_separators ( x ) return number
Format a number according to the standards .
26,645
def add_separators ( x ) : try : s = '{0:,}' . format ( x ) except ValueError : return x if locale ( ) in [ 'id' , 'fr' ] : s = s . replace ( ',' , thousand_separator ( ) ) return s
Format integer with separator between thousands .
26,646
def round_affected_number ( number , use_rounding = False , use_population_rounding = False ) : decimal_number = float ( number ) rounded_number = int ( ceil ( decimal_number ) ) if use_rounding and use_population_rounding : return rounding ( rounded_number , use_population_rounding ) elif use_rounding : return rounded...
Tries to convert and round the number .
26,647
def rounding_full ( number , is_population = False ) : if number < 1000 and not is_population : rounding_number = 1 elif number < 1000 and is_population : rounding_number = 10 elif number < 100000 : rounding_number = 100 else : rounding_number = 1000 number = int ( rounding_number * ceil ( float ( number ) / rounding_n...
This function performs a rigorous rounding .
26,648
def convert_unit ( number , input_unit , expected_unit ) : for mapping in unit_mapping : if input_unit == mapping [ 0 ] and expected_unit == mapping [ 1 ] : return number * mapping [ 2 ] if input_unit == mapping [ 1 ] and expected_unit == mapping [ 0 ] : return number / mapping [ 2 ] return None
A helper to convert the unit .
26,649
def coefficient_between_units ( unit_a , unit_b ) : for mapping in unit_mapping : if unit_a == mapping [ 0 ] and unit_b == mapping [ 1 ] : return mapping [ 2 ] if unit_a == mapping [ 1 ] and unit_b == mapping [ 0 ] : return 1 / mapping [ 2 ] return None
A helper to get the coefficient between two units .
26,650
def fatalities_range ( number ) : range_format = '{min_range} - {max_range}' more_than_format = '> {min_range}' ranges = [ [ 0 , 100 ] , [ 100 , 1000 ] , [ 1000 , 10000 ] , [ 10000 , 100000 ] , [ 100000 , float ( 'inf' ) ] ] for r in ranges : min_range = r [ 0 ] max_range = r [ 1 ] if max_range == float ( 'inf' ) : ret...
A helper to return fatalities as a range of number .
26,651
def html_scientific_notation_rate ( rate ) : precision = '%.3f' if rate * 100 > 0 : decimal_rate = Decimal ( precision % ( rate * 100 ) ) if decimal_rate == Decimal ( ( precision % 0 ) ) : decimal_rate = Decimal ( str ( rate * 100 ) ) else : decimal_rate = Decimal ( str ( rate * 100 ) ) if decimal_rate . as_tuple ( ) ....
Helper for convert decimal rate using scientific notation .
26,652
def denomination ( value , min_nominal = None ) : if value is None or ( hasattr ( value , 'isNull' ) and value . isNull ( ) ) : return None , None if not value : return value , None if abs ( value ) == list ( nominal_mapping . keys ( ) ) [ 0 ] and not min_nominal : return 1 * value , nominal_mapping [ list ( nominal_ma...
Return the denomination of a number .
26,653
def legend_title_header_element ( feature , parent ) : _ = feature , parent header = legend_title_header [ 'string_format' ] return header . capitalize ( )
Retrieve legend title header string from definitions .
26,654
def exposure_summary_layer ( ) : project_context_scope = QgsExpressionContextUtils . projectScope ( QgsProject . instance ( ) ) project = QgsProject . instance ( ) key = provenance_layer_analysis_impacted_id [ 'provenance_key' ] analysis_summary_layer = project . mapLayer ( project_context_scope . variable ( key ) ) if...
Helper method for retrieving exposure summary layer .
26,655
def distance_to_nearest_place ( feature , parent ) : _ = feature , parent layer = exposure_summary_layer ( ) if not layer : return None index = layer . fields ( ) . lookupField ( distance_field [ 'field_name' ] ) if index < 0 : return None feature = next ( layer . getFeatures ( ) ) return feature [ index ]
If the impact layer has a distance field it will return the distance to the nearest place in metres .
26,656
def direction_to_nearest_place ( feature , parent ) : _ = feature , parent layer = exposure_summary_layer ( ) if not layer : return None index = layer . fields ( ) . lookupField ( direction_field [ 'field_name' ] ) if index < 0 : return None feature = next ( layer . getFeatures ( ) ) return feature [ index ]
If the impact layer has a distance field it will return the direction to the nearest place .
26,657
def bearing_to_nearest_place ( feature , parent ) : _ = feature , parent layer = exposure_summary_layer ( ) if not layer : return None index = layer . fields ( ) . lookupField ( bearing_field [ 'field_name' ] ) if index < 0 : return None feature = next ( layer . getFeatures ( ) ) return feature [ index ]
If the impact layer has a distance field it will return the bearing to the nearest place in degrees .
26,658
def name_of_the_nearest_place ( feature , parent ) : _ = feature , parent layer = exposure_summary_layer ( ) if not layer : return None index = layer . fields ( ) . lookupField ( exposure_name_field [ 'field_name' ] ) if index < 0 : return None feature = next ( layer . getFeatures ( ) ) return feature [ index ]
If the impact layer has a distance field it will return the name of the nearest place .
26,659
def disclaimer_title_header_element ( feature , parent ) : _ = feature , parent header = disclaimer_title_header [ 'string_format' ] return header . capitalize ( )
Retrieve disclaimer title header string from definitions .
26,660
def information_title_header_element ( feature , parent ) : _ = feature , parent header = information_title_header [ 'string_format' ] return header . capitalize ( )
Retrieve information title header string from definitions .
26,661
def time_title_header_element ( feature , parent ) : _ = feature , parent header = time_title_header [ 'string_format' ] return header . capitalize ( )
Retrieve time title header string from definitions .
26,662
def caution_title_header_element ( feature , parent ) : _ = feature , parent header = caution_title_header [ 'string_format' ] return header . capitalize ( )
Retrieve caution title header string from definitions .
26,663
def source_title_header_element ( feature , parent ) : _ = feature , parent header = source_title_header [ 'string_format' ] return header . capitalize ( )
Retrieve source title header string from definitions .
26,664
def analysis_title_header_element ( feature , parent ) : _ = feature , parent header = analysis_title_header [ 'string_format' ] return header . capitalize ( )
Retrieve analysis title header string from definitions .
26,665
def version_title_header_element ( feature , parent ) : _ = feature , parent header = version_title_header [ 'string_format' ] return header . capitalize ( )
Retrieve version title header string from definitions .
26,666
def crs_text_element ( crs , feature , parent ) : _ = feature , parent crs_definition = QgsCoordinateReferenceSystem ( crs ) crs_description = crs_definition . description ( ) text = crs_text [ 'string_format' ] . format ( crs = crs_description ) return text
Retrieve coordinate reference system text string from definitions .
26,667
def north_arrow_path ( feature , parent ) : _ = feature , parent north_arrow_file = setting ( inasafe_north_arrow_path [ 'setting_key' ] ) if os . path . exists ( north_arrow_file ) : return north_arrow_file else : LOGGER . info ( 'The custom north arrow is not found in {north_arrow_file}. ' 'Default north arrow will b...
Retrieve the full path of default north arrow logo .
26,668
def organisation_logo_path ( feature , parent ) : _ = feature , parent organisation_logo_file = setting ( inasafe_organisation_logo_path [ 'setting_key' ] ) if os . path . exists ( organisation_logo_file ) : return organisation_logo_file else : LOGGER . info ( 'The custom organisation logo is not found in {logo_path}. ...
Retrieve the full path of used specified organisation logo .
26,669
def multi_buffer_help ( ) : message = m . Message ( ) message . add ( m . Brand ( ) ) message . add ( heading ( ) ) message . add ( content ( ) ) return message
Help message for multi buffer dialog .
26,670
def multiply ( ** kwargs ) : result = 1 for i in list ( kwargs . values ( ) ) : if not i : return i result *= i return result
Simple postprocessor where we multiply the input values .
26,671
def calculate_distance ( distance_calculator , place_geometry , latitude , longitude , earthquake_hazard = None , place_exposure = None ) : _ = earthquake_hazard , place_exposure epicenter = QgsPointXY ( longitude , latitude ) place_point = place_geometry . asPoint ( ) distance = distance_calculator . measure_distance ...
Simple postprocessor where we compute the distance between two points .
26,672
def calculate_bearing ( place_geometry , latitude , longitude , earthquake_hazard = None , place_exposure = None ) : _ = earthquake_hazard , place_exposure epicenter = QgsPointXY ( longitude , latitude ) place_point = place_geometry . asPoint ( ) bearing = place_point . azimuth ( epicenter ) return bearing
Simple postprocessor where we compute the bearing angle between two points .
26,673
def calculate_cardinality ( angle , earthquake_hazard = None , place_exposure = None ) : _ = earthquake_hazard , place_exposure direction_list = tr ( 'N,NNE,NE,ENE,E,ESE,SE,SSE,S,SSW,SW,WSW,W,WNW,NW,NNW' ) . split ( ',' ) bearing = float ( angle ) direction_count = len ( direction_list ) direction_interval = 360. / dir...
Simple postprocessor where we compute the cardinality of an angle .
26,674
def post_processor_affected_function ( exposure = None , hazard = None , classification = None , hazard_class = None ) : if exposure == exposure_population [ 'key' ] : affected = is_affected ( hazard , classification , hazard_class ) else : classes = None for hazard in hazard_classes_all : if hazard [ 'key' ] == classi...
Private function used in the affected postprocessor .
26,675
def post_processor_population_displacement_function ( hazard = None , classification = None , hazard_class = None , population = None ) : _ = population return get_displacement_rate ( hazard , classification , hazard_class )
Private function used in the displacement postprocessor .
26,676
def post_processor_population_fatality_function ( classification = None , hazard_class = None , population = None ) : _ = population for hazard in hazard_classes_all : if hazard [ 'key' ] == classification : classification = hazard [ 'classes' ] break for hazard_class_def in classification : if hazard_class_def [ 'key'...
Private function used in the fatality postprocessor .
26,677
def append_ISO19115_keywords ( keywords ) : ISO19115_mapping = { 'ISO19115_ORGANIZATION' : 'organisation' , 'ISO19115_URL' : 'url' , 'ISO19115_EMAIL' : 'email' , 'ISO19115_LICENSE' : 'license' } ISO19115_keywords = { } for key , value in list ( ISO19115_mapping . items ( ) ) : ISO19115_keywords [ value ] = setting ( ke...
Append ISO19115 from setting to keywords .
26,678
def write_iso19115_metadata ( layer_uri , keywords , version_35 = False ) : active_metadata_classes = METADATA_CLASSES if version_35 : active_metadata_classes = METADATA_CLASSES35 if 'layer_purpose' in keywords : if keywords [ 'layer_purpose' ] in active_metadata_classes : metadata = active_metadata_classes [ keywords ...
Create metadata object from a layer path and keywords dictionary .
26,679
def read_iso19115_metadata ( layer_uri , keyword = None , version_35 = False ) : xml_uri = os . path . splitext ( layer_uri ) [ 0 ] + '.xml' file_prefix = 'file:' if xml_uri . startswith ( file_prefix ) : xml_uri = xml_uri [ len ( file_prefix ) : ] if not os . path . exists ( xml_uri ) : xml_uri = None if not xml_uri a...
Retrieve keywords from a metadata object
26,680
def active_classification ( keywords , exposure_key ) : classifications = None if 'classification' in keywords : return keywords [ 'classification' ] if 'layer_mode' in keywords and keywords [ 'layer_mode' ] == layer_mode_continuous [ 'key' ] : classifications = keywords [ 'thresholds' ] . get ( exposure_key ) elif 'va...
Helper to retrieve active classification for an exposure .
26,681
def active_thresholds_value_maps ( keywords , exposure_key ) : if 'classification' in keywords : if keywords [ 'layer_mode' ] == layer_mode_continuous [ 'key' ] : return keywords [ 'thresholds' ] else : return keywords [ 'value_map' ] if keywords [ 'layer_mode' ] == layer_mode_continuous [ 'key' ] : classifications = k...
Helper to retrieve active value maps or thresholds for an exposure .
26,682
def copy_layer_keywords ( layer_keywords ) : copy_keywords = { } for key , value in list ( layer_keywords . items ( ) ) : if isinstance ( value , QUrl ) : copy_keywords [ key ] = value . toString ( ) elif isinstance ( value , datetime ) : copy_keywords [ key ] = value . date ( ) . isoformat ( ) elif isinstance ( value ...
Helper to make a deep copy of a layer keywords .
26,683
def set_widgets ( self ) : on_the_fly_metadata = { } layer_purpose = self . parent . step_kw_purpose . selected_purpose ( ) on_the_fly_metadata [ 'layer_purpose' ] = layer_purpose [ 'key' ] if layer_purpose != layer_purpose_aggregation : subcategory = self . parent . step_kw_subcategory . selected_subcategory ( ) if la...
Set widgets on the Field Mapping step .
26,684
def check_inasafe_fields ( layer , keywords_only = False ) : inasafe_fields = layer . keywords [ 'inasafe_fields' ] real_fields = [ field . name ( ) for field in layer . fields ( ) . toList ( ) ] inasafe_fields_flat = [ ] for value in list ( inasafe_fields . values ( ) ) : if isinstance ( value , list ) : inasafe_field...
Helper to check inasafe_fields .
26,685
def check_layer ( layer , has_geometry = True ) : if is_vector_layer ( layer ) or is_raster_layer ( layer ) : if not layer . isValid ( ) : raise InvalidLayerError ( 'The layer is invalid : %s' % layer . publicSource ( ) ) if is_vector_layer ( layer ) : sub_layers = layer . dataProvider ( ) . subLayers ( ) if len ( sub_...
Helper to check layer validity .
26,686
def default_provenance ( ) : field = TextParameter ( ) field . name = tr ( 'Provenance' ) field . description = tr ( 'The provenance of minimum needs' ) field . value = 'The minimum needs are based on BNPB Perka 7/2008.' return field
The provenance for the default values .
26,687
def accept ( self ) : self . save_state ( ) try : self . require_directory ( ) except CanceledImportDialogError : return QgsApplication . instance ( ) . setOverrideCursor ( QtGui . QCursor ( QtCore . Qt . WaitCursor ) ) source = self . define_url ( ) name = 'jakarta_flood.json' output_directory = self . output_director...
Do PetaBencana download and display it in QGIS .
26,688
def add_flooded_field ( self , shapefile_path ) : layer = QgsVectorLayer ( shapefile_path , self . tr ( 'Jakarta Floods' ) , 'ogr' ) layer . startEditing ( ) flood_class_field = QgsField ( 'floodclass' , QVariant . Int ) layer . addAttribute ( flood_class_field ) layer . commitChanges ( ) layer . startEditing ( ) flood...
Create the layer from the local shp adding the flooded field .
26,689
def copy_keywords ( self , shapefile_path ) : source_xml_path = resources_path ( 'petabencana' , 'flood-keywords.xml' ) output_xml_path = shapefile_path . replace ( 'shp' , 'xml' ) LOGGER . info ( 'Copying xml to: %s' % output_xml_path ) title_token = '[TITLE]' new_title = self . tr ( 'Jakarta Floods - %s' % self . tim...
Copy keywords from the OSM resource directory to the output path .
26,690
def copy_style ( shapefile_path ) : source_qml_path = resources_path ( 'petabencana' , 'flood-style.qml' ) output_qml_path = shapefile_path . replace ( 'shp' , 'qml' ) LOGGER . info ( 'Copying qml to: %s' % output_qml_path ) copy ( source_qml_path , output_qml_path )
Copy style from the OSM resource directory to the output path .
26,691
def download ( self , url , output_path ) : request_failed_message = self . tr ( "Can't access PetaBencana API: {source}" ) . format ( source = url ) downloader = FileDownloader ( url , output_path ) result , message = downloader . download ( ) if not result : display_warning_message_box ( self , self . tr ( 'Download ...
Download file from API url and write to output path .
26,692
def populate_combo_box ( self ) : if self . radio_button_production . isChecked ( ) : self . source = production_api [ 'url' ] available_data = production_api [ 'available_data' ] else : self . source = development_api [ 'url' ] available_data = development_api [ 'available_data' ] self . city_combo_box . clear ( ) for...
Populate combobox for selecting city .
26,693
def define_url ( self ) : current_index = self . city_combo_box . currentIndex ( ) city_code = self . city_combo_box . itemData ( current_index , Qt . UserRole ) source = ( self . source ) . format ( city_code = city_code ) return source
Define API url based on which source is selected .
26,694
def analysis_provenance_details_simplified_extractor ( impact_report , component_metadata ) : context = { } extra_args = component_metadata . extra_args default_source = resolve_from_dictionary ( extra_args , [ 'defaults' , 'source' ] ) default_reference = resolve_from_dictionary ( extra_args , [ 'defaults' , 'referenc...
Extracting simplified version of provenance details of layers .
26,695
def analysis_provenance_details_pdf_extractor ( impact_report , component_metadata ) : context = QGISComposerContext ( ) html_frame_elements = [ { 'id' : 'analysis-provenance-details-report' , 'mode' : 'text' , 'text' : jinja2_output_as_string ( impact_report , 'analysis-provenance-details-report' ) , 'margin_left' : 1...
Extracting the main provenance details to its own pdf report .
26,696
def headerize ( provenances ) : special_case = { 'Inasafe' : 'InaSAFE' , 'Qgis' : 'QGIS' , 'Pyqt' : 'PyQt' , 'Os' : 'OS' , 'Gdal' : 'GDAL' , 'Maps' : 'Map' } for key , value in list ( provenances . items ( ) ) : if '_' in key : header = key . replace ( '_' , ' ' ) . title ( ) else : header = key . title ( ) header_list...
Create a header for each keyword .
26,697
def resolve_dict_keywords ( keywords ) : for keyword in [ 'value_map' , 'inasafe_fields' , 'inasafe_default_values' ] : value = keywords . get ( keyword ) if value : value = value . get ( 'content' ) value = KeywordIO . _dict_to_row ( value ) . to_html ( ) keywords [ keyword ] [ 'content' ] = value value_maps = keyword...
Replace dictionary content with html .
26,698
def sorted_keywords_by_order ( keywords , order ) : for key , value in list ( keywords . items ( ) ) : if value is None : del keywords [ key ] ordered_keywords = OrderedDict ( ) for key in order : if key in list ( keywords . keys ( ) ) : ordered_keywords [ key ] = keywords . get ( key ) for keyword in keywords : if key...
Sort keywords based on defined order .
26,699
def add_action ( self , action , add_to_toolbar = True , add_to_legend = False ) : self . actions . append ( action ) self . iface . addPluginToMenu ( self . tr ( 'InaSAFE' ) , action ) if add_to_toolbar : self . toolbar . addAction ( action ) if add_to_legend : self . iface . addCustomActionForLayerType ( action , sel...
Add a toolbar icon to the InaSAFE toolbar .