repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1 value | code stringlengths 75 19.8k | code_tokens listlengths 20 707 | docstring stringlengths 3 17.3k | docstring_tokens listlengths 3 222 | sha stringlengths 40 40 | url stringlengths 87 242 | partition stringclasses 1 value | idx int64 0 252k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
inasafe/inasafe | safe/plugin.py | Plugin._create_keywords_wizard_action | def _create_keywords_wizard_action(self):
"""Create action for keywords creation wizard."""
icon = resources_path('img', 'icons', 'show-keyword-wizard.svg')
self.action_keywords_wizard = QAction(
QIcon(icon),
self.tr('Keywords Creation Wizard'),
self.iface.mainWindow())
self.action_keywords_wizard.setStatusTip(self.tr(
'Open InaSAFE keywords creation wizard'))
self.action_keywords_wizard.setWhatsThis(self.tr(
'Open InaSAFE keywords creation wizard'))
self.action_keywords_wizard.setEnabled(False)
self.action_keywords_wizard.triggered.connect(
self.show_keywords_wizard)
self.add_action(self.action_keywords_wizard, add_to_legend=True) | python | def _create_keywords_wizard_action(self):
"""Create action for keywords creation wizard."""
icon = resources_path('img', 'icons', 'show-keyword-wizard.svg')
self.action_keywords_wizard = QAction(
QIcon(icon),
self.tr('Keywords Creation Wizard'),
self.iface.mainWindow())
self.action_keywords_wizard.setStatusTip(self.tr(
'Open InaSAFE keywords creation wizard'))
self.action_keywords_wizard.setWhatsThis(self.tr(
'Open InaSAFE keywords creation wizard'))
self.action_keywords_wizard.setEnabled(False)
self.action_keywords_wizard.triggered.connect(
self.show_keywords_wizard)
self.add_action(self.action_keywords_wizard, add_to_legend=True) | [
"def",
"_create_keywords_wizard_action",
"(",
"self",
")",
":",
"icon",
"=",
"resources_path",
"(",
"'img'",
",",
"'icons'",
",",
"'show-keyword-wizard.svg'",
")",
"self",
".",
"action_keywords_wizard",
"=",
"QAction",
"(",
"QIcon",
"(",
"icon",
")",
",",
"self"... | Create action for keywords creation wizard. | [
"Create",
"action",
"for",
"keywords",
"creation",
"wizard",
"."
] | 831d60abba919f6d481dc94a8d988cc205130724 | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/plugin.py#L191-L205 | train | 26,700 |
inasafe/inasafe | safe/plugin.py | Plugin._create_analysis_wizard_action | def _create_analysis_wizard_action(self):
"""Create action for IF-centric wizard."""
icon = resources_path('img', 'icons', 'show-wizard.svg')
self.action_function_centric_wizard = QAction(
QIcon(icon),
self.tr('Impact Function Centric Wizard'),
self.iface.mainWindow())
self.action_function_centric_wizard.setStatusTip(self.tr(
'Open InaSAFE impact function centric wizard'))
self.action_function_centric_wizard.setWhatsThis(self.tr(
'Open InaSAFE impact function centric wizard'))
self.action_function_centric_wizard.setEnabled(True)
self.action_function_centric_wizard.triggered.connect(
self.show_function_centric_wizard)
self.add_action(self.action_function_centric_wizard) | python | def _create_analysis_wizard_action(self):
"""Create action for IF-centric wizard."""
icon = resources_path('img', 'icons', 'show-wizard.svg')
self.action_function_centric_wizard = QAction(
QIcon(icon),
self.tr('Impact Function Centric Wizard'),
self.iface.mainWindow())
self.action_function_centric_wizard.setStatusTip(self.tr(
'Open InaSAFE impact function centric wizard'))
self.action_function_centric_wizard.setWhatsThis(self.tr(
'Open InaSAFE impact function centric wizard'))
self.action_function_centric_wizard.setEnabled(True)
self.action_function_centric_wizard.triggered.connect(
self.show_function_centric_wizard)
self.add_action(self.action_function_centric_wizard) | [
"def",
"_create_analysis_wizard_action",
"(",
"self",
")",
":",
"icon",
"=",
"resources_path",
"(",
"'img'",
",",
"'icons'",
",",
"'show-wizard.svg'",
")",
"self",
".",
"action_function_centric_wizard",
"=",
"QAction",
"(",
"QIcon",
"(",
"icon",
")",
",",
"self"... | Create action for IF-centric wizard. | [
"Create",
"action",
"for",
"IF",
"-",
"centric",
"wizard",
"."
] | 831d60abba919f6d481dc94a8d988cc205130724 | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/plugin.py#L207-L221 | train | 26,701 |
inasafe/inasafe | safe/plugin.py | Plugin._create_options_dialog_action | def _create_options_dialog_action(self):
"""Create action for options dialog."""
icon = resources_path('img', 'icons', 'configure-inasafe.svg')
self.action_options = QAction(
QIcon(icon),
self.tr('Options'), self.iface.mainWindow())
self.action_options.setStatusTip(self.tr(
'Open InaSAFE options dialog'))
self.action_options.setWhatsThis(self.tr(
'Open InaSAFE options dialog'))
self.action_options.triggered.connect(self.show_options)
self.add_action(self.action_options, add_to_toolbar=self.full_toolbar) | python | def _create_options_dialog_action(self):
"""Create action for options dialog."""
icon = resources_path('img', 'icons', 'configure-inasafe.svg')
self.action_options = QAction(
QIcon(icon),
self.tr('Options'), self.iface.mainWindow())
self.action_options.setStatusTip(self.tr(
'Open InaSAFE options dialog'))
self.action_options.setWhatsThis(self.tr(
'Open InaSAFE options dialog'))
self.action_options.triggered.connect(self.show_options)
self.add_action(self.action_options, add_to_toolbar=self.full_toolbar) | [
"def",
"_create_options_dialog_action",
"(",
"self",
")",
":",
"icon",
"=",
"resources_path",
"(",
"'img'",
",",
"'icons'",
",",
"'configure-inasafe.svg'",
")",
"self",
".",
"action_options",
"=",
"QAction",
"(",
"QIcon",
"(",
"icon",
")",
",",
"self",
".",
... | Create action for options dialog. | [
"Create",
"action",
"for",
"options",
"dialog",
"."
] | 831d60abba919f6d481dc94a8d988cc205130724 | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/plugin.py#L223-L234 | train | 26,702 |
inasafe/inasafe | safe/plugin.py | Plugin._create_minimum_needs_action | def _create_minimum_needs_action(self):
"""Create action for minimum needs dialog."""
icon = resources_path('img', 'icons', 'show-minimum-needs.svg')
self.action_minimum_needs = QAction(
QIcon(icon),
self.tr('Minimum Needs Calculator'), self.iface.mainWindow())
self.action_minimum_needs.setStatusTip(self.tr(
'Open InaSAFE minimum needs calculator'))
self.action_minimum_needs.setWhatsThis(self.tr(
'Open InaSAFE minimum needs calculator'))
self.action_minimum_needs.triggered.connect(self.show_minimum_needs)
self.add_action(
self.action_minimum_needs, add_to_toolbar=self.full_toolbar) | python | def _create_minimum_needs_action(self):
"""Create action for minimum needs dialog."""
icon = resources_path('img', 'icons', 'show-minimum-needs.svg')
self.action_minimum_needs = QAction(
QIcon(icon),
self.tr('Minimum Needs Calculator'), self.iface.mainWindow())
self.action_minimum_needs.setStatusTip(self.tr(
'Open InaSAFE minimum needs calculator'))
self.action_minimum_needs.setWhatsThis(self.tr(
'Open InaSAFE minimum needs calculator'))
self.action_minimum_needs.triggered.connect(self.show_minimum_needs)
self.add_action(
self.action_minimum_needs, add_to_toolbar=self.full_toolbar) | [
"def",
"_create_minimum_needs_action",
"(",
"self",
")",
":",
"icon",
"=",
"resources_path",
"(",
"'img'",
",",
"'icons'",
",",
"'show-minimum-needs.svg'",
")",
"self",
".",
"action_minimum_needs",
"=",
"QAction",
"(",
"QIcon",
"(",
"icon",
")",
",",
"self",
"... | Create action for minimum needs dialog. | [
"Create",
"action",
"for",
"minimum",
"needs",
"dialog",
"."
] | 831d60abba919f6d481dc94a8d988cc205130724 | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/plugin.py#L236-L248 | train | 26,703 |
inasafe/inasafe | safe/plugin.py | Plugin._create_multi_buffer_action | def _create_multi_buffer_action(self):
"""Create action for multi buffer dialog."""
icon = resources_path('img', 'icons', 'show-multi-buffer.svg')
self.action_multi_buffer = QAction(
QIcon(icon),
self.tr('Multi Buffer'), self.iface.mainWindow())
self.action_multi_buffer.setStatusTip(self.tr(
'Open InaSAFE multi buffer'))
self.action_multi_buffer.setWhatsThis(self.tr(
'Open InaSAFE multi buffer'))
self.action_multi_buffer.triggered.connect(self.show_multi_buffer)
self.add_action(
self.action_multi_buffer,
add_to_toolbar=self.full_toolbar) | python | def _create_multi_buffer_action(self):
"""Create action for multi buffer dialog."""
icon = resources_path('img', 'icons', 'show-multi-buffer.svg')
self.action_multi_buffer = QAction(
QIcon(icon),
self.tr('Multi Buffer'), self.iface.mainWindow())
self.action_multi_buffer.setStatusTip(self.tr(
'Open InaSAFE multi buffer'))
self.action_multi_buffer.setWhatsThis(self.tr(
'Open InaSAFE multi buffer'))
self.action_multi_buffer.triggered.connect(self.show_multi_buffer)
self.add_action(
self.action_multi_buffer,
add_to_toolbar=self.full_toolbar) | [
"def",
"_create_multi_buffer_action",
"(",
"self",
")",
":",
"icon",
"=",
"resources_path",
"(",
"'img'",
",",
"'icons'",
",",
"'show-multi-buffer.svg'",
")",
"self",
".",
"action_multi_buffer",
"=",
"QAction",
"(",
"QIcon",
"(",
"icon",
")",
",",
"self",
".",... | Create action for multi buffer dialog. | [
"Create",
"action",
"for",
"multi",
"buffer",
"dialog",
"."
] | 831d60abba919f6d481dc94a8d988cc205130724 | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/plugin.py#L250-L263 | train | 26,704 |
inasafe/inasafe | safe/plugin.py | Plugin._create_minimum_needs_options_action | def _create_minimum_needs_options_action(self):
"""Create action for global minimum needs dialog."""
icon = resources_path('img', 'icons', 'show-global-minimum-needs.svg')
self.action_minimum_needs_config = QAction(
QIcon(icon),
self.tr('Minimum Needs Configuration'),
self.iface.mainWindow())
self.action_minimum_needs_config.setStatusTip(self.tr(
'Open InaSAFE minimum needs configuration'))
self.action_minimum_needs_config.setWhatsThis(self.tr(
'Open InaSAFE minimum needs configuration'))
self.action_minimum_needs_config.triggered.connect(
self.show_minimum_needs_configuration)
self.add_action(
self.action_minimum_needs_config, add_to_toolbar=self.full_toolbar) | python | def _create_minimum_needs_options_action(self):
"""Create action for global minimum needs dialog."""
icon = resources_path('img', 'icons', 'show-global-minimum-needs.svg')
self.action_minimum_needs_config = QAction(
QIcon(icon),
self.tr('Minimum Needs Configuration'),
self.iface.mainWindow())
self.action_minimum_needs_config.setStatusTip(self.tr(
'Open InaSAFE minimum needs configuration'))
self.action_minimum_needs_config.setWhatsThis(self.tr(
'Open InaSAFE minimum needs configuration'))
self.action_minimum_needs_config.triggered.connect(
self.show_minimum_needs_configuration)
self.add_action(
self.action_minimum_needs_config, add_to_toolbar=self.full_toolbar) | [
"def",
"_create_minimum_needs_options_action",
"(",
"self",
")",
":",
"icon",
"=",
"resources_path",
"(",
"'img'",
",",
"'icons'",
",",
"'show-global-minimum-needs.svg'",
")",
"self",
".",
"action_minimum_needs_config",
"=",
"QAction",
"(",
"QIcon",
"(",
"icon",
")"... | Create action for global minimum needs dialog. | [
"Create",
"action",
"for",
"global",
"minimum",
"needs",
"dialog",
"."
] | 831d60abba919f6d481dc94a8d988cc205130724 | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/plugin.py#L265-L279 | train | 26,705 |
inasafe/inasafe | safe/plugin.py | Plugin._create_shakemap_converter_action | def _create_shakemap_converter_action(self):
"""Create action for converter dialog."""
icon = resources_path('img', 'icons', 'show-converter-tool.svg')
self.action_shake_converter = QAction(
QIcon(icon),
self.tr('Shakemap Converter'), self.iface.mainWindow())
self.action_shake_converter.setStatusTip(self.tr(
'Open InaSAFE Converter'))
self.action_shake_converter.setWhatsThis(self.tr(
'Open InaSAFE Converter'))
self.action_shake_converter.triggered.connect(
self.show_shakemap_importer)
self.add_action(
self.action_shake_converter, add_to_toolbar=self.full_toolbar) | python | def _create_shakemap_converter_action(self):
"""Create action for converter dialog."""
icon = resources_path('img', 'icons', 'show-converter-tool.svg')
self.action_shake_converter = QAction(
QIcon(icon),
self.tr('Shakemap Converter'), self.iface.mainWindow())
self.action_shake_converter.setStatusTip(self.tr(
'Open InaSAFE Converter'))
self.action_shake_converter.setWhatsThis(self.tr(
'Open InaSAFE Converter'))
self.action_shake_converter.triggered.connect(
self.show_shakemap_importer)
self.add_action(
self.action_shake_converter, add_to_toolbar=self.full_toolbar) | [
"def",
"_create_shakemap_converter_action",
"(",
"self",
")",
":",
"icon",
"=",
"resources_path",
"(",
"'img'",
",",
"'icons'",
",",
"'show-converter-tool.svg'",
")",
"self",
".",
"action_shake_converter",
"=",
"QAction",
"(",
"QIcon",
"(",
"icon",
")",
",",
"se... | Create action for converter dialog. | [
"Create",
"action",
"for",
"converter",
"dialog",
"."
] | 831d60abba919f6d481dc94a8d988cc205130724 | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/plugin.py#L281-L294 | train | 26,706 |
inasafe/inasafe | safe/plugin.py | Plugin._create_batch_runner_action | def _create_batch_runner_action(self):
"""Create action for batch runner dialog."""
icon = resources_path('img', 'icons', 'show-batch-runner.svg')
self.action_batch_runner = QAction(
QIcon(icon),
self.tr('Batch Runner'), self.iface.mainWindow())
self.action_batch_runner.setStatusTip(self.tr(
'Open Batch Runner'))
self.action_batch_runner.setWhatsThis(self.tr(
'Open Batch Runner'))
self.action_batch_runner.triggered.connect(self.show_batch_runner)
self.add_action(
self.action_batch_runner, add_to_toolbar=self.full_toolbar) | python | def _create_batch_runner_action(self):
"""Create action for batch runner dialog."""
icon = resources_path('img', 'icons', 'show-batch-runner.svg')
self.action_batch_runner = QAction(
QIcon(icon),
self.tr('Batch Runner'), self.iface.mainWindow())
self.action_batch_runner.setStatusTip(self.tr(
'Open Batch Runner'))
self.action_batch_runner.setWhatsThis(self.tr(
'Open Batch Runner'))
self.action_batch_runner.triggered.connect(self.show_batch_runner)
self.add_action(
self.action_batch_runner, add_to_toolbar=self.full_toolbar) | [
"def",
"_create_batch_runner_action",
"(",
"self",
")",
":",
"icon",
"=",
"resources_path",
"(",
"'img'",
",",
"'icons'",
",",
"'show-batch-runner.svg'",
")",
"self",
".",
"action_batch_runner",
"=",
"QAction",
"(",
"QIcon",
"(",
"icon",
")",
",",
"self",
".",... | Create action for batch runner dialog. | [
"Create",
"action",
"for",
"batch",
"runner",
"dialog",
"."
] | 831d60abba919f6d481dc94a8d988cc205130724 | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/plugin.py#L296-L308 | train | 26,707 |
inasafe/inasafe | safe/plugin.py | Plugin._create_save_scenario_action | def _create_save_scenario_action(self):
"""Create action for save scenario dialog."""
icon = resources_path('img', 'icons', 'save-as-scenario.svg')
self.action_save_scenario = QAction(
QIcon(icon),
self.tr('Save Current Scenario'), self.iface.mainWindow())
message = self.tr('Save current scenario to text file')
self.action_save_scenario.setStatusTip(message)
self.action_save_scenario.setWhatsThis(message)
# noinspection PyUnresolvedReferences
self.action_save_scenario.triggered.connect(self.save_scenario)
self.add_action(
self.action_save_scenario, add_to_toolbar=self.full_toolbar) | python | def _create_save_scenario_action(self):
"""Create action for save scenario dialog."""
icon = resources_path('img', 'icons', 'save-as-scenario.svg')
self.action_save_scenario = QAction(
QIcon(icon),
self.tr('Save Current Scenario'), self.iface.mainWindow())
message = self.tr('Save current scenario to text file')
self.action_save_scenario.setStatusTip(message)
self.action_save_scenario.setWhatsThis(message)
# noinspection PyUnresolvedReferences
self.action_save_scenario.triggered.connect(self.save_scenario)
self.add_action(
self.action_save_scenario, add_to_toolbar=self.full_toolbar) | [
"def",
"_create_save_scenario_action",
"(",
"self",
")",
":",
"icon",
"=",
"resources_path",
"(",
"'img'",
",",
"'icons'",
",",
"'save-as-scenario.svg'",
")",
"self",
".",
"action_save_scenario",
"=",
"QAction",
"(",
"QIcon",
"(",
"icon",
")",
",",
"self",
"."... | Create action for save scenario dialog. | [
"Create",
"action",
"for",
"save",
"scenario",
"dialog",
"."
] | 831d60abba919f6d481dc94a8d988cc205130724 | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/plugin.py#L310-L322 | train | 26,708 |
inasafe/inasafe | safe/plugin.py | Plugin._create_geonode_uploader_action | def _create_geonode_uploader_action(self):
"""Create action for Geonode uploader dialog."""
icon = resources_path('img', 'icons', 'geonode.png')
label = tr('Geonode Uploader')
self.action_geonode = QAction(
QIcon(icon), label, self.iface.mainWindow())
self.action_geonode.setStatusTip(label)
self.action_geonode.setWhatsThis(label)
self.action_geonode.triggered.connect(self.show_geonode_uploader)
self.add_action(self.action_geonode, add_to_toolbar=False) | python | def _create_geonode_uploader_action(self):
"""Create action for Geonode uploader dialog."""
icon = resources_path('img', 'icons', 'geonode.png')
label = tr('Geonode Uploader')
self.action_geonode = QAction(
QIcon(icon), label, self.iface.mainWindow())
self.action_geonode.setStatusTip(label)
self.action_geonode.setWhatsThis(label)
self.action_geonode.triggered.connect(self.show_geonode_uploader)
self.add_action(self.action_geonode, add_to_toolbar=False) | [
"def",
"_create_geonode_uploader_action",
"(",
"self",
")",
":",
"icon",
"=",
"resources_path",
"(",
"'img'",
",",
"'icons'",
",",
"'geonode.png'",
")",
"label",
"=",
"tr",
"(",
"'Geonode Uploader'",
")",
"self",
".",
"action_geonode",
"=",
"QAction",
"(",
"QI... | Create action for Geonode uploader dialog. | [
"Create",
"action",
"for",
"Geonode",
"uploader",
"dialog",
"."
] | 831d60abba919f6d481dc94a8d988cc205130724 | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/plugin.py#L338-L347 | train | 26,709 |
inasafe/inasafe | safe/plugin.py | Plugin._create_metadata_converter_action | def _create_metadata_converter_action(self):
"""Create action for showing metadata converter dialog."""
icon = resources_path('img', 'icons', 'show-metadata-converter.svg')
self.action_metadata_converter = QAction(
QIcon(icon),
self.tr('InaSAFE Metadata Converter'),
self.iface.mainWindow())
self.action_metadata_converter.setStatusTip(self.tr(
'Convert metadata from version 4.3 to version 3.5.'))
self.action_metadata_converter.setWhatsThis(self.tr(
'Use this tool to convert metadata 4.3 to version 3.5'))
self.action_metadata_converter.triggered.connect(
self.show_metadata_converter)
self.add_action(
self.action_metadata_converter, add_to_toolbar=self.full_toolbar) | python | def _create_metadata_converter_action(self):
"""Create action for showing metadata converter dialog."""
icon = resources_path('img', 'icons', 'show-metadata-converter.svg')
self.action_metadata_converter = QAction(
QIcon(icon),
self.tr('InaSAFE Metadata Converter'),
self.iface.mainWindow())
self.action_metadata_converter.setStatusTip(self.tr(
'Convert metadata from version 4.3 to version 3.5.'))
self.action_metadata_converter.setWhatsThis(self.tr(
'Use this tool to convert metadata 4.3 to version 3.5'))
self.action_metadata_converter.triggered.connect(
self.show_metadata_converter)
self.add_action(
self.action_metadata_converter, add_to_toolbar=self.full_toolbar) | [
"def",
"_create_metadata_converter_action",
"(",
"self",
")",
":",
"icon",
"=",
"resources_path",
"(",
"'img'",
",",
"'icons'",
",",
"'show-metadata-converter.svg'",
")",
"self",
".",
"action_metadata_converter",
"=",
"QAction",
"(",
"QIcon",
"(",
"icon",
")",
","... | Create action for showing metadata converter dialog. | [
"Create",
"action",
"for",
"showing",
"metadata",
"converter",
"dialog",
"."
] | 831d60abba919f6d481dc94a8d988cc205130724 | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/plugin.py#L381-L395 | train | 26,710 |
inasafe/inasafe | safe/plugin.py | Plugin._create_field_mapping_action | def _create_field_mapping_action(self):
"""Create action for showing field mapping dialog."""
icon = resources_path('img', 'icons', 'show-mapping-tool.svg')
self.action_field_mapping = QAction(
QIcon(icon),
self.tr('InaSAFE Field Mapping Tool'),
self.iface.mainWindow())
self.action_field_mapping.setStatusTip(self.tr(
'Assign field mapping to layer.'))
self.action_field_mapping.setWhatsThis(self.tr(
'Use this tool to assign field mapping in layer.'))
self.action_field_mapping.setEnabled(False)
self.action_field_mapping.triggered.connect(self.show_field_mapping)
self.add_action(
self.action_field_mapping, add_to_toolbar=self.full_toolbar) | python | def _create_field_mapping_action(self):
"""Create action for showing field mapping dialog."""
icon = resources_path('img', 'icons', 'show-mapping-tool.svg')
self.action_field_mapping = QAction(
QIcon(icon),
self.tr('InaSAFE Field Mapping Tool'),
self.iface.mainWindow())
self.action_field_mapping.setStatusTip(self.tr(
'Assign field mapping to layer.'))
self.action_field_mapping.setWhatsThis(self.tr(
'Use this tool to assign field mapping in layer.'))
self.action_field_mapping.setEnabled(False)
self.action_field_mapping.triggered.connect(self.show_field_mapping)
self.add_action(
self.action_field_mapping, add_to_toolbar=self.full_toolbar) | [
"def",
"_create_field_mapping_action",
"(",
"self",
")",
":",
"icon",
"=",
"resources_path",
"(",
"'img'",
",",
"'icons'",
",",
"'show-mapping-tool.svg'",
")",
"self",
".",
"action_field_mapping",
"=",
"QAction",
"(",
"QIcon",
"(",
"icon",
")",
",",
"self",
".... | Create action for showing field mapping dialog. | [
"Create",
"action",
"for",
"showing",
"field",
"mapping",
"dialog",
"."
] | 831d60abba919f6d481dc94a8d988cc205130724 | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/plugin.py#L397-L411 | train | 26,711 |
inasafe/inasafe | safe/plugin.py | Plugin._create_multi_exposure_action | def _create_multi_exposure_action(self):
"""Create action for showing the multi exposure tool."""
self.action_multi_exposure = QAction(
QIcon(resources_path('img', 'icons', 'show-multi-exposure.svg')),
self.tr('InaSAFE Multi Exposure Tool'),
self.iface.mainWindow())
self.action_multi_exposure.setStatusTip(self.tr(
'Open the multi exposure tool.'))
self.action_multi_exposure.setWhatsThis(self.tr(
'Open the multi exposure tool.'))
self.action_multi_exposure.setEnabled(True)
self.action_multi_exposure.triggered.connect(self.show_multi_exposure)
self.add_action(
self.action_multi_exposure, add_to_toolbar=self.full_toolbar) | python | def _create_multi_exposure_action(self):
"""Create action for showing the multi exposure tool."""
self.action_multi_exposure = QAction(
QIcon(resources_path('img', 'icons', 'show-multi-exposure.svg')),
self.tr('InaSAFE Multi Exposure Tool'),
self.iface.mainWindow())
self.action_multi_exposure.setStatusTip(self.tr(
'Open the multi exposure tool.'))
self.action_multi_exposure.setWhatsThis(self.tr(
'Open the multi exposure tool.'))
self.action_multi_exposure.setEnabled(True)
self.action_multi_exposure.triggered.connect(self.show_multi_exposure)
self.add_action(
self.action_multi_exposure, add_to_toolbar=self.full_toolbar) | [
"def",
"_create_multi_exposure_action",
"(",
"self",
")",
":",
"self",
".",
"action_multi_exposure",
"=",
"QAction",
"(",
"QIcon",
"(",
"resources_path",
"(",
"'img'",
",",
"'icons'",
",",
"'show-multi-exposure.svg'",
")",
")",
",",
"self",
".",
"tr",
"(",
"'I... | Create action for showing the multi exposure tool. | [
"Create",
"action",
"for",
"showing",
"the",
"multi",
"exposure",
"tool",
"."
] | 831d60abba919f6d481dc94a8d988cc205130724 | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/plugin.py#L413-L426 | train | 26,712 |
inasafe/inasafe | safe/plugin.py | Plugin._create_rubber_bands_action | def _create_rubber_bands_action(self):
"""Create action for toggling rubber bands."""
icon = resources_path('img', 'icons', 'toggle-rubber-bands.svg')
self.action_toggle_rubberbands = QAction(
QIcon(icon),
self.tr('Toggle Scenario Outlines'), self.iface.mainWindow())
message = self.tr('Toggle rubber bands showing scenario extents.')
self.action_toggle_rubberbands.setStatusTip(message)
self.action_toggle_rubberbands.setWhatsThis(message)
# Set initial state
self.action_toggle_rubberbands.setCheckable(True)
flag = setting('showRubberBands', False, expected_type=bool)
self.action_toggle_rubberbands.setChecked(flag)
# noinspection PyUnresolvedReferences
self.action_toggle_rubberbands.triggered.connect(
self.dock_widget.toggle_rubber_bands)
self.add_action(self.action_toggle_rubberbands) | python | def _create_rubber_bands_action(self):
"""Create action for toggling rubber bands."""
icon = resources_path('img', 'icons', 'toggle-rubber-bands.svg')
self.action_toggle_rubberbands = QAction(
QIcon(icon),
self.tr('Toggle Scenario Outlines'), self.iface.mainWindow())
message = self.tr('Toggle rubber bands showing scenario extents.')
self.action_toggle_rubberbands.setStatusTip(message)
self.action_toggle_rubberbands.setWhatsThis(message)
# Set initial state
self.action_toggle_rubberbands.setCheckable(True)
flag = setting('showRubberBands', False, expected_type=bool)
self.action_toggle_rubberbands.setChecked(flag)
# noinspection PyUnresolvedReferences
self.action_toggle_rubberbands.triggered.connect(
self.dock_widget.toggle_rubber_bands)
self.add_action(self.action_toggle_rubberbands) | [
"def",
"_create_rubber_bands_action",
"(",
"self",
")",
":",
"icon",
"=",
"resources_path",
"(",
"'img'",
",",
"'icons'",
",",
"'toggle-rubber-bands.svg'",
")",
"self",
".",
"action_toggle_rubberbands",
"=",
"QAction",
"(",
"QIcon",
"(",
"icon",
")",
",",
"self"... | Create action for toggling rubber bands. | [
"Create",
"action",
"for",
"toggling",
"rubber",
"bands",
"."
] | 831d60abba919f6d481dc94a8d988cc205130724 | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/plugin.py#L446-L462 | train | 26,713 |
inasafe/inasafe | safe/plugin.py | Plugin._create_analysis_extent_action | def _create_analysis_extent_action(self):
"""Create action for analysis extent dialog."""
icon = resources_path('img', 'icons', 'set-extents-tool.svg')
self.action_extent_selector = QAction(
QIcon(icon),
self.tr('Set Analysis Area'),
self.iface.mainWindow())
self.action_extent_selector.setStatusTip(self.tr(
'Set the analysis area for InaSAFE'))
self.action_extent_selector.setWhatsThis(self.tr(
'Set the analysis area for InaSAFE'))
self.action_extent_selector.triggered.connect(
self.show_extent_selector)
self.add_action(self.action_extent_selector) | python | def _create_analysis_extent_action(self):
"""Create action for analysis extent dialog."""
icon = resources_path('img', 'icons', 'set-extents-tool.svg')
self.action_extent_selector = QAction(
QIcon(icon),
self.tr('Set Analysis Area'),
self.iface.mainWindow())
self.action_extent_selector.setStatusTip(self.tr(
'Set the analysis area for InaSAFE'))
self.action_extent_selector.setWhatsThis(self.tr(
'Set the analysis area for InaSAFE'))
self.action_extent_selector.triggered.connect(
self.show_extent_selector)
self.add_action(self.action_extent_selector) | [
"def",
"_create_analysis_extent_action",
"(",
"self",
")",
":",
"icon",
"=",
"resources_path",
"(",
"'img'",
",",
"'icons'",
",",
"'set-extents-tool.svg'",
")",
"self",
".",
"action_extent_selector",
"=",
"QAction",
"(",
"QIcon",
"(",
"icon",
")",
",",
"self",
... | Create action for analysis extent dialog. | [
"Create",
"action",
"for",
"analysis",
"extent",
"dialog",
"."
] | 831d60abba919f6d481dc94a8d988cc205130724 | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/plugin.py#L464-L477 | train | 26,714 |
inasafe/inasafe | safe/plugin.py | Plugin._create_dock | def _create_dock(self):
"""Create dockwidget and tabify it with the legend."""
# Import dock here as it needs to be imported AFTER i18n is set up
from safe.gui.widgets.dock import Dock
self.dock_widget = Dock(self.iface)
self.dock_widget.setObjectName('InaSAFE-Dock')
self.iface.addDockWidget(Qt.RightDockWidgetArea, self.dock_widget)
legend_tab = self.iface.mainWindow().findChild(QApplication, 'Legend')
if legend_tab:
self.iface.mainWindow().tabifyDockWidget(
legend_tab, self.dock_widget)
self.dock_widget.raise_() | python | def _create_dock(self):
"""Create dockwidget and tabify it with the legend."""
# Import dock here as it needs to be imported AFTER i18n is set up
from safe.gui.widgets.dock import Dock
self.dock_widget = Dock(self.iface)
self.dock_widget.setObjectName('InaSAFE-Dock')
self.iface.addDockWidget(Qt.RightDockWidgetArea, self.dock_widget)
legend_tab = self.iface.mainWindow().findChild(QApplication, 'Legend')
if legend_tab:
self.iface.mainWindow().tabifyDockWidget(
legend_tab, self.dock_widget)
self.dock_widget.raise_() | [
"def",
"_create_dock",
"(",
"self",
")",
":",
"# Import dock here as it needs to be imported AFTER i18n is set up",
"from",
"safe",
".",
"gui",
".",
"widgets",
".",
"dock",
"import",
"Dock",
"self",
".",
"dock_widget",
"=",
"Dock",
"(",
"self",
".",
"iface",
")",
... | Create dockwidget and tabify it with the legend. | [
"Create",
"dockwidget",
"and",
"tabify",
"it",
"with",
"the",
"legend",
"."
] | 831d60abba919f6d481dc94a8d988cc205130724 | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/plugin.py#L535-L546 | train | 26,715 |
inasafe/inasafe | safe/plugin.py | Plugin._add_spacer_to_menu | def _add_spacer_to_menu(self):
"""Create a spacer to the menu to separate action groups."""
separator = QAction(self.iface.mainWindow())
separator.setSeparator(True)
self.iface.addPluginToMenu(self.tr('InaSAFE'), separator) | python | def _add_spacer_to_menu(self):
"""Create a spacer to the menu to separate action groups."""
separator = QAction(self.iface.mainWindow())
separator.setSeparator(True)
self.iface.addPluginToMenu(self.tr('InaSAFE'), separator) | [
"def",
"_add_spacer_to_menu",
"(",
"self",
")",
":",
"separator",
"=",
"QAction",
"(",
"self",
".",
"iface",
".",
"mainWindow",
"(",
")",
")",
"separator",
".",
"setSeparator",
"(",
"True",
")",
"self",
".",
"iface",
".",
"addPluginToMenu",
"(",
"self",
... | Create a spacer to the menu to separate action groups. | [
"Create",
"a",
"spacer",
"to",
"the",
"menu",
"to",
"separate",
"action",
"groups",
"."
] | 831d60abba919f6d481dc94a8d988cc205130724 | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/plugin.py#L605-L609 | train | 26,716 |
inasafe/inasafe | safe/plugin.py | Plugin.clear_modules | def clear_modules():
"""Unload inasafe functions and try to return QGIS to before InaSAFE.
.. todo:: I think this function can be removed. TS.
"""
# next lets force remove any inasafe related modules
modules = []
for module in sys.modules:
if 'inasafe' in module:
# Check if it is really one of our modules i.e. exists in the
# plugin directory
tokens = module.split('.')
path = ''
for myToken in tokens:
path += os.path.sep + myToken
parent = os.path.abspath(os.path.join(
__file__, os.path.pardir, os.path.pardir))
full_path = os.path.join(parent, path + '.py')
if os.path.exists(os.path.abspath(full_path)):
LOGGER.debug('Removing: %s' % module)
modules.append(module)
for module in modules:
del (sys.modules[module])
for module in sys.modules:
if 'inasafe' in module:
print(module)
# Lets also clean up all the path additions that were made
package_path = os.path.abspath(os.path.join(
os.path.dirname(__file__), os.path.pardir))
LOGGER.debug('Path to remove: %s' % package_path)
# We use a list comprehension to ensure duplicate entries are removed
LOGGER.debug(sys.path)
sys.path = [y for y in sys.path if package_path not in y]
LOGGER.debug(sys.path) | python | def clear_modules():
"""Unload inasafe functions and try to return QGIS to before InaSAFE.
.. todo:: I think this function can be removed. TS.
"""
# next lets force remove any inasafe related modules
modules = []
for module in sys.modules:
if 'inasafe' in module:
# Check if it is really one of our modules i.e. exists in the
# plugin directory
tokens = module.split('.')
path = ''
for myToken in tokens:
path += os.path.sep + myToken
parent = os.path.abspath(os.path.join(
__file__, os.path.pardir, os.path.pardir))
full_path = os.path.join(parent, path + '.py')
if os.path.exists(os.path.abspath(full_path)):
LOGGER.debug('Removing: %s' % module)
modules.append(module)
for module in modules:
del (sys.modules[module])
for module in sys.modules:
if 'inasafe' in module:
print(module)
# Lets also clean up all the path additions that were made
package_path = os.path.abspath(os.path.join(
os.path.dirname(__file__), os.path.pardir))
LOGGER.debug('Path to remove: %s' % package_path)
# We use a list comprehension to ensure duplicate entries are removed
LOGGER.debug(sys.path)
sys.path = [y for y in sys.path if package_path not in y]
LOGGER.debug(sys.path) | [
"def",
"clear_modules",
"(",
")",
":",
"# next lets force remove any inasafe related modules",
"modules",
"=",
"[",
"]",
"for",
"module",
"in",
"sys",
".",
"modules",
":",
"if",
"'inasafe'",
"in",
"module",
":",
"# Check if it is really one of our modules i.e. exists in t... | Unload inasafe functions and try to return QGIS to before InaSAFE.
.. todo:: I think this function can be removed. TS. | [
"Unload",
"inasafe",
"functions",
"and",
"try",
"to",
"return",
"QGIS",
"to",
"before",
"InaSAFE",
"."
] | 831d60abba919f6d481dc94a8d988cc205130724 | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/plugin.py#L612-L646 | train | 26,717 |
inasafe/inasafe | safe/plugin.py | Plugin.toggle_dock_visibility | def toggle_dock_visibility(self):
"""Show or hide the dock widget."""
if self.dock_widget.isVisible():
self.dock_widget.setVisible(False)
else:
self.dock_widget.setVisible(True)
self.dock_widget.raise_() | python | def toggle_dock_visibility(self):
"""Show or hide the dock widget."""
if self.dock_widget.isVisible():
self.dock_widget.setVisible(False)
else:
self.dock_widget.setVisible(True)
self.dock_widget.raise_() | [
"def",
"toggle_dock_visibility",
"(",
"self",
")",
":",
"if",
"self",
".",
"dock_widget",
".",
"isVisible",
"(",
")",
":",
"self",
".",
"dock_widget",
".",
"setVisible",
"(",
"False",
")",
"else",
":",
"self",
".",
"dock_widget",
".",
"setVisible",
"(",
... | Show or hide the dock widget. | [
"Show",
"or",
"hide",
"the",
"dock",
"widget",
"."
] | 831d60abba919f6d481dc94a8d988cc205130724 | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/plugin.py#L685-L691 | train | 26,718 |
inasafe/inasafe | safe/plugin.py | Plugin.show_extent_selector | def show_extent_selector(self):
"""Show the extent selector widget for defining analysis extents."""
# 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() | python | def show_extent_selector(self):
"""Show the extent selector widget for defining analysis extents."""
# 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() | [
"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",
".",
... | Show the extent selector widget for defining analysis extents. | [
"Show",
"the",
"extent",
"selector",
"widget",
"for",
"defining",
"analysis",
"extents",
"."
] | 831d60abba919f6d481dc94a8d988cc205130724 | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/plugin.py#L740-L757 | train | 26,719 |
inasafe/inasafe | safe/plugin.py | Plugin.show_options | def show_options(self):
"""Show the options dialog."""
# 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() | python | def show_options(self):
"""Show the options dialog."""
# 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() | [
"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",
... | Show the options dialog. | [
"Show",
"the",
"options",
"dialog",
"."
] | 831d60abba919f6d481dc94a8d988cc205130724 | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/plugin.py#L780-L795 | train | 26,720 |
inasafe/inasafe | safe/plugin.py | Plugin.show_welcome_message | def show_welcome_message(self):
"""Show the welcome message."""
# 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() | python | def show_welcome_message(self):
"""Show the welcome message."""
# 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() | [
"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_versio... | Show the welcome message. | [
"Show",
"the",
"welcome",
"message",
"."
] | 831d60abba919f6d481dc94a8d988cc205130724 | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/plugin.py#L797-L828 | train | 26,721 |
inasafe/inasafe | safe/plugin.py | Plugin.show_keywords_wizard | def show_keywords_wizard(self):
"""Show the keywords creation wizard."""
# 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_() | python | def show_keywords_wizard(self):
"""Show the keywords creation wizard."""
# 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_() | [
"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",
"(",
... | Show the keywords creation wizard. | [
"Show",
"the",
"keywords",
"creation",
"wizard",
"."
] | 831d60abba919f6d481dc94a8d988cc205130724 | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/plugin.py#L830-L849 | train | 26,722 |
inasafe/inasafe | safe/plugin.py | Plugin.show_function_centric_wizard | def show_function_centric_wizard(self):
"""Show the function centric wizard."""
# 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() | python | def show_function_centric_wizard(self):
"""Show the function centric wizard."""
# 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() | [
"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... | Show the function centric wizard. | [
"Show",
"the",
"function",
"centric",
"wizard",
"."
] | 831d60abba919f6d481dc94a8d988cc205130724 | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/plugin.py#L851-L868 | train | 26,723 |
inasafe/inasafe | safe/plugin.py | Plugin.show_shakemap_importer | def show_shakemap_importer(self):
"""Show the converter dialog."""
# 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_() | python | def show_shakemap_importer(self):
"""Show the converter dialog."""
# 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_() | [
"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",
"=",
"Sh... | Show the converter dialog. | [
"Show",
"the",
"converter",
"dialog",
"."
] | 831d60abba919f6d481dc94a8d988cc205130724 | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/plugin.py#L870-L878 | train | 26,724 |
inasafe/inasafe | safe/plugin.py | Plugin.show_multi_buffer | def show_multi_buffer(self):
"""Show the multi buffer tool."""
from safe.gui.tools.multi_buffer_dialog import (
MultiBufferDialog)
dialog = MultiBufferDialog(
self.iface.mainWindow(), self.iface, self.dock_widget)
dialog.exec_() | python | def show_multi_buffer(self):
"""Show the multi buffer tool."""
from safe.gui.tools.multi_buffer_dialog import (
MultiBufferDialog)
dialog = MultiBufferDialog(
self.iface.mainWindow(), self.iface, self.dock_widget)
dialog.exec_() | [
"def",
"show_multi_buffer",
"(",
"self",
")",
":",
"from",
"safe",
".",
"gui",
".",
"tools",
".",
"multi_buffer_dialog",
"import",
"(",
"MultiBufferDialog",
")",
"dialog",
"=",
"MultiBufferDialog",
"(",
"self",
".",
"iface",
".",
"mainWindow",
"(",
")",
",",... | Show the multi buffer tool. | [
"Show",
"the",
"multi",
"buffer",
"tool",
"."
] | 831d60abba919f6d481dc94a8d988cc205130724 | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/plugin.py#L880-L887 | train | 26,725 |
inasafe/inasafe | safe/plugin.py | Plugin.show_osm_downloader | def show_osm_downloader(self):
"""Show the OSM buildings downloader dialog."""
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() | python | def show_osm_downloader(self):
"""Show the OSM buildings downloader dialog."""
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() | [
"def",
"show_osm_downloader",
"(",
"self",
")",
":",
"from",
"safe",
".",
"gui",
".",
"tools",
".",
"osm_downloader_dialog",
"import",
"OsmDownloaderDialog",
"dialog",
"=",
"OsmDownloaderDialog",
"(",
"self",
".",
"iface",
".",
"mainWindow",
"(",
")",
",",
"se... | Show the OSM buildings downloader dialog. | [
"Show",
"the",
"OSM",
"buildings",
"downloader",
"dialog",
"."
] | 831d60abba919f6d481dc94a8d988cc205130724 | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/plugin.py#L889-L896 | train | 26,726 |
inasafe/inasafe | safe/plugin.py | Plugin.show_geonode_uploader | def show_geonode_uploader(self):
"""Show the Geonode uploader dialog."""
from safe.gui.tools.geonode_uploader import GeonodeUploaderDialog
dialog = GeonodeUploaderDialog(self.iface.mainWindow())
dialog.show() | python | def show_geonode_uploader(self):
"""Show the Geonode uploader dialog."""
from safe.gui.tools.geonode_uploader import GeonodeUploaderDialog
dialog = GeonodeUploaderDialog(self.iface.mainWindow())
dialog.show() | [
"def",
"show_geonode_uploader",
"(",
"self",
")",
":",
"from",
"safe",
".",
"gui",
".",
"tools",
".",
"geonode_uploader",
"import",
"GeonodeUploaderDialog",
"dialog",
"=",
"GeonodeUploaderDialog",
"(",
"self",
".",
"iface",
".",
"mainWindow",
"(",
")",
")",
"d... | Show the Geonode uploader dialog. | [
"Show",
"the",
"Geonode",
"uploader",
"dialog",
"."
] | 831d60abba919f6d481dc94a8d988cc205130724 | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/plugin.py#L898-L903 | train | 26,727 |
inasafe/inasafe | safe/plugin.py | Plugin.add_osm_layer | def add_osm_layer(self):
"""Add OSM tile layer to the map.
This uses a gdal wrapper around the OSM tile service - see the
WorldOSM.gdal file for how it is constructed.
"""
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) | python | def add_osm_layer(self):
"""Add OSM tile layer to the map.
This uses a gdal wrapper around the OSM tile service - see the
WorldOSM.gdal file for how it is constructed.
"""
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) | [
"def",
"add_osm_layer",
"(",
"self",
")",
":",
"path",
"=",
"resources_path",
"(",
"'osm'",
",",
"'WorldOSM.gdal'",
")",
"layer",
"=",
"QgsRasterLayer",
"(",
"path",
",",
"self",
".",
"tr",
"(",
"'OpenStreetMap'",
")",
")",
"project",
"=",
"QgsProject",
".... | Add OSM tile layer to the map.
This uses a gdal wrapper around the OSM tile service - see the
WorldOSM.gdal file for how it is constructed. | [
"Add",
"OSM",
"tile",
"layer",
"to",
"the",
"map",
"."
] | 831d60abba919f6d481dc94a8d988cc205130724 | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/plugin.py#L905-L923 | train | 26,728 |
inasafe/inasafe | safe/plugin.py | Plugin.show_field_mapping | def show_field_mapping(self):
"""Show InaSAFE Field Mapping."""
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') | python | def show_field_mapping(self):
"""Show InaSAFE Field Mapping."""
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') | [
"def",
"show_field_mapping",
"(",
"self",
")",
":",
"from",
"safe",
".",
"gui",
".",
"tools",
".",
"field_mapping_dialog",
"import",
"FieldMappingDialog",
"dialog",
"=",
"FieldMappingDialog",
"(",
"parent",
"=",
"self",
".",
"iface",
".",
"mainWindow",
"(",
")... | Show InaSAFE Field Mapping. | [
"Show",
"InaSAFE",
"Field",
"Mapping",
"."
] | 831d60abba919f6d481dc94a8d988cc205130724 | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/plugin.py#L931-L941 | train | 26,729 |
inasafe/inasafe | safe/plugin.py | Plugin.show_metadata_converter | def show_metadata_converter(self):
"""Show InaSAFE Metadata Converter."""
from safe.gui.tools.metadata_converter_dialog import (
MetadataConverterDialog)
dialog = MetadataConverterDialog(
parent=self.iface.mainWindow(),
iface=self.iface,
)
dialog.exec_() | python | def show_metadata_converter(self):
"""Show InaSAFE Metadata Converter."""
from safe.gui.tools.metadata_converter_dialog import (
MetadataConverterDialog)
dialog = MetadataConverterDialog(
parent=self.iface.mainWindow(),
iface=self.iface,
)
dialog.exec_() | [
"def",
"show_metadata_converter",
"(",
"self",
")",
":",
"from",
"safe",
".",
"gui",
".",
"tools",
".",
"metadata_converter_dialog",
"import",
"(",
"MetadataConverterDialog",
")",
"dialog",
"=",
"MetadataConverterDialog",
"(",
"parent",
"=",
"self",
".",
"iface",
... | Show InaSAFE Metadata Converter. | [
"Show",
"InaSAFE",
"Metadata",
"Converter",
"."
] | 831d60abba919f6d481dc94a8d988cc205130724 | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/plugin.py#L943-L951 | train | 26,730 |
inasafe/inasafe | safe/plugin.py | Plugin.show_multi_exposure | def show_multi_exposure(self):
"""Show InaSAFE Multi Exposure."""
from safe.gui.tools.multi_exposure_dialog import MultiExposureDialog
dialog = MultiExposureDialog(
self.iface.mainWindow(), self.iface)
dialog.exec_() | python | def show_multi_exposure(self):
"""Show InaSAFE Multi Exposure."""
from safe.gui.tools.multi_exposure_dialog import MultiExposureDialog
dialog = MultiExposureDialog(
self.iface.mainWindow(), self.iface)
dialog.exec_() | [
"def",
"show_multi_exposure",
"(",
"self",
")",
":",
"from",
"safe",
".",
"gui",
".",
"tools",
".",
"multi_exposure_dialog",
"import",
"MultiExposureDialog",
"dialog",
"=",
"MultiExposureDialog",
"(",
"self",
".",
"iface",
".",
"mainWindow",
"(",
")",
",",
"se... | Show InaSAFE Multi Exposure. | [
"Show",
"InaSAFE",
"Multi",
"Exposure",
"."
] | 831d60abba919f6d481dc94a8d988cc205130724 | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/plugin.py#L953-L958 | train | 26,731 |
inasafe/inasafe | safe/plugin.py | Plugin.add_petabencana_layer | def add_petabencana_layer(self):
"""Add petabencana layer to the map.
This uses the PetaBencana API to fetch the latest floods in JK. See
https://data.petabencana.id/floods
"""
from safe.gui.tools.peta_bencana_dialog import PetaBencanaDialog
dialog = PetaBencanaDialog(self.iface.mainWindow(), self.iface)
dialog.show() | python | def add_petabencana_layer(self):
"""Add petabencana layer to the map.
This uses the PetaBencana API to fetch the latest floods in JK. See
https://data.petabencana.id/floods
"""
from safe.gui.tools.peta_bencana_dialog import PetaBencanaDialog
dialog = PetaBencanaDialog(self.iface.mainWindow(), self.iface)
dialog.show() | [
"def",
"add_petabencana_layer",
"(",
"self",
")",
":",
"from",
"safe",
".",
"gui",
".",
"tools",
".",
"peta_bencana_dialog",
"import",
"PetaBencanaDialog",
"dialog",
"=",
"PetaBencanaDialog",
"(",
"self",
".",
"iface",
".",
"mainWindow",
"(",
")",
",",
"self",... | Add petabencana layer to the map.
This uses the PetaBencana API to fetch the latest floods in JK. See
https://data.petabencana.id/floods | [
"Add",
"petabencana",
"layer",
"to",
"the",
"map",
"."
] | 831d60abba919f6d481dc94a8d988cc205130724 | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/plugin.py#L960-L968 | train | 26,732 |
inasafe/inasafe | safe/plugin.py | Plugin.show_batch_runner | def show_batch_runner(self):
"""Show the batch runner dialog."""
from safe.gui.tools.batch.batch_dialog import BatchDialog
dialog = BatchDialog(
parent=self.iface.mainWindow(),
iface=self.iface,
dock=self.dock_widget)
dialog.exec_() | python | def show_batch_runner(self):
"""Show the batch runner dialog."""
from safe.gui.tools.batch.batch_dialog import BatchDialog
dialog = BatchDialog(
parent=self.iface.mainWindow(),
iface=self.iface,
dock=self.dock_widget)
dialog.exec_() | [
"def",
"show_batch_runner",
"(",
"self",
")",
":",
"from",
"safe",
".",
"gui",
".",
"tools",
".",
"batch",
".",
"batch_dialog",
"import",
"BatchDialog",
"dialog",
"=",
"BatchDialog",
"(",
"parent",
"=",
"self",
".",
"iface",
".",
"mainWindow",
"(",
")",
... | Show the batch runner dialog. | [
"Show",
"the",
"batch",
"runner",
"dialog",
"."
] | 831d60abba919f6d481dc94a8d988cc205130724 | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/plugin.py#L970-L978 | train | 26,733 |
inasafe/inasafe | safe/plugin.py | Plugin.save_scenario | def save_scenario(self):
"""Save current scenario to text file."""
from safe.gui.tools.save_scenario import SaveScenarioDialog
dialog = SaveScenarioDialog(
iface=self.iface,
dock=self.dock_widget)
dialog.save_scenario() | python | def save_scenario(self):
"""Save current scenario to text file."""
from safe.gui.tools.save_scenario import SaveScenarioDialog
dialog = SaveScenarioDialog(
iface=self.iface,
dock=self.dock_widget)
dialog.save_scenario() | [
"def",
"save_scenario",
"(",
"self",
")",
":",
"from",
"safe",
".",
"gui",
".",
"tools",
".",
"save_scenario",
"import",
"SaveScenarioDialog",
"dialog",
"=",
"SaveScenarioDialog",
"(",
"iface",
"=",
"self",
".",
"iface",
",",
"dock",
"=",
"self",
".",
"doc... | Save current scenario to text file. | [
"Save",
"current",
"scenario",
"to",
"text",
"file",
"."
] | 831d60abba919f6d481dc94a8d988cc205130724 | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/plugin.py#L980-L987 | train | 26,734 |
inasafe/inasafe | safe/plugin.py | Plugin.layer_changed | def layer_changed(self, layer):
"""Enable or disable keywords editor icon when active layer changes.
:param layer: The layer that is now active.
:type layer: QgsMapLayer
"""
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) | python | def layer_changed(self, layer):
"""Enable or disable keywords editor icon when active layer changes.
:param layer: The layer that is now active.
:type layer: QgsMapLayer
"""
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) | [
"def",
"layer_changed",
"(",
"self",
",",
"layer",
")",
":",
"if",
"not",
"layer",
":",
"enable_keyword_wizard",
"=",
"False",
"elif",
"not",
"hasattr",
"(",
"layer",
",",
"'providerType'",
")",
":",
"enable_keyword_wizard",
"=",
"False",
"elif",
"layer",
".... | Enable or disable keywords editor icon when active layer changes.
:param layer: The layer that is now active.
:type layer: QgsMapLayer | [
"Enable",
"or",
"disable",
"keywords",
"editor",
"icon",
"when",
"active",
"layer",
"changes",
"."
] | 831d60abba919f6d481dc94a8d988cc205130724 | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/plugin.py#L989-L1044 | train | 26,735 |
inasafe/inasafe | safe/gui/widgets/field_mapping_widget.py | FieldMappingWidget.populate_tabs | def populate_tabs(self):
"""Populating tabs based on layer metadata."""
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) | python | def populate_tabs(self):
"""Populating tabs based on layer metadata."""
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) | [
"def",
"populate_tabs",
"(",
"self",
")",
":",
"self",
".",
"delete_tabs",
"(",
")",
"layer_purpose",
"=",
"self",
".",
"metadata",
".",
"get",
"(",
"'layer_purpose'",
")",
"if",
"not",
"layer_purpose",
":",
"message",
"=",
"tr",
"(",
"'Key layer_purpose is ... | Populating tabs based on layer metadata. | [
"Populating",
"tabs",
"based",
"on",
"layer",
"metadata",
"."
] | 831d60abba919f6d481dc94a8d988cc205130724 | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/widgets/field_mapping_widget.py#L60-L81 | train | 26,736 |
inasafe/inasafe | safe/impact_function/postprocessors.py | evaluate_formula | def evaluate_formula(formula, variables):
"""Very simple formula evaluator. Beware the security.
:param formula: A simple formula.
:type formula: str
:param variables: A collection of variable (key and value).
:type variables: dict
:returns: The result of the formula execution.
:rtype: float, int
"""
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 | python | def evaluate_formula(formula, variables):
"""Very simple formula evaluator. Beware the security.
:param formula: A simple formula.
:type formula: str
:param variables: A collection of variable (key and value).
:type variables: dict
:returns: The result of the formula execution.
:rtype: float, int
"""
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 | [
"def",
"evaluate_formula",
"(",
"formula",
",",
"variables",
")",
":",
"for",
"key",
",",
"value",
"in",
"list",
"(",
"variables",
".",
"items",
"(",
")",
")",
":",
"if",
"value",
"is",
"None",
"or",
"(",
"hasattr",
"(",
"value",
",",
"'isNull'",
")"... | Very simple formula evaluator. Beware the security.
:param formula: A simple formula.
:type formula: str
:param variables: A collection of variable (key and value).
:type variables: dict
:returns: The result of the formula execution.
:rtype: float, int | [
"Very",
"simple",
"formula",
"evaluator",
".",
"Beware",
"the",
"security",
"."
] | 831d60abba919f6d481dc94a8d988cc205130724 | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/impact_function/postprocessors.py#L34-L52 | train | 26,737 |
inasafe/inasafe | safe/impact_function/postprocessors.py | enough_input | def enough_input(layer, post_processor_input):
"""Check if the input from impact_fields in enough.
:param layer: The vector layer to use for post processing.
:type layer: QgsVectorLayer
:param post_processor_input: Collection of post processor input
requirements.
:type post_processor_input: dict
:returns: Tuple with True if success, else False with an error message.
:rtype: (bool, str)
"""
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 | python | def enough_input(layer, post_processor_input):
"""Check if the input from impact_fields in enough.
:param layer: The vector layer to use for post processing.
:type layer: QgsVectorLayer
:param post_processor_input: Collection of post processor input
requirements.
:type post_processor_input: dict
:returns: Tuple with True if success, else False with an error message.
:rtype: (bool, str)
"""
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 | [
"def",
"enough_input",
"(",
"layer",
",",
"post_processor_input",
")",
":",
"impact_fields",
"=",
"list",
"(",
"layer",
".",
"keywords",
"[",
"'inasafe_fields'",
"]",
".",
"keys",
"(",
")",
")",
"for",
"input_key",
",",
"input_values",
"in",
"list",
"(",
"... | Check if the input from impact_fields in enough.
:param layer: The vector layer to use for post processing.
:type layer: QgsVectorLayer
:param post_processor_input: Collection of post processor input
requirements.
:type post_processor_input: dict
:returns: Tuple with True if success, else False with an error message.
:rtype: (bool, str) | [
"Check",
"if",
"the",
"input",
"from",
"impact_fields",
"in",
"enough",
"."
] | 831d60abba919f6d481dc94a8d988cc205130724 | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/impact_function/postprocessors.py#L311-L397 | train | 26,738 |
inasafe/inasafe | safe/common/parameters/group_select_parameter.py | GroupSelectParameter.set_value_for_key | def set_value_for_key(self, key, value):
"""Set the value of key to value.
:param key: The key.
:type key: str
:param value: The value to be assigned.
:type value: list, float, int
"""
if key in self.options:
self.options[key]['value'] = value | python | def set_value_for_key(self, key, value):
"""Set the value of key to value.
:param key: The key.
:type key: str
:param value: The value to be assigned.
:type value: list, float, int
"""
if key in self.options:
self.options[key]['value'] = value | [
"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.
:param key: The key.
:type key: str
:param value: The value to be assigned.
:type value: list, float, int | [
"Set",
"the",
"value",
"of",
"key",
"to",
"value",
"."
] | 831d60abba919f6d481dc94a8d988cc205130724 | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/common/parameters/group_select_parameter.py#L107-L117 | train | 26,739 |
inasafe/inasafe | safe/gui/tools/wizard/step_kw20_unit.py | StepKwUnit.on_lstUnits_itemSelectionChanged | def on_lstUnits_itemSelectionChanged(self):
"""Update unit description label and field widgets.
.. note:: This is an automatic Qt slot
executed when the unit selection changes.
"""
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) | python | def on_lstUnits_itemSelectionChanged(self):
"""Update unit description label and field widgets.
.. note:: This is an automatic Qt slot
executed when the unit selection changes.
"""
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) | [
"def",
"on_lstUnits_itemSelectionChanged",
"(",
"self",
")",
":",
"self",
".",
"clear_further_steps",
"(",
")",
"# Set widgets",
"unit",
"=",
"self",
".",
"selected_unit",
"(",
")",
"# Exit if no selection",
"if",
"not",
"unit",
":",
"return",
"self",
".",
"lblD... | Update unit description label and field widgets.
.. note:: This is an automatic Qt slot
executed when the unit selection changes. | [
"Update",
"unit",
"description",
"label",
"and",
"field",
"widgets",
"."
] | 831d60abba919f6d481dc94a8d988cc205130724 | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/tools/wizard/step_kw20_unit.py#L63-L77 | train | 26,740 |
inasafe/inasafe | safe/gui/tools/wizard/step_kw20_unit.py | StepKwUnit.selected_unit | def selected_unit(self):
"""Obtain the unit selected by user.
:returns: Metadata of the selected unit.
:rtype: dict, None
"""
item = self.lstUnits.currentItem()
try:
return definition(item.data(QtCore.Qt.UserRole))
except (AttributeError, NameError):
return None | python | def selected_unit(self):
"""Obtain the unit selected by user.
:returns: Metadata of the selected unit.
:rtype: dict, None
"""
item = self.lstUnits.currentItem()
try:
return definition(item.data(QtCore.Qt.UserRole))
except (AttributeError, NameError):
return None | [
"def",
"selected_unit",
"(",
"self",
")",
":",
"item",
"=",
"self",
".",
"lstUnits",
".",
"currentItem",
"(",
")",
"try",
":",
"return",
"definition",
"(",
"item",
".",
"data",
"(",
"QtCore",
".",
"Qt",
".",
"UserRole",
")",
")",
"except",
"(",
"Attr... | Obtain the unit selected by user.
:returns: Metadata of the selected unit.
:rtype: dict, None | [
"Obtain",
"the",
"unit",
"selected",
"by",
"user",
"."
] | 831d60abba919f6d481dc94a8d988cc205130724 | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/tools/wizard/step_kw20_unit.py#L79-L89 | train | 26,741 |
inasafe/inasafe | safe/gui/tools/wizard/step_kw20_unit.py | StepKwUnit.set_widgets | def set_widgets(self):
"""Set widgets on the Unit tab."""
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) | python | def set_widgets(self):
"""Set widgets on the Unit tab."""
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) | [
"def",
"set_widgets",
"(",
"self",
")",
":",
"self",
".",
"clear_further_steps",
"(",
")",
"# Set widgets",
"purpose",
"=",
"self",
".",
"parent",
".",
"step_kw_purpose",
".",
"selected_purpose",
"(",
")",
"subcategory",
"=",
"self",
".",
"parent",
".",
"ste... | Set widgets on the Unit tab. | [
"Set",
"widgets",
"on",
"the",
"Unit",
"tab",
"."
] | 831d60abba919f6d481dc94a8d988cc205130724 | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/tools/wizard/step_kw20_unit.py#L97-L132 | train | 26,742 |
inasafe/inasafe | safe/report/expressions/html_report.py | get_report_section | def get_report_section(
html_report, component_id, container_wrapper_format=container_format):
"""Get specific report section from InaSAFE analysis summary report.
:param html_report: The html report.
:type html_report: basestring
:param component_id: The component key.
:type component_id: str
:param container_wrapper_format: A string format for wrapping the section.
:type container_wrapper_format: basestring
:return: Requested report section as an html.
:rtype: basestring
"""
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 | python | def get_report_section(
html_report, component_id, container_wrapper_format=container_format):
"""Get specific report section from InaSAFE analysis summary report.
:param html_report: The html report.
:type html_report: basestring
:param component_id: The component key.
:type component_id: str
:param container_wrapper_format: A string format for wrapping the section.
:type container_wrapper_format: basestring
:return: Requested report section as an html.
:rtype: basestring
"""
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 | [
"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",
"=",
... | Get specific report section from InaSAFE analysis summary report.
:param html_report: The html report.
:type html_report: basestring
:param component_id: The component key.
:type component_id: str
:param container_wrapper_format: A string format for wrapping the section.
:type container_wrapper_format: basestring
:return: Requested report section as an html.
:rtype: basestring | [
"Get",
"specific",
"report",
"section",
"from",
"InaSAFE",
"analysis",
"summary",
"report",
"."
] | 831d60abba919f6d481dc94a8d988cc205130724 | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/report/expressions/html_report.py#L155-L181 | train | 26,743 |
inasafe/inasafe | safe/report/expressions/html_report.py | analysis_summary_report | def analysis_summary_report(feature, parent):
"""Retrieve an HTML table report of current selected analysis.
"""
_ = 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) | python | def analysis_summary_report(feature, parent):
"""Retrieve an HTML table report of current selected analysis.
"""
_ = 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) | [
"def",
"analysis_summary_report",
"(",
"feature",
",",
"parent",
")",
":",
"_",
"=",
"feature",
",",
"parent",
"# NOQA",
"project_context_scope",
"=",
"QgsExpressionContextUtils",
".",
"projectScope",
"(",
"QgsProject",
".",
"instance",
"(",
")",
")",
"key",
"="... | Retrieve an HTML table report of current selected analysis. | [
"Retrieve",
"an",
"HTML",
"table",
"report",
"of",
"current",
"selected",
"analysis",
"."
] | 831d60abba919f6d481dc94a8d988cc205130724 | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/report/expressions/html_report.py#L235-L246 | train | 26,744 |
inasafe/inasafe | safe/report/expressions/html_report.py | analysis_question_report | def analysis_question_report(feature, parent):
"""Retrieve the analysis question section from InaSAFE report.
"""
_ = 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 | python | def analysis_question_report(feature, parent):
"""Retrieve the analysis question section from InaSAFE report.
"""
_ = 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 | [
"def",
"analysis_question_report",
"(",
"feature",
",",
"parent",
")",
":",
"_",
"=",
"feature",
",",
"parent",
"# NOQA",
"project_context_scope",
"=",
"QgsExpressionContextUtils",
".",
"projectScope",
"(",
")",
"key",
"=",
"provenance_layer_analysis_impacted",
"[",
... | Retrieve the analysis question section from InaSAFE report. | [
"Retrieve",
"the",
"analysis",
"question",
"section",
"from",
"InaSAFE",
"report",
"."
] | 831d60abba919f6d481dc94a8d988cc205130724 | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/report/expressions/html_report.py#L260-L275 | train | 26,745 |
inasafe/inasafe | safe/report/expressions/html_report.py | population_analysis_summary_report | def population_analysis_summary_report(feature, parent):
"""Retrieve an HTML population analysis table report from a multi exposure
analysis.
"""
_ = feature, parent # NOQA
analysis_dir = get_analysis_dir(exposure_population['key'])
if analysis_dir:
return get_impact_report_as_string(analysis_dir)
return None | python | def population_analysis_summary_report(feature, parent):
"""Retrieve an HTML population analysis table report from a multi exposure
analysis.
"""
_ = feature, parent # NOQA
analysis_dir = get_analysis_dir(exposure_population['key'])
if analysis_dir:
return get_impact_report_as_string(analysis_dir)
return None | [
"def",
"population_analysis_summary_report",
"(",
"feature",
",",
"parent",
")",
":",
"_",
"=",
"feature",
",",
"parent",
"# NOQA",
"analysis_dir",
"=",
"get_analysis_dir",
"(",
"exposure_population",
"[",
"'key'",
"]",
")",
"if",
"analysis_dir",
":",
"return",
... | Retrieve an HTML population analysis table report from a multi exposure
analysis. | [
"Retrieve",
"an",
"HTML",
"population",
"analysis",
"table",
"report",
"from",
"a",
"multi",
"exposure",
"analysis",
"."
] | 831d60abba919f6d481dc94a8d988cc205130724 | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/report/expressions/html_report.py#L552-L560 | train | 26,746 |
inasafe/inasafe | safe/report/expressions/html_report.py | road_analysis_summary_report | def road_analysis_summary_report(feature, parent):
"""Retrieve an HTML road analysis table report from a multi exposure
analysis.
"""
_ = feature, parent # NOQA
analysis_dir = get_analysis_dir(exposure_road['key'])
if analysis_dir:
return get_impact_report_as_string(analysis_dir)
return None | python | def road_analysis_summary_report(feature, parent):
"""Retrieve an HTML road analysis table report from a multi exposure
analysis.
"""
_ = feature, parent # NOQA
analysis_dir = get_analysis_dir(exposure_road['key'])
if analysis_dir:
return get_impact_report_as_string(analysis_dir)
return None | [
"def",
"road_analysis_summary_report",
"(",
"feature",
",",
"parent",
")",
":",
"_",
"=",
"feature",
",",
"parent",
"# NOQA",
"analysis_dir",
"=",
"get_analysis_dir",
"(",
"exposure_road",
"[",
"'key'",
"]",
")",
"if",
"analysis_dir",
":",
"return",
"get_impact_... | Retrieve an HTML road analysis table report from a multi exposure
analysis. | [
"Retrieve",
"an",
"HTML",
"road",
"analysis",
"table",
"report",
"from",
"a",
"multi",
"exposure",
"analysis",
"."
] | 831d60abba919f6d481dc94a8d988cc205130724 | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/report/expressions/html_report.py#L574-L582 | train | 26,747 |
inasafe/inasafe | safe/report/expressions/html_report.py | structure_analysis_summary_report | def structure_analysis_summary_report(feature, parent):
"""Retrieve an HTML structure analysis table report from a multi exposure
analysis.
"""
_ = feature, parent # NOQA
analysis_dir = get_analysis_dir(exposure_structure['key'])
if analysis_dir:
return get_impact_report_as_string(analysis_dir)
return None | python | def structure_analysis_summary_report(feature, parent):
"""Retrieve an HTML structure analysis table report from a multi exposure
analysis.
"""
_ = feature, parent # NOQA
analysis_dir = get_analysis_dir(exposure_structure['key'])
if analysis_dir:
return get_impact_report_as_string(analysis_dir)
return None | [
"def",
"structure_analysis_summary_report",
"(",
"feature",
",",
"parent",
")",
":",
"_",
"=",
"feature",
",",
"parent",
"# NOQA",
"analysis_dir",
"=",
"get_analysis_dir",
"(",
"exposure_structure",
"[",
"'key'",
"]",
")",
"if",
"analysis_dir",
":",
"return",
"g... | Retrieve an HTML structure analysis table report from a multi exposure
analysis. | [
"Retrieve",
"an",
"HTML",
"structure",
"analysis",
"table",
"report",
"from",
"a",
"multi",
"exposure",
"analysis",
"."
] | 831d60abba919f6d481dc94a8d988cc205130724 | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/report/expressions/html_report.py#L596-L604 | train | 26,748 |
inasafe/inasafe | safe/report/expressions/html_report.py | place_analysis_summary_report | def place_analysis_summary_report(feature, parent):
"""Retrieve an HTML place analysis table report from a multi exposure
analysis.
"""
_ = feature, parent # NOQA
analysis_dir = get_analysis_dir(exposure_place['key'])
if analysis_dir:
return get_impact_report_as_string(analysis_dir)
return None | python | def place_analysis_summary_report(feature, parent):
"""Retrieve an HTML place analysis table report from a multi exposure
analysis.
"""
_ = feature, parent # NOQA
analysis_dir = get_analysis_dir(exposure_place['key'])
if analysis_dir:
return get_impact_report_as_string(analysis_dir)
return None | [
"def",
"place_analysis_summary_report",
"(",
"feature",
",",
"parent",
")",
":",
"_",
"=",
"feature",
",",
"parent",
"# NOQA",
"analysis_dir",
"=",
"get_analysis_dir",
"(",
"exposure_place",
"[",
"'key'",
"]",
")",
"if",
"analysis_dir",
":",
"return",
"get_impac... | Retrieve an HTML place analysis table report from a multi exposure
analysis. | [
"Retrieve",
"an",
"HTML",
"place",
"analysis",
"table",
"report",
"from",
"a",
"multi",
"exposure",
"analysis",
"."
] | 831d60abba919f6d481dc94a8d988cc205130724 | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/report/expressions/html_report.py#L618-L626 | train | 26,749 |
inasafe/inasafe | safe/report/expressions/html_report.py | land_cover_analysis_summary_report | def land_cover_analysis_summary_report(feature, parent):
"""Retrieve an HTML land cover analysis table report from a multi exposure
analysis.
"""
_ = 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 | python | def land_cover_analysis_summary_report(feature, parent):
"""Retrieve an HTML land cover analysis table report from a multi exposure
analysis.
"""
_ = 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 | [
"def",
"land_cover_analysis_summary_report",
"(",
"feature",
",",
"parent",
")",
":",
"_",
"=",
"feature",
",",
"parent",
"# NOQA",
"analysis_dir",
"=",
"get_analysis_dir",
"(",
"exposure_land_cover",
"[",
"'key'",
"]",
")",
"if",
"analysis_dir",
":",
"return",
... | Retrieve an HTML land cover analysis table report from a multi exposure
analysis. | [
"Retrieve",
"an",
"HTML",
"land",
"cover",
"analysis",
"table",
"report",
"from",
"a",
"multi",
"exposure",
"analysis",
"."
] | 831d60abba919f6d481dc94a8d988cc205130724 | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/report/expressions/html_report.py#L640-L648 | train | 26,750 |
inasafe/inasafe | safe/report/expressions/html_report.py | multi_exposure_analysis_summary_report | def multi_exposure_analysis_summary_report(feature, parent):
"""Retrieve an HTML multi exposure analysis table report.
"""
_ = feature, parent # NOQA
analysis_dir = get_analysis_dir()
if analysis_dir:
return get_impact_report_as_string(analysis_dir)
return None | python | def multi_exposure_analysis_summary_report(feature, parent):
"""Retrieve an HTML multi exposure analysis table report.
"""
_ = feature, parent # NOQA
analysis_dir = get_analysis_dir()
if analysis_dir:
return get_impact_report_as_string(analysis_dir)
return None | [
"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",
"(",
"analy... | Retrieve an HTML multi exposure analysis table report. | [
"Retrieve",
"an",
"HTML",
"multi",
"exposure",
"analysis",
"table",
"report",
"."
] | 831d60abba919f6d481dc94a8d988cc205130724 | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/report/expressions/html_report.py#L661-L668 | train | 26,751 |
inasafe/inasafe | safe/gui/tools/wizard/wizard_help.py | WizardHelp.show_help | def show_help(self, wizard_step):
"""Set wizard step and show the help text."""
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) | python | def show_help(self, wizard_step):
"""Set wizard step and show the help text."""
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) | [
"def",
"show_help",
"(",
"self",
",",
"wizard_step",
")",
":",
"self",
".",
"wizard_step",
"=",
"wizard_step",
"header",
"=",
"html_header",
"(",
")",
"footer",
"=",
"html_footer",
"(",
")",
"content",
"=",
"header",
"message",
"=",
"self",
".",
"wizard_st... | Set wizard step and show the help text. | [
"Set",
"wizard",
"step",
"and",
"show",
"the",
"help",
"text",
"."
] | 831d60abba919f6d481dc94a8d988cc205130724 | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/tools/wizard/wizard_help.py#L39-L61 | train | 26,752 |
inasafe/inasafe | safe/gui/tools/wizard/wizard_help.py | WizardHelp.restore_button_state | def restore_button_state(self):
"""Helper to restore button state."""
self.parent.pbnNext.setEnabled(self.next_button_state)
self.parent.pbnBack.setEnabled(self.back_button_state) | python | def restore_button_state(self):
"""Helper to restore button state."""
self.parent.pbnNext.setEnabled(self.next_button_state)
self.parent.pbnBack.setEnabled(self.back_button_state) | [
"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. | [
"Helper",
"to",
"restore",
"button",
"state",
"."
] | 831d60abba919f6d481dc94a8d988cc205130724 | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/tools/wizard/wizard_help.py#L63-L66 | train | 26,753 |
inasafe/inasafe | safe/utilities/resources.py | html_footer | def html_footer():
"""Get a standard html footer for wrapping content in.
:returns: A header containing a web page closing content in html - up to
and including the body close tag.
:rtype: str
"""
file_path = resources_path('footer.html')
with open(file_path) as header_file:
content = header_file.read()
return content | python | def html_footer():
"""Get a standard html footer for wrapping content in.
:returns: A header containing a web page closing content in html - up to
and including the body close tag.
:rtype: str
"""
file_path = resources_path('footer.html')
with open(file_path) as header_file:
content = header_file.read()
return content | [
"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.
:returns: A header containing a web page closing content in html - up to
and including the body close tag.
:rtype: str | [
"Get",
"a",
"standard",
"html",
"footer",
"for",
"wrapping",
"content",
"in",
"."
] | 831d60abba919f6d481dc94a8d988cc205130724 | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/utilities/resources.py#L19-L29 | train | 26,754 |
inasafe/inasafe | safe/utilities/resources.py | html_header | def html_header():
"""Get a standard html header for wrapping content in.
:returns: A header containing a web page preamble in html - up to and
including the body open tag.
:rtype: str
"""
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 | python | def html_header():
"""Get a standard html header for wrapping content in.
:returns: A header containing a web page preamble in html - up to and
including the body open tag.
:rtype: str
"""
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 | [
"def",
"html_header",
"(",
")",
":",
"file_path",
"=",
"resources_path",
"(",
"'header.html'",
")",
"with",
"codecs",
".",
"open",
"(",
"file_path",
",",
"'r'",
",",
"encoding",
"=",
"'utf8'",
")",
"as",
"header_file",
":",
"content",
"=",
"header_file",
"... | Get a standard html header for wrapping content in.
:returns: A header containing a web page preamble in html - up to and
including the body open tag.
:rtype: str | [
"Get",
"a",
"standard",
"html",
"header",
"for",
"wrapping",
"content",
"in",
"."
] | 831d60abba919f6d481dc94a8d988cc205130724 | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/utilities/resources.py#L32-L44 | train | 26,755 |
inasafe/inasafe | safe/utilities/resources.py | resources_path | def resources_path(*args):
"""Get the path to our resources folder.
.. versionadded:: 3.0
Note that in version 3.0 we removed the use of Qt Resource files in
favour of directly accessing on-disk resources.
:param args List of path elements e.g. ['img', 'logos', 'image.png']
:type args: str
:return: Absolute path to the resources folder.
:rtype: str
"""
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 | python | def resources_path(*args):
"""Get the path to our resources folder.
.. versionadded:: 3.0
Note that in version 3.0 we removed the use of Qt Resource files in
favour of directly accessing on-disk resources.
:param args List of path elements e.g. ['img', 'logos', 'image.png']
:type args: str
:return: Absolute path to the resources folder.
:rtype: str
"""
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 | [
"def",
"resources_path",
"(",
"*",
"args",
")",
":",
"path",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"__file__",
")",
"path",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"os",
".",
"path",
".",
"join",
"(",
"path",
",",
"os",
".",
"path",
... | Get the path to our resources folder.
.. versionadded:: 3.0
Note that in version 3.0 we removed the use of Qt Resource files in
favour of directly accessing on-disk resources.
:param args List of path elements e.g. ['img', 'logos', 'image.png']
:type args: str
:return: Absolute path to the resources folder.
:rtype: str | [
"Get",
"the",
"path",
"to",
"our",
"resources",
"folder",
"."
] | 831d60abba919f6d481dc94a8d988cc205130724 | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/utilities/resources.py#L67-L87 | train | 26,756 |
inasafe/inasafe | safe/utilities/resources.py | resource_url | def resource_url(path):
"""Get the a local filesystem url to a given resource.
.. versionadded:: 3.0
Note that in version 3.0 we removed the use of Qt Resource files in
favour of directly accessing on-disk resources.
:param path: Path to resource e.g. /home/timlinux/foo/bar.png
:type path: str
:return: A valid file url e.g. file:///home/timlinux/foo/bar.png
:rtype: str
"""
url = QtCore.QUrl.fromLocalFile(path)
return str(url.toString()) | python | def resource_url(path):
"""Get the a local filesystem url to a given resource.
.. versionadded:: 3.0
Note that in version 3.0 we removed the use of Qt Resource files in
favour of directly accessing on-disk resources.
:param path: Path to resource e.g. /home/timlinux/foo/bar.png
:type path: str
:return: A valid file url e.g. file:///home/timlinux/foo/bar.png
:rtype: str
"""
url = QtCore.QUrl.fromLocalFile(path)
return str(url.toString()) | [
"def",
"resource_url",
"(",
"path",
")",
":",
"url",
"=",
"QtCore",
".",
"QUrl",
".",
"fromLocalFile",
"(",
"path",
")",
"return",
"str",
"(",
"url",
".",
"toString",
"(",
")",
")"
] | Get the a local filesystem url to a given resource.
.. versionadded:: 3.0
Note that in version 3.0 we removed the use of Qt Resource files in
favour of directly accessing on-disk resources.
:param path: Path to resource e.g. /home/timlinux/foo/bar.png
:type path: str
:return: A valid file url e.g. file:///home/timlinux/foo/bar.png
:rtype: str | [
"Get",
"the",
"a",
"local",
"filesystem",
"url",
"to",
"a",
"given",
"resource",
"."
] | 831d60abba919f6d481dc94a8d988cc205130724 | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/utilities/resources.py#L90-L105 | train | 26,757 |
inasafe/inasafe | safe/utilities/resources.py | get_ui_class | def get_ui_class(ui_file):
"""Get UI Python class from .ui file.
Can be filename.ui or subdirectory/filename.ui
:param ui_file: The file of the ui in safe.gui.ui
:type ui_file: str
"""
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] | python | def get_ui_class(ui_file):
"""Get UI Python class from .ui file.
Can be filename.ui or subdirectory/filename.ui
:param ui_file: The file of the ui in safe.gui.ui
:type ui_file: str
"""
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] | [
"def",
"get_ui_class",
"(",
"ui_file",
")",
":",
"os",
".",
"path",
".",
"sep",
".",
"join",
"(",
"ui_file",
".",
"split",
"(",
"'/'",
")",
")",
"ui_file_path",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"os",
".",
"path",
".",
"join",
"(",
"os... | Get UI Python class from .ui file.
Can be filename.ui or subdirectory/filename.ui
:param ui_file: The file of the ui in safe.gui.ui
:type ui_file: str | [
"Get",
"UI",
"Python",
"class",
"from",
".",
"ui",
"file",
"."
] | 831d60abba919f6d481dc94a8d988cc205130724 | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/utilities/resources.py#L108-L126 | train | 26,758 |
inasafe/inasafe | safe/gui/tools/wizard/step_kw55_source.py | StepKwSource.set_widgets | def set_widgets(self):
"""Set widgets on the Source tab."""
# 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() | python | def set_widgets(self):
"""Set widgets on the Source tab."""
# 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() | [
"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",
".",
... | Set widgets on the Source tab. | [
"Set",
"widgets",
"on",
"the",
"Source",
"tab",
"."
] | 831d60abba919f6d481dc94a8d988cc205130724 | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/tools/wizard/step_kw55_source.py#L82-L120 | train | 26,759 |
inasafe/inasafe | safe/gui/tools/help/welcome_message.py | welcome_message | def welcome_message():
"""Welcome message for first running users.
.. versionadded:: 4.3.0
:returns: A message object containing helpful information.
:rtype: messaging.message.Message
"""
message = m.Message()
message.add(m.Brand())
message.add(heading())
message.add(content())
return message | python | def welcome_message():
"""Welcome message for first running users.
.. versionadded:: 4.3.0
:returns: A message object containing helpful information.
:rtype: messaging.message.Message
"""
message = m.Message()
message.add(m.Brand())
message.add(heading())
message.add(content())
return message | [
"def",
"welcome_message",
"(",
")",
":",
"message",
"=",
"m",
".",
"Message",
"(",
")",
"message",
".",
"add",
"(",
"m",
".",
"Brand",
"(",
")",
")",
"message",
".",
"add",
"(",
"heading",
"(",
")",
")",
"message",
".",
"add",
"(",
"content",
"("... | Welcome message for first running users.
.. versionadded:: 4.3.0
:returns: A message object containing helpful information.
:rtype: messaging.message.Message | [
"Welcome",
"message",
"for",
"first",
"running",
"users",
"."
] | 831d60abba919f6d481dc94a8d988cc205130724 | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/tools/help/welcome_message.py#L30-L43 | train | 26,760 |
inasafe/inasafe | safe/gui/tools/batch/batch_dialog.py | read_scenarios | def read_scenarios(filename):
"""Read keywords dictionary from file.
:param filename: Name of file holding scenarios .
:return Dictionary of with structure like this
{{ 'foo' : { 'a': 'b', 'c': 'd'},
{ 'bar' : { 'd': 'e', 'f': 'g'}}
A scenarios file may look like this:
[jakarta_flood]
hazard: /path/to/hazard.tif
exposure: /path/to/exposure.tif
function: function_id
aggregation: /path/to/aggregation_layer.tif
extent: minx, miny, maxx, maxy
Notes:
path for hazard, exposure, and aggregation are relative to scenario
file path
"""
# 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 | python | def read_scenarios(filename):
"""Read keywords dictionary from file.
:param filename: Name of file holding scenarios .
:return Dictionary of with structure like this
{{ 'foo' : { 'a': 'b', 'c': 'd'},
{ 'bar' : { 'd': 'e', 'f': 'g'}}
A scenarios file may look like this:
[jakarta_flood]
hazard: /path/to/hazard.tif
exposure: /path/to/exposure.tif
function: function_id
aggregation: /path/to/aggregation_layer.tif
extent: minx, miny, maxx, maxy
Notes:
path for hazard, exposure, and aggregation are relative to scenario
file path
"""
# 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 | [
"def",
"read_scenarios",
"(",
"filename",
")",
":",
"# Input checks",
"filename",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"filename",
")",
"blocks",
"=",
"{",
"}",
"parser",
"=",
"ConfigParser",
"(",
")",
"# Parse the file content.",
"# if the content don't... | Read keywords dictionary from file.
:param filename: Name of file holding scenarios .
:return Dictionary of with structure like this
{{ 'foo' : { 'a': 'b', 'c': 'd'},
{ 'bar' : { 'd': 'e', 'f': 'g'}}
A scenarios file may look like this:
[jakarta_flood]
hazard: /path/to/hazard.tif
exposure: /path/to/exposure.tif
function: function_id
aggregation: /path/to/aggregation_layer.tif
extent: minx, miny, maxx, maxy
Notes:
path for hazard, exposure, and aggregation are relative to scenario
file path | [
"Read",
"keywords",
"dictionary",
"from",
"file",
"."
] | 831d60abba919f6d481dc94a8d988cc205130724 | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/tools/batch/batch_dialog.py#L849-L905 | train | 26,761 |
inasafe/inasafe | safe/gui/tools/batch/batch_dialog.py | validate_scenario | def validate_scenario(blocks, scenario_directory):
"""Function to validate input layer stored in scenario file.
Check whether the files that are used in scenario file need to be
updated or not.
:param blocks: dictionary from read_scenarios
:type blocks: dictionary
:param scenario_directory: directory where scenario text file is saved
:type scenario_directory: file directory
:return: pass message to dialog and log detailed status
"""
# 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'] | python | def validate_scenario(blocks, scenario_directory):
"""Function to validate input layer stored in scenario file.
Check whether the files that are used in scenario file need to be
updated or not.
:param blocks: dictionary from read_scenarios
:type blocks: dictionary
:param scenario_directory: directory where scenario text file is saved
:type scenario_directory: file directory
:return: pass message to dialog and log detailed status
"""
# 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'] | [
"def",
"validate_scenario",
"(",
"blocks",
",",
"scenario_directory",
")",
":",
"# dictionary to temporary contain status message",
"blocks_update",
"=",
"{",
"}",
"for",
"section",
",",
"section_item",
"in",
"list",
"(",
"blocks",
".",
"items",
"(",
")",
")",
":"... | Function to validate input layer stored in scenario file.
Check whether the files that are used in scenario file need to be
updated or not.
:param blocks: dictionary from read_scenarios
:type blocks: dictionary
:param scenario_directory: directory where scenario text file is saved
:type scenario_directory: file directory
:return: pass message to dialog and log detailed status | [
"Function",
"to",
"validate",
"input",
"layer",
"stored",
"in",
"scenario",
"file",
"."
] | 831d60abba919f6d481dc94a8d988cc205130724 | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/tools/batch/batch_dialog.py#L908-L942 | train | 26,762 |
inasafe/inasafe | safe/gui/tools/batch/batch_dialog.py | append_row | def append_row(table, label, data):
"""Append new row to table widget.
:param table: The table that shall have the row added to it.
:type table: QTableWidget
:param label: Label for the row.
:type label: str
:param data: custom data associated with label value.
:type data: str
"""
# 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'])) | python | def append_row(table, label, data):
"""Append new row to table widget.
:param table: The table that shall have the row added to it.
:type table: QTableWidget
:param label: Label for the row.
:type label: str
:param data: custom data associated with label value.
:type data: str
"""
# 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'])) | [
"def",
"append_row",
"(",
"table",
",",
"label",
",",
"data",
")",
":",
"# noinspection PyUnresolvedReferences",
"count",
"=",
"table",
".",
"rowCount",
"(",
")",
"# noinspection PyUnresolvedReferences",
"table",
".",
"insertRow",
"(",
"table",
".",
"rowCount",
"(... | Append new row to table widget.
:param table: The table that shall have the row added to it.
:type table: QTableWidget
:param label: Label for the row.
:type label: str
:param data: custom data associated with label value.
:type data: str | [
"Append",
"new",
"row",
"to",
"table",
"widget",
"."
] | 831d60abba919f6d481dc94a8d988cc205130724 | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/tools/batch/batch_dialog.py#L945-L976 | train | 26,763 |
inasafe/inasafe | safe/gui/tools/batch/batch_dialog.py | BatchDialog.restore_state | def restore_state(self):
"""Restore GUI state from configuration file."""
# 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) | python | def restore_state(self):
"""Restore GUI state from configuration file."""
# 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) | [
"def",
"restore_state",
"(",
"self",
")",
":",
"# restore last source path",
"last_source_path",
"=",
"setting",
"(",
"'lastSourceDir'",
",",
"self",
".",
"default_directory",
",",
"expected_type",
"=",
"str",
")",
"self",
".",
"source_directory",
".",
"setText",
... | Restore GUI state from configuration file. | [
"Restore",
"GUI",
"state",
"from",
"configuration",
"file",
"."
] | 831d60abba919f6d481dc94a8d988cc205130724 | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/tools/batch/batch_dialog.py#L169-L185 | train | 26,764 |
inasafe/inasafe | safe/gui/tools/batch/batch_dialog.py | BatchDialog.save_state | def save_state(self):
"""Save current state of GUI to configuration file."""
set_setting('lastSourceDir', self.source_directory.text())
set_setting('lastOutputDir', self.output_directory.text())
set_setting(
'useDefaultOutputDir', self.scenario_directory_radio.isChecked()) | python | def save_state(self):
"""Save current state of GUI to configuration file."""
set_setting('lastSourceDir', self.source_directory.text())
set_setting('lastOutputDir', self.output_directory.text())
set_setting(
'useDefaultOutputDir', self.scenario_directory_radio.isChecked()) | [
"def",
"save_state",
"(",
"self",
")",
":",
"set_setting",
"(",
"'lastSourceDir'",
",",
"self",
".",
"source_directory",
".",
"text",
"(",
")",
")",
"set_setting",
"(",
"'lastOutputDir'",
",",
"self",
".",
"output_directory",
".",
"text",
"(",
")",
")",
"s... | Save current state of GUI to configuration file. | [
"Save",
"current",
"state",
"of",
"GUI",
"to",
"configuration",
"file",
"."
] | 831d60abba919f6d481dc94a8d988cc205130724 | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/tools/batch/batch_dialog.py#L187-L192 | train | 26,765 |
inasafe/inasafe | safe/gui/tools/batch/batch_dialog.py | BatchDialog.choose_directory | def choose_directory(self, line_edit, title):
""" Show a directory selection dialog.
This function will show the dialog then set line_edit widget
text with output from the dialog.
:param line_edit: Widget whose text should be updated.
:type line_edit: QLineEdit
:param title: title of dialog
:type title: str, QString
"""
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) | python | def choose_directory(self, line_edit, title):
""" Show a directory selection dialog.
This function will show the dialog then set line_edit widget
text with output from the dialog.
:param line_edit: Widget whose text should be updated.
:type line_edit: QLineEdit
:param title: title of dialog
:type title: str, QString
"""
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) | [
"def",
"choose_directory",
"(",
"self",
",",
"line_edit",
",",
"title",
")",
":",
"path",
"=",
"line_edit",
".",
"text",
"(",
")",
"# noinspection PyCallByClass,PyTypeChecker",
"new_path",
"=",
"QFileDialog",
".",
"getExistingDirectory",
"(",
"self",
",",
"title",... | Show a directory selection dialog.
This function will show the dialog then set line_edit widget
text with output from the dialog.
:param line_edit: Widget whose text should be updated.
:type line_edit: QLineEdit
:param title: title of dialog
:type title: str, QString | [
"Show",
"a",
"directory",
"selection",
"dialog",
".",
"This",
"function",
"will",
"show",
"the",
"dialog",
"then",
"set",
"line_edit",
"widget",
"text",
"with",
"output",
"from",
"the",
"dialog",
"."
] | 831d60abba919f6d481dc94a8d988cc205130724 | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/tools/batch/batch_dialog.py#L194-L210 | train | 26,766 |
inasafe/inasafe | safe/gui/tools/batch/batch_dialog.py | BatchDialog.populate_table | def populate_table(self, scenario_directory):
""" Populate table with files from scenario_directory directory.
:param scenario_directory: Path where .txt & .py reside.
:type scenario_directory: QString
"""
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) | python | def populate_table(self, scenario_directory):
""" Populate table with files from scenario_directory directory.
:param scenario_directory: Path where .txt & .py reside.
:type scenario_directory: QString
"""
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) | [
"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",
"se... | Populate table with files from scenario_directory directory.
:param scenario_directory: Path where .txt & .py reside.
:type scenario_directory: QString | [
"Populate",
"table",
"with",
"files",
"from",
"scenario_directory",
"directory",
"."
] | 831d60abba919f6d481dc94a8d988cc205130724 | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/tools/batch/batch_dialog.py#L213-L251 | train | 26,767 |
inasafe/inasafe | safe/gui/tools/batch/batch_dialog.py | BatchDialog.run_script | def run_script(self, filename):
""" Run a python script in QGIS to exercise InaSAFE functionality.
This functionality was originally intended for verifying that the key
elements are InaSAFE are loading correctly and available. However,
the utility of this function is such that you can run any arbitrary
python scripts with it. As such you can use it it automate
activities in QGIS, for example automatically running an impact
assessment in response to an event.
:param filename: the script filename.
:type filename: str
"""
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() | python | def run_script(self, filename):
""" Run a python script in QGIS to exercise InaSAFE functionality.
This functionality was originally intended for verifying that the key
elements are InaSAFE are loading correctly and available. However,
the utility of this function is such that you can run any arbitrary
python scripts with it. As such you can use it it automate
activities in QGIS, for example automatically running an impact
assessment in response to an event.
:param filename: the script filename.
:type filename: str
"""
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() | [
"def",
"run_script",
"(",
"self",
",",
"filename",
")",
":",
"module",
",",
"_",
"=",
"os",
".",
"path",
".",
"splitext",
"(",
"filename",
")",
"if",
"module",
"in",
"sys",
".",
"modules",
":",
"script",
"=",
"reload",
"(",
"sys",
".",
"modules",
"... | Run a python script in QGIS to exercise InaSAFE functionality.
This functionality was originally intended for verifying that the key
elements are InaSAFE are loading correctly and available. However,
the utility of this function is such that you can run any arbitrary
python scripts with it. As such you can use it it automate
activities in QGIS, for example automatically running an impact
assessment in response to an event.
:param filename: the script filename.
:type filename: str | [
"Run",
"a",
"python",
"script",
"in",
"QGIS",
"to",
"exercise",
"InaSAFE",
"functionality",
"."
] | 831d60abba919f6d481dc94a8d988cc205130724 | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/tools/batch/batch_dialog.py#L254-L278 | train | 26,768 |
inasafe/inasafe | safe/gui/tools/batch/batch_dialog.py | BatchDialog.reset_status | def reset_status(self):
"""Set all scenarios' status to empty in the table."""
for row in range(self.table.rowCount()):
status_item = self.table.item(row, 1)
status_item.setText(self.tr('')) | python | def reset_status(self):
"""Set all scenarios' status to empty in the table."""
for row in range(self.table.rowCount()):
status_item = self.table.item(row, 1)
status_item.setText(self.tr('')) | [
"def",
"reset_status",
"(",
"self",
")",
":",
"for",
"row",
"in",
"range",
"(",
"self",
".",
"table",
".",
"rowCount",
"(",
")",
")",
":",
"status_item",
"=",
"self",
".",
"table",
".",
"item",
"(",
"row",
",",
"1",
")",
"status_item",
".",
"setTex... | Set all scenarios' status to empty in the table. | [
"Set",
"all",
"scenarios",
"status",
"to",
"empty",
"in",
"the",
"table",
"."
] | 831d60abba919f6d481dc94a8d988cc205130724 | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/tools/batch/batch_dialog.py#L280-L284 | train | 26,769 |
inasafe/inasafe | safe/gui/tools/batch/batch_dialog.py | BatchDialog.prepare_task | def prepare_task(self, items):
"""Prepare scenario for impact function variable.
:param items: Dictionary containing settings for impact function.
:type items: Python dictionary.
:return: A tuple containing True and dictionary containing parameters
if post processor success. Or False and an error message
if something went wrong.
"""
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 | python | def prepare_task(self, items):
"""Prepare scenario for impact function variable.
:param items: Dictionary containing settings for impact function.
:type items: Python dictionary.
:return: A tuple containing True and dictionary containing parameters
if post processor success. Or False and an error message
if something went wrong.
"""
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 | [
"def",
"prepare_task",
"(",
"self",
",",
"items",
")",
":",
"status",
"=",
"True",
"message",
"=",
"''",
"# get hazard",
"if",
"'hazard'",
"in",
"items",
":",
"hazard_path",
"=",
"items",
"[",
"'hazard'",
"]",
"hazard",
"=",
"self",
".",
"define_layer",
... | Prepare scenario for impact function variable.
:param items: Dictionary containing settings for impact function.
:type items: Python dictionary.
:return: A tuple containing True and dictionary containing parameters
if post processor success. Or False and an error message
if something went wrong. | [
"Prepare",
"scenario",
"for",
"impact",
"function",
"variable",
"."
] | 831d60abba919f6d481dc94a8d988cc205130724 | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/tools/batch/batch_dialog.py#L286-L371 | train | 26,770 |
inasafe/inasafe | safe/gui/tools/batch/batch_dialog.py | BatchDialog.set_layer_visible | def set_layer_visible(layer, visible):
"""Sets a layer in the project visible or not
:param layer: layer to change
:type layer: QgsMapLayer
:param visible: True to show layer, False to hide layer
:type visible: bool
"""
if layer is None:
return
QgsProject.instance().layerTreeRoot().findLayer(
layer.id()).setItemVisibilityChecked(visible) | python | def set_layer_visible(layer, visible):
"""Sets a layer in the project visible or not
:param layer: layer to change
:type layer: QgsMapLayer
:param visible: True to show layer, False to hide layer
:type visible: bool
"""
if layer is None:
return
QgsProject.instance().layerTreeRoot().findLayer(
layer.id()).setItemVisibilityChecked(visible) | [
"def",
"set_layer_visible",
"(",
"layer",
",",
"visible",
")",
":",
"if",
"layer",
"is",
"None",
":",
"return",
"QgsProject",
".",
"instance",
"(",
")",
".",
"layerTreeRoot",
"(",
")",
".",
"findLayer",
"(",
"layer",
".",
"id",
"(",
")",
")",
".",
"s... | Sets a layer in the project visible or not
:param layer: layer to change
:type layer: QgsMapLayer
:param visible: True to show layer, False to hide layer
:type visible: bool | [
"Sets",
"a",
"layer",
"in",
"the",
"project",
"visible",
"or",
"not"
] | 831d60abba919f6d481dc94a8d988cc205130724 | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/tools/batch/batch_dialog.py#L404-L417 | train | 26,771 |
inasafe/inasafe | safe/gui/tools/batch/batch_dialog.py | BatchDialog.run_selected_clicked | def run_selected_clicked(self):
"""Run the selected scenario."""
# 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() | python | def run_selected_clicked(self):
"""Run the selected scenario."""
# 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() | [
"def",
"run_selected_clicked",
"(",
"self",
")",
":",
"# get all selected rows",
"rows",
"=",
"sorted",
"(",
"set",
"(",
"index",
".",
"row",
"(",
")",
"for",
"index",
"in",
"self",
".",
"table",
".",
"selectedIndexes",
"(",
")",
")",
")",
"self",
".",
... | Run the selected scenario. | [
"Run",
"the",
"selected",
"scenario",
"."
] | 831d60abba919f6d481dc94a8d988cc205130724 | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/tools/batch/batch_dialog.py#L598-L610 | train | 26,772 |
inasafe/inasafe | safe/gui/tools/batch/batch_dialog.py | BatchDialog.run_all_clicked | def run_all_clicked(self):
"""Run all scenario when pbRunAll is clicked."""
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() | python | def run_all_clicked(self):
"""Run all scenario when pbRunAll is clicked."""
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() | [
"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"... | Run all scenario when pbRunAll is clicked. | [
"Run",
"all",
"scenario",
"when",
"pbRunAll",
"is",
"clicked",
"."
] | 831d60abba919f6d481dc94a8d988cc205130724 | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/tools/batch/batch_dialog.py#L613-L654 | train | 26,773 |
inasafe/inasafe | safe/gui/tools/batch/batch_dialog.py | BatchDialog.write_report | def write_report(self, report, pass_count, fail_count):
"""Write a report status of Batch Runner.
For convenience, the name will use current time.
:param report: A list of each scenario and its status.
:type report: list
:param pass_count: Number of passing scenarios.
:type pass_count: int
:param fail_count: Number of failed scenarios.
:type fail_count: int
:returns: A string containing the path to the report file.
:rtype: str
:raises: IOError
"""
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 | python | def write_report(self, report, pass_count, fail_count):
"""Write a report status of Batch Runner.
For convenience, the name will use current time.
:param report: A list of each scenario and its status.
:type report: list
:param pass_count: Number of passing scenarios.
:type pass_count: int
:param fail_count: Number of failed scenarios.
:type fail_count: int
:returns: A string containing the path to the report file.
:rtype: str
:raises: IOError
"""
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 | [
"def",
"write_report",
"(",
"self",
",",
"report",
",",
"pass_count",
",",
"fail_count",
")",
":",
"separator",
"=",
"'-----------------------------\\n'",
"current_time",
"=",
"datetime",
".",
"now",
"(",
")",
".",
"strftime",
"(",
"'%Y%m%d%H%M%S'",
")",
"report... | Write a report status of Batch Runner.
For convenience, the name will use current time.
:param report: A list of each scenario and its status.
:type report: list
:param pass_count: Number of passing scenarios.
:type pass_count: int
:param fail_count: Number of failed scenarios.
:type fail_count: int
:returns: A string containing the path to the report file.
:rtype: str
:raises: IOError | [
"Write",
"a",
"report",
"status",
"of",
"Batch",
"Runner",
"."
] | 831d60abba919f6d481dc94a8d988cc205130724 | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/tools/batch/batch_dialog.py#L656-L697 | train | 26,774 |
inasafe/inasafe | safe/gui/tools/batch/batch_dialog.py | BatchDialog.generate_pdf_report | def generate_pdf_report(self, impact_function, iface, scenario_name):
"""Generate and store map and impact report from impact function.
Directory where the report stored is specified by user input from the
dialog. This function is adapted from analysis_utilities.py
:param impact_function: Impact Function.
:type impact_function: ImpactFunction()
:param iface: iface.
:type iface: iface
:param scenario_name: name of the scenario
:type scenario_name: str
"""
# 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() | python | def generate_pdf_report(self, impact_function, iface, scenario_name):
"""Generate and store map and impact report from impact function.
Directory where the report stored is specified by user input from the
dialog. This function is adapted from analysis_utilities.py
:param impact_function: Impact Function.
:type impact_function: ImpactFunction()
:param iface: iface.
:type iface: iface
:param scenario_name: name of the scenario
:type scenario_name: str
"""
# 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() | [
"def",
"generate_pdf_report",
"(",
"self",
",",
"impact_function",
",",
"iface",
",",
"scenario_name",
")",
":",
"# output folder",
"output_dir",
"=",
"self",
".",
"output_directory",
".",
"text",
"(",
")",
"file_path",
"=",
"os",
".",
"path",
".",
"join",
"... | Generate and store map and impact report from impact function.
Directory where the report stored is specified by user input from the
dialog. This function is adapted from analysis_utilities.py
:param impact_function: Impact Function.
:type impact_function: ImpactFunction()
:param iface: iface.
:type iface: iface
:param scenario_name: name of the scenario
:type scenario_name: str | [
"Generate",
"and",
"store",
"map",
"and",
"impact",
"report",
"from",
"impact",
"function",
"."
] | 831d60abba919f6d481dc94a8d988cc205130724 | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/tools/batch/batch_dialog.py#L699-L741 | train | 26,775 |
inasafe/inasafe | safe/gui/tools/batch/batch_dialog.py | BatchDialog.show_report | def show_report(self, report_path):
"""Show batch report file in batchReportFileName using an external app.
This method uses QDesktop services to display the report (typically
using gedit or similar text editor).
:param report_path: Path to the file of batch report.
:type report_path: str
"""
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 | python | def show_report(self, report_path):
"""Show batch report file in batchReportFileName using an external app.
This method uses QDesktop services to display the report (typically
using gedit or similar text editor).
:param report_path: Path to the file of batch report.
:type report_path: str
"""
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 | [
"def",
"show_report",
"(",
"self",
",",
"report_path",
")",
":",
"if",
"self",
".",
"show_results_popup",
":",
"url",
"=",
"QtCore",
".",
"QUrl",
".",
"fromLocalFile",
"(",
"report_path",
")",
"# noinspection PyTypeChecker,PyCallByClass,PyArgumentList",
"QtGui",
"."... | Show batch report file in batchReportFileName using an external app.
This method uses QDesktop services to display the report (typically
using gedit or similar text editor).
:param report_path: Path to the file of batch report.
:type report_path: str | [
"Show",
"batch",
"report",
"file",
"in",
"batchReportFileName",
"using",
"an",
"external",
"app",
"."
] | 831d60abba919f6d481dc94a8d988cc205130724 | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/tools/batch/batch_dialog.py#L743-L759 | train | 26,776 |
inasafe/inasafe | safe/gui/tools/batch/batch_dialog.py | BatchDialog.update_default_output_dir | def update_default_output_dir(self):
"""Update output dir if set to default."""
if self.scenario_directory_radio.isChecked():
self.output_directory.setText(self.source_directory.text()) | python | def update_default_output_dir(self):
"""Update output dir if set to default."""
if self.scenario_directory_radio.isChecked():
self.output_directory.setText(self.source_directory.text()) | [
"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. | [
"Update",
"output",
"dir",
"if",
"set",
"to",
"default",
"."
] | 831d60abba919f6d481dc94a8d988cc205130724 | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/tools/batch/batch_dialog.py#L761-L764 | train | 26,777 |
inasafe/inasafe | safe/gui/tools/batch/batch_dialog.py | BatchDialog.enable_busy_cursor | def enable_busy_cursor(self):
"""Set the hourglass enabled."""
QgsApplication.instance().setOverrideCursor(
QtGui.QCursor(QtCore.Qt.WaitCursor)
) | python | def enable_busy_cursor(self):
"""Set the hourglass enabled."""
QgsApplication.instance().setOverrideCursor(
QtGui.QCursor(QtCore.Qt.WaitCursor)
) | [
"def",
"enable_busy_cursor",
"(",
"self",
")",
":",
"QgsApplication",
".",
"instance",
"(",
")",
".",
"setOverrideCursor",
"(",
"QtGui",
".",
"QCursor",
"(",
"QtCore",
".",
"Qt",
".",
"WaitCursor",
")",
")"
] | Set the hourglass enabled. | [
"Set",
"the",
"hourglass",
"enabled",
"."
] | 831d60abba919f6d481dc94a8d988cc205130724 | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/tools/batch/batch_dialog.py#L767-L771 | train | 26,778 |
inasafe/inasafe | safe/gui/tools/batch/batch_dialog.py | BatchDialog.on_scenario_directory_radio_toggled | def on_scenario_directory_radio_toggled(self, flag):
"""Autoconnect slot activated when scenario_directory_radio is checked.
:param flag: Flag indicating whether the checkbox was toggled on or
off.
:type flag: bool
"""
if flag:
self.output_directory.setText(self.source_directory.text())
self.output_directory_chooser.setEnabled(not flag) | python | def on_scenario_directory_radio_toggled(self, flag):
"""Autoconnect slot activated when scenario_directory_radio is checked.
:param flag: Flag indicating whether the checkbox was toggled on or
off.
:type flag: bool
"""
if flag:
self.output_directory.setText(self.source_directory.text())
self.output_directory_chooser.setEnabled(not flag) | [
"def",
"on_scenario_directory_radio_toggled",
"(",
"self",
",",
"flag",
")",
":",
"if",
"flag",
":",
"self",
".",
"output_directory",
".",
"setText",
"(",
"self",
".",
"source_directory",
".",
"text",
"(",
")",
")",
"self",
".",
"output_directory_chooser",
"."... | Autoconnect slot activated when scenario_directory_radio is checked.
:param flag: Flag indicating whether the checkbox was toggled on or
off.
:type flag: bool | [
"Autoconnect",
"slot",
"activated",
"when",
"scenario_directory_radio",
"is",
"checked",
"."
] | 831d60abba919f6d481dc94a8d988cc205130724 | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/tools/batch/batch_dialog.py#L779-L788 | train | 26,779 |
inasafe/inasafe | safe/gui/tools/batch/batch_dialog.py | BatchDialog.on_source_directory_chooser_clicked | def on_source_directory_chooser_clicked(self):
"""Autoconnect slot activated when tbSourceDir is clicked."""
title = self.tr('Set the source directory for script and scenario')
self.choose_directory(self.source_directory, title) | python | def on_source_directory_chooser_clicked(self):
"""Autoconnect slot activated when tbSourceDir is clicked."""
title = self.tr('Set the source directory for script and scenario')
self.choose_directory(self.source_directory, title) | [
"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. | [
"Autoconnect",
"slot",
"activated",
"when",
"tbSourceDir",
"is",
"clicked",
"."
] | 831d60abba919f6d481dc94a8d988cc205130724 | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/tools/batch/batch_dialog.py#L791-L795 | train | 26,780 |
inasafe/inasafe | safe/gui/tools/batch/batch_dialog.py | BatchDialog.on_output_directory_chooser_clicked | def on_output_directory_chooser_clicked(self):
"""Auto connect slot activated when tbOutputDiris clicked."""
title = self.tr('Set the output directory for pdf report files')
self.choose_directory(self.output_directory, title) | python | def on_output_directory_chooser_clicked(self):
"""Auto connect slot activated when tbOutputDiris clicked."""
title = self.tr('Set the output directory for pdf report files')
self.choose_directory(self.output_directory, title) | [
"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. | [
"Auto",
"connect",
"slot",
"activated",
"when",
"tbOutputDiris",
"clicked",
"."
] | 831d60abba919f6d481dc94a8d988cc205130724 | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/tools/batch/batch_dialog.py#L798-L801 | train | 26,781 |
inasafe/inasafe | safe/messaging/item/cell.py | Cell.to_html | def to_html(self):
"""Render a Cell MessageElement as html
:returns: The html representation of the Cell MessageElement
:rtype: basestring
"""
# 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) | python | def to_html(self):
"""Render a Cell MessageElement as html
:returns: The html representation of the Cell MessageElement
:rtype: basestring
"""
# 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) | [
"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",
"... | Render a Cell MessageElement as html
:returns: The html representation of the Cell MessageElement
:rtype: basestring | [
"Render",
"a",
"Cell",
"MessageElement",
"as",
"html"
] | 831d60abba919f6d481dc94a8d988cc205130724 | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/messaging/item/cell.py#L104-L141 | train | 26,782 |
inasafe/inasafe | safe/messaging/example/error_message_example.py | error_creator5 | def error_creator5():
"""Raise a safe style error and append a full message."""
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 | python | def error_creator5():
"""Raise a safe style error and append a full message."""
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 | [
"def",
"error_creator5",
"(",
")",
":",
"try",
":",
"error_creator4",
"(",
")",
"except",
"SafeError",
"as",
"e4",
":",
"message",
"=",
"ErrorMessage",
"(",
"'Creator 5 problem'",
",",
"detail",
"=",
"Message",
"(",
"Paragraph",
"(",
"'Could not'",
",",
"Imp... | Raise a safe style error and append a full message. | [
"Raise",
"a",
"safe",
"style",
"error",
"and",
"append",
"a",
"full",
"message",
"."
] | 831d60abba919f6d481dc94a8d988cc205130724 | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/messaging/example/error_message_example.py#L77-L89 | train | 26,783 |
inasafe/inasafe | safe/report/extractors/composer.py | qgis_composer_infographic_extractor | def qgis_composer_infographic_extractor(impact_report, component_metadata):
"""Extract composer context specific for infographic template.
This method extract necessary context for a given impact report and
component metadata and save the context so it can be used in composer
rendering phase
:param impact_report: the impact report that acts as a proxy to fetch
all the data that extractor needed
:type impact_report: safe.report.impact_report.ImpactReport
:param component_metadata: the component metadata. Used to obtain
information about the component we want to render
:type component_metadata: safe.report.report_metadata.
ReportComponentsMetadata
:return: context for rendering phase
:rtype: dict
.. versionadded:: 4.2
"""
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 | python | def qgis_composer_infographic_extractor(impact_report, component_metadata):
"""Extract composer context specific for infographic template.
This method extract necessary context for a given impact report and
component metadata and save the context so it can be used in composer
rendering phase
:param impact_report: the impact report that acts as a proxy to fetch
all the data that extractor needed
:type impact_report: safe.report.impact_report.ImpactReport
:param component_metadata: the component metadata. Used to obtain
information about the component we want to render
:type component_metadata: safe.report.report_metadata.
ReportComponentsMetadata
:return: context for rendering phase
:rtype: dict
.. versionadded:: 4.2
"""
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 | [
"def",
"qgis_composer_infographic_extractor",
"(",
"impact_report",
",",
"component_metadata",
")",
":",
"qgis_context",
"=",
"impact_report",
".",
"qgis_composition_context",
"extra_args",
"=",
"component_metadata",
".",
"extra_args",
"context",
"=",
"QGISComposerContext",
... | Extract composer context specific for infographic template.
This method extract necessary context for a given impact report and
component metadata and save the context so it can be used in composer
rendering phase
:param impact_report: the impact report that acts as a proxy to fetch
all the data that extractor needed
:type impact_report: safe.report.impact_report.ImpactReport
:param component_metadata: the component metadata. Used to obtain
information about the component we want to render
:type component_metadata: safe.report.report_metadata.
ReportComponentsMetadata
:return: context for rendering phase
:rtype: dict
.. versionadded:: 4.2 | [
"Extract",
"composer",
"context",
"specific",
"for",
"infographic",
"template",
"."
] | 831d60abba919f6d481dc94a8d988cc205130724 | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/report/extractors/composer.py#L488-L574 | train | 26,784 |
inasafe/inasafe | safe/gui/tools/wizard/step_kw45_inasafe_fields.py | StepKwInaSAFEFields.inasafe_fields_for_the_layer | def inasafe_fields_for_the_layer(self):
"""Return a list of inasafe fields the current layer.
:returns: A list where each value represents inasafe field.
:rtype: list
"""
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 | python | def inasafe_fields_for_the_layer(self):
"""Return a list of inasafe fields the current layer.
:returns: A list where each value represents inasafe field.
:rtype: list
"""
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 | [
"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_purpos... | Return a list of inasafe fields the current layer.
:returns: A list where each value represents inasafe field.
:rtype: list | [
"Return",
"a",
"list",
"of",
"inasafe",
"fields",
"the",
"current",
"layer",
"."
] | 831d60abba919f6d481dc94a8d988cc205130724 | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/tools/wizard/step_kw45_inasafe_fields.py#L87-L116 | train | 26,785 |
inasafe/inasafe | safe/utilities/unicode.py | __if_not_basestring | def __if_not_basestring(text_object):
"""Convert to str"""
converted_str = text_object
if not isinstance(text_object, str):
converted_str = str(text_object)
return converted_str | python | def __if_not_basestring(text_object):
"""Convert to str"""
converted_str = text_object
if not isinstance(text_object, str):
converted_str = str(text_object)
return converted_str | [
"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 | [
"Convert",
"to",
"str"
] | 831d60abba919f6d481dc94a8d988cc205130724 | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/utilities/unicode.py#L25-L30 | train | 26,786 |
inasafe/inasafe | safe/utilities/unicode.py | get_string | def get_string(input_text, encoding='utf-8'):
"""Get byte string representation of an object.
:param input_text: The input text.
:type input_text: unicode, str, float, int
:param encoding: The encoding used to do the conversion, default to utf-8.
:type encoding: str
:returns: Byte string representation of the input.
:rtype: bytes
"""
if isinstance(input_text, str):
return input_text.encode(encoding)
return input_text | python | def get_string(input_text, encoding='utf-8'):
"""Get byte string representation of an object.
:param input_text: The input text.
:type input_text: unicode, str, float, int
:param encoding: The encoding used to do the conversion, default to utf-8.
:type encoding: str
:returns: Byte string representation of the input.
:rtype: bytes
"""
if isinstance(input_text, str):
return input_text.encode(encoding)
return input_text | [
"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.
:param input_text: The input text.
:type input_text: unicode, str, float, int
:param encoding: The encoding used to do the conversion, default to utf-8.
:type encoding: str
:returns: Byte string representation of the input.
:rtype: bytes | [
"Get",
"byte",
"string",
"representation",
"of",
"an",
"object",
"."
] | 831d60abba919f6d481dc94a8d988cc205130724 | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/utilities/unicode.py#L50-L64 | train | 26,787 |
inasafe/inasafe | safe/utilities/unicode.py | byteify | def byteify(input_object):
"""Recursive function to transform an object to byte.
:param input_object: A python object such as unicode, dictionary or list.
:type: unicode, list, dict
:return: The object with byte only.
"""
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 | python | def byteify(input_object):
"""Recursive function to transform an object to byte.
:param input_object: A python object such as unicode, dictionary or list.
:type: unicode, list, dict
:return: The object with byte only.
"""
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 | [
"def",
"byteify",
"(",
"input_object",
")",
":",
"if",
"isinstance",
"(",
"input_object",
",",
"dict",
")",
":",
"return",
"{",
"byteify",
"(",
"key",
")",
":",
"byteify",
"(",
"value",
")",
"for",
"key",
",",
"value",
"in",
"list",
"(",
"input_object"... | Recursive function to transform an object to byte.
:param input_object: A python object such as unicode, dictionary or list.
:type: unicode, list, dict
:return: The object with byte only. | [
"Recursive",
"function",
"to",
"transform",
"an",
"object",
"to",
"byte",
"."
] | 831d60abba919f6d481dc94a8d988cc205130724 | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/utilities/unicode.py#L67-L83 | train | 26,788 |
inasafe/inasafe | safe/metadata35/impact_layer_metadata.py | ImpactLayerMetadata.dict | def dict(self):
"""
calls the overridden method and adds provenance and summary data
:return: dictionary representation of the metadata
:rtype: dict
"""
metadata = super(ImpactLayerMetadata, self).dict
metadata['provenance'] = self.provenance
metadata['summary_data'] = self.summary_data
return metadata | python | def dict(self):
"""
calls the overridden method and adds provenance and summary data
:return: dictionary representation of the metadata
:rtype: dict
"""
metadata = super(ImpactLayerMetadata, self).dict
metadata['provenance'] = self.provenance
metadata['summary_data'] = self.summary_data
return metadata | [
"def",
"dict",
"(",
"self",
")",
":",
"metadata",
"=",
"super",
"(",
"ImpactLayerMetadata",
",",
"self",
")",
".",
"dict",
"metadata",
"[",
"'provenance'",
"]",
"=",
"self",
".",
"provenance",
"metadata",
"[",
"'summary_data'",
"]",
"=",
"self",
".",
"su... | calls the overridden method and adds provenance and summary data
:return: dictionary representation of the metadata
:rtype: dict | [
"calls",
"the",
"overridden",
"method",
"and",
"adds",
"provenance",
"and",
"summary",
"data"
] | 831d60abba919f6d481dc94a8d988cc205130724 | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/metadata35/impact_layer_metadata.py#L203-L215 | train | 26,789 |
inasafe/inasafe | safe/metadata35/impact_layer_metadata.py | ImpactLayerMetadata._read_provenance_from_xml | def _read_provenance_from_xml(self, root):
"""
read metadata provenance from xml.
:param root: container in which we search
:type root: ElementTree.Element
"""
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) | python | def _read_provenance_from_xml(self, root):
"""
read metadata provenance from xml.
:param root: container in which we search
:type root: ElementTree.Element
"""
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) | [
"def",
"_read_provenance_from_xml",
"(",
"self",
",",
"root",
")",
":",
"path",
"=",
"self",
".",
"_special_properties",
"[",
"'provenance'",
"]",
"provenance",
"=",
"root",
".",
"find",
"(",
"path",
",",
"XML_NS",
")",
"for",
"step",
"in",
"provenance",
"... | read metadata provenance from xml.
:param root: container in which we search
:type root: ElementTree.Element | [
"read",
"metadata",
"provenance",
"from",
"xml",
"."
] | 831d60abba919f6d481dc94a8d988cc205130724 | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/metadata35/impact_layer_metadata.py#L312-L339 | train | 26,790 |
inasafe/inasafe | safe/metadata35/impact_layer_metadata.py | ImpactLayerMetadata.append_provenance_step | def append_provenance_step(self, title, description, timestamp=None):
"""
Add a step to the provenance of the metadata
:param title: The title of the step.
:type title: str
:param description: The content of the step
:type description: str
:param timestamp: the time of the step
:type timestamp: datetime, str
"""
step_time = self._provenance.append_step(title, description, timestamp)
if step_time > self.last_update:
self.last_update = step_time | python | def append_provenance_step(self, title, description, timestamp=None):
"""
Add a step to the provenance of the metadata
:param title: The title of the step.
:type title: str
:param description: The content of the step
:type description: str
:param timestamp: the time of the step
:type timestamp: datetime, str
"""
step_time = self._provenance.append_step(title, description, timestamp)
if step_time > self.last_update:
self.last_update = step_time | [
"def",
"append_provenance_step",
"(",
"self",
",",
"title",
",",
"description",
",",
"timestamp",
"=",
"None",
")",
":",
"step_time",
"=",
"self",
".",
"_provenance",
".",
"append_step",
"(",
"title",
",",
"description",
",",
"timestamp",
")",
"if",
"step_ti... | Add a step to the provenance of the metadata
:param title: The title of the step.
:type title: str
:param description: The content of the step
:type description: str
:param timestamp: the time of the step
:type timestamp: datetime, str | [
"Add",
"a",
"step",
"to",
"the",
"provenance",
"of",
"the",
"metadata"
] | 831d60abba919f6d481dc94a8d988cc205130724 | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/metadata35/impact_layer_metadata.py#L354-L369 | train | 26,791 |
inasafe/inasafe | safe/metadata35/impact_layer_metadata.py | ImpactLayerMetadata.append_if_provenance_step | def append_if_provenance_step(
self, title, description, timestamp=None, data=None):
"""Add a if provenance step to the provenance of the metadata
:param title: The title of the step.
:type title: str
:param description: The content of the step
:type description: str
:param timestamp: the time of the step
:type timestamp: datetime, str
:param data: The data of the step.
:type data: dict
"""
step_time = self._provenance.append_if_provenance_step(
title, description, timestamp, data)
if step_time > self.last_update:
self.last_update = step_time | python | def append_if_provenance_step(
self, title, description, timestamp=None, data=None):
"""Add a if provenance step to the provenance of the metadata
:param title: The title of the step.
:type title: str
:param description: The content of the step
:type description: str
:param timestamp: the time of the step
:type timestamp: datetime, str
:param data: The data of the step.
:type data: dict
"""
step_time = self._provenance.append_if_provenance_step(
title, description, timestamp, data)
if step_time > self.last_update:
self.last_update = step_time | [
"def",
"append_if_provenance_step",
"(",
"self",
",",
"title",
",",
"description",
",",
"timestamp",
"=",
"None",
",",
"data",
"=",
"None",
")",
":",
"step_time",
"=",
"self",
".",
"_provenance",
".",
"append_if_provenance_step",
"(",
"title",
",",
"descriptio... | Add a if provenance step to the provenance of the metadata
:param title: The title of the step.
:type title: str
:param description: The content of the step
:type description: str
:param timestamp: the time of the step
:type timestamp: datetime, str
:param data: The data of the step.
:type data: dict | [
"Add",
"a",
"if",
"provenance",
"step",
"to",
"the",
"provenance",
"of",
"the",
"metadata"
] | 831d60abba919f6d481dc94a8d988cc205130724 | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/metadata35/impact_layer_metadata.py#L371-L390 | train | 26,792 |
inasafe/inasafe | safe/metadata35/impact_layer_metadata.py | ImpactLayerMetadata.update_from_dict | def update_from_dict(self, keywords):
"""Update metadata value from a keywords dictionary.
:param keywords:
:return:
"""
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) | python | def update_from_dict(self, keywords):
"""Update metadata value from a keywords dictionary.
:param keywords:
:return:
"""
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) | [
"def",
"update_from_dict",
"(",
"self",
",",
"keywords",
")",
":",
"super",
"(",
"ImpactLayerMetadata",
",",
"self",
")",
".",
"update_from_dict",
"(",
"keywords",
")",
"if",
"'if_provenance'",
"in",
"list",
"(",
"keywords",
".",
"keys",
"(",
")",
")",
":"... | Update metadata value from a keywords dictionary.
:param keywords:
:return: | [
"Update",
"metadata",
"value",
"from",
"a",
"keywords",
"dictionary",
"."
] | 831d60abba919f6d481dc94a8d988cc205130724 | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/metadata35/impact_layer_metadata.py#L392-L403 | train | 26,793 |
inasafe/inasafe | safe/common/parameters/group_select_parameter_widget.py | GroupSelectParameterWidget.update_list_widget | def update_list_widget(self):
"""Update list widget when radio button is clicked."""
# 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) | python | def update_list_widget(self):
"""Update list widget when radio button is clicked."""
# 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) | [
"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",
">",
"-",... | Update list widget when radio button is clicked. | [
"Update",
"list",
"widget",
"when",
"radio",
"button",
"is",
"clicked",
"."
] | 831d60abba919f6d481dc94a8d988cc205130724 | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/common/parameters/group_select_parameter_widget.py#L180-L198 | train | 26,794 |
inasafe/inasafe | safe/common/parameters/group_select_parameter_widget.py | GroupSelectParameterWidget.radio_buttons_clicked | def radio_buttons_clicked(self):
"""Handler when selected radio button changed."""
# 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) | python | def radio_buttons_clicked(self):
"""Handler when selected radio button changed."""
# 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) | [
"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",
"s... | Handler when selected radio button changed. | [
"Handler",
"when",
"selected",
"radio",
"button",
"changed",
"."
] | 831d60abba919f6d481dc94a8d988cc205130724 | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/common/parameters/group_select_parameter_widget.py#L200-L220 | train | 26,795 |
inasafe/inasafe | safe/common/parameters/group_select_parameter_widget.py | GroupSelectParameterWidget.select_radio_button | def select_radio_button(self, key):
"""Helper to select a radio button with key.
:param key: The key of the radio button.
:type key: str
"""
key_index = list(self._parameter.options.keys()).index(key)
radio_button = self.input_button_group.button(key_index)
radio_button.click() | python | def select_radio_button(self, key):
"""Helper to select a radio button with key.
:param key: The key of the radio button.
:type key: str
"""
key_index = list(self._parameter.options.keys()).index(key)
radio_button = self.input_button_group.button(key_index)
radio_button.click() | [
"def",
"select_radio_button",
"(",
"self",
",",
"key",
")",
":",
"key_index",
"=",
"list",
"(",
"self",
".",
"_parameter",
".",
"options",
".",
"keys",
"(",
")",
")",
".",
"index",
"(",
"key",
")",
"radio_button",
"=",
"self",
".",
"input_button_group",
... | Helper to select a radio button with key.
:param key: The key of the radio button.
:type key: str | [
"Helper",
"to",
"select",
"a",
"radio",
"button",
"with",
"key",
"."
] | 831d60abba919f6d481dc94a8d988cc205130724 | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/common/parameters/group_select_parameter_widget.py#L222-L230 | train | 26,796 |
inasafe/inasafe | safe/messaging/item/brand.py | Brand.to_html | def to_html(self):
"""Render as html.
"""
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 | python | def to_html(self):
"""Render as html.
"""
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 | [
"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>'"... | Render as html. | [
"Render",
"as",
"html",
"."
] | 831d60abba919f6d481dc94a8d988cc205130724 | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/messaging/item/brand.py#L52-L64 | train | 26,797 |
inasafe/inasafe | safe/report/extractors/mmi_detail.py | mmi_detail_extractor | def mmi_detail_extractor(impact_report, component_metadata):
"""Extracting MMI-related analysis result.
This extractor should only be used for EQ Raster with Population.
:param impact_report: the impact report that acts as a proxy to fetch
all the data that extractor needed
:type impact_report: safe.report.impact_report.ImpactReport
:param component_metadata: the component metadata. Used to obtain
information about the component we want to render
:type component_metadata: safe.report.report_metadata.
ReportComponentsMetadata
:return: context for rendering phase
:rtype: dict
.. versionadded:: 4.0
"""
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 | python | def mmi_detail_extractor(impact_report, component_metadata):
"""Extracting MMI-related analysis result.
This extractor should only be used for EQ Raster with Population.
:param impact_report: the impact report that acts as a proxy to fetch
all the data that extractor needed
:type impact_report: safe.report.impact_report.ImpactReport
:param component_metadata: the component metadata. Used to obtain
information about the component we want to render
:type component_metadata: safe.report.report_metadata.
ReportComponentsMetadata
:return: context for rendering phase
:rtype: dict
.. versionadded:: 4.0
"""
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 | [
"def",
"mmi_detail_extractor",
"(",
"impact_report",
",",
"component_metadata",
")",
":",
"context",
"=",
"{",
"}",
"analysis_layer",
"=",
"impact_report",
".",
"analysis",
"analysis_layer_keywords",
"=",
"analysis_layer",
".",
"keywords",
"extra_args",
"=",
"componen... | Extracting MMI-related analysis result.
This extractor should only be used for EQ Raster with Population.
:param impact_report: the impact report that acts as a proxy to fetch
all the data that extractor needed
:type impact_report: safe.report.impact_report.ImpactReport
:param component_metadata: the component metadata. Used to obtain
information about the component we want to render
:type component_metadata: safe.report.report_metadata.
ReportComponentsMetadata
:return: context for rendering phase
:rtype: dict
.. versionadded:: 4.0 | [
"Extracting",
"MMI",
"-",
"related",
"analysis",
"result",
"."
] | 831d60abba919f6d481dc94a8d988cc205130724 | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/report/extractors/mmi_detail.py#L21-L137 | train | 26,798 |
inasafe/inasafe | safe/report/expressions/infographic.py | inasafe_field_header | def inasafe_field_header(field, feature, parent):
"""Retrieve a header name of the field name from definitions.
For instance:
inasafe_field_header('minimum_needs__clean_water') -> 'Clean water'
"""
_ = 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 | python | def inasafe_field_header(field, feature, parent):
"""Retrieve a header name of the field name from definitions.
For instance:
inasafe_field_header('minimum_needs__clean_water') -> 'Clean water'
"""
_ = 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 | [
"def",
"inasafe_field_header",
"(",
"field",
",",
"feature",
",",
"parent",
")",
":",
"_",
"=",
"feature",
",",
"parent",
"# NOQA",
"age_fields",
"=",
"[",
"under_5_displaced_count_field",
",",
"over_60_displaced_count_field",
"]",
"symbol_mapping",
"=",
"{",
"'ov... | Retrieve a header name of the field name from definitions.
For instance:
inasafe_field_header('minimum_needs__clean_water') -> 'Clean water' | [
"Retrieve",
"a",
"header",
"name",
"of",
"the",
"field",
"name",
"from",
"definitions",
"."
] | 831d60abba919f6d481dc94a8d988cc205130724 | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/report/expressions/infographic.py#L55-L88 | train | 26,799 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.