idx
int64
0
251k
question
stringlengths
53
3.53k
target
stringlengths
5
1.23k
len_question
int64
20
893
len_target
int64
3
238
26,600
def toggle_dock_visibility ( self ) : if self . dock_widget . isVisible ( ) : self . dock_widget . setVisible ( False ) else : self . dock_widget . setVisible ( True ) self . dock_widget . raise_ ( )
Show or hide the dock widget .
61
7
26,601
def show_extent_selector ( self ) : # import here only so that it is AFTER i18n set up from safe . gui . tools . extent_selector_dialog import ExtentSelectorDialog widget = ExtentSelectorDialog ( self . iface , self . iface . mainWindow ( ) , extent = self . dock_widget . extent . user_extent , crs = self . dock_widget . extent . crs ) widget . clear_extent . connect ( self . dock_widget . extent . clear_user_analysis_extent ) widget . extent_defined . connect ( self . dock_widget . define_user_analysis_extent ) # This ensures that run button state is updated on dialog close widget . extent_selector_closed . connect ( self . dock_widget . validate_impact_function ) # Needs to be non modal to support hide -> interact with map -> show widget . show ( )
Show the extent selector widget for defining analysis extents .
203
11
26,602
def show_options ( self ) : # import here only so that it is AFTER i18n set up from safe . gui . tools . options_dialog import OptionsDialog dialog = OptionsDialog ( iface = self . iface , parent = self . iface . mainWindow ( ) ) dialog . show_option_dialog ( ) if dialog . exec_ ( ) : # modal self . dock_widget . read_settings ( ) from safe . gui . widgets . message import getting_started_message send_static_message ( self . dock_widget , getting_started_message ( ) ) # Issue #4734, make sure to update the combobox after update the # InaSAFE option self . dock_widget . get_layers ( )
Show the options dialog .
162
5
26,603
def show_welcome_message ( self ) : # import here only so that it is AFTER i18n set up from safe . gui . tools . options_dialog import OptionsDialog # Do not show by default show_message = False previous_version = StrictVersion ( setting ( 'previous_version' ) ) current_version = StrictVersion ( inasafe_version ) # Set previous_version to the current inasafe_version set_setting ( 'previous_version' , inasafe_version ) if setting ( 'always_show_welcome_message' , expected_type = bool ) : # Show if it the setting said so show_message = True elif previous_version < current_version : # Always show if the user installed new version show_message = True # Allow to disable welcome message when running automated tests if os . environ . get ( 'INASAFE_DISABLE_WELCOME_MESSAGE' , False ) : show_message = False if show_message : dialog = OptionsDialog ( iface = self . iface , parent = self . iface . mainWindow ( ) ) dialog . show_welcome_dialog ( ) if dialog . exec_ ( ) : # modal self . dock_widget . read_settings ( )
Show the welcome message .
279
5
26,604
def show_keywords_wizard ( self ) : # import here only so that it is AFTER i18n set up from safe . gui . tools . wizard . wizard_dialog import WizardDialog if self . iface . activeLayer ( ) is None : return # Don't break an existing wizard session if accidentally clicked if self . wizard and self . wizard . isVisible ( ) : return # Prevent spawning multiple copies since the IFCW is non modal if not self . wizard : self . wizard = WizardDialog ( self . iface . mainWindow ( ) , self . iface , self . dock_widget ) self . wizard . set_keywords_creation_mode ( ) self . wizard . exec_ ( )
Show the keywords creation wizard .
153
6
26,605
def show_function_centric_wizard ( self ) : # import here only so that it is AFTER i18n set up from safe . gui . tools . wizard . wizard_dialog import WizardDialog # Don't break an existing wizard session if accidentally clicked if self . wizard and self . wizard . isVisible ( ) : return # Prevent spawning multiple copies since it is non modal if not self . wizard : self . wizard = WizardDialog ( self . iface . mainWindow ( ) , self . iface , self . dock_widget ) self . wizard . set_function_centric_mode ( ) # non-modal in order to hide for selecting user extent self . wizard . show ( )
Show the function centric wizard .
148
7
26,606
def show_shakemap_importer ( self ) : # import here only so that it is AFTER i18n set up from safe . gui . tools . shake_grid . shakemap_converter_dialog import ( ShakemapConverterDialog ) dialog = ShakemapConverterDialog ( self . iface . mainWindow ( ) , self . iface , self . dock_widget ) dialog . exec_ ( )
Show the converter dialog .
91
5
26,607
def show_multi_buffer ( self ) : from safe . gui . tools . multi_buffer_dialog import ( MultiBufferDialog ) dialog = MultiBufferDialog ( self . iface . mainWindow ( ) , self . iface , self . dock_widget ) dialog . exec_ ( )
Show the multi buffer tool .
62
6
26,608
def show_osm_downloader ( self ) : from safe . gui . tools . osm_downloader_dialog import OsmDownloaderDialog dialog = OsmDownloaderDialog ( self . iface . mainWindow ( ) , self . iface ) # otherwise dialog is never deleted dialog . setAttribute ( Qt . WA_DeleteOnClose , True ) dialog . show ( )
Show the OSM buildings downloader dialog .
82
9
26,609
def show_geonode_uploader ( self ) : from safe . gui . tools . geonode_uploader import GeonodeUploaderDialog dialog = GeonodeUploaderDialog ( self . iface . mainWindow ( ) ) dialog . show ( )
Show the Geonode uploader dialog .
56
9
26,610
def add_osm_layer ( self ) : path = resources_path ( 'osm' , 'WorldOSM.gdal' ) layer = QgsRasterLayer ( path , self . tr ( 'OpenStreetMap' ) ) project = QgsProject . instance ( ) # Try to add it as the last layer in the list # False flag prevents layer being added to legend project . addMapLayer ( layer , False ) root = QgsProject . instance ( ) . layerTreeRoot ( ) index = len ( root . findLayers ( ) ) + 1 # LOGGER.info('Inserting layer %s at position %s' % ( # layer.source(), index)) root . insertLayer ( index , layer ) project . addMapLayer ( layer )
Add OSM tile layer to the map .
163
9
26,611
def show_field_mapping ( self ) : from safe . gui . tools . field_mapping_dialog import FieldMappingDialog dialog = FieldMappingDialog ( parent = self . iface . mainWindow ( ) , iface = self . iface , ) if dialog . exec_ ( ) : # modal LOGGER . debug ( 'Show field mapping accepted' ) self . dock_widget . layer_changed ( self . iface . activeLayer ( ) ) else : LOGGER . debug ( 'Show field mapping not accepted' )
Show InaSAFE Field Mapping .
116
9
26,612
def show_metadata_converter ( self ) : from safe . gui . tools . metadata_converter_dialog import ( MetadataConverterDialog ) dialog = MetadataConverterDialog ( parent = self . iface . mainWindow ( ) , iface = self . iface , ) dialog . exec_ ( )
Show InaSAFE Metadata Converter .
72
10
26,613
def show_multi_exposure ( self ) : from safe . gui . tools . multi_exposure_dialog import MultiExposureDialog dialog = MultiExposureDialog ( self . iface . mainWindow ( ) , self . iface ) dialog . exec_ ( )
Show InaSAFE Multi Exposure .
58
8
26,614
def add_petabencana_layer ( self ) : from safe . gui . tools . peta_bencana_dialog import PetaBencanaDialog dialog = PetaBencanaDialog ( self . iface . mainWindow ( ) , self . iface ) dialog . show ( )
Add petabencana layer to the map .
65
10
26,615
def show_batch_runner ( self ) : from safe . gui . tools . batch . batch_dialog import BatchDialog dialog = BatchDialog ( parent = self . iface . mainWindow ( ) , iface = self . iface , dock = self . dock_widget ) dialog . exec_ ( )
Show the batch runner dialog .
67
6
26,616
def save_scenario ( self ) : from safe . gui . tools . save_scenario import SaveScenarioDialog dialog = SaveScenarioDialog ( iface = self . iface , dock = self . dock_widget ) dialog . save_scenario ( )
Save current scenario to text file .
56
7
26,617
def layer_changed ( self , layer ) : if not layer : enable_keyword_wizard = False elif not hasattr ( layer , 'providerType' ) : enable_keyword_wizard = False elif layer . providerType ( ) == 'wms' : enable_keyword_wizard = False else : enable_keyword_wizard = True try : if layer : if is_raster_layer ( layer ) : enable_field_mapping_tool = False else : keywords = KeywordIO ( ) . read_keywords ( layer ) keywords_version = keywords . get ( 'keyword_version' ) if not keywords_version : supported = False else : supported = ( is_keyword_version_supported ( keywords_version ) ) if not supported : enable_field_mapping_tool = False else : layer_purpose = keywords . get ( 'layer_purpose' ) if not layer_purpose : enable_field_mapping_tool = False else : if layer_purpose == layer_purpose_exposure [ 'key' ] : layer_subcategory = keywords . get ( 'exposure' ) elif layer_purpose == layer_purpose_hazard [ 'key' ] : layer_subcategory = keywords . get ( 'hazard' ) else : layer_subcategory = None field_groups = get_field_groups ( layer_purpose , layer_subcategory ) if len ( field_groups ) == 0 : # No field group, disable field mapping tool. enable_field_mapping_tool = False else : enable_field_mapping_tool = True else : enable_field_mapping_tool = False except ( KeywordNotFoundError , NoKeywordsFoundError , MetadataReadError ) : # No keywords, disable field mapping tool. enable_field_mapping_tool = False self . action_keywords_wizard . setEnabled ( enable_keyword_wizard ) self . action_field_mapping . setEnabled ( enable_field_mapping_tool )
Enable or disable keywords editor icon when active layer changes .
438
11
26,618
def populate_tabs ( self ) : self . delete_tabs ( ) layer_purpose = self . metadata . get ( 'layer_purpose' ) if not layer_purpose : message = tr ( 'Key layer_purpose is not found in the layer {layer_name}' ) . format ( layer_name = self . layer . name ( ) ) raise KeywordNotFoundError ( message ) if layer_purpose == layer_purpose_exposure [ 'key' ] : layer_subcategory = self . metadata . get ( 'exposure' ) elif layer_purpose == layer_purpose_hazard [ 'key' ] : layer_subcategory = self . metadata . get ( 'hazard' ) else : layer_subcategory = None field_groups = get_field_groups ( layer_purpose , layer_subcategory ) for field_group in field_groups : tab = FieldMappingTab ( field_group , self , self . iface ) tab . set_layer ( self . layer , self . metadata ) self . addTab ( tab , field_group [ 'name' ] ) self . tabs . append ( tab )
Populating tabs based on layer metadata .
242
8
26,619
def evaluate_formula ( formula , variables ) : for key , value in list ( variables . items ( ) ) : if value is None or ( hasattr ( value , 'isNull' ) and value . isNull ( ) ) : # If one value is null, we return null. return value formula = formula . replace ( key , str ( value ) ) result = eval ( formula ) return result
Very simple formula evaluator . Beware the security .
84
11
26,620
def enough_input ( layer , post_processor_input ) : impact_fields = list ( layer . keywords [ 'inasafe_fields' ] . keys ( ) ) for input_key , input_values in list ( post_processor_input . items ( ) ) : input_values = ( input_values if isinstance ( input_values , list ) else [ input_values ] ) msg = None for input_value in input_values : is_constant_input = input_value [ 'type' ] == constant_input_type is_field_input = input_value [ 'type' ] == field_input_type is_dynamic_input = input_value [ 'type' ] == dynamic_field_input_type is_needs_input = input_value [ 'type' ] == needs_profile_input_type is_keyword_input = input_value [ 'type' ] == keyword_input_type is_layer_input = input_value [ 'type' ] == layer_property_input_type is_keyword_value = input_value [ 'type' ] == keyword_value_expected is_geometry_input = ( input_value [ 'type' ] == geometry_property_input_type ) if is_constant_input : # constant input doesn't need any check break elif is_field_input : key = input_value [ 'value' ] [ 'key' ] if key in impact_fields : break else : msg = 'Key %s is missing in fields %s' % ( key , impact_fields ) elif is_dynamic_input : key_template = input_value [ 'value' ] [ 'key' ] field_param = input_value [ 'field_param' ] key = key_template % field_param if key in impact_fields : break else : msg = 'Key %s is missing in dynamic fields %s' % ( key , impact_fields ) elif is_needs_input : parameter_name = input_value [ 'value' ] if minimum_needs_parameter ( parameter_name = parameter_name ) : break else : msg = ( 'Minimum needs %s is missing from current ' 'profile' ) % ( parameter_name , ) elif is_keyword_input : try : reduce ( lambda d , k : d [ k ] , input_value [ 'value' ] , layer . keywords ) break except KeyError : msg = 'Value %s is missing in keyword: %s' % ( input_key , input_value [ 'value' ] ) elif is_layer_input or is_geometry_input : # will be taken from the layer itself, so always true break elif is_keyword_value : try : value = reduce ( lambda d , k : d [ k ] , input_value [ 'value' ] , layer . keywords ) if value == input_value [ 'expected_value' ] : break else : msg = 'Value %s is not expected in keyword: %s' % ( input_value [ 'expected_value' ] , input_value [ 'value' ] ) except KeyError : msg = 'Value %s is missing in keyword: %s' % ( input_key , input_value [ 'value' ] ) else : return False , msg return True , None
Check if the input from impact_fields in enough .
719
11
26,621
def set_value_for_key ( self , key , value ) : if key in self . options : self . options [ key ] [ 'value' ] = value
Set the value of key to value .
36
8
26,622
def on_lstUnits_itemSelectionChanged ( self ) : self . clear_further_steps ( ) # Set widgets unit = self . selected_unit ( ) # Exit if no selection if not unit : return self . lblDescribeUnit . setText ( unit [ 'description' ] ) # Enable the next button self . parent . pbnNext . setEnabled ( True )
Update unit description label and field widgets .
84
8
26,623
def selected_unit ( self ) : item = self . lstUnits . currentItem ( ) try : return definition ( item . data ( QtCore . Qt . UserRole ) ) except ( AttributeError , NameError ) : return None
Obtain the unit selected by user .
51
8
26,624
def set_widgets ( self ) : self . clear_further_steps ( ) # Set widgets purpose = self . parent . step_kw_purpose . selected_purpose ( ) subcategory = self . parent . step_kw_subcategory . selected_subcategory ( ) self . lblSelectUnit . setText ( unit_question % ( subcategory [ 'name' ] , purpose [ 'name' ] ) ) self . lblDescribeUnit . setText ( '' ) self . lstUnits . clear ( ) subcat = self . parent . step_kw_subcategory . selected_subcategory ( ) [ 'key' ] if purpose == layer_purpose_hazard : units_for_layer = hazard_units ( subcat ) else : units_for_layer = exposure_units ( subcat ) for unit_for_layer in units_for_layer : item = QListWidgetItem ( unit_for_layer [ 'name' ] , self . lstUnits ) item . setData ( QtCore . Qt . UserRole , unit_for_layer [ 'key' ] ) self . lstUnits . addItem ( item ) # Set values based on existing keywords (if already assigned) if self . parent . step_kw_purpose . selected_purpose ( ) == layer_purpose_hazard : key = continuous_hazard_unit [ 'key' ] else : key = exposure_unit [ 'key' ] unit_id = self . parent . get_existing_keyword ( key ) if unit_id : units = [ ] for index in range ( self . lstUnits . count ( ) ) : item = self . lstUnits . item ( index ) units . append ( item . data ( QtCore . Qt . UserRole ) ) if unit_id in units : self . lstUnits . setCurrentRow ( units . index ( unit_id ) ) self . auto_select_one_item ( self . lstUnits )
Set widgets on the Unit tab .
425
7
26,625
def get_report_section ( html_report , component_id , container_wrapper_format = container_format ) : no_element_error = tr ( 'No element match the tag or component id.' ) root_element , dict_of_elements = ET . XMLID ( html_report ) section_element = dict_of_elements . get ( component_id ) if section_element : requested_section = container_wrapper_format . format ( section_content = str ( ET . tostring ( section_element ) ) ) return requested_section else : return no_element_error
Get specific report section from InaSAFE analysis summary report .
128
13
26,626
def analysis_summary_report ( feature , parent ) : _ = feature , parent # NOQA project_context_scope = QgsExpressionContextUtils . projectScope ( QgsProject . instance ( ) ) key = provenance_layer_analysis_impacted [ 'provenance_key' ] if not project_context_scope . hasVariable ( key ) : return None analysis_dir = dirname ( project_context_scope . variable ( key ) ) return get_impact_report_as_string ( analysis_dir )
Retrieve an HTML table report of current selected analysis .
114
11
26,627
def analysis_question_report ( feature , parent ) : _ = feature , parent # NOQA project_context_scope = QgsExpressionContextUtils . projectScope ( ) key = provenance_layer_analysis_impacted [ 'provenance_key' ] if not project_context_scope . hasVariable ( key ) : return None analysis_dir = dirname ( project_context_scope . variable ( key ) ) complete_html_report = get_impact_report_as_string ( analysis_dir ) requested_html_report = get_report_section ( complete_html_report , component_id = analysis_question_component [ 'key' ] ) return requested_html_report
Retrieve the analysis question section from InaSAFE report .
151
13
26,628
def population_analysis_summary_report ( feature , parent ) : _ = feature , parent # NOQA analysis_dir = get_analysis_dir ( exposure_population [ 'key' ] ) if analysis_dir : return get_impact_report_as_string ( analysis_dir ) return None
Retrieve an HTML population analysis table report from a multi exposure analysis .
64
14
26,629
def road_analysis_summary_report ( feature , parent ) : _ = feature , parent # NOQA analysis_dir = get_analysis_dir ( exposure_road [ 'key' ] ) if analysis_dir : return get_impact_report_as_string ( analysis_dir ) return None
Retrieve an HTML road analysis table report from a multi exposure analysis .
64
14
26,630
def structure_analysis_summary_report ( feature , parent ) : _ = feature , parent # NOQA analysis_dir = get_analysis_dir ( exposure_structure [ 'key' ] ) if analysis_dir : return get_impact_report_as_string ( analysis_dir ) return None
Retrieve an HTML structure analysis table report from a multi exposure analysis .
65
14
26,631
def place_analysis_summary_report ( feature , parent ) : _ = feature , parent # NOQA analysis_dir = get_analysis_dir ( exposure_place [ 'key' ] ) if analysis_dir : return get_impact_report_as_string ( analysis_dir ) return None
Retrieve an HTML place analysis table report from a multi exposure analysis .
64
14
26,632
def land_cover_analysis_summary_report ( feature , parent ) : _ = feature , parent # NOQA analysis_dir = get_analysis_dir ( exposure_land_cover [ 'key' ] ) if analysis_dir : return get_impact_report_as_string ( analysis_dir ) return None
Retrieve an HTML land cover analysis table report from a multi exposure analysis .
68
15
26,633
def multi_exposure_analysis_summary_report ( feature , parent ) : _ = feature , parent # NOQA analysis_dir = get_analysis_dir ( ) if analysis_dir : return get_impact_report_as_string ( analysis_dir ) return None
Retrieve an HTML multi exposure analysis table report .
59
10
26,634
def show_help ( self , wizard_step ) : self . wizard_step = wizard_step header = html_header ( ) footer = html_footer ( ) content = header message = self . wizard_step . help ( ) content += message . to_html ( ) content += footer self . help_web_view . setHtml ( content ) # Store buttons' state self . next_button_state = self . parent . pbnNext . isEnabled ( ) self . back_button_state = self . parent . pbnBack . isEnabled ( ) # Disable those buttons self . parent . pbnNext . setEnabled ( False ) self . parent . pbnBack . setEnabled ( False )
Set wizard step and show the help text .
151
9
26,635
def restore_button_state ( self ) : self . parent . pbnNext . setEnabled ( self . next_button_state ) self . parent . pbnBack . setEnabled ( self . back_button_state )
Helper to restore button state .
48
6
26,636
def html_footer ( ) : file_path = resources_path ( 'footer.html' ) with open ( file_path ) as header_file : content = header_file . read ( ) return content
Get a standard html footer for wrapping content in .
46
11
26,637
def html_header ( ) : file_path = resources_path ( 'header.html' ) with codecs . open ( file_path , 'r' , encoding = 'utf8' ) as header_file : content = header_file . read ( ) content = content . replace ( 'PATH' , resources_path ( ) ) return content
Get a standard html header for wrapping content in .
74
10
26,638
def resources_path ( * args ) : path = os . path . dirname ( __file__ ) path = os . path . abspath ( os . path . join ( path , os . path . pardir , 'resources' ) ) for item in args : path = os . path . abspath ( os . path . join ( path , item ) ) return path
Get the path to our resources folder .
78
8
26,639
def resource_url ( path ) : url = QtCore . QUrl . fromLocalFile ( path ) return str ( url . toString ( ) )
Get the a local filesystem url to a given resource .
32
11
26,640
def get_ui_class ( ui_file ) : os . path . sep . join ( ui_file . split ( '/' ) ) ui_file_path = os . path . abspath ( os . path . join ( os . path . dirname ( __file__ ) , os . pardir , 'gui' , 'ui' , ui_file ) ) return uic . loadUiType ( ui_file_path ) [ 0 ]
Get UI Python class from . ui file .
102
10
26,641
def set_widgets ( self ) : # Just set values based on existing keywords source = self . parent . get_existing_keyword ( 'source' ) if source or source == 0 : self . leSource . setText ( source ) else : self . leSource . clear ( ) source_scale = self . parent . get_existing_keyword ( 'scale' ) if source_scale or source_scale == 0 : self . leSource_scale . setText ( source_scale ) else : self . leSource_scale . clear ( ) source_date = self . parent . get_existing_keyword ( 'date' ) if source_date : self . ckbSource_date . setChecked ( True ) self . dtSource_date . setDateTime ( source_date ) else : self . ckbSource_date . setChecked ( False ) self . dtSource_date . clear ( ) source_url = self . parent . get_existing_keyword ( 'url' ) try : source_url = source_url . toString ( ) except AttributeError : pass if source_url or source_url == 0 : self . leSource_url . setText ( source_url ) else : self . leSource_url . clear ( ) source_license = self . parent . get_existing_keyword ( 'license' ) if source_license or source_license == 0 : self . leSource_license . setText ( source_license ) else : self . leSource_license . clear ( )
Set widgets on the Source tab .
330
7
26,642
def welcome_message ( ) : message = m . Message ( ) message . add ( m . Brand ( ) ) message . add ( heading ( ) ) message . add ( content ( ) ) return message
Welcome message for first running users .
42
7
26,643
def read_scenarios ( filename ) : # Input checks filename = os . path . abspath ( filename ) blocks = { } parser = ConfigParser ( ) # Parse the file content. # if the content don't have section header # we use the filename. try : parser . read ( filename ) except MissingSectionHeaderError : base_name = os . path . basename ( filename ) name = os . path . splitext ( base_name ) [ 0 ] section = '[%s]\n' % name content = section + open ( filename ) . read ( ) parser . readfp ( StringIO ( content ) ) # convert to dictionary for section in parser . sections ( ) : items = parser . items ( section ) # add section as scenario name items . append ( ( 'scenario_name' , section ) ) # add full path to the blocks items . append ( ( 'full_path' , filename ) ) blocks [ section ] = { } for key , value in items : blocks [ section ] [ key ] = value # Ok we have generated a structure that looks like this: # blocks = {{ 'foo' : { 'a': 'b', 'c': 'd'}, # { 'bar' : { 'd': 'e', 'f': 'g'}} # where foo and bar are scenarios and their dicts are the options for # that scenario (e.g. hazard, exposure etc) return blocks
Read keywords dictionary from file .
304
6
26,644
def validate_scenario ( blocks , scenario_directory ) : # dictionary to temporary contain status message blocks_update = { } for section , section_item in list ( blocks . items ( ) ) : ready = True for item in section_item : if item in [ 'hazard' , 'exposure' , 'aggregation' ] : # get relative path rel_path = section_item [ item ] full_path = os . path . join ( scenario_directory , rel_path ) filepath = os . path . normpath ( full_path ) if not os . path . exists ( filepath ) : blocks_update [ section ] = { 'status' : 'Please update scenario' } LOGGER . info ( section + ' needs to be updated' ) LOGGER . info ( 'Unable to find ' + filepath ) ready = False if ready : blocks_update [ section ] = { 'status' : 'Scenario ready' } # LOGGER.info(section + " scenario is ready") for section , section_item in list ( blocks_update . items ( ) ) : blocks [ section ] [ 'status' ] = blocks_update [ section ] [ 'status' ]
Function to validate input layer stored in scenario file .
252
10
26,645
def append_row ( table , label , data ) : # noinspection PyUnresolvedReferences count = table . rowCount ( ) # noinspection PyUnresolvedReferences table . insertRow ( table . rowCount ( ) ) items = QTableWidgetItem ( label ) # see for details of why we follow this pattern # http://stackoverflow.com/questions/9257422/ # how-to-get-the-original-python-data-from-qvariant # Make the value immutable. variant = ( data , ) # To retrieve it again you would need to do: # value = myVariant.toPyObject()[0] items . setData ( Qt . UserRole , variant ) # set scenario status (ready or not) into table # noinspection PyUnresolvedReferences table . setItem ( count , 0 , items ) # noinspection PyUnresolvedReferences table . setItem ( count , 1 , QTableWidgetItem ( data [ 'status' ] ) )
Append new row to table widget .
216
8
26,646
def restore_state ( self ) : # restore last source path last_source_path = setting ( 'lastSourceDir' , self . default_directory , expected_type = str ) self . source_directory . setText ( last_source_path ) # restore path pdf output last_output_dir = setting ( 'lastOutputDir' , self . default_directory , expected_type = str ) self . output_directory . setText ( last_output_dir ) # restore default output dir combo box use_default_output_dir = bool ( setting ( 'useDefaultOutputDir' , True , expected_type = bool ) ) self . scenario_directory_radio . setChecked ( use_default_output_dir )
Restore GUI state from configuration file .
155
8
26,647
def save_state ( self ) : set_setting ( 'lastSourceDir' , self . source_directory . text ( ) ) set_setting ( 'lastOutputDir' , self . output_directory . text ( ) ) set_setting ( 'useDefaultOutputDir' , self . scenario_directory_radio . isChecked ( ) )
Save current state of GUI to configuration file .
73
9
26,648
def choose_directory ( self , line_edit , title ) : path = line_edit . text ( ) # noinspection PyCallByClass,PyTypeChecker new_path = QFileDialog . getExistingDirectory ( self , title , path , QFileDialog . ShowDirsOnly ) if new_path is not None and os . path . exists ( new_path ) : line_edit . setText ( new_path )
Show a directory selection dialog . This function will show the dialog then set line_edit widget text with output from the dialog .
94
25
26,649
def populate_table ( self , scenario_directory ) : parsed_files = [ ] unparsed_files = [ ] self . table . clearContents ( ) # Block signal to allow update checking only when the table is ready self . table . blockSignals ( True ) # NOTE(gigih): need this line to remove existing rows self . table . setRowCount ( 0 ) if not os . path . exists ( scenario_directory ) : # LOGGER.info('Scenario directory does not exist: %s' % path) return # only support .py and .txt files for current_path in os . listdir ( scenario_directory ) : extension = os . path . splitext ( current_path ) [ 1 ] absolute_path = os . path . join ( scenario_directory , current_path ) if extension == '.py' : append_row ( self . table , current_path , absolute_path ) elif extension == '.txt' : # insert scenarios from file into table widget try : scenarios = read_scenarios ( absolute_path ) validate_scenario ( scenarios , scenario_directory ) for key , value in list ( scenarios . items ( ) ) : append_row ( self . table , key , value ) parsed_files . append ( current_path ) except Error : unparsed_files . append ( current_path ) # unblock signal self . table . blockSignals ( False )
Populate table with files from scenario_directory directory .
302
11
26,650
def run_script ( self , filename ) : module , _ = os . path . splitext ( filename ) if module in sys . modules : script = reload ( sys . modules [ module ] ) else : script = __import__ ( module ) # run entry function function = script . runScript if function . __code__ . co_argcount == 1 : function ( self . iface ) else : function ( )
Run a python script in QGIS to exercise InaSAFE functionality .
88
16
26,651
def reset_status ( self ) : for row in range ( self . table . rowCount ( ) ) : status_item = self . table . item ( row , 1 ) status_item . setText ( self . tr ( '' ) )
Set all scenarios status to empty in the table .
51
10
26,652
def prepare_task ( self , items ) : status = True message = '' # get hazard if 'hazard' in items : hazard_path = items [ 'hazard' ] hazard = self . define_layer ( hazard_path ) if not hazard : status = False message = self . tr ( 'Unable to find {hazard_path}' ) . format ( hazard_path = hazard_path ) else : hazard = None LOGGER . warning ( 'Scenario does not contain hazard path' ) # get exposure if 'exposure' in items : exposure_path = items [ 'exposure' ] exposure = self . define_layer ( exposure_path ) if not exposure : status = False if message : message += '\n' message += self . tr ( 'Unable to find {exposure_path}' ) . format ( exposure_path = exposure_path ) else : exposure = None LOGGER . warning ( 'Scenario does not contain hazard path' ) # get aggregation if 'aggregation' in items : aggregation_path = items [ 'aggregation' ] aggregation = self . define_layer ( aggregation_path ) else : aggregation = None LOGGER . info ( 'Scenario does not contain aggregation path' ) # get extent if 'extent' in items : LOGGER . info ( 'Extent coordinate is found' ) coordinates = items [ 'extent' ] array_coord = extent_string_to_array ( coordinates ) extent = QgsRectangle ( * array_coord ) else : extent = None LOGGER . info ( 'Scenario does not contain extent coordinates' ) # get extent crs id if 'extent_crs' in items : LOGGER . info ( 'Extent CRS is found' ) crs = items [ 'extent_crs' ] extent_crs = QgsCoordinateReferenceSystem ( crs ) else : LOGGER . info ( 'Extent crs is not found, assuming crs to EPSG:4326' ) extent_crs = QgsCoordinateReferenceSystem ( 'EPSG:4326' ) # make sure at least hazard and exposure data are available in # scenario. Aggregation and extent checking will be done when # assigning layer to impact_function if status : parameters = { layer_purpose_hazard [ 'key' ] : hazard , layer_purpose_exposure [ 'key' ] : exposure , layer_purpose_aggregation [ 'key' ] : aggregation , 'extent' : extent , 'crs' : extent_crs } return True , parameters else : LOGGER . warning ( message ) display_critical_message_box ( title = self . tr ( 'Error while preparing scenario' ) , message = message ) return False , None
Prepare scenario for impact function variable .
582
8
26,653
def set_layer_visible ( layer , visible ) : if layer is None : return QgsProject . instance ( ) . layerTreeRoot ( ) . findLayer ( layer . id ( ) ) . setItemVisibilityChecked ( visible )
Sets a layer in the project visible or not
51
10
26,654
def run_selected_clicked ( self ) : # get all selected rows rows = sorted ( set ( index . row ( ) for index in self . table . selectedIndexes ( ) ) ) self . enable_busy_cursor ( ) # iterate over selected rows for row in rows : current_row = row item = self . table . item ( current_row , 0 ) status_item = self . table . item ( current_row , 1 ) self . run_task ( item , status_item ) self . disable_busy_cursor ( )
Run the selected scenario .
121
5
26,655
def run_all_clicked ( self ) : self . reset_status ( ) self . enable_busy_cursor ( ) report = [ ] fail_count = 0 pass_count = 0 index = 0 for row in range ( self . table . rowCount ( ) ) : item = self . table . item ( row , 0 ) status_item = self . table . item ( row , 1 ) name_item = item . text ( ) try : index += 1 result = self . run_task ( item , status_item , index = index ) if result : # P for passed report . append ( 'P: %s\n' % name_item ) pass_count += 1 else : report . append ( 'F: %s\n' % name_item ) fail_count += 1 except Exception as e : # pylint: disable=W0703 LOGGER . exception ( 'Batch execution failed. The exception: ' + str ( e ) ) report . append ( 'F: %s\n' % name_item ) fail_count += 1 self . disable_busy_cursor ( ) try : report_path = self . write_report ( report , pass_count , fail_count ) self . show_report ( report_path ) except IOError : # noinspection PyArgumentList,PyCallByClass,PyTypeChecker QMessageBox . question ( self , 'Error' , 'Failed to write report file.' ) self . disable_busy_cursor ( ) self . disable_busy_cursor ( )
Run all scenario when pbRunAll is clicked .
338
11
26,656
def write_report ( self , report , pass_count , fail_count ) : separator = '-----------------------------\n' current_time = datetime . now ( ) . strftime ( '%Y%m%d%H%M%S' ) report_path = 'batch-report-' + current_time + '.txt' output_path = self . output_directory . text ( ) path = os . path . join ( output_path , report_path ) try : report_file = open ( path , 'w' ) report_file . write ( 'InaSAFE Batch Report File\n' ) report_file . write ( separator ) for myLine in report : report_file . write ( myLine ) report_file . write ( separator ) report_file . write ( 'Total passed: %s\n' % pass_count ) report_file . write ( 'Total failed: %s\n' % fail_count ) report_file . write ( 'Total tasks: %s\n' % len ( report ) ) report_file . write ( separator ) report_file . close ( ) # LOGGER.info('Log written to %s' % path) return path except IOError : raise IOError
Write a report status of Batch Runner .
269
9
26,657
def generate_pdf_report ( self , impact_function , iface , scenario_name ) : # output folder output_dir = self . output_directory . text ( ) file_path = os . path . join ( output_dir , scenario_name ) # create impact table report instance table_report_metadata = ReportMetadata ( metadata_dict = standard_impact_report_metadata_pdf ) impact_table_report = ImpactReport ( iface , table_report_metadata , impact_function = impact_function ) impact_table_report . output_folder = file_path impact_table_report . process_components ( ) # create impact map report instance map_report_metadata = ReportMetadata ( metadata_dict = update_template_component ( map_report ) ) impact_map_report = ImpactReport ( iface , map_report_metadata , impact_function = impact_function ) # TODO: Get from settings file # get the extent of impact layer impact_map_report . qgis_composition_context . extent = impact_function . impact . extent ( ) impact_map_report . output_folder = file_path impact_map_report . process_components ( )
Generate and store map and impact report from impact function .
259
12
26,658
def show_report ( self , report_path ) : if self . show_results_popup : url = QtCore . QUrl . fromLocalFile ( report_path ) # noinspection PyTypeChecker,PyCallByClass,PyArgumentList QtGui . QDesktopServices . openUrl ( url ) else : # report = open(report_path).read() # LOGGER.info(report) pass
Show batch report file in batchReportFileName using an external app .
91
14
26,659
def update_default_output_dir ( self ) : if self . scenario_directory_radio . isChecked ( ) : self . output_directory . setText ( self . source_directory . text ( ) )
Update output dir if set to default .
46
8
26,660
def enable_busy_cursor ( self ) : QgsApplication . instance ( ) . setOverrideCursor ( QtGui . QCursor ( QtCore . Qt . WaitCursor ) )
Set the hourglass enabled .
42
6
26,661
def on_scenario_directory_radio_toggled ( self , flag ) : if flag : self . output_directory . setText ( self . source_directory . text ( ) ) self . output_directory_chooser . setEnabled ( not flag )
Autoconnect slot activated when scenario_directory_radio is checked .
56
14
26,662
def on_source_directory_chooser_clicked ( self ) : title = self . tr ( 'Set the source directory for script and scenario' ) self . choose_directory ( self . source_directory , title )
Autoconnect slot activated when tbSourceDir is clicked .
47
13
26,663
def on_output_directory_chooser_clicked ( self ) : title = self . tr ( 'Set the output directory for pdf report files' ) self . choose_directory ( self . output_directory , title )
Auto connect slot activated when tbOutputDiris clicked .
47
12
26,664
def to_html ( self ) : # Apply bootstrap alignment classes first if self . align is 'left' : if self . style_class is None : self . style_class = 'text-left' else : self . style_class += ' text-left' elif self . align is 'right' : if self . style_class is None : self . style_class = 'text-right' else : self . style_class += ' text-right' elif self . align is 'center' : if self . style_class is None : self . style_class = 'text-center' else : self . style_class += ' text-center' # Special case for when we want to put a nested table in a cell # We don't use isinstance because of recursive imports with table class_name = self . content . __class__ . __name__ if class_name in [ 'BulletedList' , 'Table' , 'Image' , 'Message' ] : html = self . content . to_html ( ) else : html = self . content . to_html ( wrap_slash = self . wrap_slash ) # Check if we have a header or not then render if self . header_flag is True : return '<th%s colspan=%i>%s</th>\n' % ( self . html_attributes ( ) , self . span , html ) else : return '<td%s colspan=%i>%s</td>\n' % ( self . html_attributes ( ) , self . span , html )
Render a Cell MessageElement as html
342
7
26,665
def error_creator5 ( ) : try : error_creator4 ( ) except SafeError as e4 : message = ErrorMessage ( 'Creator 5 problem' , detail = Message ( Paragraph ( 'Could not' , ImportantText ( 'call' ) , 'function.' ) , Paragraph ( 'Try reinstalling your computer with windows.' ) ) , suggestion = Message ( ImportantText ( 'Important note' ) ) ) e4 . error_message . append ( message ) raise
Raise a safe style error and append a full message .
102
12
26,666
def qgis_composer_infographic_extractor ( impact_report , component_metadata ) : qgis_context = impact_report . qgis_composition_context extra_args = component_metadata . extra_args context = QGISComposerContext ( ) """Image Elements.""" # get all image elements with their respective source path image_elements = deepcopy ( image_item_elements ) # remove inasafe_logo_white because we use expression for the image source image_elements . remove ( inasafe_logo_white ) # remove population_chart because we still don't have the source path image_elements . remove ( population_chart ) context . image_elements = image_elements # get the source path of population_chart population_donut_path = impact_report . component_absolute_output_path ( 'population-chart-png' ) population_chart [ 'path' ] = population_donut_path context . image_elements . append ( population_chart ) """HTML Elements.""" components = resolve_from_dictionary ( extra_args , 'components' ) html_elements = deepcopy ( html_frame_elements ) # get the html content from component that has been proceed for element in html_elements : component = components . get ( element [ 'component' ] ) if component : element [ 'text' ] = jinja2_output_as_string ( impact_report , component [ 'key' ] ) context . html_frame_elements = html_elements """Map Elements.""" map_overview_layer = None project = QgsProject . instance ( ) for layer in list ( project . mapLayers ( ) . values ( ) ) : if layer . name ( ) == map_overview [ 'id' ] : map_overview_layer = layer layers = [ impact_report . impact_function . analysis_impacted ] if map_overview_layer : layers . append ( map_overview_layer ) # default extent is analysis extent if not qgis_context . extent : qgis_context . extent = impact_report . impact_function . analysis_extent map_elements = [ { 'id' : 'map-overview' , 'extent' : qgis_context . extent , 'grid_split_count' : 5 , 'layers' : layers , } ] context . map_elements = map_elements return context
Extract composer context specific for infographic template .
542
9
26,667
def inasafe_fields_for_the_layer ( self ) : if ( self . parent . get_layer_geometry_key ( ) == layer_geometry_raster [ 'key' ] ) : return [ ] # Get hazard or exposure value layer_purpose_key = self . parent . step_kw_purpose . selected_purpose ( ) [ 'key' ] if layer_purpose_key != layer_purpose_aggregation [ 'key' ] : subcategory_key = self . parent . step_kw_subcategory . selected_subcategory ( ) [ 'key' ] else : subcategory_key = None # Get all fields with replace_null = False inasafe_fields = get_fields ( layer_purpose_key , subcategory_key , replace_null = False , in_group = False ) # remove compulsory field since it has been set in previous step try : inasafe_fields . remove ( get_compulsory_fields ( layer_purpose_key , subcategory_key ) ) except ValueError : pass return inasafe_fields
Return a list of inasafe fields the current layer .
232
12
26,668
def __if_not_basestring ( text_object ) : converted_str = text_object if not isinstance ( text_object , str ) : converted_str = str ( text_object ) return converted_str
Convert to str
48
4
26,669
def get_string ( input_text , encoding = 'utf-8' ) : if isinstance ( input_text , str ) : return input_text . encode ( encoding ) return input_text
Get byte string representation of an object .
42
8
26,670
def byteify ( input_object ) : if isinstance ( input_object , dict ) : return { byteify ( key ) : byteify ( value ) for key , value in list ( input_object . items ( ) ) } elif isinstance ( input_object , list ) : return [ byteify ( element ) for element in input_object ] elif isinstance ( input_object , str ) : return input_object . encode ( 'utf-8' ) else : return input_object
Recursive function to transform an object to byte .
106
10
26,671
def dict ( self ) : metadata = super ( ImpactLayerMetadata , self ) . dict metadata [ 'provenance' ] = self . provenance metadata [ 'summary_data' ] = self . summary_data return metadata
calls the overridden method and adds provenance and summary data
47
13
26,672
def _read_provenance_from_xml ( self , root ) : path = self . _special_properties [ 'provenance' ] provenance = root . find ( path , XML_NS ) for step in provenance . iter ( 'provenance_step' ) : title = step . find ( 'title' ) . text description = step . find ( 'description' ) . text timestamp = step . get ( 'timestamp' ) if 'IF Provenance' in title : data = { } from safe . metadata35 . provenance import IFProvenanceStep keys = IFProvenanceStep . impact_functions_fields for key in keys : value = step . find ( key ) if value is not None : data [ key ] = value . text else : data [ key ] = '' self . append_if_provenance_step ( title , description , timestamp , data ) else : self . append_provenance_step ( title , description , timestamp )
read metadata provenance from xml .
207
7
26,673
def append_provenance_step ( self , title , description , timestamp = None ) : step_time = self . _provenance . append_step ( title , description , timestamp ) if step_time > self . last_update : self . last_update = step_time
Add a step to the provenance of the metadata
59
10
26,674
def append_if_provenance_step ( self , title , description , timestamp = None , data = None ) : step_time = self . _provenance . append_if_provenance_step ( title , description , timestamp , data ) if step_time > self . last_update : self . last_update = step_time
Add a if provenance step to the provenance of the metadata
72
13
26,675
def update_from_dict ( self , keywords ) : super ( ImpactLayerMetadata , self ) . update_from_dict ( keywords ) if 'if_provenance' in list ( keywords . keys ( ) ) : if_provenance = keywords [ 'if_provenance' ] for provenance_step in if_provenance : self . provenance . append_provenance_step ( provenance_step )
Update metadata value from a keywords dictionary .
89
8
26,676
def update_list_widget ( self ) : # Get selected radio button radio_button_checked_id = self . input_button_group . checkedId ( ) # No radio button checked, then default value = None if radio_button_checked_id > - 1 : selected_dict = list ( self . _parameter . options . values ( ) ) [ radio_button_checked_id ] if selected_dict . get ( 'type' ) == MULTIPLE_DYNAMIC : for field in selected_dict . get ( 'value' ) : # Update list widget field_item = QListWidgetItem ( self . list_widget ) field_item . setFlags ( Qt . ItemIsEnabled | Qt . ItemIsSelectable | Qt . ItemIsDragEnabled ) field_item . setData ( Qt . UserRole , field ) field_item . setText ( field ) self . list_widget . addItem ( field_item )
Update list widget when radio button is clicked .
203
9
26,677
def radio_buttons_clicked ( self ) : # Disable all spin boxes for spin_box in list ( self . spin_boxes . values ( ) ) : spin_box . setEnabled ( False ) # Disable list widget self . list_widget . setEnabled ( False ) # Get selected radio button radio_button_checked_id = self . input_button_group . checkedId ( ) if radio_button_checked_id > - 1 : selected_value = list ( self . _parameter . options . values ( ) ) [ radio_button_checked_id ] if selected_value . get ( 'type' ) == MULTIPLE_DYNAMIC : # Enable list widget self . list_widget . setEnabled ( True ) elif selected_value . get ( 'type' ) == SINGLE_DYNAMIC : selected_key = list ( self . _parameter . options . keys ( ) ) [ radio_button_checked_id ] self . spin_boxes [ selected_key ] . setEnabled ( True )
Handler when selected radio button changed .
225
7
26,678
def select_radio_button ( self , key ) : key_index = list ( self . _parameter . options . keys ( ) ) . index ( key ) radio_button = self . input_button_group . button ( key_index ) radio_button . click ( )
Helper to select a radio button with key .
60
9
26,679
def to_html ( self ) : uri = resource_url ( resources_path ( 'img' , 'logos' , 'inasafe-logo-white.png' ) ) snippet = ( '<div class="branding">' '<img src="%s" title="%s" alt="%s" %s/></div>' ) % ( uri , 'InaSAFE' , 'InaSAFE' , self . html_attributes ( ) ) return snippet
Render as html .
109
4
26,680
def mmi_detail_extractor ( impact_report , component_metadata ) : context = { } analysis_layer = impact_report . analysis analysis_layer_keywords = analysis_layer . keywords extra_args = component_metadata . extra_args use_rounding = impact_report . impact_function . use_rounding provenance = impact_report . impact_function . provenance hazard_keywords = provenance [ 'hazard_keywords' ] exposure_keywords = provenance [ 'exposure_keywords' ] # check if this is EQ raster with population hazard_type = definition ( hazard_keywords [ 'hazard' ] ) if not hazard_type == hazard_earthquake : return context hazard_geometry = hazard_keywords [ layer_geometry [ 'key' ] ] if not hazard_geometry == layer_geometry_raster [ 'key' ] : return context exposure_type = definition ( exposure_keywords [ 'exposure' ] ) if not exposure_type == exposure_population : return context header = resolve_from_dictionary ( extra_args , 'header' ) context [ 'header' ] = header reported_fields = resolve_from_dictionary ( extra_args , 'reported_fields' ) """Generate headers.""" table_header = [ resolve_from_dictionary ( extra_args , 'mmi_header' ) ] + [ v [ 'header' ] for v in reported_fields ] """Extract MMI-related data""" # mmi is ranged from 1 to 10, which means: [1, 11) mmi_range = list ( range ( 1 , 11 ) ) rows = [ ] roman_numeral = [ 'I' , 'II' , 'III' , 'IV' , 'V' , 'VI' , 'VII' , 'VIII' , 'IX' , 'X' ] for i in mmi_range : columns = [ roman_numeral [ i - 1 ] ] for value in reported_fields : field = value [ 'field' ] try : key_name = field [ 'key' ] % ( i , ) field_name = analysis_layer_keywords [ key_name ] # check field exists count = value_from_field_name ( field_name , analysis_layer ) if not count : count = 0 except KeyError : count = 0 count = format_number ( count , use_rounding = use_rounding , is_population = True ) columns . append ( count ) rows . append ( columns ) """Extract total.""" total_footer = [ resolve_from_dictionary ( extra_args , 'total_header' ) ] total_fields = resolve_from_dictionary ( extra_args , 'total_fields' ) for field in total_fields : try : field_name = analysis_layer_keywords [ field [ 'key' ] ] total = value_from_field_name ( field_name , analysis_layer ) if not total : total = 0 except KeyError : total = 0 total = format_number ( total , use_rounding = use_rounding , is_population = True ) total_footer . append ( total ) context [ 'component_key' ] = component_metadata . key context [ 'mmi' ] = { 'header' : table_header , 'rows' : rows , 'footer' : total_footer } return context
Extracting MMI - related analysis result .
743
10
26,681
def inasafe_field_header ( field , feature , parent ) : _ = feature , parent # NOQA age_fields = [ under_5_displaced_count_field , over_60_displaced_count_field ] symbol_mapping = { 'over' : '>' , 'under' : '<' } field_definition = definition ( field , 'field_name' ) if field_definition : if field_definition in age_fields : header_format = tr ( '{symbol} {age} y.o' ) field_name = field_definition . get ( 'field_name' ) if field_name : symbol , age = field_name . split ( '_' ) [ : 2 ] if symbol . lower ( ) in list ( symbol_mapping . keys ( ) ) : header_name = header_format . format ( symbol = symbol_mapping [ symbol . lower ( ) ] , age = age ) return header_name header_name = field_definition . get ( 'header_name' ) name = field_definition . get ( 'name' ) if header_name : return header_name . capitalize ( ) else : return name . capitalize ( ) return None
Retrieve a header name of the field name from definitions .
262
12
26,682
def minimum_needs_unit ( field , feature , parent ) : _ = feature , parent # NOQA field_definition = definition ( field , 'field_name' ) if field_definition : unit_abbreviation = None frequency = None if field_definition . get ( 'need_parameter' ) : need = field_definition [ 'need_parameter' ] if isinstance ( need , ResourceParameter ) : unit_abbreviation = need . unit . abbreviation frequency = need . frequency elif field_definition . get ( 'unit' ) : need_unit = field_definition . get ( 'unit' ) unit_abbreviation = need_unit . get ( 'abbreviation' ) if field_definition . get ( 'frequency' ) and not frequency : frequency = field_definition . get ( 'frequency' ) if not unit_abbreviation : unit_abbreviation = exposure_unit [ 'plural_name' ] once_frequency_field_keys = [ 'minimum_needs__toilets_count_field' ] if not frequency or ( field_definition [ 'key' ] in once_frequency_field_keys ) : return unit_abbreviation . lower ( ) unit_format = '{unit_abbreviation}/{frequency}' return unit_format . format ( unit_abbreviation = unit_abbreviation , frequency = frequency ) . lower ( ) return None
Retrieve units of the given minimum needs field name .
306
11
26,683
def infographic_header_element ( impact_function_name , feature , parent ) : _ = feature , parent # NOQA string_format = infographic_header [ 'string_format' ] if impact_function_name : header = string_format . format ( impact_function_name = impact_function_name ) return header . capitalize ( ) return None
Get a formatted infographic header sentence for an impact function .
76
11
26,684
def map_overview_header_element ( feature , parent ) : _ = feature , parent # NOQA header = map_overview_header [ 'string_format' ] return header . capitalize ( )
Retrieve map overview header string from definitions .
45
9
26,685
def population_chart_header_element ( feature , parent ) : _ = feature , parent # NOQA header = population_chart_header [ 'string_format' ] return header . capitalize ( )
Retrieve population chart header string from definitions .
43
9
26,686
def people_section_header_element ( feature , parent ) : _ = feature , parent # NOQA header = people_section_header [ 'string_format' ] return header . capitalize ( )
Retrieve people section header string from definitions .
43
9
26,687
def age_gender_section_header_element ( feature , parent ) : _ = feature , parent # NOQA header = age_gender_section_header [ 'string_format' ] return header . capitalize ( )
Retrieve age gender section header string from definitions .
47
10
26,688
def vulnerability_section_header_element ( feature , parent ) : _ = feature , parent # NOQA header = vulnerability_section_header [ 'string_format' ] return header . capitalize ( )
Retrieve vulnerability section header string from definitions .
43
9
26,689
def female_vulnerability_section_header_element ( feature , parent ) : _ = feature , parent # NOQA header = female_vulnerability_section_header [ 'string_format' ] return header . capitalize ( )
Retrieve female vulnerability section header string from definitions .
49
10
26,690
def minimum_needs_section_header_element ( feature , parent ) : _ = feature , parent # NOQA header = minimum_needs_section_header [ 'string_format' ] return header . capitalize ( )
Retrieve minimum needs section header string from definitions .
47
10
26,691
def additional_minimum_needs_section_header_element ( feature , parent ) : _ = feature , parent # NOQA header = additional_minimum_needs_section_header [ 'string_format' ] return header . capitalize ( )
Retrieve additional minimum needs section header string from definitions .
51
11
26,692
def serialize ( self ) : pickle = super ( ResourceParameter , self ) . serialize ( ) pickle [ 'frequency' ] = self . frequency pickle [ 'unit' ] = self . _unit . serialize ( ) return pickle
Convert the parameter into a dictionary .
53
8
26,693
def reject ( self ) : if self . stacked_widget . currentWidget ( ) == self . resource_edit_page : self . edit_item = None self . switch_context ( self . profile_edit_page ) else : super ( NeedsManagerDialog , self ) . reject ( )
Overload the base dialog reject event so we can handle state change .
61
14
26,694
def populate_resource_list ( self ) : minimum_needs = self . minimum_needs . get_full_needs ( ) for full_resource in minimum_needs [ "resources" ] : self . add_resource ( full_resource ) self . provenance . setText ( minimum_needs [ "provenance" ] )
Populate the list resource list .
69
7
26,695
def add_resource ( self , resource ) : updated_sentence = NeedsProfile . format_sentence ( resource [ 'Readable sentence' ] , resource ) if self . edit_item : item = self . edit_item item . setText ( updated_sentence ) self . edit_item = None else : item = QtWidgets . QListWidgetItem ( updated_sentence ) item . resource_full = resource self . resources_list . addItem ( item )
Add a resource to the minimum needs table .
102
9
26,696
def restore_defaults ( self ) : title = tr ( 'Restore defaults' ) msg = tr ( 'Restoring defaults will overwrite your changes on profiles ' 'provided by InaSAFE. Do you want to continue ?' ) # noinspection PyCallByClass reply = QMessageBox . question ( self , title , msg , QtWidgets . QMessageBox . Yes , QtWidgets . QMessageBox . No ) if reply == QtWidgets . QMessageBox . Yes : self . profile_combo . clear ( ) self . load_profiles ( True ) # Next 2 lines fixes issues #1388 #1389 #1390 #1391 if self . profile_combo . count ( ) > 0 : self . select_profile ( 0 )
Restore defaults profiles .
167
5
26,697
def load_profiles ( self , overwrite = False ) : for profile in self . minimum_needs . get_profiles ( overwrite ) : self . profile_combo . addItem ( profile ) minimum_needs = self . minimum_needs . get_full_needs ( ) self . profile_combo . setCurrentIndex ( self . profile_combo . findText ( minimum_needs [ 'profile' ] ) )
Load the profiles into the dropdown list .
90
9
26,698
def select_profile ( self , index ) : new_profile = self . profile_combo . itemText ( index ) self . resources_list . clear ( ) self . minimum_needs . load_profile ( new_profile ) self . clear_resource_list ( ) self . populate_resource_list ( ) self . minimum_needs . save ( )
Select a given profile by index .
76
7
26,699
def mark_current_profile_as_pending ( self ) : index = self . profile_combo . currentIndex ( ) item = self . profile_combo . model ( ) . item ( index ) item . setForeground ( QtGui . QColor ( 'red' ) )
Mark the current profile as pending by colouring the text red .
63
13