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/gui/widgets/dock.py | Dock.hide_busy | def hide_busy(self, check_next_impact=True):
"""A helper function to indicate processing is done.
:param check_next_impact: Flag to check if we can validate the next IF.
:type check_next_impact: bool
"""
self.progress_bar.hide()
self.show_question_button.setVisible(True)
self.question_group.setEnabled(True)
self.question_group.setVisible(False)
if check_next_impact:
# We check if we can run an IF
self.validate_impact_function()
self.repaint()
disable_busy_cursor()
self.busy = False | python | def hide_busy(self, check_next_impact=True):
"""A helper function to indicate processing is done.
:param check_next_impact: Flag to check if we can validate the next IF.
:type check_next_impact: bool
"""
self.progress_bar.hide()
self.show_question_button.setVisible(True)
self.question_group.setEnabled(True)
self.question_group.setVisible(False)
if check_next_impact:
# We check if we can run an IF
self.validate_impact_function()
self.repaint()
disable_busy_cursor()
self.busy = False | [
"def",
"hide_busy",
"(",
"self",
",",
"check_next_impact",
"=",
"True",
")",
":",
"self",
".",
"progress_bar",
".",
"hide",
"(",
")",
"self",
".",
"show_question_button",
".",
"setVisible",
"(",
"True",
")",
"self",
".",
"question_group",
".",
"setEnabled",
... | A helper function to indicate processing is done.
:param check_next_impact: Flag to check if we can validate the next IF.
:type check_next_impact: bool | [
"A",
"helper",
"function",
"to",
"indicate",
"processing",
"is",
"done",
"."
] | 831d60abba919f6d481dc94a8d988cc205130724 | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/widgets/dock.py#L882-L899 | train | 27,100 |
inasafe/inasafe | safe/gui/widgets/dock.py | Dock.show_impact | def show_impact(self, report_path):
"""Show the report.
.. versionadded: 4.0
:param report_path: The path to the report.
:type report_path: basestring
"""
# We can display an impact report.
# We need to open the file in UTF-8, the HTML may have some accents
with codecs.open(report_path, 'r', 'utf-8') as report_file:
report = report_file.read()
self.print_button.setEnabled(True)
# right now send the report as html texts, not message
send_static_message(self, report)
# also hide the question and show the show question button
self.show_question_button.setVisible(True)
self.question_group.setEnabled(True)
self.question_group.setVisible(False) | python | def show_impact(self, report_path):
"""Show the report.
.. versionadded: 4.0
:param report_path: The path to the report.
:type report_path: basestring
"""
# We can display an impact report.
# We need to open the file in UTF-8, the HTML may have some accents
with codecs.open(report_path, 'r', 'utf-8') as report_file:
report = report_file.read()
self.print_button.setEnabled(True)
# right now send the report as html texts, not message
send_static_message(self, report)
# also hide the question and show the show question button
self.show_question_button.setVisible(True)
self.question_group.setEnabled(True)
self.question_group.setVisible(False) | [
"def",
"show_impact",
"(",
"self",
",",
"report_path",
")",
":",
"# We can display an impact report.",
"# We need to open the file in UTF-8, the HTML may have some accents",
"with",
"codecs",
".",
"open",
"(",
"report_path",
",",
"'r'",
",",
"'utf-8'",
")",
"as",
"report_... | Show the report.
.. versionadded: 4.0
:param report_path: The path to the report.
:type report_path: basestring | [
"Show",
"the",
"report",
"."
] | 831d60abba919f6d481dc94a8d988cc205130724 | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/widgets/dock.py#L901-L920 | train | 27,101 |
inasafe/inasafe | safe/gui/widgets/dock.py | Dock.show_generic_keywords | def show_generic_keywords(self, layer):
"""Show the keywords defined for the active layer.
.. note:: The print button will be disabled if this method is called.
.. versionchanged:: 3.3 - changed parameter from keywords object
to a layer object so that we can show extra stuff like CRS and
data source in the keywords.
:param layer: A QGIS layer.
:type layer: QgsMapLayer
"""
keywords = KeywordIO(layer)
self.print_button.setEnabled(False)
try:
message = keywords.to_message()
send_static_message(self, message)
except InvalidMessageItemError:
# FIXME (elpaso)
pass
self.show_question_button.setVisible(False)
self.question_group.setEnabled(True)
self.question_group.setVisible(True) | python | def show_generic_keywords(self, layer):
"""Show the keywords defined for the active layer.
.. note:: The print button will be disabled if this method is called.
.. versionchanged:: 3.3 - changed parameter from keywords object
to a layer object so that we can show extra stuff like CRS and
data source in the keywords.
:param layer: A QGIS layer.
:type layer: QgsMapLayer
"""
keywords = KeywordIO(layer)
self.print_button.setEnabled(False)
try:
message = keywords.to_message()
send_static_message(self, message)
except InvalidMessageItemError:
# FIXME (elpaso)
pass
self.show_question_button.setVisible(False)
self.question_group.setEnabled(True)
self.question_group.setVisible(True) | [
"def",
"show_generic_keywords",
"(",
"self",
",",
"layer",
")",
":",
"keywords",
"=",
"KeywordIO",
"(",
"layer",
")",
"self",
".",
"print_button",
".",
"setEnabled",
"(",
"False",
")",
"try",
":",
"message",
"=",
"keywords",
".",
"to_message",
"(",
")",
... | Show the keywords defined for the active layer.
.. note:: The print button will be disabled if this method is called.
.. versionchanged:: 3.3 - changed parameter from keywords object
to a layer object so that we can show extra stuff like CRS and
data source in the keywords.
:param layer: A QGIS layer.
:type layer: QgsMapLayer | [
"Show",
"the",
"keywords",
"defined",
"for",
"the",
"active",
"layer",
"."
] | 831d60abba919f6d481dc94a8d988cc205130724 | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/widgets/dock.py#L922-L944 | train | 27,102 |
inasafe/inasafe | safe/gui/widgets/dock.py | Dock.layer_changed | def layer_changed(self, layer):
"""Handler for when the QGIS active layer is changed.
If the active layer is changed and it has keywords and a report,
show the report.
:param layer: QgsMapLayer instance that is now active.
:type layer: QgsMapLayer, QgsRasterLayer, QgsVectorLayer
"""
# Don't handle this event if we are already handling another layer
# addition or removal event.
if self.get_layers_lock or layer is None:
return
# Do nothing if there is no active layer - see #1861
if not self._has_active_layer():
if self.conflicting_plugin_detected:
send_static_message(self, conflicting_plugin_message())
else:
send_static_message(self, getting_started_message())
# Now try to read the keywords and show them in the dock
try:
keywords = self.keyword_io.read_keywords(layer)
# list of layer purpose to show impact report
impacted_layer = [
layer_purpose_exposure_summary['key'],
layer_purpose_aggregate_hazard_impacted['key'],
layer_purpose_aggregation_summary['key'],
layer_purpose_analysis_impacted['key'],
layer_purpose_exposure_summary_table['key'],
layer_purpose_profiling['key'],
# Legacy from InaSAFE < 4.2. We still want to open old
# analysis made with 4.0 an 4.1.
# We should remove them later.
'exposure_summary',
'aggregate_hazard_impacted',
'aggregation_summary',
'analysis_impacted'
]
provenances = keywords.get('provenance_data', {})
extra_keywords = keywords.get('extra_keywords', {})
is_multi_exposure = (
extra_keywords.get(extra_keyword_analysis_type['key']) == (
MULTI_EXPOSURE_ANALYSIS_FLAG))
if provenances:
set_provenance_to_project_variables(provenances)
try:
if is_multi_exposure:
self.impact_function = (
MultiExposureImpactFunction.load_from_output_metadata(
keywords))
elif provenances:
self.impact_function = (
ImpactFunction.load_from_output_metadata(
keywords))
except InvalidLayerError as e:
display_critical_message_bar(
tr("Invalid Layer"), str(e), iface_object=self.iface)
self.impact_function = None
show_keywords = True
if keywords.get('layer_purpose') in impacted_layer:
analysis_dir = os.path.dirname(layer.source())
output_dir_path = os.path.join(analysis_dir, 'output')
html_report_products = [
'impact-report-output.html',
'multi-exposure-impact-report-output.html']
for html_report_product in html_report_products:
table_report_path = os.path.join(
output_dir_path, html_report_product)
if os.path.exists(table_report_path):
show_keywords = False
self.show_impact(table_report_path)
break
if show_keywords:
if inasafe_keyword_version_key not in list(keywords.keys()):
show_keyword_version_message(
self, tr('No Version'), self.inasafe_version)
self.print_button.setEnabled(False)
else:
keyword_version = str(keywords.get(
inasafe_keyword_version_key))
supported = is_keyword_version_supported(
keyword_version)
if supported:
self.show_generic_keywords(layer)
else:
# Layer version is not supported
show_keyword_version_message(
self, keyword_version, self.inasafe_version)
self.print_button.setEnabled(False)
# TODO: maybe we need to split these apart more to give mode
# TODO: granular error messages TS
except (KeywordNotFoundError,
HashNotFoundError,
InvalidParameterError,
NoKeywordsFoundError,
MetadataReadError,
AttributeError) as e:
# Added this check in 3.2 for #1861
active_layer = self.iface.activeLayer()
if active_layer is None:
if self.conflicting_plugin_detected:
send_static_message(self, conflicting_plugin_message())
else:
send_static_message(self, getting_started_message())
else:
LOGGER.debug(e)
show_no_keywords_message(self)
self.print_button.setEnabled(False)
except Exception as e: # pylint: disable=broad-except
error_message = get_error_message(e)
send_error_message(self, error_message) | python | def layer_changed(self, layer):
"""Handler for when the QGIS active layer is changed.
If the active layer is changed and it has keywords and a report,
show the report.
:param layer: QgsMapLayer instance that is now active.
:type layer: QgsMapLayer, QgsRasterLayer, QgsVectorLayer
"""
# Don't handle this event if we are already handling another layer
# addition or removal event.
if self.get_layers_lock or layer is None:
return
# Do nothing if there is no active layer - see #1861
if not self._has_active_layer():
if self.conflicting_plugin_detected:
send_static_message(self, conflicting_plugin_message())
else:
send_static_message(self, getting_started_message())
# Now try to read the keywords and show them in the dock
try:
keywords = self.keyword_io.read_keywords(layer)
# list of layer purpose to show impact report
impacted_layer = [
layer_purpose_exposure_summary['key'],
layer_purpose_aggregate_hazard_impacted['key'],
layer_purpose_aggregation_summary['key'],
layer_purpose_analysis_impacted['key'],
layer_purpose_exposure_summary_table['key'],
layer_purpose_profiling['key'],
# Legacy from InaSAFE < 4.2. We still want to open old
# analysis made with 4.0 an 4.1.
# We should remove them later.
'exposure_summary',
'aggregate_hazard_impacted',
'aggregation_summary',
'analysis_impacted'
]
provenances = keywords.get('provenance_data', {})
extra_keywords = keywords.get('extra_keywords', {})
is_multi_exposure = (
extra_keywords.get(extra_keyword_analysis_type['key']) == (
MULTI_EXPOSURE_ANALYSIS_FLAG))
if provenances:
set_provenance_to_project_variables(provenances)
try:
if is_multi_exposure:
self.impact_function = (
MultiExposureImpactFunction.load_from_output_metadata(
keywords))
elif provenances:
self.impact_function = (
ImpactFunction.load_from_output_metadata(
keywords))
except InvalidLayerError as e:
display_critical_message_bar(
tr("Invalid Layer"), str(e), iface_object=self.iface)
self.impact_function = None
show_keywords = True
if keywords.get('layer_purpose') in impacted_layer:
analysis_dir = os.path.dirname(layer.source())
output_dir_path = os.path.join(analysis_dir, 'output')
html_report_products = [
'impact-report-output.html',
'multi-exposure-impact-report-output.html']
for html_report_product in html_report_products:
table_report_path = os.path.join(
output_dir_path, html_report_product)
if os.path.exists(table_report_path):
show_keywords = False
self.show_impact(table_report_path)
break
if show_keywords:
if inasafe_keyword_version_key not in list(keywords.keys()):
show_keyword_version_message(
self, tr('No Version'), self.inasafe_version)
self.print_button.setEnabled(False)
else:
keyword_version = str(keywords.get(
inasafe_keyword_version_key))
supported = is_keyword_version_supported(
keyword_version)
if supported:
self.show_generic_keywords(layer)
else:
# Layer version is not supported
show_keyword_version_message(
self, keyword_version, self.inasafe_version)
self.print_button.setEnabled(False)
# TODO: maybe we need to split these apart more to give mode
# TODO: granular error messages TS
except (KeywordNotFoundError,
HashNotFoundError,
InvalidParameterError,
NoKeywordsFoundError,
MetadataReadError,
AttributeError) as e:
# Added this check in 3.2 for #1861
active_layer = self.iface.activeLayer()
if active_layer is None:
if self.conflicting_plugin_detected:
send_static_message(self, conflicting_plugin_message())
else:
send_static_message(self, getting_started_message())
else:
LOGGER.debug(e)
show_no_keywords_message(self)
self.print_button.setEnabled(False)
except Exception as e: # pylint: disable=broad-except
error_message = get_error_message(e)
send_error_message(self, error_message) | [
"def",
"layer_changed",
"(",
"self",
",",
"layer",
")",
":",
"# Don't handle this event if we are already handling another layer",
"# addition or removal event.",
"if",
"self",
".",
"get_layers_lock",
"or",
"layer",
"is",
"None",
":",
"return",
"# Do nothing if there is no ac... | Handler for when the QGIS active layer is changed.
If the active layer is changed and it has keywords and a report,
show the report.
:param layer: QgsMapLayer instance that is now active.
:type layer: QgsMapLayer, QgsRasterLayer, QgsVectorLayer | [
"Handler",
"for",
"when",
"the",
"QGIS",
"active",
"layer",
"is",
"changed",
"."
] | 831d60abba919f6d481dc94a8d988cc205130724 | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/widgets/dock.py#L947-L1068 | train | 27,103 |
inasafe/inasafe | safe/gui/widgets/dock.py | Dock.save_state | def save_state(self):
"""Save the current state of the ui to an internal class member.
The saved state can be restored again easily using
:func:`restore_state`
"""
state = {
'hazard': self.hazard_layer_combo.currentText(),
'exposure': self.exposure_layer_combo.currentText(),
'aggregation': self.aggregation_layer_combo.currentText(),
'report': self.results_webview.page().currentFrame().toHtml()}
self.state = state | python | def save_state(self):
"""Save the current state of the ui to an internal class member.
The saved state can be restored again easily using
:func:`restore_state`
"""
state = {
'hazard': self.hazard_layer_combo.currentText(),
'exposure': self.exposure_layer_combo.currentText(),
'aggregation': self.aggregation_layer_combo.currentText(),
'report': self.results_webview.page().currentFrame().toHtml()}
self.state = state | [
"def",
"save_state",
"(",
"self",
")",
":",
"state",
"=",
"{",
"'hazard'",
":",
"self",
".",
"hazard_layer_combo",
".",
"currentText",
"(",
")",
",",
"'exposure'",
":",
"self",
".",
"exposure_layer_combo",
".",
"currentText",
"(",
")",
",",
"'aggregation'",
... | Save the current state of the ui to an internal class member.
The saved state can be restored again easily using
:func:`restore_state` | [
"Save",
"the",
"current",
"state",
"of",
"the",
"ui",
"to",
"an",
"internal",
"class",
"member",
"."
] | 831d60abba919f6d481dc94a8d988cc205130724 | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/widgets/dock.py#L1070-L1081 | train | 27,104 |
inasafe/inasafe | safe/gui/widgets/dock.py | Dock.restore_state | def restore_state(self):
"""Restore the state of the dock to the last known state."""
if self.state is None:
return
for myCount in range(0, self.exposure_layer_combo.count()):
item_text = self.exposure_layer_combo.itemText(myCount)
if item_text == self.state['exposure']:
self.exposure_layer_combo.setCurrentIndex(myCount)
break
for myCount in range(0, self.hazard_layer_combo.count()):
item_text = self.hazard_layer_combo.itemText(myCount)
if item_text == self.state['hazard']:
self.hazard_layer_combo.setCurrentIndex(myCount)
break
for myCount in range(0, self.aggregation_layer_combo.count()):
item_text = self.aggregation_layer_combo.itemText(myCount)
if item_text == self.state['aggregation']:
self.aggregation_layer_combo.setCurrentIndex(myCount)
break
self.results_webview.setHtml(self.state['report']) | python | def restore_state(self):
"""Restore the state of the dock to the last known state."""
if self.state is None:
return
for myCount in range(0, self.exposure_layer_combo.count()):
item_text = self.exposure_layer_combo.itemText(myCount)
if item_text == self.state['exposure']:
self.exposure_layer_combo.setCurrentIndex(myCount)
break
for myCount in range(0, self.hazard_layer_combo.count()):
item_text = self.hazard_layer_combo.itemText(myCount)
if item_text == self.state['hazard']:
self.hazard_layer_combo.setCurrentIndex(myCount)
break
for myCount in range(0, self.aggregation_layer_combo.count()):
item_text = self.aggregation_layer_combo.itemText(myCount)
if item_text == self.state['aggregation']:
self.aggregation_layer_combo.setCurrentIndex(myCount)
break
self.results_webview.setHtml(self.state['report']) | [
"def",
"restore_state",
"(",
"self",
")",
":",
"if",
"self",
".",
"state",
"is",
"None",
":",
"return",
"for",
"myCount",
"in",
"range",
"(",
"0",
",",
"self",
".",
"exposure_layer_combo",
".",
"count",
"(",
")",
")",
":",
"item_text",
"=",
"self",
"... | Restore the state of the dock to the last known state. | [
"Restore",
"the",
"state",
"of",
"the",
"dock",
"to",
"the",
"last",
"known",
"state",
"."
] | 831d60abba919f6d481dc94a8d988cc205130724 | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/widgets/dock.py#L1083-L1102 | train | 27,105 |
inasafe/inasafe | safe/gui/widgets/dock.py | Dock.define_user_analysis_extent | def define_user_analysis_extent(self, extent, crs):
"""Slot called when user has defined a custom analysis extent.
.. versionadded: 2.2.0
:param extent: Extent of the user's preferred analysis area.
:type extent: QgsRectangle
:param crs: Coordinate reference system for user defined analysis
extent.
:type crs: QgsCoordinateReferenceSystem
"""
extent = QgsGeometry.fromRect(extent)
self.extent.set_user_extent(extent, crs)
self.validate_impact_function() | python | def define_user_analysis_extent(self, extent, crs):
"""Slot called when user has defined a custom analysis extent.
.. versionadded: 2.2.0
:param extent: Extent of the user's preferred analysis area.
:type extent: QgsRectangle
:param crs: Coordinate reference system for user defined analysis
extent.
:type crs: QgsCoordinateReferenceSystem
"""
extent = QgsGeometry.fromRect(extent)
self.extent.set_user_extent(extent, crs)
self.validate_impact_function() | [
"def",
"define_user_analysis_extent",
"(",
"self",
",",
"extent",
",",
"crs",
")",
":",
"extent",
"=",
"QgsGeometry",
".",
"fromRect",
"(",
"extent",
")",
"self",
".",
"extent",
".",
"set_user_extent",
"(",
"extent",
",",
"crs",
")",
"self",
".",
"validate... | Slot called when user has defined a custom analysis extent.
.. versionadded: 2.2.0
:param extent: Extent of the user's preferred analysis area.
:type extent: QgsRectangle
:param crs: Coordinate reference system for user defined analysis
extent.
:type crs: QgsCoordinateReferenceSystem | [
"Slot",
"called",
"when",
"user",
"has",
"defined",
"a",
"custom",
"analysis",
"extent",
"."
] | 831d60abba919f6d481dc94a8d988cc205130724 | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/widgets/dock.py#L1227-L1241 | train | 27,106 |
inasafe/inasafe | safe/gui/widgets/dock.py | Dock._search_inasafe_layer | def _search_inasafe_layer(self):
"""Search for an inasafe layer in an active group.
:returns: A valid layer.
:rtype: QgsMapLayer
.. versionadded:: 4.3
"""
selected_nodes = self.iface.layerTreeView().selectedNodes()
for selected_node in selected_nodes:
tree_layers = [
child for child in selected_node.children() if (
isinstance(child, QgsLayerTreeLayer))]
for tree_layer in tree_layers:
layer = tree_layer.layer()
keywords = self.keyword_io.read_keywords(layer)
if keywords.get('inasafe_fields'):
return layer | python | def _search_inasafe_layer(self):
"""Search for an inasafe layer in an active group.
:returns: A valid layer.
:rtype: QgsMapLayer
.. versionadded:: 4.3
"""
selected_nodes = self.iface.layerTreeView().selectedNodes()
for selected_node in selected_nodes:
tree_layers = [
child for child in selected_node.children() if (
isinstance(child, QgsLayerTreeLayer))]
for tree_layer in tree_layers:
layer = tree_layer.layer()
keywords = self.keyword_io.read_keywords(layer)
if keywords.get('inasafe_fields'):
return layer | [
"def",
"_search_inasafe_layer",
"(",
"self",
")",
":",
"selected_nodes",
"=",
"self",
".",
"iface",
".",
"layerTreeView",
"(",
")",
".",
"selectedNodes",
"(",
")",
"for",
"selected_node",
"in",
"selected_nodes",
":",
"tree_layers",
"=",
"[",
"child",
"for",
... | Search for an inasafe layer in an active group.
:returns: A valid layer.
:rtype: QgsMapLayer
.. versionadded:: 4.3 | [
"Search",
"for",
"an",
"inasafe",
"layer",
"in",
"an",
"active",
"group",
"."
] | 831d60abba919f6d481dc94a8d988cc205130724 | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/widgets/dock.py#L1265-L1282 | train | 27,107 |
inasafe/inasafe | safe/gui/widgets/dock.py | Dock._visible_layers_count | def _visible_layers_count(self):
"""Calculate the number of visible layers in the legend.
.. versionadded: 3.1
:returns: Count of layers that are actually visible.
:rtype: int
"""
treeroot = QgsProject.instance().layerTreeRoot()
return len([lyr for lyr in treeroot.findLayers() if lyr.isVisible()]) | python | def _visible_layers_count(self):
"""Calculate the number of visible layers in the legend.
.. versionadded: 3.1
:returns: Count of layers that are actually visible.
:rtype: int
"""
treeroot = QgsProject.instance().layerTreeRoot()
return len([lyr for lyr in treeroot.findLayers() if lyr.isVisible()]) | [
"def",
"_visible_layers_count",
"(",
"self",
")",
":",
"treeroot",
"=",
"QgsProject",
".",
"instance",
"(",
")",
".",
"layerTreeRoot",
"(",
")",
"return",
"len",
"(",
"[",
"lyr",
"for",
"lyr",
"in",
"treeroot",
".",
"findLayers",
"(",
")",
"if",
"lyr",
... | Calculate the number of visible layers in the legend.
.. versionadded: 3.1
:returns: Count of layers that are actually visible.
:rtype: int | [
"Calculate",
"the",
"number",
"of",
"visible",
"layers",
"in",
"the",
"legend",
"."
] | 831d60abba919f6d481dc94a8d988cc205130724 | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/widgets/dock.py#L1296-L1305 | train | 27,108 |
inasafe/inasafe | safe/gui/widgets/dock.py | Dock._validate_question_area | def _validate_question_area(self):
"""Helper method to evaluate the current state of the dialog.
This function will determine if it is appropriate for the OK button to
be enabled or not.
.. note:: The enabled state of the OK button on the dialog will
NOT be updated (set True or False) depending on the outcome of
the UI readiness tests performed - **only** True or False
will be returned by the function.
:returns: A two-tuple where the first element is a Boolean reflecting
the results of the validation tests and the second is a message
indicating any reason why the validation may have failed.
:rtype: (Boolean, safe.messaging.Message)
Example::
flag,message = self._validate_question_area()
"""
hazard_index = self.hazard_layer_combo.currentIndex()
exposure_index = self.exposure_layer_combo.currentIndex()
if hazard_index == -1 or exposure_index == -1:
if self.conflicting_plugin_detected:
message = conflicting_plugin_message()
else:
message = getting_started_message()
return False, message
else:
return True, None | python | def _validate_question_area(self):
"""Helper method to evaluate the current state of the dialog.
This function will determine if it is appropriate for the OK button to
be enabled or not.
.. note:: The enabled state of the OK button on the dialog will
NOT be updated (set True or False) depending on the outcome of
the UI readiness tests performed - **only** True or False
will be returned by the function.
:returns: A two-tuple where the first element is a Boolean reflecting
the results of the validation tests and the second is a message
indicating any reason why the validation may have failed.
:rtype: (Boolean, safe.messaging.Message)
Example::
flag,message = self._validate_question_area()
"""
hazard_index = self.hazard_layer_combo.currentIndex()
exposure_index = self.exposure_layer_combo.currentIndex()
if hazard_index == -1 or exposure_index == -1:
if self.conflicting_plugin_detected:
message = conflicting_plugin_message()
else:
message = getting_started_message()
return False, message
else:
return True, None | [
"def",
"_validate_question_area",
"(",
"self",
")",
":",
"hazard_index",
"=",
"self",
".",
"hazard_layer_combo",
".",
"currentIndex",
"(",
")",
"exposure_index",
"=",
"self",
".",
"exposure_layer_combo",
".",
"currentIndex",
"(",
")",
"if",
"hazard_index",
"==",
... | Helper method to evaluate the current state of the dialog.
This function will determine if it is appropriate for the OK button to
be enabled or not.
.. note:: The enabled state of the OK button on the dialog will
NOT be updated (set True or False) depending on the outcome of
the UI readiness tests performed - **only** True or False
will be returned by the function.
:returns: A two-tuple where the first element is a Boolean reflecting
the results of the validation tests and the second is a message
indicating any reason why the validation may have failed.
:rtype: (Boolean, safe.messaging.Message)
Example::
flag,message = self._validate_question_area() | [
"Helper",
"method",
"to",
"evaluate",
"the",
"current",
"state",
"of",
"the",
"dialog",
"."
] | 831d60abba919f6d481dc94a8d988cc205130724 | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/widgets/dock.py#L1564-L1593 | train | 27,109 |
inasafe/inasafe | safe/common/parameters/default_select_parameter.py | DefaultSelectParameter.default_value | def default_value(self, default_value):
"""Setter for default_value.
:param default_value: The default value.
:type default_value: object
"""
# For custom value
if default_value not in self.default_values:
if len(self.default_labels) == len(self.default_values):
self.default_values[-1] = default_value
else:
self.default_values.append(default_value)
self._default_value = default_value | python | def default_value(self, default_value):
"""Setter for default_value.
:param default_value: The default value.
:type default_value: object
"""
# For custom value
if default_value not in self.default_values:
if len(self.default_labels) == len(self.default_values):
self.default_values[-1] = default_value
else:
self.default_values.append(default_value)
self._default_value = default_value | [
"def",
"default_value",
"(",
"self",
",",
"default_value",
")",
":",
"# For custom value",
"if",
"default_value",
"not",
"in",
"self",
".",
"default_values",
":",
"if",
"len",
"(",
"self",
".",
"default_labels",
")",
"==",
"len",
"(",
"self",
".",
"default_v... | Setter for default_value.
:param default_value: The default value.
:type default_value: object | [
"Setter",
"for",
"default_value",
"."
] | 831d60abba919f6d481dc94a8d988cc205130724 | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/common/parameters/default_select_parameter.py#L101-L114 | train | 27,110 |
inasafe/inasafe | __init__.py | classFactory | def classFactory(iface):
"""Load Plugin class from file Plugin."""
# Try to import submodule to check if there are present.
try:
from parameters.generic_parameter import GenericParameter
except ImportError:
# Don't use safe.utilities.i18n.tr as we need to be outside of `safe`.
# Some safe functions will import safe_extras.parameters
QMessageBox.warning(
None,
QCoreApplication.translate(
'@default', 'InaSAFE submodule not found'),
QCoreApplication.translate(
'@default',
'InaSAFE could not find the submodule "parameters". '
'You should do "git submodule update" or if you need a new '
'clone, do "git clone --recursive git@github.com:inasafe/'
'inasafe.git". If this is already a new clone, you should '
'do "git submodule init" before "git submodule update".'
'Finally, restart QGIS.'))
from .safe.plugin import Plugin
return Plugin(iface) | python | def classFactory(iface):
"""Load Plugin class from file Plugin."""
# Try to import submodule to check if there are present.
try:
from parameters.generic_parameter import GenericParameter
except ImportError:
# Don't use safe.utilities.i18n.tr as we need to be outside of `safe`.
# Some safe functions will import safe_extras.parameters
QMessageBox.warning(
None,
QCoreApplication.translate(
'@default', 'InaSAFE submodule not found'),
QCoreApplication.translate(
'@default',
'InaSAFE could not find the submodule "parameters". '
'You should do "git submodule update" or if you need a new '
'clone, do "git clone --recursive git@github.com:inasafe/'
'inasafe.git". If this is already a new clone, you should '
'do "git submodule init" before "git submodule update".'
'Finally, restart QGIS.'))
from .safe.plugin import Plugin
return Plugin(iface) | [
"def",
"classFactory",
"(",
"iface",
")",
":",
"# Try to import submodule to check if there are present.",
"try",
":",
"from",
"parameters",
".",
"generic_parameter",
"import",
"GenericParameter",
"except",
"ImportError",
":",
"# Don't use safe.utilities.i18n.tr as we need to be ... | Load Plugin class from file Plugin. | [
"Load",
"Plugin",
"class",
"from",
"file",
"Plugin",
"."
] | 831d60abba919f6d481dc94a8d988cc205130724 | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/__init__.py#L68-L90 | train | 27,111 |
inasafe/inasafe | safe/gui/tools/help/metadata_converter_help.py | metadata_converter_help | def metadata_converter_help():
"""Help message for metadata converter Dialog.
.. versionadded:: 4.3
: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 metadata_converter_help():
"""Help message for metadata converter Dialog.
.. versionadded:: 4.3
: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",
"metadata_converter_help",
"(",
")",
":",
"message",
"=",
"m",
".",
"Message",
"(",
")",
"message",
".",
"add",
"(",
"m",
".",
"Brand",
"(",
")",
")",
"message",
".",
"add",
"(",
"heading",
"(",
")",
")",
"message",
".",
"add",
"(",
"content... | Help message for metadata converter Dialog.
.. versionadded:: 4.3
:returns: A message object containing helpful information.
:rtype: messaging.message.Message | [
"Help",
"message",
"for",
"metadata",
"converter",
"Dialog",
"."
] | 831d60abba919f6d481dc94a8d988cc205130724 | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/tools/help/metadata_converter_help.py#L19-L31 | train | 27,112 |
inasafe/inasafe | safe/utilities/qt.py | qt_at_least | def qt_at_least(needed_version, test_version=None):
"""Check if the installed Qt version is greater than the requested
:param needed_version: minimally needed Qt version in format like 4.8.4
:type needed_version: str
:param test_version: Qt version as returned from Qt.QT_VERSION. As in
0x040100 This is used only for tests
:type test_version: int
:returns: True if the installed Qt version is greater than the requested
:rtype: bool
"""
major, minor, patch = needed_version.split('.')
needed_version = '0x0%s0%s0%s' % (major, minor, patch)
needed_version = int(needed_version, 0)
installed_version = Qt.QT_VERSION
if test_version is not None:
installed_version = test_version
if needed_version <= installed_version:
return True
else:
return False | python | def qt_at_least(needed_version, test_version=None):
"""Check if the installed Qt version is greater than the requested
:param needed_version: minimally needed Qt version in format like 4.8.4
:type needed_version: str
:param test_version: Qt version as returned from Qt.QT_VERSION. As in
0x040100 This is used only for tests
:type test_version: int
:returns: True if the installed Qt version is greater than the requested
:rtype: bool
"""
major, minor, patch = needed_version.split('.')
needed_version = '0x0%s0%s0%s' % (major, minor, patch)
needed_version = int(needed_version, 0)
installed_version = Qt.QT_VERSION
if test_version is not None:
installed_version = test_version
if needed_version <= installed_version:
return True
else:
return False | [
"def",
"qt_at_least",
"(",
"needed_version",
",",
"test_version",
"=",
"None",
")",
":",
"major",
",",
"minor",
",",
"patch",
"=",
"needed_version",
".",
"split",
"(",
"'.'",
")",
"needed_version",
"=",
"'0x0%s0%s0%s'",
"%",
"(",
"major",
",",
"minor",
","... | Check if the installed Qt version is greater than the requested
:param needed_version: minimally needed Qt version in format like 4.8.4
:type needed_version: str
:param test_version: Qt version as returned from Qt.QT_VERSION. As in
0x040100 This is used only for tests
:type test_version: int
:returns: True if the installed Qt version is greater than the requested
:rtype: bool | [
"Check",
"if",
"the",
"installed",
"Qt",
"version",
"is",
"greater",
"than",
"the",
"requested"
] | 831d60abba919f6d481dc94a8d988cc205130724 | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/utilities/qt.py#L15-L39 | train | 27,113 |
inasafe/inasafe | safe/utilities/qt.py | disable_busy_cursor | def disable_busy_cursor():
"""Disable the hourglass cursor and listen for layer changes."""
while QgsApplication.instance().overrideCursor() is not None and \
QgsApplication.instance().overrideCursor().shape() == \
QtCore.Qt.WaitCursor:
QgsApplication.instance().restoreOverrideCursor() | python | def disable_busy_cursor():
"""Disable the hourglass cursor and listen for layer changes."""
while QgsApplication.instance().overrideCursor() is not None and \
QgsApplication.instance().overrideCursor().shape() == \
QtCore.Qt.WaitCursor:
QgsApplication.instance().restoreOverrideCursor() | [
"def",
"disable_busy_cursor",
"(",
")",
":",
"while",
"QgsApplication",
".",
"instance",
"(",
")",
".",
"overrideCursor",
"(",
")",
"is",
"not",
"None",
"and",
"QgsApplication",
".",
"instance",
"(",
")",
".",
"overrideCursor",
"(",
")",
".",
"shape",
"(",... | Disable the hourglass cursor and listen for layer changes. | [
"Disable",
"the",
"hourglass",
"cursor",
"and",
"listen",
"for",
"layer",
"changes",
"."
] | 831d60abba919f6d481dc94a8d988cc205130724 | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/utilities/qt.py#L49-L54 | train | 27,114 |
inasafe/inasafe | safe/gui/tools/wizard/step_kw05_subcategory.py | StepKwSubcategory.subcategories_for_layer | def subcategories_for_layer(self):
"""Return a list of valid subcategories for a layer.
Subcategory is hazard type or exposure type.
:returns: A list where each value represents a valid subcategory.
:rtype: list
"""
purpose = self.parent.step_kw_purpose.selected_purpose()
layer_geometry_key = self.parent.get_layer_geometry_key()
if purpose == layer_purpose_hazard:
return hazards_for_layer(layer_geometry_key)
elif purpose == layer_purpose_exposure:
return exposures_for_layer(layer_geometry_key) | python | def subcategories_for_layer(self):
"""Return a list of valid subcategories for a layer.
Subcategory is hazard type or exposure type.
:returns: A list where each value represents a valid subcategory.
:rtype: list
"""
purpose = self.parent.step_kw_purpose.selected_purpose()
layer_geometry_key = self.parent.get_layer_geometry_key()
if purpose == layer_purpose_hazard:
return hazards_for_layer(layer_geometry_key)
elif purpose == layer_purpose_exposure:
return exposures_for_layer(layer_geometry_key) | [
"def",
"subcategories_for_layer",
"(",
"self",
")",
":",
"purpose",
"=",
"self",
".",
"parent",
".",
"step_kw_purpose",
".",
"selected_purpose",
"(",
")",
"layer_geometry_key",
"=",
"self",
".",
"parent",
".",
"get_layer_geometry_key",
"(",
")",
"if",
"purpose",... | Return a list of valid subcategories for a layer.
Subcategory is hazard type or exposure type.
:returns: A list where each value represents a valid subcategory.
:rtype: list | [
"Return",
"a",
"list",
"of",
"valid",
"subcategories",
"for",
"a",
"layer",
".",
"Subcategory",
"is",
"hazard",
"type",
"or",
"exposure",
"type",
"."
] | 831d60abba919f6d481dc94a8d988cc205130724 | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/tools/wizard/step_kw05_subcategory.py#L59-L71 | train | 27,115 |
inasafe/inasafe | safe/gui/tools/wizard/step_kw05_subcategory.py | StepKwSubcategory.on_lstSubcategories_itemSelectionChanged | def on_lstSubcategories_itemSelectionChanged(self):
"""Update subcategory description label.
.. note:: This is an automatic Qt slot
executed when the subcategory selection changes.
"""
self.clear_further_steps()
# Set widgets
subcategory = self.selected_subcategory()
# Exit if no selection
if not subcategory:
return
# Set description label
self.lblDescribeSubcategory.setText(subcategory['description'])
icon_path = get_image_path(subcategory)
self.lblIconSubcategory.setPixmap(QPixmap(icon_path))
# Enable the next button
self.parent.pbnNext.setEnabled(True) | python | def on_lstSubcategories_itemSelectionChanged(self):
"""Update subcategory description label.
.. note:: This is an automatic Qt slot
executed when the subcategory selection changes.
"""
self.clear_further_steps()
# Set widgets
subcategory = self.selected_subcategory()
# Exit if no selection
if not subcategory:
return
# Set description label
self.lblDescribeSubcategory.setText(subcategory['description'])
icon_path = get_image_path(subcategory)
self.lblIconSubcategory.setPixmap(QPixmap(icon_path))
# Enable the next button
self.parent.pbnNext.setEnabled(True) | [
"def",
"on_lstSubcategories_itemSelectionChanged",
"(",
"self",
")",
":",
"self",
".",
"clear_further_steps",
"(",
")",
"# Set widgets",
"subcategory",
"=",
"self",
".",
"selected_subcategory",
"(",
")",
"# Exit if no selection",
"if",
"not",
"subcategory",
":",
"retu... | Update subcategory description label.
.. note:: This is an automatic Qt slot
executed when the subcategory selection changes. | [
"Update",
"subcategory",
"description",
"label",
"."
] | 831d60abba919f6d481dc94a8d988cc205130724 | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/tools/wizard/step_kw05_subcategory.py#L74-L93 | train | 27,116 |
inasafe/inasafe | safe/gui/tools/wizard/step_kw05_subcategory.py | StepKwSubcategory.selected_subcategory | def selected_subcategory(self):
"""Obtain the subcategory selected by user.
:returns: Metadata of the selected subcategory.
:rtype: dict, None
"""
item = self.lstSubcategories.currentItem()
try:
return definition(item.data(QtCore.Qt.UserRole))
except (AttributeError, NameError):
return None | python | def selected_subcategory(self):
"""Obtain the subcategory selected by user.
:returns: Metadata of the selected subcategory.
:rtype: dict, None
"""
item = self.lstSubcategories.currentItem()
try:
return definition(item.data(QtCore.Qt.UserRole))
except (AttributeError, NameError):
return None | [
"def",
"selected_subcategory",
"(",
"self",
")",
":",
"item",
"=",
"self",
".",
"lstSubcategories",
".",
"currentItem",
"(",
")",
"try",
":",
"return",
"definition",
"(",
"item",
".",
"data",
"(",
"QtCore",
".",
"Qt",
".",
"UserRole",
")",
")",
"except",... | Obtain the subcategory selected by user.
:returns: Metadata of the selected subcategory.
:rtype: dict, None | [
"Obtain",
"the",
"subcategory",
"selected",
"by",
"user",
"."
] | 831d60abba919f6d481dc94a8d988cc205130724 | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/tools/wizard/step_kw05_subcategory.py#L95-L105 | train | 27,117 |
inasafe/inasafe | safe/gui/tools/wizard/step_kw05_subcategory.py | StepKwSubcategory.set_widgets | def set_widgets(self):
"""Set widgets on the Subcategory tab."""
self.clear_further_steps()
# Set widgets
purpose = self.parent.step_kw_purpose.selected_purpose()
self.lstSubcategories.clear()
self.lblDescribeSubcategory.setText('')
self.lblIconSubcategory.setPixmap(QPixmap())
self.lblSelectSubcategory.setText(
get_question_text('%s_question' % purpose['key']))
for i in self.subcategories_for_layer():
# noinspection PyTypeChecker
item = QListWidgetItem(i['name'], self.lstSubcategories)
# noinspection PyTypeChecker
item.setData(QtCore.Qt.UserRole, i['key'])
self.lstSubcategories.addItem(item)
# Check if layer keywords are already assigned
key = self.parent.step_kw_purpose.selected_purpose()['key']
keyword = self.parent.get_existing_keyword(key)
# Overwrite the keyword if it's KW mode embedded in IFCW mode
if self.parent.parent_step:
keyword = self.parent.get_parent_mode_constraints()[1]['key']
# Set values based on existing keywords or parent mode
if keyword:
subcategories = []
for index in range(self.lstSubcategories.count()):
item = self.lstSubcategories.item(index)
subcategories.append(item.data(QtCore.Qt.UserRole))
if keyword in subcategories:
self.lstSubcategories.setCurrentRow(
subcategories.index(keyword))
self.auto_select_one_item(self.lstSubcategories) | python | def set_widgets(self):
"""Set widgets on the Subcategory tab."""
self.clear_further_steps()
# Set widgets
purpose = self.parent.step_kw_purpose.selected_purpose()
self.lstSubcategories.clear()
self.lblDescribeSubcategory.setText('')
self.lblIconSubcategory.setPixmap(QPixmap())
self.lblSelectSubcategory.setText(
get_question_text('%s_question' % purpose['key']))
for i in self.subcategories_for_layer():
# noinspection PyTypeChecker
item = QListWidgetItem(i['name'], self.lstSubcategories)
# noinspection PyTypeChecker
item.setData(QtCore.Qt.UserRole, i['key'])
self.lstSubcategories.addItem(item)
# Check if layer keywords are already assigned
key = self.parent.step_kw_purpose.selected_purpose()['key']
keyword = self.parent.get_existing_keyword(key)
# Overwrite the keyword if it's KW mode embedded in IFCW mode
if self.parent.parent_step:
keyword = self.parent.get_parent_mode_constraints()[1]['key']
# Set values based on existing keywords or parent mode
if keyword:
subcategories = []
for index in range(self.lstSubcategories.count()):
item = self.lstSubcategories.item(index)
subcategories.append(item.data(QtCore.Qt.UserRole))
if keyword in subcategories:
self.lstSubcategories.setCurrentRow(
subcategories.index(keyword))
self.auto_select_one_item(self.lstSubcategories) | [
"def",
"set_widgets",
"(",
"self",
")",
":",
"self",
".",
"clear_further_steps",
"(",
")",
"# Set widgets",
"purpose",
"=",
"self",
".",
"parent",
".",
"step_kw_purpose",
".",
"selected_purpose",
"(",
")",
"self",
".",
"lstSubcategories",
".",
"clear",
"(",
... | Set widgets on the Subcategory tab. | [
"Set",
"widgets",
"on",
"the",
"Subcategory",
"tab",
"."
] | 831d60abba919f6d481dc94a8d988cc205130724 | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/tools/wizard/step_kw05_subcategory.py#L116-L151 | train | 27,118 |
inasafe/inasafe | safe/gui/tools/metadata_converter_dialog.py | MetadataConverterDialog.select_output_directory | def select_output_directory(self):
"""Select output directory"""
# Input layer
input_layer_path = self.layer.source()
input_file_name = os.path.basename(input_layer_path)
input_extension = os.path.splitext(input_file_name)[1]
# Get current path
current_file_path = self.output_path_line_edit.text()
if not current_file_path or not os.path.exists(current_file_path):
current_file_path = input_layer_path
# Filtering based on input layer
extension_mapping = {
'.shp': tr('Shapefile (*.shp);;'),
'.geojson': tr('GeoJSON (*.geojson);;'),
'.tif': tr('Raster TIF/TIFF (*.tif, *.tiff);;'),
'.tiff': tr('Raster TIF/TIFF (*.tiff, *.tiff);;'),
'.asc': tr('Raster ASCII File (*.asc);;'),
}
# Open File Dialog
file_path, __ = QFileDialog.getSaveFileName(
self,
tr('Output File'),
current_file_path,
extension_mapping[input_extension]
)
if file_path:
self.output_path_line_edit.setText(file_path) | python | def select_output_directory(self):
"""Select output directory"""
# Input layer
input_layer_path = self.layer.source()
input_file_name = os.path.basename(input_layer_path)
input_extension = os.path.splitext(input_file_name)[1]
# Get current path
current_file_path = self.output_path_line_edit.text()
if not current_file_path or not os.path.exists(current_file_path):
current_file_path = input_layer_path
# Filtering based on input layer
extension_mapping = {
'.shp': tr('Shapefile (*.shp);;'),
'.geojson': tr('GeoJSON (*.geojson);;'),
'.tif': tr('Raster TIF/TIFF (*.tif, *.tiff);;'),
'.tiff': tr('Raster TIF/TIFF (*.tiff, *.tiff);;'),
'.asc': tr('Raster ASCII File (*.asc);;'),
}
# Open File Dialog
file_path, __ = QFileDialog.getSaveFileName(
self,
tr('Output File'),
current_file_path,
extension_mapping[input_extension]
)
if file_path:
self.output_path_line_edit.setText(file_path) | [
"def",
"select_output_directory",
"(",
"self",
")",
":",
"# Input layer",
"input_layer_path",
"=",
"self",
".",
"layer",
".",
"source",
"(",
")",
"input_file_name",
"=",
"os",
".",
"path",
".",
"basename",
"(",
"input_layer_path",
")",
"input_extension",
"=",
... | Select output directory | [
"Select",
"output",
"directory"
] | 831d60abba919f6d481dc94a8d988cc205130724 | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/tools/metadata_converter_dialog.py#L297-L325 | train | 27,119 |
inasafe/inasafe | safe/gui/tools/metadata_converter_dialog.py | MetadataConverterDialog.show_current_metadata | def show_current_metadata(self):
"""Show metadata of the current selected layer."""
LOGGER.debug('Showing layer: ' + self.layer.name())
keywords = KeywordIO(self.layer)
content_html = keywords.to_message().to_html()
full_html = html_header() + content_html + html_footer()
self.metadata_preview_web_view.setHtml(full_html) | python | def show_current_metadata(self):
"""Show metadata of the current selected layer."""
LOGGER.debug('Showing layer: ' + self.layer.name())
keywords = KeywordIO(self.layer)
content_html = keywords.to_message().to_html()
full_html = html_header() + content_html + html_footer()
self.metadata_preview_web_view.setHtml(full_html) | [
"def",
"show_current_metadata",
"(",
"self",
")",
":",
"LOGGER",
".",
"debug",
"(",
"'Showing layer: '",
"+",
"self",
".",
"layer",
".",
"name",
"(",
")",
")",
"keywords",
"=",
"KeywordIO",
"(",
"self",
".",
"layer",
")",
"content_html",
"=",
"keywords",
... | Show metadata of the current selected layer. | [
"Show",
"metadata",
"of",
"the",
"current",
"selected",
"layer",
"."
] | 831d60abba919f6d481dc94a8d988cc205130724 | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/tools/metadata_converter_dialog.py#L327-L333 | train | 27,120 |
inasafe/inasafe | extras/system_tools.py | get_user_name | def get_user_name():
"""Get user name provide by operating system
"""
if sys.platform == 'win32':
#user = os.getenv('USERPROFILE')
user = os.getenv('USERNAME')
else:
user = os.getenv('LOGNAME')
return user | python | def get_user_name():
"""Get user name provide by operating system
"""
if sys.platform == 'win32':
#user = os.getenv('USERPROFILE')
user = os.getenv('USERNAME')
else:
user = os.getenv('LOGNAME')
return user | [
"def",
"get_user_name",
"(",
")",
":",
"if",
"sys",
".",
"platform",
"==",
"'win32'",
":",
"#user = os.getenv('USERPROFILE')",
"user",
"=",
"os",
".",
"getenv",
"(",
"'USERNAME'",
")",
"else",
":",
"user",
"=",
"os",
".",
"getenv",
"(",
"'LOGNAME'",
")",
... | Get user name provide by operating system | [
"Get",
"user",
"name",
"provide",
"by",
"operating",
"system"
] | 831d60abba919f6d481dc94a8d988cc205130724 | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/extras/system_tools.py#L19-L29 | train | 27,121 |
inasafe/inasafe | extras/system_tools.py | get_host_name | def get_host_name():
"""Get host name provide by operating system
"""
if sys.platform == 'win32':
host = os.getenv('COMPUTERNAME')
else:
host = os.uname()[1]
return host | python | def get_host_name():
"""Get host name provide by operating system
"""
if sys.platform == 'win32':
host = os.getenv('COMPUTERNAME')
else:
host = os.uname()[1]
return host | [
"def",
"get_host_name",
"(",
")",
":",
"if",
"sys",
".",
"platform",
"==",
"'win32'",
":",
"host",
"=",
"os",
".",
"getenv",
"(",
"'COMPUTERNAME'",
")",
"else",
":",
"host",
"=",
"os",
".",
"uname",
"(",
")",
"[",
"1",
"]",
"return",
"host"
] | Get host name provide by operating system | [
"Get",
"host",
"name",
"provide",
"by",
"operating",
"system"
] | 831d60abba919f6d481dc94a8d988cc205130724 | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/extras/system_tools.py#L31-L41 | train | 27,122 |
inasafe/inasafe | extras/system_tools.py | compute_checksum | def compute_checksum(filename, max_length=2**20):
"""Compute the CRC32 checksum for specified file
Optional parameter max_length sets the maximum number
of bytes used to limit time used with large files.
Default = 2**20 (1MB)
"""
fid = open(filename, 'rb') # Use binary for portability
crcval = safe_crc(fid.read(max_length))
fid.close()
return crcval | python | def compute_checksum(filename, max_length=2**20):
"""Compute the CRC32 checksum for specified file
Optional parameter max_length sets the maximum number
of bytes used to limit time used with large files.
Default = 2**20 (1MB)
"""
fid = open(filename, 'rb') # Use binary for portability
crcval = safe_crc(fid.read(max_length))
fid.close()
return crcval | [
"def",
"compute_checksum",
"(",
"filename",
",",
"max_length",
"=",
"2",
"**",
"20",
")",
":",
"fid",
"=",
"open",
"(",
"filename",
",",
"'rb'",
")",
"# Use binary for portability",
"crcval",
"=",
"safe_crc",
"(",
"fid",
".",
"read",
"(",
"max_length",
")"... | Compute the CRC32 checksum for specified file
Optional parameter max_length sets the maximum number
of bytes used to limit time used with large files.
Default = 2**20 (1MB) | [
"Compute",
"the",
"CRC32",
"checksum",
"for",
"specified",
"file"
] | 831d60abba919f6d481dc94a8d988cc205130724 | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/extras/system_tools.py#L58-L70 | train | 27,123 |
inasafe/inasafe | extras/system_tools.py | clean_line | def clean_line(str, delimiter):
"""Split string on given delimiter, remove whitespace from each field."""
return [x.strip() for x in str.strip().split(delimiter) if x != ''] | python | def clean_line(str, delimiter):
"""Split string on given delimiter, remove whitespace from each field."""
return [x.strip() for x in str.strip().split(delimiter) if x != ''] | [
"def",
"clean_line",
"(",
"str",
",",
"delimiter",
")",
":",
"return",
"[",
"x",
".",
"strip",
"(",
")",
"for",
"x",
"in",
"str",
".",
"strip",
"(",
")",
".",
"split",
"(",
"delimiter",
")",
"if",
"x",
"!=",
"''",
"]"
] | Split string on given delimiter, remove whitespace from each field. | [
"Split",
"string",
"on",
"given",
"delimiter",
"remove",
"whitespace",
"from",
"each",
"field",
"."
] | 831d60abba919f6d481dc94a8d988cc205130724 | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/extras/system_tools.py#L112-L115 | train | 27,124 |
inasafe/inasafe | extras/system_tools.py | string_to_char | def string_to_char(l):
'''Convert 1-D list of strings to 2-D list of chars.'''
if not l:
return []
if l == ['']:
l = [' ']
maxlen = reduce(max, map(len, l))
ll = [x.ljust(maxlen) for x in l]
result = []
for s in ll:
result.append([x for x in s])
return result | python | def string_to_char(l):
'''Convert 1-D list of strings to 2-D list of chars.'''
if not l:
return []
if l == ['']:
l = [' ']
maxlen = reduce(max, map(len, l))
ll = [x.ljust(maxlen) for x in l]
result = []
for s in ll:
result.append([x for x in s])
return result | [
"def",
"string_to_char",
"(",
"l",
")",
":",
"if",
"not",
"l",
":",
"return",
"[",
"]",
"if",
"l",
"==",
"[",
"''",
"]",
":",
"l",
"=",
"[",
"' '",
"]",
"maxlen",
"=",
"reduce",
"(",
"max",
",",
"map",
"(",
"len",
",",
"l",
")",
")",
"ll",
... | Convert 1-D list of strings to 2-D list of chars. | [
"Convert",
"1",
"-",
"D",
"list",
"of",
"strings",
"to",
"2",
"-",
"D",
"list",
"of",
"chars",
"."
] | 831d60abba919f6d481dc94a8d988cc205130724 | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/extras/system_tools.py#L148-L162 | train | 27,125 |
inasafe/inasafe | extras/system_tools.py | get_vars_in_expression | def get_vars_in_expression(source):
'''Get list of variable names in a python expression.'''
import compiler
from compiler.ast import Node
##
# @brief Internal recursive function.
# @param node An AST parse Node.
# @param var_list Input list of variables.
# @return An updated list of variables.
def get_vars_body(node, var_list=[]):
if isinstance(node, Node):
if node.__class__.__name__ == 'Name':
for child in node.getChildren():
if child not in var_list:
var_list.append(child)
for child in node.getChildren():
if isinstance(child, Node):
for child in node.getChildren():
var_list = get_vars_body(child, var_list)
break
return var_list
return get_vars_body(compiler.parse(source)) | python | def get_vars_in_expression(source):
'''Get list of variable names in a python expression.'''
import compiler
from compiler.ast import Node
##
# @brief Internal recursive function.
# @param node An AST parse Node.
# @param var_list Input list of variables.
# @return An updated list of variables.
def get_vars_body(node, var_list=[]):
if isinstance(node, Node):
if node.__class__.__name__ == 'Name':
for child in node.getChildren():
if child not in var_list:
var_list.append(child)
for child in node.getChildren():
if isinstance(child, Node):
for child in node.getChildren():
var_list = get_vars_body(child, var_list)
break
return var_list
return get_vars_body(compiler.parse(source)) | [
"def",
"get_vars_in_expression",
"(",
"source",
")",
":",
"import",
"compiler",
"from",
"compiler",
".",
"ast",
"import",
"Node",
"##",
"# @brief Internal recursive function.",
"# @param node An AST parse Node.",
"# @param var_list Input list of variables.",
"# @return An updated... | Get list of variable names in a python expression. | [
"Get",
"list",
"of",
"variable",
"names",
"in",
"a",
"python",
"expression",
"."
] | 831d60abba919f6d481dc94a8d988cc205130724 | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/extras/system_tools.py#L182-L207 | train | 27,126 |
inasafe/inasafe | extras/system_tools.py | tar_file | def tar_file(files, tarname):
'''Compress a file or directory into a tar file.'''
if isinstance(files, basestring):
files = [files]
o = tarfile.open(tarname, 'w:gz')
for file in files:
o.add(file)
o.close() | python | def tar_file(files, tarname):
'''Compress a file or directory into a tar file.'''
if isinstance(files, basestring):
files = [files]
o = tarfile.open(tarname, 'w:gz')
for file in files:
o.add(file)
o.close() | [
"def",
"tar_file",
"(",
"files",
",",
"tarname",
")",
":",
"if",
"isinstance",
"(",
"files",
",",
"basestring",
")",
":",
"files",
"=",
"[",
"files",
"]",
"o",
"=",
"tarfile",
".",
"open",
"(",
"tarname",
",",
"'w:gz'",
")",
"for",
"file",
"in",
"f... | Compress a file or directory into a tar file. | [
"Compress",
"a",
"file",
"or",
"directory",
"into",
"a",
"tar",
"file",
"."
] | 831d60abba919f6d481dc94a8d988cc205130724 | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/extras/system_tools.py#L323-L332 | train | 27,127 |
inasafe/inasafe | extras/system_tools.py | untar_file | def untar_file(tarname, target_dir='.'):
'''Uncompress a tar file.'''
o = tarfile.open(tarname, 'r:gz')
members = o.getmembers()
for member in members:
o.extract(member, target_dir)
o.close() | python | def untar_file(tarname, target_dir='.'):
'''Uncompress a tar file.'''
o = tarfile.open(tarname, 'r:gz')
members = o.getmembers()
for member in members:
o.extract(member, target_dir)
o.close() | [
"def",
"untar_file",
"(",
"tarname",
",",
"target_dir",
"=",
"'.'",
")",
":",
"o",
"=",
"tarfile",
".",
"open",
"(",
"tarname",
",",
"'r:gz'",
")",
"members",
"=",
"o",
".",
"getmembers",
"(",
")",
"for",
"member",
"in",
"members",
":",
"o",
".",
"... | Uncompress a tar file. | [
"Uncompress",
"a",
"tar",
"file",
"."
] | 831d60abba919f6d481dc94a8d988cc205130724 | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/extras/system_tools.py#L339-L346 | train | 27,128 |
inasafe/inasafe | extras/system_tools.py | get_file_hexdigest | def get_file_hexdigest(filename, blocksize=1024*1024*10):
'''Get a hex digest of a file.'''
if hashlib.__name__ == 'hashlib':
m = hashlib.md5() # new - 'hashlib' module
else:
m = hashlib.new() # old - 'md5' module - remove once py2.4 gone
fd = open(filename, 'r')
while True:
data = fd.read(blocksize)
if len(data) == 0:
break
m.update(data)
fd.close()
return m.hexdigest() | python | def get_file_hexdigest(filename, blocksize=1024*1024*10):
'''Get a hex digest of a file.'''
if hashlib.__name__ == 'hashlib':
m = hashlib.md5() # new - 'hashlib' module
else:
m = hashlib.new() # old - 'md5' module - remove once py2.4 gone
fd = open(filename, 'r')
while True:
data = fd.read(blocksize)
if len(data) == 0:
break
m.update(data)
fd.close()
return m.hexdigest() | [
"def",
"get_file_hexdigest",
"(",
"filename",
",",
"blocksize",
"=",
"1024",
"*",
"1024",
"*",
"10",
")",
":",
"if",
"hashlib",
".",
"__name__",
"==",
"'hashlib'",
":",
"m",
"=",
"hashlib",
".",
"md5",
"(",
")",
"# new - 'hashlib' module",
"else",
":",
"... | Get a hex digest of a file. | [
"Get",
"a",
"hex",
"digest",
"of",
"a",
"file",
"."
] | 831d60abba919f6d481dc94a8d988cc205130724 | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/extras/system_tools.py#L355-L371 | train | 27,129 |
inasafe/inasafe | extras/system_tools.py | make_digest_file | def make_digest_file(data_file, digest_file):
'''Create a file containing the hex digest string of a data file.'''
hexdigest = get_file_hexdigest(data_file)
fd = open(digest_file, 'w')
fd.write(hexdigest)
fd.close() | python | def make_digest_file(data_file, digest_file):
'''Create a file containing the hex digest string of a data file.'''
hexdigest = get_file_hexdigest(data_file)
fd = open(digest_file, 'w')
fd.write(hexdigest)
fd.close() | [
"def",
"make_digest_file",
"(",
"data_file",
",",
"digest_file",
")",
":",
"hexdigest",
"=",
"get_file_hexdigest",
"(",
"data_file",
")",
"fd",
"=",
"open",
"(",
"digest_file",
",",
"'w'",
")",
"fd",
".",
"write",
"(",
"hexdigest",
")",
"fd",
".",
"close",... | Create a file containing the hex digest string of a data file. | [
"Create",
"a",
"file",
"containing",
"the",
"hex",
"digest",
"string",
"of",
"a",
"data",
"file",
"."
] | 831d60abba919f6d481dc94a8d988cc205130724 | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/extras/system_tools.py#L379-L385 | train | 27,130 |
inasafe/inasafe | extras/system_tools.py | file_length | def file_length(in_file):
'''Function to return the length of a file.'''
fid = open(in_file)
data = fid.readlines()
fid.close()
return len(data) | python | def file_length(in_file):
'''Function to return the length of a file.'''
fid = open(in_file)
data = fid.readlines()
fid.close()
return len(data) | [
"def",
"file_length",
"(",
"in_file",
")",
":",
"fid",
"=",
"open",
"(",
"in_file",
")",
"data",
"=",
"fid",
".",
"readlines",
"(",
")",
"fid",
".",
"close",
"(",
")",
"return",
"len",
"(",
"data",
")"
] | Function to return the length of a file. | [
"Function",
"to",
"return",
"the",
"length",
"of",
"a",
"file",
"."
] | 831d60abba919f6d481dc94a8d988cc205130724 | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/extras/system_tools.py#L395-L401 | train | 27,131 |
inasafe/inasafe | safe/gis/vector/convert_geojson_to_shapefile.py | convert_geojson_to_shapefile | def convert_geojson_to_shapefile(geojson_path):
"""Convert geojson file to shapefile.
It will create a necessary file next to the geojson file. It will not
affect another files (e.g. .xml, .qml, etc).
:param geojson_path: The path to geojson file.
:type geojson_path: basestring
:returns: True if shapefile layer created, False otherwise.
:rtype: bool
"""
layer = QgsVectorLayer(geojson_path, 'vector layer', 'ogr')
if not layer.isValid():
return False
# Construct shapefile path
shapefile_path = os.path.splitext(geojson_path)[0] + '.shp'
QgsVectorFileWriter.writeAsVectorFormat(
layer,
shapefile_path,
'utf-8',
layer.crs(),
'ESRI Shapefile')
if os.path.exists(shapefile_path):
return True
return False | python | def convert_geojson_to_shapefile(geojson_path):
"""Convert geojson file to shapefile.
It will create a necessary file next to the geojson file. It will not
affect another files (e.g. .xml, .qml, etc).
:param geojson_path: The path to geojson file.
:type geojson_path: basestring
:returns: True if shapefile layer created, False otherwise.
:rtype: bool
"""
layer = QgsVectorLayer(geojson_path, 'vector layer', 'ogr')
if not layer.isValid():
return False
# Construct shapefile path
shapefile_path = os.path.splitext(geojson_path)[0] + '.shp'
QgsVectorFileWriter.writeAsVectorFormat(
layer,
shapefile_path,
'utf-8',
layer.crs(),
'ESRI Shapefile')
if os.path.exists(shapefile_path):
return True
return False | [
"def",
"convert_geojson_to_shapefile",
"(",
"geojson_path",
")",
":",
"layer",
"=",
"QgsVectorLayer",
"(",
"geojson_path",
",",
"'vector layer'",
",",
"'ogr'",
")",
"if",
"not",
"layer",
".",
"isValid",
"(",
")",
":",
"return",
"False",
"# Construct shapefile path... | Convert geojson file to shapefile.
It will create a necessary file next to the geojson file. It will not
affect another files (e.g. .xml, .qml, etc).
:param geojson_path: The path to geojson file.
:type geojson_path: basestring
:returns: True if shapefile layer created, False otherwise.
:rtype: bool | [
"Convert",
"geojson",
"file",
"to",
"shapefile",
"."
] | 831d60abba919f6d481dc94a8d988cc205130724 | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gis/vector/convert_geojson_to_shapefile.py#L18-L43 | train | 27,132 |
inasafe/inasafe | safe/gui/tools/help/peta_bencana_help.py | peta_bencana_help | def peta_bencana_help():
"""Help message for PetaBencana dialog.
.. versionadded:: 3.2.1
: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 peta_bencana_help():
"""Help message for PetaBencana dialog.
.. versionadded:: 3.2.1
: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",
"peta_bencana_help",
"(",
")",
":",
"message",
"=",
"m",
".",
"Message",
"(",
")",
"message",
".",
"add",
"(",
"m",
".",
"Brand",
"(",
")",
")",
"message",
".",
"add",
"(",
"heading",
"(",
")",
")",
"message",
".",
"add",
"(",
"content",
"... | Help message for PetaBencana dialog.
.. versionadded:: 3.2.1
:returns: A message object containing helpful information.
:rtype: messaging.message.Message | [
"Help",
"message",
"for",
"PetaBencana",
"dialog",
"."
] | 831d60abba919f6d481dc94a8d988cc205130724 | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/tools/help/peta_bencana_help.py#L13-L26 | train | 27,133 |
inasafe/inasafe | safe/messaging/item/row.py | Row.add | def add(self, item, header_flag=False, align=None):
"""Add a Cell to the row
:param item: An element to add to the Cells can be list or Cell object.
:type item: basestring, QString, list, Cell
:param header_flag: Flag indicating it the item is a header or not.
:type header_flag: bool
:param align: Optional alignment qualifier for all cells in the row.
:type align: basestring
"""
if self._is_stringable(item) or self._is_qstring(item):
self.cells.append(Cell(item, header=header_flag, align=align))
elif isinstance(item, Cell):
self.cells.append(item)
elif isinstance(item, Image):
self.cells.append(Cell(item))
elif isinstance(item, list):
for i in item:
self.cells.append(Cell(i, header=header_flag, align=align))
else:
raise InvalidMessageItemError(item, item.__class__) | python | def add(self, item, header_flag=False, align=None):
"""Add a Cell to the row
:param item: An element to add to the Cells can be list or Cell object.
:type item: basestring, QString, list, Cell
:param header_flag: Flag indicating it the item is a header or not.
:type header_flag: bool
:param align: Optional alignment qualifier for all cells in the row.
:type align: basestring
"""
if self._is_stringable(item) or self._is_qstring(item):
self.cells.append(Cell(item, header=header_flag, align=align))
elif isinstance(item, Cell):
self.cells.append(item)
elif isinstance(item, Image):
self.cells.append(Cell(item))
elif isinstance(item, list):
for i in item:
self.cells.append(Cell(i, header=header_flag, align=align))
else:
raise InvalidMessageItemError(item, item.__class__) | [
"def",
"add",
"(",
"self",
",",
"item",
",",
"header_flag",
"=",
"False",
",",
"align",
"=",
"None",
")",
":",
"if",
"self",
".",
"_is_stringable",
"(",
"item",
")",
"or",
"self",
".",
"_is_qstring",
"(",
"item",
")",
":",
"self",
".",
"cells",
"."... | Add a Cell to the row
:param item: An element to add to the Cells can be list or Cell object.
:type item: basestring, QString, list, Cell
:param header_flag: Flag indicating it the item is a header or not.
:type header_flag: bool
:param align: Optional alignment qualifier for all cells in the row.
:type align: basestring | [
"Add",
"a",
"Cell",
"to",
"the",
"row"
] | 831d60abba919f6d481dc94a8d988cc205130724 | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/messaging/item/row.py#L76-L100 | train | 27,134 |
inasafe/inasafe | safe/messaging/utilities.py | generate_insufficient_overlap_message | def generate_insufficient_overlap_message(
e,
exposure_geoextent,
exposure_layer,
hazard_geoextent,
hazard_layer,
viewport_geoextent):
"""Generate insufficient overlap message.
:param e: An exception.
:type e: Exception
:param exposure_geoextent: Extent of the exposure layer in the form
[xmin, ymin, xmax, ymax] in EPSG:4326.
:type exposure_geoextent: list
:param exposure_layer: Exposure layer.
:type exposure_layer: QgsMapLayer
:param hazard_geoextent: Extent of the hazard layer in the form
[xmin, ymin, xmax, ymax] in EPSG:4326.
:type hazard_geoextent: list
:param hazard_layer: Hazard layer instance.
:type hazard_layer: QgsMapLayer
:param viewport_geoextent: Viewport extents
as a list [xmin, ymin, xmax, ymax] in EPSG:4326.
:type viewport_geoextent: list
:return: An InaSAFE message object.
:rtype: safe.messaging.Message
"""
description = tr(
'There was insufficient overlap between the input layers and / or the '
'layers and the viewable area. Please select two overlapping layers '
'and zoom or pan to them or disable viewable area clipping in the '
'options dialog. Full details follow:')
message = m.Message(description)
text = m.Paragraph(tr('Failed to obtain the optimal extent given:'))
message.add(text)
analysis_inputs = m.BulletedList()
# We must use Qt string interpolators for tr to work properly
analysis_inputs.add(tr('Hazard: %s') % (hazard_layer.source()))
analysis_inputs.add(tr('Exposure: %s') % (exposure_layer.source()))
analysis_inputs.add(
tr('Viewable area Geo Extent: %s') % (
viewport_geoextent))
analysis_inputs.add(
tr('Hazard Geo Extent: %s') % (
hazard_geoextent))
analysis_inputs.add(
tr('Exposure Geo Extent: %s') % (
exposure_geoextent))
analysis_inputs.add(
tr('Details: %s') % (
e))
message.add(analysis_inputs)
return message | python | def generate_insufficient_overlap_message(
e,
exposure_geoextent,
exposure_layer,
hazard_geoextent,
hazard_layer,
viewport_geoextent):
"""Generate insufficient overlap message.
:param e: An exception.
:type e: Exception
:param exposure_geoextent: Extent of the exposure layer in the form
[xmin, ymin, xmax, ymax] in EPSG:4326.
:type exposure_geoextent: list
:param exposure_layer: Exposure layer.
:type exposure_layer: QgsMapLayer
:param hazard_geoextent: Extent of the hazard layer in the form
[xmin, ymin, xmax, ymax] in EPSG:4326.
:type hazard_geoextent: list
:param hazard_layer: Hazard layer instance.
:type hazard_layer: QgsMapLayer
:param viewport_geoextent: Viewport extents
as a list [xmin, ymin, xmax, ymax] in EPSG:4326.
:type viewport_geoextent: list
:return: An InaSAFE message object.
:rtype: safe.messaging.Message
"""
description = tr(
'There was insufficient overlap between the input layers and / or the '
'layers and the viewable area. Please select two overlapping layers '
'and zoom or pan to them or disable viewable area clipping in the '
'options dialog. Full details follow:')
message = m.Message(description)
text = m.Paragraph(tr('Failed to obtain the optimal extent given:'))
message.add(text)
analysis_inputs = m.BulletedList()
# We must use Qt string interpolators for tr to work properly
analysis_inputs.add(tr('Hazard: %s') % (hazard_layer.source()))
analysis_inputs.add(tr('Exposure: %s') % (exposure_layer.source()))
analysis_inputs.add(
tr('Viewable area Geo Extent: %s') % (
viewport_geoextent))
analysis_inputs.add(
tr('Hazard Geo Extent: %s') % (
hazard_geoextent))
analysis_inputs.add(
tr('Exposure Geo Extent: %s') % (
exposure_geoextent))
analysis_inputs.add(
tr('Details: %s') % (
e))
message.add(analysis_inputs)
return message | [
"def",
"generate_insufficient_overlap_message",
"(",
"e",
",",
"exposure_geoextent",
",",
"exposure_layer",
",",
"hazard_geoextent",
",",
"hazard_layer",
",",
"viewport_geoextent",
")",
":",
"description",
"=",
"tr",
"(",
"'There was insufficient overlap between the input lay... | Generate insufficient overlap message.
:param e: An exception.
:type e: Exception
:param exposure_geoextent: Extent of the exposure layer in the form
[xmin, ymin, xmax, ymax] in EPSG:4326.
:type exposure_geoextent: list
:param exposure_layer: Exposure layer.
:type exposure_layer: QgsMapLayer
:param hazard_geoextent: Extent of the hazard layer in the form
[xmin, ymin, xmax, ymax] in EPSG:4326.
:type hazard_geoextent: list
:param hazard_layer: Hazard layer instance.
:type hazard_layer: QgsMapLayer
:param viewport_geoextent: Viewport extents
as a list [xmin, ymin, xmax, ymax] in EPSG:4326.
:type viewport_geoextent: list
:return: An InaSAFE message object.
:rtype: safe.messaging.Message | [
"Generate",
"insufficient",
"overlap",
"message",
"."
] | 831d60abba919f6d481dc94a8d988cc205130724 | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/messaging/utilities.py#L18-L77 | train | 27,135 |
inasafe/inasafe | safe/utilities/extent.py | singleton | def singleton(class_):
"""Singleton definition.
Method 1 from
https://stackoverflow.com/questions/6760685/creating-a-singleton-in-python
"""
instances = {}
def get_instance(*args, **kwargs):
if class_ not in instances:
instances[class_] = class_(*args, **kwargs)
return instances[class_]
return get_instance | python | def singleton(class_):
"""Singleton definition.
Method 1 from
https://stackoverflow.com/questions/6760685/creating-a-singleton-in-python
"""
instances = {}
def get_instance(*args, **kwargs):
if class_ not in instances:
instances[class_] = class_(*args, **kwargs)
return instances[class_]
return get_instance | [
"def",
"singleton",
"(",
"class_",
")",
":",
"instances",
"=",
"{",
"}",
"def",
"get_instance",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"class_",
"not",
"in",
"instances",
":",
"instances",
"[",
"class_",
"]",
"=",
"class_",
"(",
... | Singleton definition.
Method 1 from
https://stackoverflow.com/questions/6760685/creating-a-singleton-in-python | [
"Singleton",
"definition",
"."
] | 831d60abba919f6d481dc94a8d988cc205130724 | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/utilities/extent.py#L30-L42 | train | 27,136 |
inasafe/inasafe | safe/report/extractors/infographics.py | population_chart_legend_extractor | def population_chart_legend_extractor(impact_report, component_metadata):
"""Extracting legend of population chart.
: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
"""
context = {}
context['inasafe_resources_base_dir'] = resources_path()
"""Population Charts."""
population_donut_path = impact_report.component_absolute_output_path(
'population-chart-png')
css_label_classes = []
try:
population_chart_context = impact_report.metadata.component_by_key(
'population-chart').context['context']
"""
:type: safe.report.extractors.infographic_elements.svg_charts.
DonutChartContext
"""
for pie_slice in population_chart_context.slices:
label = pie_slice['label']
if not label:
continue
css_class = label.replace(' ', '').lower()
css_label_classes.append(css_class)
except KeyError:
population_chart_context = None
context['population_chart'] = {
'img_path': resource_url(population_donut_path),
'context': population_chart_context,
'css_label_classes': css_label_classes
}
return context | python | def population_chart_legend_extractor(impact_report, component_metadata):
"""Extracting legend of population chart.
: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
"""
context = {}
context['inasafe_resources_base_dir'] = resources_path()
"""Population Charts."""
population_donut_path = impact_report.component_absolute_output_path(
'population-chart-png')
css_label_classes = []
try:
population_chart_context = impact_report.metadata.component_by_key(
'population-chart').context['context']
"""
:type: safe.report.extractors.infographic_elements.svg_charts.
DonutChartContext
"""
for pie_slice in population_chart_context.slices:
label = pie_slice['label']
if not label:
continue
css_class = label.replace(' ', '').lower()
css_label_classes.append(css_class)
except KeyError:
population_chart_context = None
context['population_chart'] = {
'img_path': resource_url(population_donut_path),
'context': population_chart_context,
'css_label_classes': css_label_classes
}
return context | [
"def",
"population_chart_legend_extractor",
"(",
"impact_report",
",",
"component_metadata",
")",
":",
"context",
"=",
"{",
"}",
"context",
"[",
"'inasafe_resources_base_dir'",
"]",
"=",
"resources_path",
"(",
")",
"\"\"\"Population Charts.\"\"\"",
"population_donut_path",
... | Extracting legend of population chart.
: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 | [
"Extracting",
"legend",
"of",
"population",
"chart",
"."
] | 831d60abba919f6d481dc94a8d988cc205130724 | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/report/extractors/infographics.py#L18-L67 | train | 27,137 |
inasafe/inasafe | safe/report/extractors/infographics.py | infographic_people_section_notes_extractor | def infographic_people_section_notes_extractor(
impact_report, component_metadata):
"""Extracting notes for people section in the infographic.
: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
"""
extra_args = component_metadata.extra_args
provenance = impact_report.impact_function.provenance
hazard_keywords = provenance['hazard_keywords']
exposure_keywords = provenance['exposure_keywords']
context = {}
context['notes'] = []
note = {
'title': None,
'description': resolve_from_dictionary(extra_args, 'extra_note'),
'citations': None
}
context['notes'].append(note)
concept_keys = ['affected_people', 'displaced_people']
for key in concept_keys:
note = {
'title': concepts[key].get('name'),
'description': concepts[key].get('description'),
'citations': concepts[key].get('citations')[0]['text']
}
context['notes'].append(note)
hazard_classification = definition(
active_classification(hazard_keywords, exposure_keywords['exposure']))
# generate rate description
displacement_rates_note_format = resolve_from_dictionary(
extra_args, 'hazard_displacement_rates_note_format')
displacement_rates_note = []
for hazard_class in hazard_classification['classes']:
hazard_class['classification_unit'] = (
hazard_classification['classification_unit'])
displacement_rates_note.append(
displacement_rates_note_format.format(**hazard_class))
rate_description = ', '.join(displacement_rates_note)
note = {
'title': concepts['displacement_rate'].get('name'),
'description': rate_description,
'citations': concepts['displacement_rate'].get('citations')[0]['text']
}
context['notes'].append(note)
return context | python | def infographic_people_section_notes_extractor(
impact_report, component_metadata):
"""Extracting notes for people section in the infographic.
: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
"""
extra_args = component_metadata.extra_args
provenance = impact_report.impact_function.provenance
hazard_keywords = provenance['hazard_keywords']
exposure_keywords = provenance['exposure_keywords']
context = {}
context['notes'] = []
note = {
'title': None,
'description': resolve_from_dictionary(extra_args, 'extra_note'),
'citations': None
}
context['notes'].append(note)
concept_keys = ['affected_people', 'displaced_people']
for key in concept_keys:
note = {
'title': concepts[key].get('name'),
'description': concepts[key].get('description'),
'citations': concepts[key].get('citations')[0]['text']
}
context['notes'].append(note)
hazard_classification = definition(
active_classification(hazard_keywords, exposure_keywords['exposure']))
# generate rate description
displacement_rates_note_format = resolve_from_dictionary(
extra_args, 'hazard_displacement_rates_note_format')
displacement_rates_note = []
for hazard_class in hazard_classification['classes']:
hazard_class['classification_unit'] = (
hazard_classification['classification_unit'])
displacement_rates_note.append(
displacement_rates_note_format.format(**hazard_class))
rate_description = ', '.join(displacement_rates_note)
note = {
'title': concepts['displacement_rate'].get('name'),
'description': rate_description,
'citations': concepts['displacement_rate'].get('citations')[0]['text']
}
context['notes'].append(note)
return context | [
"def",
"infographic_people_section_notes_extractor",
"(",
"impact_report",
",",
"component_metadata",
")",
":",
"extra_args",
"=",
"component_metadata",
".",
"extra_args",
"provenance",
"=",
"impact_report",
".",
"impact_function",
".",
"provenance",
"hazard_keywords",
"=",... | Extracting notes for people section in the infographic.
: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 | [
"Extracting",
"notes",
"for",
"people",
"section",
"in",
"the",
"infographic",
"."
] | 831d60abba919f6d481dc94a8d988cc205130724 | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/report/extractors/infographics.py#L70-L135 | train | 27,138 |
inasafe/inasafe | safe/gui/tools/wizard/step_kw33_multi_classifications.py | StepKwMultiClassifications.is_ready_to_next_step | def is_ready_to_next_step(self):
"""Check if the step is complete.
:returns: True if new step may be enabled.
:rtype: bool
"""
# Still editing
if self.mode == EDIT_MODE:
return False
for combo_box in self.exposure_combo_boxes:
# Enable if there is one that has classification
if combo_box.currentIndex() > 0:
return True
# Trick for EQ raster for population #3853
if self.use_default_thresholds:
return True
return False | python | def is_ready_to_next_step(self):
"""Check if the step is complete.
:returns: True if new step may be enabled.
:rtype: bool
"""
# Still editing
if self.mode == EDIT_MODE:
return False
for combo_box in self.exposure_combo_boxes:
# Enable if there is one that has classification
if combo_box.currentIndex() > 0:
return True
# Trick for EQ raster for population #3853
if self.use_default_thresholds:
return True
return False | [
"def",
"is_ready_to_next_step",
"(",
"self",
")",
":",
"# Still editing",
"if",
"self",
".",
"mode",
"==",
"EDIT_MODE",
":",
"return",
"False",
"for",
"combo_box",
"in",
"self",
".",
"exposure_combo_boxes",
":",
"# Enable if there is one that has classification",
"if"... | Check if the step is complete.
:returns: True if new step may be enabled.
:rtype: bool | [
"Check",
"if",
"the",
"step",
"is",
"complete",
"."
] | 831d60abba919f6d481dc94a8d988cc205130724 | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/tools/wizard/step_kw33_multi_classifications.py#L125-L141 | train | 27,139 |
inasafe/inasafe | safe/gui/tools/wizard/step_kw33_multi_classifications.py | StepKwMultiClassifications.set_wizard_step_description | def set_wizard_step_description(self):
"""Set the text for description."""
subcategory = self.parent.step_kw_subcategory.selected_subcategory()
field = self.parent.step_kw_field.selected_fields()
is_raster = is_raster_layer(self.parent.layer)
if is_raster:
if self.layer_mode == layer_mode_continuous:
text_label = multiple_continuous_hazard_classifications_raster
else:
text_label = multiple_classified_hazard_classifications_raster
# noinspection PyAugmentAssignment
text_label = text_label % (
subcategory['name'], self.layer_purpose['name'])
else:
if self.layer_mode == layer_mode_continuous:
text_label = multiple_continuous_hazard_classifications_vector
else:
text_label = multiple_classified_hazard_classifications_vector
# noinspection PyAugmentAssignment
text_label = text_label % (
subcategory['name'], self.layer_purpose['name'], field)
self.multi_classifications_label.setText(text_label) | python | def set_wizard_step_description(self):
"""Set the text for description."""
subcategory = self.parent.step_kw_subcategory.selected_subcategory()
field = self.parent.step_kw_field.selected_fields()
is_raster = is_raster_layer(self.parent.layer)
if is_raster:
if self.layer_mode == layer_mode_continuous:
text_label = multiple_continuous_hazard_classifications_raster
else:
text_label = multiple_classified_hazard_classifications_raster
# noinspection PyAugmentAssignment
text_label = text_label % (
subcategory['name'], self.layer_purpose['name'])
else:
if self.layer_mode == layer_mode_continuous:
text_label = multiple_continuous_hazard_classifications_vector
else:
text_label = multiple_classified_hazard_classifications_vector
# noinspection PyAugmentAssignment
text_label = text_label % (
subcategory['name'], self.layer_purpose['name'], field)
self.multi_classifications_label.setText(text_label) | [
"def",
"set_wizard_step_description",
"(",
"self",
")",
":",
"subcategory",
"=",
"self",
".",
"parent",
".",
"step_kw_subcategory",
".",
"selected_subcategory",
"(",
")",
"field",
"=",
"self",
".",
"parent",
".",
"step_kw_field",
".",
"selected_fields",
"(",
")"... | Set the text for description. | [
"Set",
"the",
"text",
"for",
"description",
"."
] | 831d60abba919f6d481dc94a8d988cc205130724 | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/tools/wizard/step_kw33_multi_classifications.py#L178-L201 | train | 27,140 |
inasafe/inasafe | safe/gui/tools/wizard/step_kw33_multi_classifications.py | StepKwMultiClassifications.edit_button_clicked | def edit_button_clicked(self, edit_button, exposure_combo_box, exposure):
"""Method to handle when an edit button is clicked.
:param edit_button: The edit button.
:type edit_button: QPushButton
:param exposure_combo_box: The combo box of the exposure, contains
list of classifications.
:type exposure_combo_box: QComboBox
:param exposure: Exposure definition.
:type exposure: dict
"""
# Note(IS): Do not change the text of edit button for now until we
# have better behaviour.
classification = self.get_classification(exposure_combo_box)
if self.mode == CHOOSE_MODE:
# Change mode
self.mode = EDIT_MODE
# Set active exposure
self.active_exposure = exposure
# Disable all edit button
for exposure_edit_button in self.exposure_edit_buttons:
exposure_edit_button.setEnabled(False)
# Except one that was clicked
# edit_button.setEnabled(True)
# Disable all combo box
for exposure_combo_box in self.exposure_combo_boxes:
exposure_combo_box.setEnabled(False)
# Change the edit button to cancel
# edit_button.setText(tr('Cancel'))
# Clear right panel
clear_layout(self.right_layout)
# Show edit threshold or value mapping
if self.layer_mode == layer_mode_continuous:
self.setup_thresholds_panel(classification)
else:
self.setup_value_mapping_panels(classification)
self.add_buttons(classification)
elif self.mode == EDIT_MODE:
# Behave the same as cancel button clicked.
self.cancel_button_clicked()
self.parent.pbnNext.setEnabled(self.is_ready_to_next_step()) | python | def edit_button_clicked(self, edit_button, exposure_combo_box, exposure):
"""Method to handle when an edit button is clicked.
:param edit_button: The edit button.
:type edit_button: QPushButton
:param exposure_combo_box: The combo box of the exposure, contains
list of classifications.
:type exposure_combo_box: QComboBox
:param exposure: Exposure definition.
:type exposure: dict
"""
# Note(IS): Do not change the text of edit button for now until we
# have better behaviour.
classification = self.get_classification(exposure_combo_box)
if self.mode == CHOOSE_MODE:
# Change mode
self.mode = EDIT_MODE
# Set active exposure
self.active_exposure = exposure
# Disable all edit button
for exposure_edit_button in self.exposure_edit_buttons:
exposure_edit_button.setEnabled(False)
# Except one that was clicked
# edit_button.setEnabled(True)
# Disable all combo box
for exposure_combo_box in self.exposure_combo_boxes:
exposure_combo_box.setEnabled(False)
# Change the edit button to cancel
# edit_button.setText(tr('Cancel'))
# Clear right panel
clear_layout(self.right_layout)
# Show edit threshold or value mapping
if self.layer_mode == layer_mode_continuous:
self.setup_thresholds_panel(classification)
else:
self.setup_value_mapping_panels(classification)
self.add_buttons(classification)
elif self.mode == EDIT_MODE:
# Behave the same as cancel button clicked.
self.cancel_button_clicked()
self.parent.pbnNext.setEnabled(self.is_ready_to_next_step()) | [
"def",
"edit_button_clicked",
"(",
"self",
",",
"edit_button",
",",
"exposure_combo_box",
",",
"exposure",
")",
":",
"# Note(IS): Do not change the text of edit button for now until we",
"# have better behaviour.",
"classification",
"=",
"self",
".",
"get_classification",
"(",
... | Method to handle when an edit button is clicked.
:param edit_button: The edit button.
:type edit_button: QPushButton
:param exposure_combo_box: The combo box of the exposure, contains
list of classifications.
:type exposure_combo_box: QComboBox
:param exposure: Exposure definition.
:type exposure: dict | [
"Method",
"to",
"handle",
"when",
"an",
"edit",
"button",
"is",
"clicked",
"."
] | 831d60abba919f6d481dc94a8d988cc205130724 | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/tools/wizard/step_kw33_multi_classifications.py#L343-L389 | train | 27,141 |
inasafe/inasafe | safe/gui/tools/wizard/step_kw33_multi_classifications.py | StepKwMultiClassifications.set_widgets | def set_widgets(self):
"""Set widgets on the Multi classification step."""
self.clear()
self.layer_mode = self.parent.step_kw_layermode.selected_layermode()
self.layer_purpose = self.parent.step_kw_purpose.selected_purpose()
self.set_current_state()
# Set the step description
self.set_wizard_step_description()
# Set the left panel
self.setup_left_panel()
# Set the right panel, for the beginning show the viewer
self.show_current_state() | python | def set_widgets(self):
"""Set widgets on the Multi classification step."""
self.clear()
self.layer_mode = self.parent.step_kw_layermode.selected_layermode()
self.layer_purpose = self.parent.step_kw_purpose.selected_purpose()
self.set_current_state()
# Set the step description
self.set_wizard_step_description()
# Set the left panel
self.setup_left_panel()
# Set the right panel, for the beginning show the viewer
self.show_current_state() | [
"def",
"set_widgets",
"(",
"self",
")",
":",
"self",
".",
"clear",
"(",
")",
"self",
".",
"layer_mode",
"=",
"self",
".",
"parent",
".",
"step_kw_layermode",
".",
"selected_layermode",
"(",
")",
"self",
".",
"layer_purpose",
"=",
"self",
".",
"parent",
"... | Set widgets on the Multi classification step. | [
"Set",
"widgets",
"on",
"the",
"Multi",
"classification",
"step",
"."
] | 831d60abba919f6d481dc94a8d988cc205130724 | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/tools/wizard/step_kw33_multi_classifications.py#L471-L485 | train | 27,142 |
inasafe/inasafe | safe/gui/tools/wizard/step_kw33_multi_classifications.py | StepKwMultiClassifications.add_buttons | def add_buttons(self, classification):
"""Helper to setup 3 buttons.
:param classification: The current classification.
:type classification: dict
"""
# Note(IS): Until we have good behaviour, we will disable cancel
# button.
# Add 3 buttons: Restore default, Cancel, Save
# Restore default button, only for continuous layer (with threshold)
if self.layer_mode == layer_mode_continuous['key']:
self.restore_default_button = QPushButton(tr('Restore Default'))
self.restore_default_button.clicked.connect(partial(
self.restore_default_button_clicked,
classification=classification))
# Cancel button
# cancel_button = QPushButton(tr('Cancel'))
# cancel_button.clicked.connect(self.cancel_button_clicked)
# Save button
self.save_button = QPushButton(tr('Save'))
self.save_button.clicked.connect(
partial(self.save_button_clicked, classification=classification))
button_layout = QHBoxLayout()
button_layout.addStretch(1)
button_layout.addWidget(self.restore_default_button)
button_layout.addWidget(self.save_button)
button_layout.setStretch(0, 3)
button_layout.setStretch(1, 1)
button_layout.setStretch(2, 1)
# button_layout.setStretch(3, 1)
self.right_layout.addLayout(button_layout) | python | def add_buttons(self, classification):
"""Helper to setup 3 buttons.
:param classification: The current classification.
:type classification: dict
"""
# Note(IS): Until we have good behaviour, we will disable cancel
# button.
# Add 3 buttons: Restore default, Cancel, Save
# Restore default button, only for continuous layer (with threshold)
if self.layer_mode == layer_mode_continuous['key']:
self.restore_default_button = QPushButton(tr('Restore Default'))
self.restore_default_button.clicked.connect(partial(
self.restore_default_button_clicked,
classification=classification))
# Cancel button
# cancel_button = QPushButton(tr('Cancel'))
# cancel_button.clicked.connect(self.cancel_button_clicked)
# Save button
self.save_button = QPushButton(tr('Save'))
self.save_button.clicked.connect(
partial(self.save_button_clicked, classification=classification))
button_layout = QHBoxLayout()
button_layout.addStretch(1)
button_layout.addWidget(self.restore_default_button)
button_layout.addWidget(self.save_button)
button_layout.setStretch(0, 3)
button_layout.setStretch(1, 1)
button_layout.setStretch(2, 1)
# button_layout.setStretch(3, 1)
self.right_layout.addLayout(button_layout) | [
"def",
"add_buttons",
"(",
"self",
",",
"classification",
")",
":",
"# Note(IS): Until we have good behaviour, we will disable cancel",
"# button.",
"# Add 3 buttons: Restore default, Cancel, Save",
"# Restore default button, only for continuous layer (with threshold)",
"if",
"self",
"."... | Helper to setup 3 buttons.
:param classification: The current classification.
:type classification: dict | [
"Helper",
"to",
"setup",
"3",
"buttons",
"."
] | 831d60abba919f6d481dc94a8d988cc205130724 | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/tools/wizard/step_kw33_multi_classifications.py#L755-L791 | train | 27,143 |
inasafe/inasafe | safe/gui/tools/wizard/step_kw33_multi_classifications.py | StepKwMultiClassifications.update_dragged_item_flags | def update_dragged_item_flags(self, item):
"""Fix the drop flag after the item is dropped.
Check if it looks like an item dragged from QListWidget
to QTreeWidget and disable the drop flag.
For some reasons the flag is set when dragging.
:param item: Item which is dragged.
:type item: QTreeWidgetItem
.. note:: This is a slot executed when the item change.
"""
if int(item.flags() & Qt.ItemIsDropEnabled) \
and int(item.flags() & Qt.ItemIsDragEnabled):
item.setFlags(item.flags() & ~Qt.ItemIsDropEnabled) | python | def update_dragged_item_flags(self, item):
"""Fix the drop flag after the item is dropped.
Check if it looks like an item dragged from QListWidget
to QTreeWidget and disable the drop flag.
For some reasons the flag is set when dragging.
:param item: Item which is dragged.
:type item: QTreeWidgetItem
.. note:: This is a slot executed when the item change.
"""
if int(item.flags() & Qt.ItemIsDropEnabled) \
and int(item.flags() & Qt.ItemIsDragEnabled):
item.setFlags(item.flags() & ~Qt.ItemIsDropEnabled) | [
"def",
"update_dragged_item_flags",
"(",
"self",
",",
"item",
")",
":",
"if",
"int",
"(",
"item",
".",
"flags",
"(",
")",
"&",
"Qt",
".",
"ItemIsDropEnabled",
")",
"and",
"int",
"(",
"item",
".",
"flags",
"(",
")",
"&",
"Qt",
".",
"ItemIsDragEnabled",
... | Fix the drop flag after the item is dropped.
Check if it looks like an item dragged from QListWidget
to QTreeWidget and disable the drop flag.
For some reasons the flag is set when dragging.
:param item: Item which is dragged.
:type item: QTreeWidgetItem
.. note:: This is a slot executed when the item change. | [
"Fix",
"the",
"drop",
"flag",
"after",
"the",
"item",
"is",
"dropped",
"."
] | 831d60abba919f6d481dc94a8d988cc205130724 | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/tools/wizard/step_kw33_multi_classifications.py#L944-L958 | train | 27,144 |
inasafe/inasafe | safe/gui/tools/wizard/step_kw33_multi_classifications.py | StepKwMultiClassifications.cancel_button_clicked | def cancel_button_clicked(self):
"""Action for cancel button clicked."""
# Change mode
self.mode = CHOOSE_MODE
# Enable all edit buttons and combo boxes
for i in range(len(self.exposures)):
if i == self.special_case_index:
self.exposure_edit_buttons[i].setEnabled(False)
self.exposure_combo_boxes[i].setEnabled(False)
continue
if self.get_classification(self.exposure_combo_boxes[i]):
self.exposure_edit_buttons[i].setEnabled(True)
else:
self.exposure_edit_buttons[i].setEnabled(False)
# self.exposure_edit_buttons[i].setText(tr('Edit'))
self.exposure_combo_boxes[i].setEnabled(True)
# Clear right panel
clear_layout(self.right_layout)
# Show current state
self.show_current_state()
# Unset active exposure
self.active_exposure = None
self.parent.pbnNext.setEnabled(self.is_ready_to_next_step()) | python | def cancel_button_clicked(self):
"""Action for cancel button clicked."""
# Change mode
self.mode = CHOOSE_MODE
# Enable all edit buttons and combo boxes
for i in range(len(self.exposures)):
if i == self.special_case_index:
self.exposure_edit_buttons[i].setEnabled(False)
self.exposure_combo_boxes[i].setEnabled(False)
continue
if self.get_classification(self.exposure_combo_boxes[i]):
self.exposure_edit_buttons[i].setEnabled(True)
else:
self.exposure_edit_buttons[i].setEnabled(False)
# self.exposure_edit_buttons[i].setText(tr('Edit'))
self.exposure_combo_boxes[i].setEnabled(True)
# Clear right panel
clear_layout(self.right_layout)
# Show current state
self.show_current_state()
# Unset active exposure
self.active_exposure = None
self.parent.pbnNext.setEnabled(self.is_ready_to_next_step()) | [
"def",
"cancel_button_clicked",
"(",
"self",
")",
":",
"# Change mode",
"self",
".",
"mode",
"=",
"CHOOSE_MODE",
"# Enable all edit buttons and combo boxes",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"self",
".",
"exposures",
")",
")",
":",
"if",
"i",
"==",
... | Action for cancel button clicked. | [
"Action",
"for",
"cancel",
"button",
"clicked",
"."
] | 831d60abba919f6d481dc94a8d988cc205130724 | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/tools/wizard/step_kw33_multi_classifications.py#L1032-L1056 | train | 27,145 |
inasafe/inasafe | safe/gui/tools/wizard/step_kw33_multi_classifications.py | StepKwMultiClassifications.save_button_clicked | def save_button_clicked(self, classification):
"""Action for save button clicked.
:param classification: The classification that being edited.
:type classification: dict
"""
# Save current edit
if self.layer_mode == layer_mode_continuous:
thresholds = self.get_threshold()
classification_class = {
'classes': thresholds,
'active': True
}
if self.thresholds.get(self.active_exposure['key']):
# Set other class to not active
for current_classification in list(self.thresholds.get(
self.active_exposure['key']).values()):
current_classification['active'] = False
else:
self.thresholds[self.active_exposure['key']] = {}
self.thresholds[self.active_exposure['key']][
classification['key']] = classification_class
else:
value_maps = self.get_value_map()
classification_class = {
'classes': value_maps,
'active': True
}
if self.value_maps.get(self.active_exposure['key']):
# Set other class to not active
for current_classification in list(self.value_maps.get(
self.active_exposure['key']).values()):
current_classification['active'] = False
else:
self.value_maps[self.active_exposure['key']] = {}
self.value_maps[self.active_exposure['key']][
classification['key']] = classification_class
# Back to choose mode
self.cancel_button_clicked() | python | def save_button_clicked(self, classification):
"""Action for save button clicked.
:param classification: The classification that being edited.
:type classification: dict
"""
# Save current edit
if self.layer_mode == layer_mode_continuous:
thresholds = self.get_threshold()
classification_class = {
'classes': thresholds,
'active': True
}
if self.thresholds.get(self.active_exposure['key']):
# Set other class to not active
for current_classification in list(self.thresholds.get(
self.active_exposure['key']).values()):
current_classification['active'] = False
else:
self.thresholds[self.active_exposure['key']] = {}
self.thresholds[self.active_exposure['key']][
classification['key']] = classification_class
else:
value_maps = self.get_value_map()
classification_class = {
'classes': value_maps,
'active': True
}
if self.value_maps.get(self.active_exposure['key']):
# Set other class to not active
for current_classification in list(self.value_maps.get(
self.active_exposure['key']).values()):
current_classification['active'] = False
else:
self.value_maps[self.active_exposure['key']] = {}
self.value_maps[self.active_exposure['key']][
classification['key']] = classification_class
# Back to choose mode
self.cancel_button_clicked() | [
"def",
"save_button_clicked",
"(",
"self",
",",
"classification",
")",
":",
"# Save current edit",
"if",
"self",
".",
"layer_mode",
"==",
"layer_mode_continuous",
":",
"thresholds",
"=",
"self",
".",
"get_threshold",
"(",
")",
"classification_class",
"=",
"{",
"'c... | Action for save button clicked.
:param classification: The classification that being edited.
:type classification: dict | [
"Action",
"for",
"save",
"button",
"clicked",
"."
] | 831d60abba919f6d481dc94a8d988cc205130724 | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/tools/wizard/step_kw33_multi_classifications.py#L1058-L1098 | train | 27,146 |
inasafe/inasafe | safe/gui/tools/wizard/step_kw33_multi_classifications.py | StepKwMultiClassifications.restore_default_button_clicked | def restore_default_button_clicked(self, classification):
"""Action for restore default button clicked.
It will set the threshold with default value.
:param classification: The classification that being edited.
:type classification: dict
"""
# Obtain default value
class_dict = {}
for the_class in classification.get('classes'):
class_dict[the_class['key']] = {
'numeric_default_min': the_class['numeric_default_min'],
'numeric_default_max': the_class['numeric_default_max'],
}
# Set for all threshold
for key, value in list(self.threshold_classes.items()):
value[0].setValue(class_dict[key]['numeric_default_min'])
value[1].setValue(class_dict[key]['numeric_default_max']) | python | def restore_default_button_clicked(self, classification):
"""Action for restore default button clicked.
It will set the threshold with default value.
:param classification: The classification that being edited.
:type classification: dict
"""
# Obtain default value
class_dict = {}
for the_class in classification.get('classes'):
class_dict[the_class['key']] = {
'numeric_default_min': the_class['numeric_default_min'],
'numeric_default_max': the_class['numeric_default_max'],
}
# Set for all threshold
for key, value in list(self.threshold_classes.items()):
value[0].setValue(class_dict[key]['numeric_default_min'])
value[1].setValue(class_dict[key]['numeric_default_max']) | [
"def",
"restore_default_button_clicked",
"(",
"self",
",",
"classification",
")",
":",
"# Obtain default value",
"class_dict",
"=",
"{",
"}",
"for",
"the_class",
"in",
"classification",
".",
"get",
"(",
"'classes'",
")",
":",
"class_dict",
"[",
"the_class",
"[",
... | Action for restore default button clicked.
It will set the threshold with default value.
:param classification: The classification that being edited.
:type classification: dict | [
"Action",
"for",
"restore",
"default",
"button",
"clicked",
"."
] | 831d60abba919f6d481dc94a8d988cc205130724 | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/tools/wizard/step_kw33_multi_classifications.py#L1100-L1118 | train | 27,147 |
inasafe/inasafe | safe/gui/tools/wizard/step_kw33_multi_classifications.py | StepKwMultiClassifications.get_threshold | def get_threshold(self):
"""Return threshold based on current state."""
value_map = dict()
for key, value in list(self.threshold_classes.items()):
value_map[key] = [
value[0].value(),
value[1].value(),
]
return value_map | python | def get_threshold(self):
"""Return threshold based on current state."""
value_map = dict()
for key, value in list(self.threshold_classes.items()):
value_map[key] = [
value[0].value(),
value[1].value(),
]
return value_map | [
"def",
"get_threshold",
"(",
"self",
")",
":",
"value_map",
"=",
"dict",
"(",
")",
"for",
"key",
",",
"value",
"in",
"list",
"(",
"self",
".",
"threshold_classes",
".",
"items",
"(",
")",
")",
":",
"value_map",
"[",
"key",
"]",
"=",
"[",
"value",
"... | Return threshold based on current state. | [
"Return",
"threshold",
"based",
"on",
"current",
"state",
"."
] | 831d60abba919f6d481dc94a8d988cc205130724 | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/tools/wizard/step_kw33_multi_classifications.py#L1120-L1128 | train | 27,148 |
inasafe/inasafe | safe/gui/tools/wizard/step_kw33_multi_classifications.py | StepKwMultiClassifications.set_current_state | def set_current_state(self):
""""Helper to set the state of the step from current keywords."""
if not self.thresholds:
self.thresholds = self.parent.get_existing_keyword('thresholds')
if not self.value_maps:
self.value_maps = self.parent.get_existing_keyword('value_maps') | python | def set_current_state(self):
""""Helper to set the state of the step from current keywords."""
if not self.thresholds:
self.thresholds = self.parent.get_existing_keyword('thresholds')
if not self.value_maps:
self.value_maps = self.parent.get_existing_keyword('value_maps') | [
"def",
"set_current_state",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"thresholds",
":",
"self",
".",
"thresholds",
"=",
"self",
".",
"parent",
".",
"get_existing_keyword",
"(",
"'thresholds'",
")",
"if",
"not",
"self",
".",
"value_maps",
":",
"self... | Helper to set the state of the step from current keywords. | [
"Helper",
"to",
"set",
"the",
"state",
"of",
"the",
"step",
"from",
"current",
"keywords",
"."
] | 831d60abba919f6d481dc94a8d988cc205130724 | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/tools/wizard/step_kw33_multi_classifications.py#L1146-L1151 | train | 27,149 |
inasafe/inasafe | safe/gui/tools/wizard/step_kw33_multi_classifications.py | StepKwMultiClassifications.classifications_combo_box_changed | def classifications_combo_box_changed(
self, index, exposure, exposure_combo_box, edit_button):
"""Action when classification combo box changed.
:param index: The index of the combo box.
:type index: int
:param exposure: The exposure associated with the combo box.
:type exposure: dict
:param exposure_combo_box: Combo box for the classification.
:type exposure_combo_box: QComboBox
:param edit_button: The edit button associate with combo box.
:type edit_button: QPushButton
"""
# Disable button if it's no classification
edit_button.setEnabled(bool(index))
classification = self.get_classification(exposure_combo_box)
self.activate_classification(exposure, classification)
clear_layout(self.right_layout)
self.show_current_state()
self.parent.pbnNext.setEnabled(self.is_ready_to_next_step())
# Open edit panel directly
edit_button.click() | python | def classifications_combo_box_changed(
self, index, exposure, exposure_combo_box, edit_button):
"""Action when classification combo box changed.
:param index: The index of the combo box.
:type index: int
:param exposure: The exposure associated with the combo box.
:type exposure: dict
:param exposure_combo_box: Combo box for the classification.
:type exposure_combo_box: QComboBox
:param edit_button: The edit button associate with combo box.
:type edit_button: QPushButton
"""
# Disable button if it's no classification
edit_button.setEnabled(bool(index))
classification = self.get_classification(exposure_combo_box)
self.activate_classification(exposure, classification)
clear_layout(self.right_layout)
self.show_current_state()
self.parent.pbnNext.setEnabled(self.is_ready_to_next_step())
# Open edit panel directly
edit_button.click() | [
"def",
"classifications_combo_box_changed",
"(",
"self",
",",
"index",
",",
"exposure",
",",
"exposure_combo_box",
",",
"edit_button",
")",
":",
"# Disable button if it's no classification",
"edit_button",
".",
"setEnabled",
"(",
"bool",
"(",
"index",
")",
")",
"class... | Action when classification combo box changed.
:param index: The index of the combo box.
:type index: int
:param exposure: The exposure associated with the combo box.
:type exposure: dict
:param exposure_combo_box: Combo box for the classification.
:type exposure_combo_box: QComboBox
:param edit_button: The edit button associate with combo box.
:type edit_button: QPushButton | [
"Action",
"when",
"classification",
"combo",
"box",
"changed",
"."
] | 831d60abba919f6d481dc94a8d988cc205130724 | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/tools/wizard/step_kw33_multi_classifications.py#L1153-L1180 | train | 27,150 |
inasafe/inasafe | safe/gui/tools/wizard/step_kw33_multi_classifications.py | StepKwMultiClassifications.activate_classification | def activate_classification(self, exposure, classification=None):
"""Set active to True for classification for the exposure.
If classification = None, all classification set active = False.
:param exposure: Exposure definition.
:type exposure: dict
:param classification: Classification definition.
:type classification: dict
"""
if self.layer_mode == layer_mode_continuous:
selected_unit = self.parent.step_kw_unit.selected_unit()['key']
target = self.thresholds.get(exposure['key'])
if target is None:
self.thresholds[exposure['key']] = {}
target = self.thresholds.get(exposure['key'])
else:
selected_unit = None
target = self.value_maps.get(exposure['key'])
if target is None:
self.value_maps[exposure['key']] = {}
target = self.value_maps.get(exposure['key'])
if classification is not None:
if classification['key'] not in target:
if self.layer_mode == layer_mode_continuous:
default_classes = default_classification_thresholds(
classification, selected_unit)
target[classification['key']] = {
'classes': default_classes,
'active': True
}
else:
# Set classes to empty, since we haven't mapped anything
target[classification['key']] = {
'classes': {},
'active': True
}
return
for classification_key, value in list(target.items()):
if classification is None:
value['active'] = False
continue
if classification_key == classification['key']:
value['active'] = True
else:
value['active'] = False | python | def activate_classification(self, exposure, classification=None):
"""Set active to True for classification for the exposure.
If classification = None, all classification set active = False.
:param exposure: Exposure definition.
:type exposure: dict
:param classification: Classification definition.
:type classification: dict
"""
if self.layer_mode == layer_mode_continuous:
selected_unit = self.parent.step_kw_unit.selected_unit()['key']
target = self.thresholds.get(exposure['key'])
if target is None:
self.thresholds[exposure['key']] = {}
target = self.thresholds.get(exposure['key'])
else:
selected_unit = None
target = self.value_maps.get(exposure['key'])
if target is None:
self.value_maps[exposure['key']] = {}
target = self.value_maps.get(exposure['key'])
if classification is not None:
if classification['key'] not in target:
if self.layer_mode == layer_mode_continuous:
default_classes = default_classification_thresholds(
classification, selected_unit)
target[classification['key']] = {
'classes': default_classes,
'active': True
}
else:
# Set classes to empty, since we haven't mapped anything
target[classification['key']] = {
'classes': {},
'active': True
}
return
for classification_key, value in list(target.items()):
if classification is None:
value['active'] = False
continue
if classification_key == classification['key']:
value['active'] = True
else:
value['active'] = False | [
"def",
"activate_classification",
"(",
"self",
",",
"exposure",
",",
"classification",
"=",
"None",
")",
":",
"if",
"self",
".",
"layer_mode",
"==",
"layer_mode_continuous",
":",
"selected_unit",
"=",
"self",
".",
"parent",
".",
"step_kw_unit",
".",
"selected_un... | Set active to True for classification for the exposure.
If classification = None, all classification set active = False.
:param exposure: Exposure definition.
:type exposure: dict
:param classification: Classification definition.
:type classification: dict | [
"Set",
"active",
"to",
"True",
"for",
"classification",
"for",
"the",
"exposure",
"."
] | 831d60abba919f6d481dc94a8d988cc205130724 | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/tools/wizard/step_kw33_multi_classifications.py#L1182-L1231 | train | 27,151 |
inasafe/inasafe | safe/utilities/default_values.py | set_inasafe_default_value_qsetting | def set_inasafe_default_value_qsetting(
qsetting, category, inasafe_field_key, value):
"""Helper method to set inasafe default value to qsetting.
:param qsetting: QSettings.
:type qsetting: QSettings
:param category: Category of the default value. It can be global or
recent. Global means the global setting for default value. Recent
means the last set custom for default value from the user.
:type category: str
:param inasafe_field_key: Key for the field.
:type inasafe_field_key: str
:param value: Value of the inasafe_default_value.
:type value: float, int
"""
key = 'inasafe/default_value/%s/%s' % (category, inasafe_field_key)
qsetting.setValue(key, value) | python | def set_inasafe_default_value_qsetting(
qsetting, category, inasafe_field_key, value):
"""Helper method to set inasafe default value to qsetting.
:param qsetting: QSettings.
:type qsetting: QSettings
:param category: Category of the default value. It can be global or
recent. Global means the global setting for default value. Recent
means the last set custom for default value from the user.
:type category: str
:param inasafe_field_key: Key for the field.
:type inasafe_field_key: str
:param value: Value of the inasafe_default_value.
:type value: float, int
"""
key = 'inasafe/default_value/%s/%s' % (category, inasafe_field_key)
qsetting.setValue(key, value) | [
"def",
"set_inasafe_default_value_qsetting",
"(",
"qsetting",
",",
"category",
",",
"inasafe_field_key",
",",
"value",
")",
":",
"key",
"=",
"'inasafe/default_value/%s/%s'",
"%",
"(",
"category",
",",
"inasafe_field_key",
")",
"qsetting",
".",
"setValue",
"(",
"key"... | Helper method to set inasafe default value to qsetting.
:param qsetting: QSettings.
:type qsetting: QSettings
:param category: Category of the default value. It can be global or
recent. Global means the global setting for default value. Recent
means the last set custom for default value from the user.
:type category: str
:param inasafe_field_key: Key for the field.
:type inasafe_field_key: str
:param value: Value of the inasafe_default_value.
:type value: float, int | [
"Helper",
"method",
"to",
"set",
"inasafe",
"default",
"value",
"to",
"qsetting",
"."
] | 831d60abba919f6d481dc94a8d988cc205130724 | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/utilities/default_values.py#L14-L33 | train | 27,152 |
inasafe/inasafe | safe/utilities/default_values.py | get_inasafe_default_value_qsetting | def get_inasafe_default_value_qsetting(
qsetting, category, inasafe_field_key):
"""Helper method to get the inasafe default value from qsetting.
:param qsetting: QSetting.
:type qsetting: QSetting
:param category: Category of the default value. It can be global or
recent. Global means the global setting for default value. Recent
means the last set custom for default value from the user.
:type category: str
:param inasafe_field_key: Key for the field.
:type inasafe_field_key: str
:returns: Value of the inasafe_default_value.
:rtype: float
"""
key = 'inasafe/default_value/%s/%s' % (category, inasafe_field_key)
default_value = qsetting.value(key)
if default_value is None:
if category == GLOBAL:
# If empty for global setting, use default one.
inasafe_field = definition(inasafe_field_key)
default_value = inasafe_field.get('default_value', {})
return default_value.get('default_value', zero_default_value)
return zero_default_value
try:
return float(default_value)
except ValueError:
return zero_default_value | python | def get_inasafe_default_value_qsetting(
qsetting, category, inasafe_field_key):
"""Helper method to get the inasafe default value from qsetting.
:param qsetting: QSetting.
:type qsetting: QSetting
:param category: Category of the default value. It can be global or
recent. Global means the global setting for default value. Recent
means the last set custom for default value from the user.
:type category: str
:param inasafe_field_key: Key for the field.
:type inasafe_field_key: str
:returns: Value of the inasafe_default_value.
:rtype: float
"""
key = 'inasafe/default_value/%s/%s' % (category, inasafe_field_key)
default_value = qsetting.value(key)
if default_value is None:
if category == GLOBAL:
# If empty for global setting, use default one.
inasafe_field = definition(inasafe_field_key)
default_value = inasafe_field.get('default_value', {})
return default_value.get('default_value', zero_default_value)
return zero_default_value
try:
return float(default_value)
except ValueError:
return zero_default_value | [
"def",
"get_inasafe_default_value_qsetting",
"(",
"qsetting",
",",
"category",
",",
"inasafe_field_key",
")",
":",
"key",
"=",
"'inasafe/default_value/%s/%s'",
"%",
"(",
"category",
",",
"inasafe_field_key",
")",
"default_value",
"=",
"qsetting",
".",
"value",
"(",
... | Helper method to get the inasafe default value from qsetting.
:param qsetting: QSetting.
:type qsetting: QSetting
:param category: Category of the default value. It can be global or
recent. Global means the global setting for default value. Recent
means the last set custom for default value from the user.
:type category: str
:param inasafe_field_key: Key for the field.
:type inasafe_field_key: str
:returns: Value of the inasafe_default_value.
:rtype: float | [
"Helper",
"method",
"to",
"get",
"the",
"inasafe",
"default",
"value",
"from",
"qsetting",
"."
] | 831d60abba919f6d481dc94a8d988cc205130724 | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/utilities/default_values.py#L36-L67 | train | 27,153 |
inasafe/inasafe | safe/utilities/file_downloader.py | FileDownloader.download | def download(self):
"""Downloading the file.
:returns: True if success, otherwise returns a tuple with format like
this (QNetworkReply.NetworkError, error_message)
:raises: IOError - when cannot create output_path
"""
# Prepare output path
self.output_file = QFile(self.output_path)
if not self.output_file.open(QFile.WriteOnly):
raise IOError(self.output_file.errorString())
# Prepare downloaded buffer
self.downloaded_file_buffer = QByteArray()
# Request the url
request = QNetworkRequest(self.url)
self.reply = self.manager.get(request)
self.reply.readyRead.connect(self.get_buffer)
self.reply.finished.connect(self.write_data)
self.manager.requestTimedOut.connect(self.request_timeout)
if self.progress_dialog:
# progress bar
def progress_event(received, total):
"""Update progress.
:param received: Data received so far.
:type received: int
:param total: Total expected data.
:type total: int
"""
# noinspection PyArgumentList
QgsApplication.processEvents()
self.progress_dialog.adjustSize()
human_received = humanize_file_size(received)
human_total = humanize_file_size(total)
label_text = tr("%s : %s of %s" % (
self.prefix_text, human_received, human_total))
self.progress_dialog.setLabelText(label_text)
self.progress_dialog.setMaximum(total)
self.progress_dialog.setValue(received)
# cancel
def cancel_action():
"""Cancel download."""
self.reply.abort()
self.reply.deleteLater()
self.reply.downloadProgress.connect(progress_event)
self.progress_dialog.canceled.connect(cancel_action)
# Wait until finished
# On Windows 32bit AND QGIS 2.2, self.reply.isFinished() always
# returns False even after finished slot is called. So, that's why we
# are adding self.finished_flag (see #864)
while not self.reply.isFinished() and not self.finished_flag:
# noinspection PyArgumentList
QgsApplication.processEvents()
result = self.reply.error()
try:
http_code = int(self.reply.attribute(
QNetworkRequest.HttpStatusCodeAttribute))
except TypeError:
# If the user cancels the request, the HTTP response will be None.
http_code = None
self.reply.abort()
self.reply.deleteLater()
if result == QNetworkReply.NoError:
return True, None
elif result == QNetworkReply.UnknownNetworkError:
return False, tr(
'The network is unreachable. Please check your internet '
'connection.')
elif http_code == 408:
msg = tr(
'Sorry, the server aborted your request. '
'Please try a smaller area.')
LOGGER.debug(msg)
return False, msg
elif http_code == 509:
msg = tr(
'Sorry, the server is currently busy with another request. '
'Please try again in a few minutes.')
LOGGER.debug(msg)
return False, msg
elif result == QNetworkReply.ProtocolUnknownError or \
result == QNetworkReply.HostNotFoundError:
# See http://doc.qt.io/qt-5/qurl-obsolete.html#encodedHost
encoded_host = self.url.toAce(self.url.host())
LOGGER.exception('Host not found : %s' % encoded_host)
return False, tr(
'Sorry, the server is unreachable. Please try again later.')
elif result == QNetworkReply.ContentNotFoundError:
LOGGER.exception('Path not found : %s' % self.url.path())
return False, tr('Sorry, the layer was not found on the server.')
else:
return result, self.reply.errorString() | python | def download(self):
"""Downloading the file.
:returns: True if success, otherwise returns a tuple with format like
this (QNetworkReply.NetworkError, error_message)
:raises: IOError - when cannot create output_path
"""
# Prepare output path
self.output_file = QFile(self.output_path)
if not self.output_file.open(QFile.WriteOnly):
raise IOError(self.output_file.errorString())
# Prepare downloaded buffer
self.downloaded_file_buffer = QByteArray()
# Request the url
request = QNetworkRequest(self.url)
self.reply = self.manager.get(request)
self.reply.readyRead.connect(self.get_buffer)
self.reply.finished.connect(self.write_data)
self.manager.requestTimedOut.connect(self.request_timeout)
if self.progress_dialog:
# progress bar
def progress_event(received, total):
"""Update progress.
:param received: Data received so far.
:type received: int
:param total: Total expected data.
:type total: int
"""
# noinspection PyArgumentList
QgsApplication.processEvents()
self.progress_dialog.adjustSize()
human_received = humanize_file_size(received)
human_total = humanize_file_size(total)
label_text = tr("%s : %s of %s" % (
self.prefix_text, human_received, human_total))
self.progress_dialog.setLabelText(label_text)
self.progress_dialog.setMaximum(total)
self.progress_dialog.setValue(received)
# cancel
def cancel_action():
"""Cancel download."""
self.reply.abort()
self.reply.deleteLater()
self.reply.downloadProgress.connect(progress_event)
self.progress_dialog.canceled.connect(cancel_action)
# Wait until finished
# On Windows 32bit AND QGIS 2.2, self.reply.isFinished() always
# returns False even after finished slot is called. So, that's why we
# are adding self.finished_flag (see #864)
while not self.reply.isFinished() and not self.finished_flag:
# noinspection PyArgumentList
QgsApplication.processEvents()
result = self.reply.error()
try:
http_code = int(self.reply.attribute(
QNetworkRequest.HttpStatusCodeAttribute))
except TypeError:
# If the user cancels the request, the HTTP response will be None.
http_code = None
self.reply.abort()
self.reply.deleteLater()
if result == QNetworkReply.NoError:
return True, None
elif result == QNetworkReply.UnknownNetworkError:
return False, tr(
'The network is unreachable. Please check your internet '
'connection.')
elif http_code == 408:
msg = tr(
'Sorry, the server aborted your request. '
'Please try a smaller area.')
LOGGER.debug(msg)
return False, msg
elif http_code == 509:
msg = tr(
'Sorry, the server is currently busy with another request. '
'Please try again in a few minutes.')
LOGGER.debug(msg)
return False, msg
elif result == QNetworkReply.ProtocolUnknownError or \
result == QNetworkReply.HostNotFoundError:
# See http://doc.qt.io/qt-5/qurl-obsolete.html#encodedHost
encoded_host = self.url.toAce(self.url.host())
LOGGER.exception('Host not found : %s' % encoded_host)
return False, tr(
'Sorry, the server is unreachable. Please try again later.')
elif result == QNetworkReply.ContentNotFoundError:
LOGGER.exception('Path not found : %s' % self.url.path())
return False, tr('Sorry, the layer was not found on the server.')
else:
return result, self.reply.errorString() | [
"def",
"download",
"(",
"self",
")",
":",
"# Prepare output path",
"self",
".",
"output_file",
"=",
"QFile",
"(",
"self",
".",
"output_path",
")",
"if",
"not",
"self",
".",
"output_file",
".",
"open",
"(",
"QFile",
".",
"WriteOnly",
")",
":",
"raise",
"I... | Downloading the file.
:returns: True if success, otherwise returns a tuple with format like
this (QNetworkReply.NetworkError, error_message)
:raises: IOError - when cannot create output_path | [
"Downloading",
"the",
"file",
"."
] | 831d60abba919f6d481dc94a8d988cc205130724 | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/utilities/file_downloader.py#L67-L179 | train | 27,154 |
inasafe/inasafe | safe/utilities/file_downloader.py | FileDownloader.get_buffer | def get_buffer(self):
"""Get buffer from self.reply and store it to our buffer container."""
buffer_size = self.reply.size()
data = self.reply.read(buffer_size)
self.downloaded_file_buffer.append(data) | python | def get_buffer(self):
"""Get buffer from self.reply and store it to our buffer container."""
buffer_size = self.reply.size()
data = self.reply.read(buffer_size)
self.downloaded_file_buffer.append(data) | [
"def",
"get_buffer",
"(",
"self",
")",
":",
"buffer_size",
"=",
"self",
".",
"reply",
".",
"size",
"(",
")",
"data",
"=",
"self",
".",
"reply",
".",
"read",
"(",
"buffer_size",
")",
"self",
".",
"downloaded_file_buffer",
".",
"append",
"(",
"data",
")"... | Get buffer from self.reply and store it to our buffer container. | [
"Get",
"buffer",
"from",
"self",
".",
"reply",
"and",
"store",
"it",
"to",
"our",
"buffer",
"container",
"."
] | 831d60abba919f6d481dc94a8d988cc205130724 | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/utilities/file_downloader.py#L181-L185 | train | 27,155 |
inasafe/inasafe | safe/gui/tools/wizard/step_kw60_title.py | StepKwTitle.on_leTitle_textChanged | def on_leTitle_textChanged(self):
"""Unlock the Next button
.. note:: This is an automatic Qt slot
executed when the title value changes.
"""
self.parent.pbnNext.setEnabled(bool(self.leTitle.text())) | python | def on_leTitle_textChanged(self):
"""Unlock the Next button
.. note:: This is an automatic Qt slot
executed when the title value changes.
"""
self.parent.pbnNext.setEnabled(bool(self.leTitle.text())) | [
"def",
"on_leTitle_textChanged",
"(",
"self",
")",
":",
"self",
".",
"parent",
".",
"pbnNext",
".",
"setEnabled",
"(",
"bool",
"(",
"self",
".",
"leTitle",
".",
"text",
"(",
")",
")",
")"
] | Unlock the Next button
.. note:: This is an automatic Qt slot
executed when the title value changes. | [
"Unlock",
"the",
"Next",
"button"
] | 831d60abba919f6d481dc94a8d988cc205130724 | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/tools/wizard/step_kw60_title.py#L52-L58 | train | 27,156 |
inasafe/inasafe | safe/gui/tools/wizard/step_kw60_title.py | StepKwTitle.set_widgets | def set_widgets(self):
"""Set widgets on the Title tab."""
# Set title from keyword first, if not found use layer name
if self.parent.layer:
if self.parent.get_existing_keyword('title'):
title = self.parent.get_existing_keyword('title')
else:
title = self.parent.layer.name()
self.leTitle.setText(title) | python | def set_widgets(self):
"""Set widgets on the Title tab."""
# Set title from keyword first, if not found use layer name
if self.parent.layer:
if self.parent.get_existing_keyword('title'):
title = self.parent.get_existing_keyword('title')
else:
title = self.parent.layer.name()
self.leTitle.setText(title) | [
"def",
"set_widgets",
"(",
"self",
")",
":",
"# Set title from keyword first, if not found use layer name",
"if",
"self",
".",
"parent",
".",
"layer",
":",
"if",
"self",
".",
"parent",
".",
"get_existing_keyword",
"(",
"'title'",
")",
":",
"title",
"=",
"self",
... | Set widgets on the Title tab. | [
"Set",
"widgets",
"on",
"the",
"Title",
"tab",
"."
] | 831d60abba919f6d481dc94a8d988cc205130724 | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/tools/wizard/step_kw60_title.py#L60-L68 | train | 27,157 |
inasafe/inasafe | safe/gui/tools/extent_selector_dialog.py | ExtentSelectorDialog.start_capture | def start_capture(self):
"""Start capturing the rectangle."""
previous_map_tool = self.canvas.mapTool()
if previous_map_tool != self.tool:
self.previous_map_tool = previous_map_tool
self.canvas.setMapTool(self.tool)
self.hide() | python | def start_capture(self):
"""Start capturing the rectangle."""
previous_map_tool = self.canvas.mapTool()
if previous_map_tool != self.tool:
self.previous_map_tool = previous_map_tool
self.canvas.setMapTool(self.tool)
self.hide() | [
"def",
"start_capture",
"(",
"self",
")",
":",
"previous_map_tool",
"=",
"self",
".",
"canvas",
".",
"mapTool",
"(",
")",
"if",
"previous_map_tool",
"!=",
"self",
".",
"tool",
":",
"self",
".",
"previous_map_tool",
"=",
"previous_map_tool",
"self",
".",
"can... | Start capturing the rectangle. | [
"Start",
"capturing",
"the",
"rectangle",
"."
] | 831d60abba919f6d481dc94a8d988cc205130724 | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/tools/extent_selector_dialog.py#L205-L211 | train | 27,158 |
inasafe/inasafe | safe/gui/tools/extent_selector_dialog.py | ExtentSelectorDialog.stop_capture | def stop_capture(self):
"""Stop capturing the rectangle and reshow the dialog."""
self._populate_coordinates()
self.canvas.setMapTool(self.previous_map_tool)
self.show() | python | def stop_capture(self):
"""Stop capturing the rectangle and reshow the dialog."""
self._populate_coordinates()
self.canvas.setMapTool(self.previous_map_tool)
self.show() | [
"def",
"stop_capture",
"(",
"self",
")",
":",
"self",
".",
"_populate_coordinates",
"(",
")",
"self",
".",
"canvas",
".",
"setMapTool",
"(",
"self",
".",
"previous_map_tool",
")",
"self",
".",
"show",
"(",
")"
] | Stop capturing the rectangle and reshow the dialog. | [
"Stop",
"capturing",
"the",
"rectangle",
"and",
"reshow",
"the",
"dialog",
"."
] | 831d60abba919f6d481dc94a8d988cc205130724 | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/tools/extent_selector_dialog.py#L213-L217 | train | 27,159 |
inasafe/inasafe | safe/gui/tools/extent_selector_dialog.py | ExtentSelectorDialog.clear | def clear(self):
"""Clear the currently set extent."""
self.tool.reset()
self._populate_coordinates()
# Revert to using hazard, exposure and view as basis for analysis
self.hazard_exposure_view_extent.setChecked(True) | python | def clear(self):
"""Clear the currently set extent."""
self.tool.reset()
self._populate_coordinates()
# Revert to using hazard, exposure and view as basis for analysis
self.hazard_exposure_view_extent.setChecked(True) | [
"def",
"clear",
"(",
"self",
")",
":",
"self",
".",
"tool",
".",
"reset",
"(",
")",
"self",
".",
"_populate_coordinates",
"(",
")",
"# Revert to using hazard, exposure and view as basis for analysis",
"self",
".",
"hazard_exposure_view_extent",
".",
"setChecked",
"(",... | Clear the currently set extent. | [
"Clear",
"the",
"currently",
"set",
"extent",
"."
] | 831d60abba919f6d481dc94a8d988cc205130724 | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/tools/extent_selector_dialog.py#L219-L224 | train | 27,160 |
inasafe/inasafe | safe/gui/tools/extent_selector_dialog.py | ExtentSelectorDialog.reject | def reject(self):
"""User rejected the rectangle."""
self.canvas.unsetMapTool(self.tool)
if self.previous_map_tool != self.tool:
self.canvas.setMapTool(self.previous_map_tool)
self.tool.reset()
self.extent_selector_closed.emit()
super(ExtentSelectorDialog, self).reject() | python | def reject(self):
"""User rejected the rectangle."""
self.canvas.unsetMapTool(self.tool)
if self.previous_map_tool != self.tool:
self.canvas.setMapTool(self.previous_map_tool)
self.tool.reset()
self.extent_selector_closed.emit()
super(ExtentSelectorDialog, self).reject() | [
"def",
"reject",
"(",
"self",
")",
":",
"self",
".",
"canvas",
".",
"unsetMapTool",
"(",
"self",
".",
"tool",
")",
"if",
"self",
".",
"previous_map_tool",
"!=",
"self",
".",
"tool",
":",
"self",
".",
"canvas",
".",
"setMapTool",
"(",
"self",
".",
"pr... | User rejected the rectangle. | [
"User",
"rejected",
"the",
"rectangle",
"."
] | 831d60abba919f6d481dc94a8d988cc205130724 | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/tools/extent_selector_dialog.py#L226-L233 | train | 27,161 |
inasafe/inasafe | safe/gui/tools/extent_selector_dialog.py | ExtentSelectorDialog.accept | def accept(self):
"""User accepted the rectangle."""
mode = None
if self.hazard_exposure_view_extent.isChecked():
mode = HAZARD_EXPOSURE_VIEW
elif self.exposure_only.isChecked():
mode = EXPOSURE
elif self.hazard_exposure_only.isChecked():
mode = HAZARD_EXPOSURE
elif self.hazard_exposure_bookmark.isChecked():
mode = HAZARD_EXPOSURE_BOOKMARK
elif self.hazard_exposure_user_extent.isChecked():
mode = HAZARD_EXPOSURE_BOUNDINGBOX
set_setting('analysis_extents_mode', mode)
self.canvas.unsetMapTool(self.tool)
if self.previous_map_tool != self.tool:
self.canvas.setMapTool(self.previous_map_tool)
if not self.tool.rectangle().isEmpty():
self.extent_defined.emit(
self.tool.rectangle(),
self.canvas.mapSettings().destinationCrs())
extent = QgsGeometry.fromRect(self.tool.rectangle())
LOGGER.info(
'Requested extent : {wkt}'.format(wkt=extent.asWkt()))
else:
self.clear_extent.emit()
# State handlers for showing warning message bars
set_setting('show_extent_warnings', self.show_warnings.isChecked())
set_setting(
'show_extent_confirmations', self.show_confirmations.isChecked())
self.tool.reset()
self.extent_selector_closed.emit()
super(ExtentSelectorDialog, self).accept() | python | def accept(self):
"""User accepted the rectangle."""
mode = None
if self.hazard_exposure_view_extent.isChecked():
mode = HAZARD_EXPOSURE_VIEW
elif self.exposure_only.isChecked():
mode = EXPOSURE
elif self.hazard_exposure_only.isChecked():
mode = HAZARD_EXPOSURE
elif self.hazard_exposure_bookmark.isChecked():
mode = HAZARD_EXPOSURE_BOOKMARK
elif self.hazard_exposure_user_extent.isChecked():
mode = HAZARD_EXPOSURE_BOUNDINGBOX
set_setting('analysis_extents_mode', mode)
self.canvas.unsetMapTool(self.tool)
if self.previous_map_tool != self.tool:
self.canvas.setMapTool(self.previous_map_tool)
if not self.tool.rectangle().isEmpty():
self.extent_defined.emit(
self.tool.rectangle(),
self.canvas.mapSettings().destinationCrs())
extent = QgsGeometry.fromRect(self.tool.rectangle())
LOGGER.info(
'Requested extent : {wkt}'.format(wkt=extent.asWkt()))
else:
self.clear_extent.emit()
# State handlers for showing warning message bars
set_setting('show_extent_warnings', self.show_warnings.isChecked())
set_setting(
'show_extent_confirmations', self.show_confirmations.isChecked())
self.tool.reset()
self.extent_selector_closed.emit()
super(ExtentSelectorDialog, self).accept() | [
"def",
"accept",
"(",
"self",
")",
":",
"mode",
"=",
"None",
"if",
"self",
".",
"hazard_exposure_view_extent",
".",
"isChecked",
"(",
")",
":",
"mode",
"=",
"HAZARD_EXPOSURE_VIEW",
"elif",
"self",
".",
"exposure_only",
".",
"isChecked",
"(",
")",
":",
"mod... | User accepted the rectangle. | [
"User",
"accepted",
"the",
"rectangle",
"."
] | 831d60abba919f6d481dc94a8d988cc205130724 | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/tools/extent_selector_dialog.py#L235-L272 | train | 27,162 |
inasafe/inasafe | safe/gui/tools/extent_selector_dialog.py | ExtentSelectorDialog._are_coordinates_valid | def _are_coordinates_valid(self):
"""Check if the coordinates are valid.
:return: True if coordinates are valid otherwise False.
:type: bool
"""
try:
QgsPointXY(
self.x_minimum.value(),
self.y_maximum.value())
QgsPointXY(
self.x_maximum.value(),
self.y_minimum.value())
except ValueError:
return False
return True | python | def _are_coordinates_valid(self):
"""Check if the coordinates are valid.
:return: True if coordinates are valid otherwise False.
:type: bool
"""
try:
QgsPointXY(
self.x_minimum.value(),
self.y_maximum.value())
QgsPointXY(
self.x_maximum.value(),
self.y_minimum.value())
except ValueError:
return False
return True | [
"def",
"_are_coordinates_valid",
"(",
"self",
")",
":",
"try",
":",
"QgsPointXY",
"(",
"self",
".",
"x_minimum",
".",
"value",
"(",
")",
",",
"self",
".",
"y_maximum",
".",
"value",
"(",
")",
")",
"QgsPointXY",
"(",
"self",
".",
"x_maximum",
".",
"valu... | Check if the coordinates are valid.
:return: True if coordinates are valid otherwise False.
:type: bool | [
"Check",
"if",
"the",
"coordinates",
"are",
"valid",
"."
] | 831d60abba919f6d481dc94a8d988cc205130724 | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/tools/extent_selector_dialog.py#L274-L290 | train | 27,163 |
inasafe/inasafe | safe/gui/tools/extent_selector_dialog.py | ExtentSelectorDialog._coordinates_changed | def _coordinates_changed(self):
"""Handle a change in the coordinate input boxes."""
if self._are_coordinates_valid():
point1 = QgsPointXY(
self.x_minimum.value(),
self.y_maximum.value())
point2 = QgsPointXY(
self.x_maximum.value(),
self.y_minimum.value())
rect = QgsRectangle(point1, point2)
self.tool.set_rectangle(rect) | python | def _coordinates_changed(self):
"""Handle a change in the coordinate input boxes."""
if self._are_coordinates_valid():
point1 = QgsPointXY(
self.x_minimum.value(),
self.y_maximum.value())
point2 = QgsPointXY(
self.x_maximum.value(),
self.y_minimum.value())
rect = QgsRectangle(point1, point2)
self.tool.set_rectangle(rect) | [
"def",
"_coordinates_changed",
"(",
"self",
")",
":",
"if",
"self",
".",
"_are_coordinates_valid",
"(",
")",
":",
"point1",
"=",
"QgsPointXY",
"(",
"self",
".",
"x_minimum",
".",
"value",
"(",
")",
",",
"self",
".",
"y_maximum",
".",
"value",
"(",
")",
... | Handle a change in the coordinate input boxes. | [
"Handle",
"a",
"change",
"in",
"the",
"coordinate",
"input",
"boxes",
"."
] | 831d60abba919f6d481dc94a8d988cc205130724 | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/tools/extent_selector_dialog.py#L292-L303 | train | 27,164 |
inasafe/inasafe | safe/gui/tools/extent_selector_dialog.py | ExtentSelectorDialog._populate_coordinates | def _populate_coordinates(self):
"""Update the UI with the current active coordinates."""
rect = self.tool.rectangle()
self.blockSignals(True)
if not rect.isEmpty():
self.x_minimum.setValue(rect.xMinimum())
self.y_minimum.setValue(rect.yMinimum())
self.x_maximum.setValue(rect.xMaximum())
self.y_maximum.setValue(rect.yMaximum())
else:
self.x_minimum.clear()
self.y_minimum.clear()
self.x_maximum.clear()
self.y_maximum.clear()
self.blockSignals(False) | python | def _populate_coordinates(self):
"""Update the UI with the current active coordinates."""
rect = self.tool.rectangle()
self.blockSignals(True)
if not rect.isEmpty():
self.x_minimum.setValue(rect.xMinimum())
self.y_minimum.setValue(rect.yMinimum())
self.x_maximum.setValue(rect.xMaximum())
self.y_maximum.setValue(rect.yMaximum())
else:
self.x_minimum.clear()
self.y_minimum.clear()
self.x_maximum.clear()
self.y_maximum.clear()
self.blockSignals(False) | [
"def",
"_populate_coordinates",
"(",
"self",
")",
":",
"rect",
"=",
"self",
".",
"tool",
".",
"rectangle",
"(",
")",
"self",
".",
"blockSignals",
"(",
"True",
")",
"if",
"not",
"rect",
".",
"isEmpty",
"(",
")",
":",
"self",
".",
"x_minimum",
".",
"se... | Update the UI with the current active coordinates. | [
"Update",
"the",
"UI",
"with",
"the",
"current",
"active",
"coordinates",
"."
] | 831d60abba919f6d481dc94a8d988cc205130724 | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/tools/extent_selector_dialog.py#L305-L319 | train | 27,165 |
inasafe/inasafe | safe/gui/tools/extent_selector_dialog.py | ExtentSelectorDialog.bookmarks_index_changed | def bookmarks_index_changed(self):
"""Update the UI when the bookmarks combobox has changed."""
index = self.bookmarks_list.currentIndex()
if index >= 0:
self.tool.reset()
rectangle = self.bookmarks_list.itemData(index)
self.tool.set_rectangle(rectangle)
self.canvas.setExtent(rectangle)
self.ok_button.setEnabled(True)
else:
self.ok_button.setDisabled(True) | python | def bookmarks_index_changed(self):
"""Update the UI when the bookmarks combobox has changed."""
index = self.bookmarks_list.currentIndex()
if index >= 0:
self.tool.reset()
rectangle = self.bookmarks_list.itemData(index)
self.tool.set_rectangle(rectangle)
self.canvas.setExtent(rectangle)
self.ok_button.setEnabled(True)
else:
self.ok_button.setDisabled(True) | [
"def",
"bookmarks_index_changed",
"(",
"self",
")",
":",
"index",
"=",
"self",
".",
"bookmarks_list",
".",
"currentIndex",
"(",
")",
"if",
"index",
">=",
"0",
":",
"self",
".",
"tool",
".",
"reset",
"(",
")",
"rectangle",
"=",
"self",
".",
"bookmarks_lis... | Update the UI when the bookmarks combobox has changed. | [
"Update",
"the",
"UI",
"when",
"the",
"bookmarks",
"combobox",
"has",
"changed",
"."
] | 831d60abba919f6d481dc94a8d988cc205130724 | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/tools/extent_selector_dialog.py#L321-L331 | train | 27,166 |
inasafe/inasafe | safe/gui/tools/extent_selector_dialog.py | ExtentSelectorDialog.on_hazard_exposure_bookmark_toggled | def on_hazard_exposure_bookmark_toggled(self, enabled):
"""Update the UI when the user toggles the bookmarks radiobutton.
:param enabled: The status of the radiobutton.
:type enabled: bool
"""
if enabled:
self.bookmarks_index_changed()
else:
self.ok_button.setEnabled(True)
self._populate_coordinates() | python | def on_hazard_exposure_bookmark_toggled(self, enabled):
"""Update the UI when the user toggles the bookmarks radiobutton.
:param enabled: The status of the radiobutton.
:type enabled: bool
"""
if enabled:
self.bookmarks_index_changed()
else:
self.ok_button.setEnabled(True)
self._populate_coordinates() | [
"def",
"on_hazard_exposure_bookmark_toggled",
"(",
"self",
",",
"enabled",
")",
":",
"if",
"enabled",
":",
"self",
".",
"bookmarks_index_changed",
"(",
")",
"else",
":",
"self",
".",
"ok_button",
".",
"setEnabled",
"(",
"True",
")",
"self",
".",
"_populate_coo... | Update the UI when the user toggles the bookmarks radiobutton.
:param enabled: The status of the radiobutton.
:type enabled: bool | [
"Update",
"the",
"UI",
"when",
"the",
"user",
"toggles",
"the",
"bookmarks",
"radiobutton",
"."
] | 831d60abba919f6d481dc94a8d988cc205130724 | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/tools/extent_selector_dialog.py#L353-L363 | train | 27,167 |
inasafe/inasafe | safe/gui/tools/extent_selector_dialog.py | ExtentSelectorDialog._populate_bookmarks_list | def _populate_bookmarks_list(self):
"""Read the sqlite database and populate the bookmarks list.
If no bookmarks are found, the bookmarks radio button will be disabled
and the label will be shown indicating that the user should add
bookmarks in QGIS first.
Every bookmark are reprojected to mapcanvas crs.
"""
# Connect to the QGIS sqlite database and check if the table exists.
# noinspection PyArgumentList
db_file_path = QgsApplication.qgisUserDatabaseFilePath()
db = sqlite3.connect(db_file_path)
cursor = db.cursor()
cursor.execute(
'SELECT COUNT(*) '
'FROM sqlite_master '
'WHERE type=\'table\' '
'AND name=\'tbl_bookmarks\';')
number_of_rows = cursor.fetchone()[0]
if number_of_rows > 0:
cursor.execute(
'SELECT * '
'FROM tbl_bookmarks;')
bookmarks = cursor.fetchall()
canvas_crs = self.canvas.mapSettings().destinationCrs()
for bookmark in bookmarks:
name = bookmark[1]
srid = bookmark[7]
rectangle = QgsRectangle(
bookmark[3], bookmark[4], bookmark[5], bookmark[6])
if srid != canvas_crs.srsid():
transform = QgsCoordinateTransform(
QgsCoordinateReferenceSystem(srid),
canvas_crs,
QgsProject.instance()
)
try:
rectangle = transform.transform(rectangle)
except QgsCsException:
rectangle = QgsRectangle()
if rectangle.isEmpty():
pass
self.bookmarks_list.addItem(name, rectangle)
if self.bookmarks_list.currentIndex() >= 0:
self.create_bookmarks_label.hide()
else:
self.create_bookmarks_label.show()
self.hazard_exposure_bookmark.setDisabled(True)
self.bookmarks_list.hide() | python | def _populate_bookmarks_list(self):
"""Read the sqlite database and populate the bookmarks list.
If no bookmarks are found, the bookmarks radio button will be disabled
and the label will be shown indicating that the user should add
bookmarks in QGIS first.
Every bookmark are reprojected to mapcanvas crs.
"""
# Connect to the QGIS sqlite database and check if the table exists.
# noinspection PyArgumentList
db_file_path = QgsApplication.qgisUserDatabaseFilePath()
db = sqlite3.connect(db_file_path)
cursor = db.cursor()
cursor.execute(
'SELECT COUNT(*) '
'FROM sqlite_master '
'WHERE type=\'table\' '
'AND name=\'tbl_bookmarks\';')
number_of_rows = cursor.fetchone()[0]
if number_of_rows > 0:
cursor.execute(
'SELECT * '
'FROM tbl_bookmarks;')
bookmarks = cursor.fetchall()
canvas_crs = self.canvas.mapSettings().destinationCrs()
for bookmark in bookmarks:
name = bookmark[1]
srid = bookmark[7]
rectangle = QgsRectangle(
bookmark[3], bookmark[4], bookmark[5], bookmark[6])
if srid != canvas_crs.srsid():
transform = QgsCoordinateTransform(
QgsCoordinateReferenceSystem(srid),
canvas_crs,
QgsProject.instance()
)
try:
rectangle = transform.transform(rectangle)
except QgsCsException:
rectangle = QgsRectangle()
if rectangle.isEmpty():
pass
self.bookmarks_list.addItem(name, rectangle)
if self.bookmarks_list.currentIndex() >= 0:
self.create_bookmarks_label.hide()
else:
self.create_bookmarks_label.show()
self.hazard_exposure_bookmark.setDisabled(True)
self.bookmarks_list.hide() | [
"def",
"_populate_bookmarks_list",
"(",
"self",
")",
":",
"# Connect to the QGIS sqlite database and check if the table exists.",
"# noinspection PyArgumentList",
"db_file_path",
"=",
"QgsApplication",
".",
"qgisUserDatabaseFilePath",
"(",
")",
"db",
"=",
"sqlite3",
".",
"conne... | Read the sqlite database and populate the bookmarks list.
If no bookmarks are found, the bookmarks radio button will be disabled
and the label will be shown indicating that the user should add
bookmarks in QGIS first.
Every bookmark are reprojected to mapcanvas crs. | [
"Read",
"the",
"sqlite",
"database",
"and",
"populate",
"the",
"bookmarks",
"list",
"."
] | 831d60abba919f6d481dc94a8d988cc205130724 | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/tools/extent_selector_dialog.py#L365-L420 | train | 27,168 |
inasafe/inasafe | safe/utilities/utilities.py | basestring_to_message | def basestring_to_message(text):
"""Convert a basestring to a Message object if needed.
Avoid using this function, better to create the Message object yourself.
This one is very generic.
This function exists ust in case we get a basestring and we really need a
Message object.
:param text: The text.
:type text: basestring, Message
:return: The message object.
:rtype: message
"""
if isinstance(text, Message):
return text
elif text is None:
return ''
else:
report = m.Message()
report.add(text)
return report | python | def basestring_to_message(text):
"""Convert a basestring to a Message object if needed.
Avoid using this function, better to create the Message object yourself.
This one is very generic.
This function exists ust in case we get a basestring and we really need a
Message object.
:param text: The text.
:type text: basestring, Message
:return: The message object.
:rtype: message
"""
if isinstance(text, Message):
return text
elif text is None:
return ''
else:
report = m.Message()
report.add(text)
return report | [
"def",
"basestring_to_message",
"(",
"text",
")",
":",
"if",
"isinstance",
"(",
"text",
",",
"Message",
")",
":",
"return",
"text",
"elif",
"text",
"is",
"None",
":",
"return",
"''",
"else",
":",
"report",
"=",
"m",
".",
"Message",
"(",
")",
"report",
... | Convert a basestring to a Message object if needed.
Avoid using this function, better to create the Message object yourself.
This one is very generic.
This function exists ust in case we get a basestring and we really need a
Message object.
:param text: The text.
:type text: basestring, Message
:return: The message object.
:rtype: message | [
"Convert",
"a",
"basestring",
"to",
"a",
"Message",
"object",
"if",
"needed",
"."
] | 831d60abba919f6d481dc94a8d988cc205130724 | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/utilities/utilities.py#L40-L62 | train | 27,169 |
inasafe/inasafe | safe/utilities/utilities.py | get_error_message | def get_error_message(exception, context=None, suggestion=None):
"""Convert exception into an ErrorMessage containing a stack trace.
:param exception: Exception object.
:type exception: Exception
:param context: Optional context message.
:type context: str
:param suggestion: Optional suggestion.
:type suggestion: str
.. see also:: https://github.com/inasafe/inasafe/issues/577
:returns: An error message with stack trace info suitable for display.
:rtype: ErrorMessage
"""
name, trace = humanise_exception(exception)
problem = m.Message(name)
if exception is None or exception == '':
problem.append = m.Text(tr('No details provided'))
else:
if hasattr(exception, 'message') and \
isinstance(exception.message, Message):
problem.append = m.Text(str(exception.message.message))
else:
problem.append = m.Text(str(exception))
suggestion = suggestion
if suggestion is None and hasattr(exception, 'suggestion'):
suggestion = exception.suggestion
error_message = ErrorMessage(
problem,
detail=context,
suggestion=suggestion,
traceback=trace
)
args = exception.args
for arg in args:
error_message.details.append(arg)
return error_message | python | def get_error_message(exception, context=None, suggestion=None):
"""Convert exception into an ErrorMessage containing a stack trace.
:param exception: Exception object.
:type exception: Exception
:param context: Optional context message.
:type context: str
:param suggestion: Optional suggestion.
:type suggestion: str
.. see also:: https://github.com/inasafe/inasafe/issues/577
:returns: An error message with stack trace info suitable for display.
:rtype: ErrorMessage
"""
name, trace = humanise_exception(exception)
problem = m.Message(name)
if exception is None or exception == '':
problem.append = m.Text(tr('No details provided'))
else:
if hasattr(exception, 'message') and \
isinstance(exception.message, Message):
problem.append = m.Text(str(exception.message.message))
else:
problem.append = m.Text(str(exception))
suggestion = suggestion
if suggestion is None and hasattr(exception, 'suggestion'):
suggestion = exception.suggestion
error_message = ErrorMessage(
problem,
detail=context,
suggestion=suggestion,
traceback=trace
)
args = exception.args
for arg in args:
error_message.details.append(arg)
return error_message | [
"def",
"get_error_message",
"(",
"exception",
",",
"context",
"=",
"None",
",",
"suggestion",
"=",
"None",
")",
":",
"name",
",",
"trace",
"=",
"humanise_exception",
"(",
"exception",
")",
"problem",
"=",
"m",
".",
"Message",
"(",
"name",
")",
"if",
"exc... | Convert exception into an ErrorMessage containing a stack trace.
:param exception: Exception object.
:type exception: Exception
:param context: Optional context message.
:type context: str
:param suggestion: Optional suggestion.
:type suggestion: str
.. see also:: https://github.com/inasafe/inasafe/issues/577
:returns: An error message with stack trace info suitable for display.
:rtype: ErrorMessage | [
"Convert",
"exception",
"into",
"an",
"ErrorMessage",
"containing",
"a",
"stack",
"trace",
"."
] | 831d60abba919f6d481dc94a8d988cc205130724 | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/utilities/utilities.py#L65-L111 | train | 27,170 |
inasafe/inasafe | safe/utilities/utilities.py | humanise_exception | def humanise_exception(exception):
"""Humanise a python exception by giving the class name and traceback.
The function will return a tuple with the exception name and the traceback.
:param exception: Exception object.
:type exception: Exception
:return: A tuple with the exception name and the traceback.
:rtype: (str, str)
"""
trace = ''.join(traceback.format_tb(sys.exc_info()[2]))
name = exception.__class__.__name__
return name, trace | python | def humanise_exception(exception):
"""Humanise a python exception by giving the class name and traceback.
The function will return a tuple with the exception name and the traceback.
:param exception: Exception object.
:type exception: Exception
:return: A tuple with the exception name and the traceback.
:rtype: (str, str)
"""
trace = ''.join(traceback.format_tb(sys.exc_info()[2]))
name = exception.__class__.__name__
return name, trace | [
"def",
"humanise_exception",
"(",
"exception",
")",
":",
"trace",
"=",
"''",
".",
"join",
"(",
"traceback",
".",
"format_tb",
"(",
"sys",
".",
"exc_info",
"(",
")",
"[",
"2",
"]",
")",
")",
"name",
"=",
"exception",
".",
"__class__",
".",
"__name__",
... | Humanise a python exception by giving the class name and traceback.
The function will return a tuple with the exception name and the traceback.
:param exception: Exception object.
:type exception: Exception
:return: A tuple with the exception name and the traceback.
:rtype: (str, str) | [
"Humanise",
"a",
"python",
"exception",
"by",
"giving",
"the",
"class",
"name",
"and",
"traceback",
"."
] | 831d60abba919f6d481dc94a8d988cc205130724 | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/utilities/utilities.py#L114-L127 | train | 27,171 |
inasafe/inasafe | safe/utilities/utilities.py | html_to_file | def html_to_file(html, file_path=None, open_browser=False):
"""Save the html to an html file adapting the paths to the filesystem.
if a file_path is passed, it is used, if not a unique_filename is
generated.
:param html: the html for the output file.
:type html: str
:param file_path: the path for the html output file.
:type file_path: str
:param open_browser: if true open the generated html in an external browser
:type open_browser: bool
"""
if file_path is None:
file_path = unique_filename(suffix='.html')
# Ensure html is in unicode for codecs module
html = html
with codecs.open(file_path, 'w', encoding='utf-8') as f:
f.write(html)
if open_browser:
open_in_browser(file_path) | python | def html_to_file(html, file_path=None, open_browser=False):
"""Save the html to an html file adapting the paths to the filesystem.
if a file_path is passed, it is used, if not a unique_filename is
generated.
:param html: the html for the output file.
:type html: str
:param file_path: the path for the html output file.
:type file_path: str
:param open_browser: if true open the generated html in an external browser
:type open_browser: bool
"""
if file_path is None:
file_path = unique_filename(suffix='.html')
# Ensure html is in unicode for codecs module
html = html
with codecs.open(file_path, 'w', encoding='utf-8') as f:
f.write(html)
if open_browser:
open_in_browser(file_path) | [
"def",
"html_to_file",
"(",
"html",
",",
"file_path",
"=",
"None",
",",
"open_browser",
"=",
"False",
")",
":",
"if",
"file_path",
"is",
"None",
":",
"file_path",
"=",
"unique_filename",
"(",
"suffix",
"=",
"'.html'",
")",
"# Ensure html is in unicode for codecs... | Save the html to an html file adapting the paths to the filesystem.
if a file_path is passed, it is used, if not a unique_filename is
generated.
:param html: the html for the output file.
:type html: str
:param file_path: the path for the html output file.
:type file_path: str
:param open_browser: if true open the generated html in an external browser
:type open_browser: bool | [
"Save",
"the",
"html",
"to",
"an",
"html",
"file",
"adapting",
"the",
"paths",
"to",
"the",
"filesystem",
"."
] | 831d60abba919f6d481dc94a8d988cc205130724 | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/utilities/utilities.py#L226-L250 | train | 27,172 |
inasafe/inasafe | safe/utilities/utilities.py | is_keyword_version_supported | def is_keyword_version_supported(
keyword_version, inasafe_version=inasafe_keyword_version):
"""Check if the keyword version is supported by this InaSAFE version.
.. versionadded: 3.3
:param keyword_version: String representation of the keyword version.
:type keyword_version: str
:param inasafe_version: String representation of InaSAFE's version.
:type inasafe_version: str
:returns: True if supported, otherwise False.
:rtype: bool
"""
def minor_version(version):
"""Obtain minor version of a version (x.y)
:param version: Version string.
:type version: str
:returns: Minor version.
:rtype: str
"""
version_split = version.split('.')
return version_split[0] + '.' + version_split[1]
# Convert to minor version.
keyword_version = minor_version(keyword_version)
inasafe_version = minor_version(inasafe_version)
if inasafe_version == keyword_version:
return True
if inasafe_version in list(keyword_version_compatibilities.keys()):
if keyword_version in keyword_version_compatibilities[inasafe_version]:
return True
else:
return False
else:
return False | python | def is_keyword_version_supported(
keyword_version, inasafe_version=inasafe_keyword_version):
"""Check if the keyword version is supported by this InaSAFE version.
.. versionadded: 3.3
:param keyword_version: String representation of the keyword version.
:type keyword_version: str
:param inasafe_version: String representation of InaSAFE's version.
:type inasafe_version: str
:returns: True if supported, otherwise False.
:rtype: bool
"""
def minor_version(version):
"""Obtain minor version of a version (x.y)
:param version: Version string.
:type version: str
:returns: Minor version.
:rtype: str
"""
version_split = version.split('.')
return version_split[0] + '.' + version_split[1]
# Convert to minor version.
keyword_version = minor_version(keyword_version)
inasafe_version = minor_version(inasafe_version)
if inasafe_version == keyword_version:
return True
if inasafe_version in list(keyword_version_compatibilities.keys()):
if keyword_version in keyword_version_compatibilities[inasafe_version]:
return True
else:
return False
else:
return False | [
"def",
"is_keyword_version_supported",
"(",
"keyword_version",
",",
"inasafe_version",
"=",
"inasafe_keyword_version",
")",
":",
"def",
"minor_version",
"(",
"version",
")",
":",
"\"\"\"Obtain minor version of a version (x.y)\n :param version: Version string.\n :type ve... | Check if the keyword version is supported by this InaSAFE version.
.. versionadded: 3.3
:param keyword_version: String representation of the keyword version.
:type keyword_version: str
:param inasafe_version: String representation of InaSAFE's version.
:type inasafe_version: str
:returns: True if supported, otherwise False.
:rtype: bool | [
"Check",
"if",
"the",
"keyword",
"version",
"is",
"supported",
"by",
"this",
"InaSAFE",
"version",
"."
] | 831d60abba919f6d481dc94a8d988cc205130724 | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/utilities/utilities.py#L267-L306 | train | 27,173 |
inasafe/inasafe | safe/utilities/utilities.py | write_json | def write_json(data, filename):
"""Custom handler for writing json file in InaSAFE.
Criteria:
- use indent = 2
- Handle NULL from QGIS
:param data: The data that will be written.
:type data: dict
:param filename: The file name.
:type filename: str
"""
def custom_default(obj):
if obj is None or (hasattr(obj, 'isNull') and obj.isNull()):
return ''
raise TypeError
with open(filename, 'w') as json_file:
json.dump(data, json_file, indent=2, default=custom_default) | python | def write_json(data, filename):
"""Custom handler for writing json file in InaSAFE.
Criteria:
- use indent = 2
- Handle NULL from QGIS
:param data: The data that will be written.
:type data: dict
:param filename: The file name.
:type filename: str
"""
def custom_default(obj):
if obj is None or (hasattr(obj, 'isNull') and obj.isNull()):
return ''
raise TypeError
with open(filename, 'w') as json_file:
json.dump(data, json_file, indent=2, default=custom_default) | [
"def",
"write_json",
"(",
"data",
",",
"filename",
")",
":",
"def",
"custom_default",
"(",
"obj",
")",
":",
"if",
"obj",
"is",
"None",
"or",
"(",
"hasattr",
"(",
"obj",
",",
"'isNull'",
")",
"and",
"obj",
".",
"isNull",
"(",
")",
")",
":",
"return"... | Custom handler for writing json file in InaSAFE.
Criteria:
- use indent = 2
- Handle NULL from QGIS
:param data: The data that will be written.
:type data: dict
:param filename: The file name.
:type filename: str | [
"Custom",
"handler",
"for",
"writing",
"json",
"file",
"in",
"InaSAFE",
"."
] | 831d60abba919f6d481dc94a8d988cc205130724 | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/utilities/utilities.py#L309-L329 | train | 27,174 |
inasafe/inasafe | safe/utilities/utilities.py | monkey_patch_keywords | def monkey_patch_keywords(layer):
"""In InaSAFE V4, we do monkey patching for keywords.
:param layer: The layer to monkey patch keywords.
:type layer: QgsMapLayer
"""
keyword_io = KeywordIO()
try:
layer.keywords = keyword_io.read_keywords(layer)
except (NoKeywordsFoundError, MetadataReadError):
layer.keywords = {}
if not layer.keywords.get('inasafe_fields'):
layer.keywords['inasafe_fields'] = {}
if not layer.keywords.get('layer_purpose'):
layer.keywords['layer_purpose'] = 'undefined' | python | def monkey_patch_keywords(layer):
"""In InaSAFE V4, we do monkey patching for keywords.
:param layer: The layer to monkey patch keywords.
:type layer: QgsMapLayer
"""
keyword_io = KeywordIO()
try:
layer.keywords = keyword_io.read_keywords(layer)
except (NoKeywordsFoundError, MetadataReadError):
layer.keywords = {}
if not layer.keywords.get('inasafe_fields'):
layer.keywords['inasafe_fields'] = {}
if not layer.keywords.get('layer_purpose'):
layer.keywords['layer_purpose'] = 'undefined' | [
"def",
"monkey_patch_keywords",
"(",
"layer",
")",
":",
"keyword_io",
"=",
"KeywordIO",
"(",
")",
"try",
":",
"layer",
".",
"keywords",
"=",
"keyword_io",
".",
"read_keywords",
"(",
"layer",
")",
"except",
"(",
"NoKeywordsFoundError",
",",
"MetadataReadError",
... | In InaSAFE V4, we do monkey patching for keywords.
:param layer: The layer to monkey patch keywords.
:type layer: QgsMapLayer | [
"In",
"InaSAFE",
"V4",
"we",
"do",
"monkey",
"patching",
"for",
"keywords",
"."
] | 831d60abba919f6d481dc94a8d988cc205130724 | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/utilities/utilities.py#L360-L375 | train | 27,175 |
inasafe/inasafe | safe/utilities/utilities.py | readable_os_version | def readable_os_version():
"""Give a proper name for OS version
:return: Proper OS version
:rtype: str
"""
if platform.system() == 'Linux':
return _linux_os_release()
elif platform.system() == 'Darwin':
return ' {version}'.format(version=platform.mac_ver()[0])
elif platform.system() == 'Windows':
return platform.platform() | python | def readable_os_version():
"""Give a proper name for OS version
:return: Proper OS version
:rtype: str
"""
if platform.system() == 'Linux':
return _linux_os_release()
elif platform.system() == 'Darwin':
return ' {version}'.format(version=platform.mac_ver()[0])
elif platform.system() == 'Windows':
return platform.platform() | [
"def",
"readable_os_version",
"(",
")",
":",
"if",
"platform",
".",
"system",
"(",
")",
"==",
"'Linux'",
":",
"return",
"_linux_os_release",
"(",
")",
"elif",
"platform",
".",
"system",
"(",
")",
"==",
"'Darwin'",
":",
"return",
"' {version}'",
".",
"forma... | Give a proper name for OS version
:return: Proper OS version
:rtype: str | [
"Give",
"a",
"proper",
"name",
"for",
"OS",
"version"
] | 831d60abba919f6d481dc94a8d988cc205130724 | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/utilities/utilities.py#L405-L416 | train | 27,176 |
inasafe/inasafe | safe/utilities/utilities.py | is_plugin_installed | def is_plugin_installed(name):
"""Check if a plugin is installed, even if it's not enabled.
:param name: Name of the plugin to check.
:type name: string
:return: If the plugin is installed.
:rtype: bool
"""
for directory in plugin_paths:
if isdir(join(directory, name)):
return True
return False | python | def is_plugin_installed(name):
"""Check if a plugin is installed, even if it's not enabled.
:param name: Name of the plugin to check.
:type name: string
:return: If the plugin is installed.
:rtype: bool
"""
for directory in plugin_paths:
if isdir(join(directory, name)):
return True
return False | [
"def",
"is_plugin_installed",
"(",
"name",
")",
":",
"for",
"directory",
"in",
"plugin_paths",
":",
"if",
"isdir",
"(",
"join",
"(",
"directory",
",",
"name",
")",
")",
":",
"return",
"True",
"return",
"False"
] | Check if a plugin is installed, even if it's not enabled.
:param name: Name of the plugin to check.
:type name: string
:return: If the plugin is installed.
:rtype: bool | [
"Check",
"if",
"a",
"plugin",
"is",
"installed",
"even",
"if",
"it",
"s",
"not",
"enabled",
"."
] | 831d60abba919f6d481dc94a8d988cc205130724 | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/utilities/utilities.py#L419-L431 | train | 27,177 |
inasafe/inasafe | safe/utilities/utilities.py | reload_inasafe_modules | def reload_inasafe_modules(module_name=None):
"""Reload python modules.
:param module_name: Specific module name.
:type module_name: str
"""
if not module_name:
module_name = 'safe'
list_modules = list(sys.modules.keys())
for module in list_modules:
if not sys.modules[module]:
continue
if module.startswith(module_name):
del sys.modules[module] | python | def reload_inasafe_modules(module_name=None):
"""Reload python modules.
:param module_name: Specific module name.
:type module_name: str
"""
if not module_name:
module_name = 'safe'
list_modules = list(sys.modules.keys())
for module in list_modules:
if not sys.modules[module]:
continue
if module.startswith(module_name):
del sys.modules[module] | [
"def",
"reload_inasafe_modules",
"(",
"module_name",
"=",
"None",
")",
":",
"if",
"not",
"module_name",
":",
"module_name",
"=",
"'safe'",
"list_modules",
"=",
"list",
"(",
"sys",
".",
"modules",
".",
"keys",
"(",
")",
")",
"for",
"module",
"in",
"list_mod... | Reload python modules.
:param module_name: Specific module name.
:type module_name: str | [
"Reload",
"python",
"modules",
"."
] | 831d60abba919f6d481dc94a8d988cc205130724 | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/utilities/utilities.py#L434-L448 | train | 27,178 |
inasafe/inasafe | safe/gui/widgets/field_mapping_tab.py | FieldMappingTab.populate_field_list | def populate_field_list(self, excluded_fields=None):
"""Helper to add field of the layer to the list.
:param excluded_fields: List of field that want to be excluded.
:type excluded_fields: list
"""
# Populate fields list
if excluded_fields is None:
excluded_fields = []
self.field_list.clear()
for field in self.layer.fields():
# Skip if it's excluded
if field.name() in excluded_fields:
continue
# Skip if it's not number (float, int, etc)
if field.type() not in qvariant_numbers:
continue
field_item = QListWidgetItem(self.field_list)
field_item.setFlags(
Qt.ItemIsEnabled
| Qt.ItemIsSelectable
| Qt.ItemIsDragEnabled)
field_item.setData(Qt.UserRole, field.name())
field_item.setText(field.name())
self.field_list.addItem(field_item) | python | def populate_field_list(self, excluded_fields=None):
"""Helper to add field of the layer to the list.
:param excluded_fields: List of field that want to be excluded.
:type excluded_fields: list
"""
# Populate fields list
if excluded_fields is None:
excluded_fields = []
self.field_list.clear()
for field in self.layer.fields():
# Skip if it's excluded
if field.name() in excluded_fields:
continue
# Skip if it's not number (float, int, etc)
if field.type() not in qvariant_numbers:
continue
field_item = QListWidgetItem(self.field_list)
field_item.setFlags(
Qt.ItemIsEnabled
| Qt.ItemIsSelectable
| Qt.ItemIsDragEnabled)
field_item.setData(Qt.UserRole, field.name())
field_item.setText(field.name())
self.field_list.addItem(field_item) | [
"def",
"populate_field_list",
"(",
"self",
",",
"excluded_fields",
"=",
"None",
")",
":",
"# Populate fields list",
"if",
"excluded_fields",
"is",
"None",
":",
"excluded_fields",
"=",
"[",
"]",
"self",
".",
"field_list",
".",
"clear",
"(",
")",
"for",
"field",... | Helper to add field of the layer to the list.
:param excluded_fields: List of field that want to be excluded.
:type excluded_fields: list | [
"Helper",
"to",
"add",
"field",
"of",
"the",
"layer",
"to",
"the",
"list",
"."
] | 831d60abba919f6d481dc94a8d988cc205130724 | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/widgets/field_mapping_tab.py#L148-L172 | train | 27,179 |
inasafe/inasafe | safe/gui/widgets/field_mapping_tab.py | FieldMappingTab.get_parameter_value | def get_parameter_value(self):
"""Get parameter of the tab.
:returns: Dictionary of parameters by type in this format:
{'fields': {}, 'values': {}}.
:rtype: dict
"""
parameters = self.parameter_container.get_parameters(True)
field_parameters = {}
value_parameters = {}
for parameter in parameters:
if parameter.selected_option_type() in [SINGLE_DYNAMIC, STATIC]:
value_parameters[parameter.guid] = parameter.value
elif parameter.selected_option_type() == MULTIPLE_DYNAMIC:
field_parameters[parameter.guid] = parameter.value
return {
'fields': field_parameters,
'values': value_parameters
} | python | def get_parameter_value(self):
"""Get parameter of the tab.
:returns: Dictionary of parameters by type in this format:
{'fields': {}, 'values': {}}.
:rtype: dict
"""
parameters = self.parameter_container.get_parameters(True)
field_parameters = {}
value_parameters = {}
for parameter in parameters:
if parameter.selected_option_type() in [SINGLE_DYNAMIC, STATIC]:
value_parameters[parameter.guid] = parameter.value
elif parameter.selected_option_type() == MULTIPLE_DYNAMIC:
field_parameters[parameter.guid] = parameter.value
return {
'fields': field_parameters,
'values': value_parameters
} | [
"def",
"get_parameter_value",
"(",
"self",
")",
":",
"parameters",
"=",
"self",
".",
"parameter_container",
".",
"get_parameters",
"(",
"True",
")",
"field_parameters",
"=",
"{",
"}",
"value_parameters",
"=",
"{",
"}",
"for",
"parameter",
"in",
"parameters",
"... | Get parameter of the tab.
:returns: Dictionary of parameters by type in this format:
{'fields': {}, 'values': {}}.
:rtype: dict | [
"Get",
"parameter",
"of",
"the",
"tab",
"."
] | 831d60abba919f6d481dc94a8d988cc205130724 | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/widgets/field_mapping_tab.py#L311-L329 | train | 27,180 |
inasafe/inasafe | safe/gui/widgets/field_mapping_tab.py | FieldMappingTab.update_footer | def update_footer(self):
"""Update footer when the field list change."""
field_item = self.field_list.currentItem()
if not field_item:
self.footer_label.setText('')
return
field_name = field_item.data(Qt.UserRole)
field = self.layer.fields().field(field_name)
index = self.layer.fields().lookupField(field_name)
unique_values = list(self.layer.uniqueValues(index))
pretty_unique_values = ', '.join([str(v) for v in unique_values[:10]])
footer_text = tr('Field type: {0}\n').format(field.typeName())
footer_text += tr('Unique values: {0}').format(pretty_unique_values)
self.footer_label.setText(footer_text) | python | def update_footer(self):
"""Update footer when the field list change."""
field_item = self.field_list.currentItem()
if not field_item:
self.footer_label.setText('')
return
field_name = field_item.data(Qt.UserRole)
field = self.layer.fields().field(field_name)
index = self.layer.fields().lookupField(field_name)
unique_values = list(self.layer.uniqueValues(index))
pretty_unique_values = ', '.join([str(v) for v in unique_values[:10]])
footer_text = tr('Field type: {0}\n').format(field.typeName())
footer_text += tr('Unique values: {0}').format(pretty_unique_values)
self.footer_label.setText(footer_text) | [
"def",
"update_footer",
"(",
"self",
")",
":",
"field_item",
"=",
"self",
".",
"field_list",
".",
"currentItem",
"(",
")",
"if",
"not",
"field_item",
":",
"self",
".",
"footer_label",
".",
"setText",
"(",
"''",
")",
"return",
"field_name",
"=",
"field_item... | Update footer when the field list change. | [
"Update",
"footer",
"when",
"the",
"field",
"list",
"change",
"."
] | 831d60abba919f6d481dc94a8d988cc205130724 | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/widgets/field_mapping_tab.py#L331-L348 | train | 27,181 |
inasafe/inasafe | safe/gui/widgets/field_mapping_tab.py | FieldMappingTab.drop_remove | def drop_remove(*args, **kwargs):
"""Action when we need to remove dropped item.
:param *args: Position arguments.
:type *args: list
:param kwargs: Keywords arguments.
:type kwargs: dict
"""
dropped_item = args[0]
field_list = kwargs['field_list']
num_duplicate = 0
for i in range(field_list.count()):
if dropped_item.text() == field_list.item(i).text():
num_duplicate += 1
if num_duplicate > 1:
# Notes(IS): For some reason, removeItemWidget is not working.
field_list.takeItem(field_list.row(dropped_item)) | python | def drop_remove(*args, **kwargs):
"""Action when we need to remove dropped item.
:param *args: Position arguments.
:type *args: list
:param kwargs: Keywords arguments.
:type kwargs: dict
"""
dropped_item = args[0]
field_list = kwargs['field_list']
num_duplicate = 0
for i in range(field_list.count()):
if dropped_item.text() == field_list.item(i).text():
num_duplicate += 1
if num_duplicate > 1:
# Notes(IS): For some reason, removeItemWidget is not working.
field_list.takeItem(field_list.row(dropped_item)) | [
"def",
"drop_remove",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"dropped_item",
"=",
"args",
"[",
"0",
"]",
"field_list",
"=",
"kwargs",
"[",
"'field_list'",
"]",
"num_duplicate",
"=",
"0",
"for",
"i",
"in",
"range",
"(",
"field_list",
".",
... | Action when we need to remove dropped item.
:param *args: Position arguments.
:type *args: list
:param kwargs: Keywords arguments.
:type kwargs: dict | [
"Action",
"when",
"we",
"need",
"to",
"remove",
"dropped",
"item",
"."
] | 831d60abba919f6d481dc94a8d988cc205130724 | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/widgets/field_mapping_tab.py#L358-L375 | train | 27,182 |
inasafe/inasafe | safe/gis/vector/smart_clip.py | smart_clip | def smart_clip(layer_to_clip, mask_layer):
"""Smart clip a vector layer with another.
Issue https://github.com/inasafe/inasafe/issues/3186
:param layer_to_clip: The vector layer to clip.
:type layer_to_clip: QgsVectorLayer
:param mask_layer: The vector layer to use for clipping.
:type mask_layer: QgsVectorLayer
:return: The clip vector layer.
:rtype: QgsVectorLayer
.. versionadded:: 4.0
"""
output_layer_name = smart_clip_steps['output_layer_name']
writer = create_memory_layer(
output_layer_name,
layer_to_clip.geometryType(),
layer_to_clip.crs(),
layer_to_clip.fields()
)
writer.startEditing()
# first build up a list of clip geometries
request = QgsFeatureRequest().setSubsetOfAttributes([])
iterator = mask_layer.getFeatures(request)
feature = next(iterator)
geometries = QgsGeometry(feature.geometry())
# use prepared geometries for faster intersection tests
# noinspection PyArgumentList
engine = QgsGeometry.createGeometryEngine(geometries.constGet())
engine.prepareGeometry()
extent = mask_layer.extent()
for feature in layer_to_clip.getFeatures(QgsFeatureRequest(extent)):
if engine.intersects(feature.geometry().constGet()):
out_feat = QgsFeature()
out_feat.setGeometry(feature.geometry())
out_feat.setAttributes(feature.attributes())
writer.addFeature(out_feat)
writer.commitChanges()
writer.keywords = layer_to_clip.keywords.copy()
writer.keywords['title'] = output_layer_name
check_layer(writer)
return writer | python | def smart_clip(layer_to_clip, mask_layer):
"""Smart clip a vector layer with another.
Issue https://github.com/inasafe/inasafe/issues/3186
:param layer_to_clip: The vector layer to clip.
:type layer_to_clip: QgsVectorLayer
:param mask_layer: The vector layer to use for clipping.
:type mask_layer: QgsVectorLayer
:return: The clip vector layer.
:rtype: QgsVectorLayer
.. versionadded:: 4.0
"""
output_layer_name = smart_clip_steps['output_layer_name']
writer = create_memory_layer(
output_layer_name,
layer_to_clip.geometryType(),
layer_to_clip.crs(),
layer_to_clip.fields()
)
writer.startEditing()
# first build up a list of clip geometries
request = QgsFeatureRequest().setSubsetOfAttributes([])
iterator = mask_layer.getFeatures(request)
feature = next(iterator)
geometries = QgsGeometry(feature.geometry())
# use prepared geometries for faster intersection tests
# noinspection PyArgumentList
engine = QgsGeometry.createGeometryEngine(geometries.constGet())
engine.prepareGeometry()
extent = mask_layer.extent()
for feature in layer_to_clip.getFeatures(QgsFeatureRequest(extent)):
if engine.intersects(feature.geometry().constGet()):
out_feat = QgsFeature()
out_feat.setGeometry(feature.geometry())
out_feat.setAttributes(feature.attributes())
writer.addFeature(out_feat)
writer.commitChanges()
writer.keywords = layer_to_clip.keywords.copy()
writer.keywords['title'] = output_layer_name
check_layer(writer)
return writer | [
"def",
"smart_clip",
"(",
"layer_to_clip",
",",
"mask_layer",
")",
":",
"output_layer_name",
"=",
"smart_clip_steps",
"[",
"'output_layer_name'",
"]",
"writer",
"=",
"create_memory_layer",
"(",
"output_layer_name",
",",
"layer_to_clip",
".",
"geometryType",
"(",
")",
... | Smart clip a vector layer with another.
Issue https://github.com/inasafe/inasafe/issues/3186
:param layer_to_clip: The vector layer to clip.
:type layer_to_clip: QgsVectorLayer
:param mask_layer: The vector layer to use for clipping.
:type mask_layer: QgsVectorLayer
:return: The clip vector layer.
:rtype: QgsVectorLayer
.. versionadded:: 4.0 | [
"Smart",
"clip",
"a",
"vector",
"layer",
"with",
"another",
"."
] | 831d60abba919f6d481dc94a8d988cc205130724 | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gis/vector/smart_clip.py#L29-L81 | train | 27,183 |
inasafe/inasafe | safe/gui/widgets/message.py | missing_keyword_message | def missing_keyword_message(sender, missing_keyword_exception):
"""Display an error when there is missing keyword.
:param sender: The sender.
:type sender: object
:param missing_keyword_exception: A KeywordNotFoundError exception.
:type missing_keyword_exception: KeywordNotFoundError
"""
warning_heading = m.Heading(
tr('Missing Keyword'), **WARNING_STYLE)
warning_message = tr(
'There is missing keyword that needed for this analysis.')
detail_heading = m.Heading(
tr('Detail'), **DETAILS_STYLE)
suggestion_heading = m.Heading(
tr('Suggestion'), **DETAILS_STYLE)
detail = tr(
'The layer <b>%s</b> is missing the keyword <i>%s</i>.' % (
missing_keyword_exception.layer_name,
missing_keyword_exception.keyword
)
)
suggestion = m.Paragraph(
tr('Please use the keyword wizard to update the keywords. You '
'can open the wizard by clicking on the '),
m.Image(
'file:///%s/img/icons/'
'show-keyword-wizard.svg' % resources_path(),
**SMALL_ICON_STYLE),
tr(' icon in the toolbar.')
)
message = m.Message()
message.add(warning_heading)
message.add(warning_message)
message.add(detail_heading)
message.add(detail)
message.add(suggestion_heading)
message.add(suggestion)
send_static_message(sender, message) | python | def missing_keyword_message(sender, missing_keyword_exception):
"""Display an error when there is missing keyword.
:param sender: The sender.
:type sender: object
:param missing_keyword_exception: A KeywordNotFoundError exception.
:type missing_keyword_exception: KeywordNotFoundError
"""
warning_heading = m.Heading(
tr('Missing Keyword'), **WARNING_STYLE)
warning_message = tr(
'There is missing keyword that needed for this analysis.')
detail_heading = m.Heading(
tr('Detail'), **DETAILS_STYLE)
suggestion_heading = m.Heading(
tr('Suggestion'), **DETAILS_STYLE)
detail = tr(
'The layer <b>%s</b> is missing the keyword <i>%s</i>.' % (
missing_keyword_exception.layer_name,
missing_keyword_exception.keyword
)
)
suggestion = m.Paragraph(
tr('Please use the keyword wizard to update the keywords. You '
'can open the wizard by clicking on the '),
m.Image(
'file:///%s/img/icons/'
'show-keyword-wizard.svg' % resources_path(),
**SMALL_ICON_STYLE),
tr(' icon in the toolbar.')
)
message = m.Message()
message.add(warning_heading)
message.add(warning_message)
message.add(detail_heading)
message.add(detail)
message.add(suggestion_heading)
message.add(suggestion)
send_static_message(sender, message) | [
"def",
"missing_keyword_message",
"(",
"sender",
",",
"missing_keyword_exception",
")",
":",
"warning_heading",
"=",
"m",
".",
"Heading",
"(",
"tr",
"(",
"'Missing Keyword'",
")",
",",
"*",
"*",
"WARNING_STYLE",
")",
"warning_message",
"=",
"tr",
"(",
"'There is... | Display an error when there is missing keyword.
:param sender: The sender.
:type sender: object
:param missing_keyword_exception: A KeywordNotFoundError exception.
:type missing_keyword_exception: KeywordNotFoundError | [
"Display",
"an",
"error",
"when",
"there",
"is",
"missing",
"keyword",
"."
] | 831d60abba919f6d481dc94a8d988cc205130724 | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/widgets/message.py#L40-L80 | train | 27,184 |
inasafe/inasafe | safe/gui/widgets/message.py | conflicting_plugin_message | def conflicting_plugin_message():
"""Unfortunately, one plugin is conflicting with InaSAFE.
We are displaying a message about this conflict.
:returns: Information for the user on how to get started.
:rtype: safe.messaging.Message
"""
message = m.Message()
message.add(LOGO_ELEMENT)
message.add(m.Heading(tr('Conflicting plugin detected'), **WARNING_STYLE))
notes = m.Paragraph(conflicting_plugin_string())
message.add(notes)
return message | python | def conflicting_plugin_message():
"""Unfortunately, one plugin is conflicting with InaSAFE.
We are displaying a message about this conflict.
:returns: Information for the user on how to get started.
:rtype: safe.messaging.Message
"""
message = m.Message()
message.add(LOGO_ELEMENT)
message.add(m.Heading(tr('Conflicting plugin detected'), **WARNING_STYLE))
notes = m.Paragraph(conflicting_plugin_string())
message.add(notes)
return message | [
"def",
"conflicting_plugin_message",
"(",
")",
":",
"message",
"=",
"m",
".",
"Message",
"(",
")",
"message",
".",
"add",
"(",
"LOGO_ELEMENT",
")",
"message",
".",
"add",
"(",
"m",
".",
"Heading",
"(",
"tr",
"(",
"'Conflicting plugin detected'",
")",
",",
... | Unfortunately, one plugin is conflicting with InaSAFE.
We are displaying a message about this conflict.
:returns: Information for the user on how to get started.
:rtype: safe.messaging.Message | [
"Unfortunately",
"one",
"plugin",
"is",
"conflicting",
"with",
"InaSAFE",
"."
] | 831d60abba919f6d481dc94a8d988cc205130724 | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/widgets/message.py#L97-L110 | train | 27,185 |
inasafe/inasafe | safe/gui/widgets/message.py | getting_started_message | def getting_started_message():
"""Generate a message for initial application state.
:returns: Information for the user on how to get started.
:rtype: safe.messaging.Message
"""
message = m.Message()
message.add(LOGO_ELEMENT)
message.add(m.Heading(tr('Getting started'), **INFO_STYLE))
notes = m.Paragraph(
tr(
'These are the minimum steps you need to follow in order '
'to use InaSAFE:'))
message.add(notes)
basics_list = m.NumberedList()
basics_list.add(m.Paragraph(
tr('Add at least one '),
m.ImportantText(tr('hazard'), **KEYWORD_STYLE),
tr(' layer (e.g. earthquake MMI) to QGIS.')))
basics_list.add(m.Paragraph(
tr('Add at least one '),
m.ImportantText(tr('exposure'), **KEYWORD_STYLE),
tr(' layer (e.g. structures) to QGIS.')))
basics_list.add(m.Paragraph(
tr(
'Make sure you have defined keywords for your hazard and '
'exposure layers. You can do this using the '
'keywords creation wizard '),
m.Image(
'file:///%s/img/icons/show-keyword-wizard.svg' %
(resources_path()), **SMALL_ICON_STYLE),
tr(' in the toolbar.')))
basics_list.add(m.Paragraph(
tr('Click on the '),
m.ImportantText(tr('Run'), **KEYWORD_STYLE),
tr(' button below.')))
message.add(basics_list)
message.add(m.Heading(tr('Limitations'), **WARNING_STYLE))
caveat_list = m.NumberedList()
for limitation in limitations():
caveat_list.add(limitation)
message.add(caveat_list)
message.add(m.Heading(tr('Disclaimer'), **WARNING_STYLE))
disclaimer = setting('reportDisclaimer')
message.add(m.Paragraph(disclaimer))
return message | python | def getting_started_message():
"""Generate a message for initial application state.
:returns: Information for the user on how to get started.
:rtype: safe.messaging.Message
"""
message = m.Message()
message.add(LOGO_ELEMENT)
message.add(m.Heading(tr('Getting started'), **INFO_STYLE))
notes = m.Paragraph(
tr(
'These are the minimum steps you need to follow in order '
'to use InaSAFE:'))
message.add(notes)
basics_list = m.NumberedList()
basics_list.add(m.Paragraph(
tr('Add at least one '),
m.ImportantText(tr('hazard'), **KEYWORD_STYLE),
tr(' layer (e.g. earthquake MMI) to QGIS.')))
basics_list.add(m.Paragraph(
tr('Add at least one '),
m.ImportantText(tr('exposure'), **KEYWORD_STYLE),
tr(' layer (e.g. structures) to QGIS.')))
basics_list.add(m.Paragraph(
tr(
'Make sure you have defined keywords for your hazard and '
'exposure layers. You can do this using the '
'keywords creation wizard '),
m.Image(
'file:///%s/img/icons/show-keyword-wizard.svg' %
(resources_path()), **SMALL_ICON_STYLE),
tr(' in the toolbar.')))
basics_list.add(m.Paragraph(
tr('Click on the '),
m.ImportantText(tr('Run'), **KEYWORD_STYLE),
tr(' button below.')))
message.add(basics_list)
message.add(m.Heading(tr('Limitations'), **WARNING_STYLE))
caveat_list = m.NumberedList()
for limitation in limitations():
caveat_list.add(limitation)
message.add(caveat_list)
message.add(m.Heading(tr('Disclaimer'), **WARNING_STYLE))
disclaimer = setting('reportDisclaimer')
message.add(m.Paragraph(disclaimer))
return message | [
"def",
"getting_started_message",
"(",
")",
":",
"message",
"=",
"m",
".",
"Message",
"(",
")",
"message",
".",
"add",
"(",
"LOGO_ELEMENT",
")",
"message",
".",
"add",
"(",
"m",
".",
"Heading",
"(",
"tr",
"(",
"'Getting started'",
")",
",",
"*",
"*",
... | Generate a message for initial application state.
:returns: Information for the user on how to get started.
:rtype: safe.messaging.Message | [
"Generate",
"a",
"message",
"for",
"initial",
"application",
"state",
"."
] | 831d60abba919f6d481dc94a8d988cc205130724 | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/widgets/message.py#L113-L160 | train | 27,186 |
inasafe/inasafe | safe/gui/widgets/message.py | ready_message | def ready_message():
"""Helper to create a message indicating inasafe is ready.
:returns Message: A localised message indicating we are ready to run.
"""
title = m.Heading(tr('Ready'), **PROGRESS_UPDATE_STYLE)
notes = m.Paragraph(
tr('You can now proceed to run your analysis by clicking the '),
m.EmphasizedText(tr('Run'), **KEYWORD_STYLE),
tr('button.'))
message = m.Message(LOGO_ELEMENT, title, notes)
return message | python | def ready_message():
"""Helper to create a message indicating inasafe is ready.
:returns Message: A localised message indicating we are ready to run.
"""
title = m.Heading(tr('Ready'), **PROGRESS_UPDATE_STYLE)
notes = m.Paragraph(
tr('You can now proceed to run your analysis by clicking the '),
m.EmphasizedText(tr('Run'), **KEYWORD_STYLE),
tr('button.'))
message = m.Message(LOGO_ELEMENT, title, notes)
return message | [
"def",
"ready_message",
"(",
")",
":",
"title",
"=",
"m",
".",
"Heading",
"(",
"tr",
"(",
"'Ready'",
")",
",",
"*",
"*",
"PROGRESS_UPDATE_STYLE",
")",
"notes",
"=",
"m",
".",
"Paragraph",
"(",
"tr",
"(",
"'You can now proceed to run your analysis by clicking t... | Helper to create a message indicating inasafe is ready.
:returns Message: A localised message indicating we are ready to run. | [
"Helper",
"to",
"create",
"a",
"message",
"indicating",
"inasafe",
"is",
"ready",
"."
] | 831d60abba919f6d481dc94a8d988cc205130724 | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/widgets/message.py#L173-L184 | train | 27,187 |
inasafe/inasafe | safe/gui/widgets/message.py | show_keyword_version_message | def show_keyword_version_message(sender, keyword_version, inasafe_version):
"""Show a message indicating that the keywords version is mismatch
.. versionadded: 3.2
:param sender: Sender of the message signal. Default to Any object.
:type sender: object
:param keyword_version: The version of the layer's keywords
:type keyword_version: str
:param inasafe_version: The version of the InaSAFE
:type inasafe_version: str
.. note:: The print button will be disabled if this method is called.
"""
LOGGER.debug('Showing Mismatch Version Message')
message = generate_input_error_message(
tr('Layer Keyword\'s Version Mismatch:'),
m.Paragraph(
tr(
'Your layer\'s keyword\'s version ({layer_version}) does not '
'match with your InaSAFE version ({inasafe_version}). If you '
'wish to use it as an exposure, hazard, or aggregation layer '
'in an analysis, please use the keyword wizard to update the '
'keywords. You can open the wizard by clicking on '
'the ').format(
layer_version=keyword_version,
inasafe_version=inasafe_version),
m.Image(
'file:///%s/img/icons/'
'show-keyword-wizard.svg' % resources_path(),
**SMALL_ICON_STYLE),
tr(
' icon in the toolbar.'))
)
send_static_message(sender, message) | python | def show_keyword_version_message(sender, keyword_version, inasafe_version):
"""Show a message indicating that the keywords version is mismatch
.. versionadded: 3.2
:param sender: Sender of the message signal. Default to Any object.
:type sender: object
:param keyword_version: The version of the layer's keywords
:type keyword_version: str
:param inasafe_version: The version of the InaSAFE
:type inasafe_version: str
.. note:: The print button will be disabled if this method is called.
"""
LOGGER.debug('Showing Mismatch Version Message')
message = generate_input_error_message(
tr('Layer Keyword\'s Version Mismatch:'),
m.Paragraph(
tr(
'Your layer\'s keyword\'s version ({layer_version}) does not '
'match with your InaSAFE version ({inasafe_version}). If you '
'wish to use it as an exposure, hazard, or aggregation layer '
'in an analysis, please use the keyword wizard to update the '
'keywords. You can open the wizard by clicking on '
'the ').format(
layer_version=keyword_version,
inasafe_version=inasafe_version),
m.Image(
'file:///%s/img/icons/'
'show-keyword-wizard.svg' % resources_path(),
**SMALL_ICON_STYLE),
tr(
' icon in the toolbar.'))
)
send_static_message(sender, message) | [
"def",
"show_keyword_version_message",
"(",
"sender",
",",
"keyword_version",
",",
"inasafe_version",
")",
":",
"LOGGER",
".",
"debug",
"(",
"'Showing Mismatch Version Message'",
")",
"message",
"=",
"generate_input_error_message",
"(",
"tr",
"(",
"'Layer Keyword\\'s Vers... | Show a message indicating that the keywords version is mismatch
.. versionadded: 3.2
:param sender: Sender of the message signal. Default to Any object.
:type sender: object
:param keyword_version: The version of the layer's keywords
:type keyword_version: str
:param inasafe_version: The version of the InaSAFE
:type inasafe_version: str
.. note:: The print button will be disabled if this method is called. | [
"Show",
"a",
"message",
"indicating",
"that",
"the",
"keywords",
"version",
"is",
"mismatch"
] | 831d60abba919f6d481dc94a8d988cc205130724 | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/widgets/message.py#L187-L223 | train | 27,188 |
inasafe/inasafe | safe/gui/widgets/message.py | show_keywords_need_review_message | def show_keywords_need_review_message(sender, message=None):
"""Show a message keywords are not adequate to run an analysis.
.. versionadded: 4.0
:param sender: Sender of the message signal. Default to Any object.
:type sender: object
:param message: Additional message to display.
:type message: str
.. note:: The print button will be disabled if this method is called.
"""
LOGGER.debug('Showing incorrect keywords for v4 message')
message = generate_input_error_message(
tr('Layer Keywords Outdated:'),
m.Paragraph(
tr(
'Please update the keywords for your layers and then '
'try to run the analysis again. Use the keyword wizard '),
m.Image(
'file:///%s/img/icons/'
'show-keyword-wizard.svg' % resources_path(),
**SMALL_ICON_STYLE),
tr(
' icon in the toolbar to update your layer\'s keywords.'),
message)
)
send_static_message(sender, message) | python | def show_keywords_need_review_message(sender, message=None):
"""Show a message keywords are not adequate to run an analysis.
.. versionadded: 4.0
:param sender: Sender of the message signal. Default to Any object.
:type sender: object
:param message: Additional message to display.
:type message: str
.. note:: The print button will be disabled if this method is called.
"""
LOGGER.debug('Showing incorrect keywords for v4 message')
message = generate_input_error_message(
tr('Layer Keywords Outdated:'),
m.Paragraph(
tr(
'Please update the keywords for your layers and then '
'try to run the analysis again. Use the keyword wizard '),
m.Image(
'file:///%s/img/icons/'
'show-keyword-wizard.svg' % resources_path(),
**SMALL_ICON_STYLE),
tr(
' icon in the toolbar to update your layer\'s keywords.'),
message)
)
send_static_message(sender, message) | [
"def",
"show_keywords_need_review_message",
"(",
"sender",
",",
"message",
"=",
"None",
")",
":",
"LOGGER",
".",
"debug",
"(",
"'Showing incorrect keywords for v4 message'",
")",
"message",
"=",
"generate_input_error_message",
"(",
"tr",
"(",
"'Layer Keywords Outdated:'",... | Show a message keywords are not adequate to run an analysis.
.. versionadded: 4.0
:param sender: Sender of the message signal. Default to Any object.
:type sender: object
:param message: Additional message to display.
:type message: str
.. note:: The print button will be disabled if this method is called. | [
"Show",
"a",
"message",
"keywords",
"are",
"not",
"adequate",
"to",
"run",
"an",
"analysis",
"."
] | 831d60abba919f6d481dc94a8d988cc205130724 | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/widgets/message.py#L227-L255 | train | 27,189 |
inasafe/inasafe | safe/gui/widgets/message.py | generate_input_error_message | def generate_input_error_message(header, text):
"""Generate an error message with a header and a text.
:param header: The header of the message.
:type header: basestring
:param text: The text of the message.
:type text: m.Paragraph
:return: The error message ready to be displayed in the dock.
:rtype: m.Message
"""
report = m.Message()
report.add(LOGO_ELEMENT)
report.add(m.Heading(header, **WARNING_STYLE))
report.add(text)
return report | python | def generate_input_error_message(header, text):
"""Generate an error message with a header and a text.
:param header: The header of the message.
:type header: basestring
:param text: The text of the message.
:type text: m.Paragraph
:return: The error message ready to be displayed in the dock.
:rtype: m.Message
"""
report = m.Message()
report.add(LOGO_ELEMENT)
report.add(m.Heading(header, **WARNING_STYLE))
report.add(text)
return report | [
"def",
"generate_input_error_message",
"(",
"header",
",",
"text",
")",
":",
"report",
"=",
"m",
".",
"Message",
"(",
")",
"report",
".",
"add",
"(",
"LOGO_ELEMENT",
")",
"report",
".",
"add",
"(",
"m",
".",
"Heading",
"(",
"header",
",",
"*",
"*",
"... | Generate an error message with a header and a text.
:param header: The header of the message.
:type header: basestring
:param text: The text of the message.
:type text: m.Paragraph
:return: The error message ready to be displayed in the dock.
:rtype: m.Message | [
"Generate",
"an",
"error",
"message",
"with",
"a",
"header",
"and",
"a",
"text",
"."
] | 831d60abba919f6d481dc94a8d988cc205130724 | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/widgets/message.py#L284-L300 | train | 27,190 |
inasafe/inasafe | safe/gui/widgets/message.py | enable_messaging | def enable_messaging(message_viewer, sender=dispatcher.Any):
"""Set up the dispatcher for messaging.
:param message_viewer: A message viewer to show the message.
:type message_viewer: MessageViewer
:param sender: Sender of the message signal. Default to Any object.
:type sender: object
"""
# Set up dispatcher for dynamic messages
# Dynamic messages will not clear the message queue so will be appended
# to existing user messages
LOGGER.debug('enable_messaging %s %s' % (message_viewer, sender))
# noinspection PyArgumentEqualDefault
dispatcher.connect(
message_viewer.dynamic_message_event,
signal=DYNAMIC_MESSAGE_SIGNAL,
sender=sender)
# Set up dispatcher for static messages
# Static messages clear the message queue and so the display is 'reset'
# noinspection PyArgumentEqualDefault
dispatcher.connect(
message_viewer.static_message_event,
signal=STATIC_MESSAGE_SIGNAL,
sender=sender)
# Set up dispatcher for error messages
# Error messages clear the message queue and so the display is 'reset'
# noinspection PyArgumentEqualDefault
dispatcher.connect(
message_viewer.static_message_event,
signal=ERROR_MESSAGE_SIGNAL,
sender=sender) | python | def enable_messaging(message_viewer, sender=dispatcher.Any):
"""Set up the dispatcher for messaging.
:param message_viewer: A message viewer to show the message.
:type message_viewer: MessageViewer
:param sender: Sender of the message signal. Default to Any object.
:type sender: object
"""
# Set up dispatcher for dynamic messages
# Dynamic messages will not clear the message queue so will be appended
# to existing user messages
LOGGER.debug('enable_messaging %s %s' % (message_viewer, sender))
# noinspection PyArgumentEqualDefault
dispatcher.connect(
message_viewer.dynamic_message_event,
signal=DYNAMIC_MESSAGE_SIGNAL,
sender=sender)
# Set up dispatcher for static messages
# Static messages clear the message queue and so the display is 'reset'
# noinspection PyArgumentEqualDefault
dispatcher.connect(
message_viewer.static_message_event,
signal=STATIC_MESSAGE_SIGNAL,
sender=sender)
# Set up dispatcher for error messages
# Error messages clear the message queue and so the display is 'reset'
# noinspection PyArgumentEqualDefault
dispatcher.connect(
message_viewer.static_message_event,
signal=ERROR_MESSAGE_SIGNAL,
sender=sender) | [
"def",
"enable_messaging",
"(",
"message_viewer",
",",
"sender",
"=",
"dispatcher",
".",
"Any",
")",
":",
"# Set up dispatcher for dynamic messages",
"# Dynamic messages will not clear the message queue so will be appended",
"# to existing user messages",
"LOGGER",
".",
"debug",
... | Set up the dispatcher for messaging.
:param message_viewer: A message viewer to show the message.
:type message_viewer: MessageViewer
:param sender: Sender of the message signal. Default to Any object.
:type sender: object | [
"Set",
"up",
"the",
"dispatcher",
"for",
"messaging",
"."
] | 831d60abba919f6d481dc94a8d988cc205130724 | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/widgets/message.py#L303-L334 | train | 27,191 |
inasafe/inasafe | safe/gui/tools/help/options_help.py | options_help | def options_help():
"""Help message for options dialog.
.. versionadded:: 3.2.1
: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 options_help():
"""Help message for options dialog.
.. versionadded:: 3.2.1
: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",
"options_help",
"(",
")",
":",
"message",
"=",
"m",
".",
"Message",
"(",
")",
"message",
".",
"add",
"(",
"m",
".",
"Brand",
"(",
")",
")",
"message",
".",
"add",
"(",
"heading",
"(",
")",
")",
"message",
".",
"add",
"(",
"content",
"(",
... | Help message for options dialog.
.. versionadded:: 3.2.1
:returns: A message object containing helpful information.
:rtype: messaging.message.Message | [
"Help",
"message",
"for",
"options",
"dialog",
"."
] | 831d60abba919f6d481dc94a8d988cc205130724 | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/tools/help/options_help.py#L19-L32 | train | 27,192 |
inasafe/inasafe | safe/report/extractors/minimum_needs.py | minimum_needs_extractor | def minimum_needs_extractor(impact_report, component_metadata):
"""Extracting minimum needs of the impact layer.
: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 = {}
extra_args = component_metadata.extra_args
analysis_layer = impact_report.analysis
analysis_keywords = analysis_layer.keywords['inasafe_fields']
use_rounding = impact_report.impact_function.use_rounding
header = resolve_from_dictionary(extra_args, 'header')
context['header'] = header
# check if displaced is not zero
try:
displaced_field_name = analysis_keywords[displaced_field['key']]
total_displaced = value_from_field_name(
displaced_field_name, analysis_layer)
if total_displaced == 0:
zero_displaced_message = resolve_from_dictionary(
extra_args, 'zero_displaced_message')
context['zero_displaced'] = {
'status': True,
'message': zero_displaced_message
}
return context
except KeyError:
# in case no displaced field
pass
# minimum needs calculation only affect population type exposure
# check if analysis keyword have minimum_needs keywords
have_minimum_needs_field = False
for field_key in analysis_keywords:
if field_key.startswith(minimum_needs_namespace):
have_minimum_needs_field = True
break
if not have_minimum_needs_field:
return context
frequencies = {}
# map each needs to its frequency groups
for field in (minimum_needs_fields + additional_minimum_needs):
need_parameter = field.get('need_parameter')
if isinstance(need_parameter, ResourceParameter):
frequency = need_parameter.frequency
else:
frequency = field.get('frequency')
if frequency:
if frequency not in frequencies:
frequencies[frequency] = [field]
else:
frequencies[frequency].append(field)
needs = []
analysis_feature = next(analysis_layer.getFeatures())
header_frequency_format = resolve_from_dictionary(
extra_args, 'header_frequency_format')
total_header = resolve_from_dictionary(extra_args, 'total_header')
need_header_format = resolve_from_dictionary(
extra_args, 'need_header_format')
# group the needs by frequency
for key, frequency in list(frequencies.items()):
group = {
'header': header_frequency_format.format(frequency=tr(key)),
'total_header': total_header,
'needs': []
}
for field in frequency:
# check value exists in the field
field_idx = analysis_layer.fields(
).lookupField(field['field_name'])
if field_idx == -1:
# skip if field doesn't exists
continue
value = format_number(
analysis_feature[field_idx],
use_rounding=use_rounding,
is_population=True)
unit_abbreviation = ''
if field.get('need_parameter'):
need_parameter = field['need_parameter']
""":type: ResourceParameter"""
name = tr(need_parameter.name)
unit_abbreviation = need_parameter.unit.abbreviation
else:
if field.get('header_name'):
name = field.get('header_name')
else:
name = field.get('name')
need_unit = field.get('unit')
if need_unit:
unit_abbreviation = need_unit.get('abbreviation')
if unit_abbreviation:
header = need_header_format.format(
name=name,
unit_abbreviation=unit_abbreviation)
else:
header = name
item = {
'header': header,
'value': value
}
group['needs'].append(item)
needs.append(group)
context['component_key'] = component_metadata.key
context['needs'] = needs
return context | python | def minimum_needs_extractor(impact_report, component_metadata):
"""Extracting minimum needs of the impact layer.
: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 = {}
extra_args = component_metadata.extra_args
analysis_layer = impact_report.analysis
analysis_keywords = analysis_layer.keywords['inasafe_fields']
use_rounding = impact_report.impact_function.use_rounding
header = resolve_from_dictionary(extra_args, 'header')
context['header'] = header
# check if displaced is not zero
try:
displaced_field_name = analysis_keywords[displaced_field['key']]
total_displaced = value_from_field_name(
displaced_field_name, analysis_layer)
if total_displaced == 0:
zero_displaced_message = resolve_from_dictionary(
extra_args, 'zero_displaced_message')
context['zero_displaced'] = {
'status': True,
'message': zero_displaced_message
}
return context
except KeyError:
# in case no displaced field
pass
# minimum needs calculation only affect population type exposure
# check if analysis keyword have minimum_needs keywords
have_minimum_needs_field = False
for field_key in analysis_keywords:
if field_key.startswith(minimum_needs_namespace):
have_minimum_needs_field = True
break
if not have_minimum_needs_field:
return context
frequencies = {}
# map each needs to its frequency groups
for field in (minimum_needs_fields + additional_minimum_needs):
need_parameter = field.get('need_parameter')
if isinstance(need_parameter, ResourceParameter):
frequency = need_parameter.frequency
else:
frequency = field.get('frequency')
if frequency:
if frequency not in frequencies:
frequencies[frequency] = [field]
else:
frequencies[frequency].append(field)
needs = []
analysis_feature = next(analysis_layer.getFeatures())
header_frequency_format = resolve_from_dictionary(
extra_args, 'header_frequency_format')
total_header = resolve_from_dictionary(extra_args, 'total_header')
need_header_format = resolve_from_dictionary(
extra_args, 'need_header_format')
# group the needs by frequency
for key, frequency in list(frequencies.items()):
group = {
'header': header_frequency_format.format(frequency=tr(key)),
'total_header': total_header,
'needs': []
}
for field in frequency:
# check value exists in the field
field_idx = analysis_layer.fields(
).lookupField(field['field_name'])
if field_idx == -1:
# skip if field doesn't exists
continue
value = format_number(
analysis_feature[field_idx],
use_rounding=use_rounding,
is_population=True)
unit_abbreviation = ''
if field.get('need_parameter'):
need_parameter = field['need_parameter']
""":type: ResourceParameter"""
name = tr(need_parameter.name)
unit_abbreviation = need_parameter.unit.abbreviation
else:
if field.get('header_name'):
name = field.get('header_name')
else:
name = field.get('name')
need_unit = field.get('unit')
if need_unit:
unit_abbreviation = need_unit.get('abbreviation')
if unit_abbreviation:
header = need_header_format.format(
name=name,
unit_abbreviation=unit_abbreviation)
else:
header = name
item = {
'header': header,
'value': value
}
group['needs'].append(item)
needs.append(group)
context['component_key'] = component_metadata.key
context['needs'] = needs
return context | [
"def",
"minimum_needs_extractor",
"(",
"impact_report",
",",
"component_metadata",
")",
":",
"context",
"=",
"{",
"}",
"extra_args",
"=",
"component_metadata",
".",
"extra_args",
"analysis_layer",
"=",
"impact_report",
".",
"analysis",
"analysis_keywords",
"=",
"analy... | Extracting minimum needs of the impact layer.
: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",
"minimum",
"needs",
"of",
"the",
"impact",
"layer",
"."
] | 831d60abba919f6d481dc94a8d988cc205130724 | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/report/extractors/minimum_needs.py#L20-L149 | train | 27,193 |
inasafe/inasafe | safe/messaging/item/bulleted_list.py | BulletedList.to_text | def to_text(self):
"""Render a Text MessageElement as plain text.
:returns: The plain text representation of the Text MessageElement.
:rtype: basestring
"""
if self.items is None:
return
else:
text = ''
for item in self.items:
text += ' - %s\n' % item.to_text()
return text | python | def to_text(self):
"""Render a Text MessageElement as plain text.
:returns: The plain text representation of the Text MessageElement.
:rtype: basestring
"""
if self.items is None:
return
else:
text = ''
for item in self.items:
text += ' - %s\n' % item.to_text()
return text | [
"def",
"to_text",
"(",
"self",
")",
":",
"if",
"self",
".",
"items",
"is",
"None",
":",
"return",
"else",
":",
"text",
"=",
"''",
"for",
"item",
"in",
"self",
".",
"items",
":",
"text",
"+=",
"' - %s\\n'",
"%",
"item",
".",
"to_text",
"(",
")",
"... | Render a Text MessageElement as plain text.
:returns: The plain text representation of the Text MessageElement.
:rtype: basestring | [
"Render",
"a",
"Text",
"MessageElement",
"as",
"plain",
"text",
"."
] | 831d60abba919f6d481dc94a8d988cc205130724 | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/messaging/item/bulleted_list.py#L63-L76 | train | 27,194 |
inasafe/inasafe | safe/utilities/settings.py | deep_convert_dict | def deep_convert_dict(value):
"""Converts any OrderedDict elements in a value to
ordinary dictionaries, safe for storage in QSettings
:param value: value to convert
:type value: Union[dict,OrderedDict]
:return: dict
"""
to_ret = value
if isinstance(value, OrderedDict):
to_ret = dict(value)
try:
for k, v in to_ret.items():
to_ret[k] = deep_convert_dict(v)
except AttributeError:
pass
return to_ret | python | def deep_convert_dict(value):
"""Converts any OrderedDict elements in a value to
ordinary dictionaries, safe for storage in QSettings
:param value: value to convert
:type value: Union[dict,OrderedDict]
:return: dict
"""
to_ret = value
if isinstance(value, OrderedDict):
to_ret = dict(value)
try:
for k, v in to_ret.items():
to_ret[k] = deep_convert_dict(v)
except AttributeError:
pass
return to_ret | [
"def",
"deep_convert_dict",
"(",
"value",
")",
":",
"to_ret",
"=",
"value",
"if",
"isinstance",
"(",
"value",
",",
"OrderedDict",
")",
":",
"to_ret",
"=",
"dict",
"(",
"value",
")",
"try",
":",
"for",
"k",
",",
"v",
"in",
"to_ret",
".",
"items",
"(",... | Converts any OrderedDict elements in a value to
ordinary dictionaries, safe for storage in QSettings
:param value: value to convert
:type value: Union[dict,OrderedDict]
:return: dict | [
"Converts",
"any",
"OrderedDict",
"elements",
"in",
"a",
"value",
"to",
"ordinary",
"dictionaries",
"safe",
"for",
"storage",
"in",
"QSettings"
] | 831d60abba919f6d481dc94a8d988cc205130724 | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/utilities/settings.py#L20-L39 | train | 27,195 |
inasafe/inasafe | safe/utilities/settings.py | set_general_setting | def set_general_setting(key, value, qsettings=None):
"""Set value to QSettings based on key.
:param key: Unique key for setting.
:type key: basestring
:param value: Value to be saved.
:type value: QVariant
:param qsettings: A custom QSettings to use. If it's not defined, it will
use the default one.
:type qsettings: qgis.PyQt.QtCore.QSettings
"""
if not qsettings:
qsettings = QSettings()
qsettings.setValue(key, deep_convert_dict(value)) | python | def set_general_setting(key, value, qsettings=None):
"""Set value to QSettings based on key.
:param key: Unique key for setting.
:type key: basestring
:param value: Value to be saved.
:type value: QVariant
:param qsettings: A custom QSettings to use. If it's not defined, it will
use the default one.
:type qsettings: qgis.PyQt.QtCore.QSettings
"""
if not qsettings:
qsettings = QSettings()
qsettings.setValue(key, deep_convert_dict(value)) | [
"def",
"set_general_setting",
"(",
"key",
",",
"value",
",",
"qsettings",
"=",
"None",
")",
":",
"if",
"not",
"qsettings",
":",
"qsettings",
"=",
"QSettings",
"(",
")",
"qsettings",
".",
"setValue",
"(",
"key",
",",
"deep_convert_dict",
"(",
"value",
")",
... | Set value to QSettings based on key.
:param key: Unique key for setting.
:type key: basestring
:param value: Value to be saved.
:type value: QVariant
:param qsettings: A custom QSettings to use. If it's not defined, it will
use the default one.
:type qsettings: qgis.PyQt.QtCore.QSettings | [
"Set",
"value",
"to",
"QSettings",
"based",
"on",
"key",
"."
] | 831d60abba919f6d481dc94a8d988cc205130724 | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/utilities/settings.py#L42-L58 | train | 27,196 |
inasafe/inasafe | safe/utilities/settings.py | general_setting | def general_setting(key, default=None, expected_type=None, qsettings=None):
"""Helper function to get a value from settings.
:param key: Unique key for setting.
:type key: basestring
:param default: The default value in case of the key is not found or there
is an error.
:type default: basestring, None, boolean, int, float
:param expected_type: The type of object expected.
:type expected_type: type
:param qsettings: A custom QSettings to use. If it's not defined, it will
use the default one.
:type qsettings: qgis.PyQt.QtCore.QSettings
:returns: The value of the key in the setting.
:rtype: object
Note:
The API for QSettings to get a value is different for PyQt and Qt C++.
In PyQt we can specify the expected type.
See: http://pyqt.sourceforge.net/Docs/PyQt4/qsettings.html#value
"""
if qsettings is None:
qsettings = QSettings()
try:
if isinstance(expected_type, type):
return qsettings.value(key, default, type=expected_type)
else:
return qsettings.value(key, default)
except TypeError as e:
LOGGER.debug('exception %s' % e)
LOGGER.debug('%s %s %s' % (key, default, expected_type))
return qsettings.value(key, default) | python | def general_setting(key, default=None, expected_type=None, qsettings=None):
"""Helper function to get a value from settings.
:param key: Unique key for setting.
:type key: basestring
:param default: The default value in case of the key is not found or there
is an error.
:type default: basestring, None, boolean, int, float
:param expected_type: The type of object expected.
:type expected_type: type
:param qsettings: A custom QSettings to use. If it's not defined, it will
use the default one.
:type qsettings: qgis.PyQt.QtCore.QSettings
:returns: The value of the key in the setting.
:rtype: object
Note:
The API for QSettings to get a value is different for PyQt and Qt C++.
In PyQt we can specify the expected type.
See: http://pyqt.sourceforge.net/Docs/PyQt4/qsettings.html#value
"""
if qsettings is None:
qsettings = QSettings()
try:
if isinstance(expected_type, type):
return qsettings.value(key, default, type=expected_type)
else:
return qsettings.value(key, default)
except TypeError as e:
LOGGER.debug('exception %s' % e)
LOGGER.debug('%s %s %s' % (key, default, expected_type))
return qsettings.value(key, default) | [
"def",
"general_setting",
"(",
"key",
",",
"default",
"=",
"None",
",",
"expected_type",
"=",
"None",
",",
"qsettings",
"=",
"None",
")",
":",
"if",
"qsettings",
"is",
"None",
":",
"qsettings",
"=",
"QSettings",
"(",
")",
"try",
":",
"if",
"isinstance",
... | Helper function to get a value from settings.
:param key: Unique key for setting.
:type key: basestring
:param default: The default value in case of the key is not found or there
is an error.
:type default: basestring, None, boolean, int, float
:param expected_type: The type of object expected.
:type expected_type: type
:param qsettings: A custom QSettings to use. If it's not defined, it will
use the default one.
:type qsettings: qgis.PyQt.QtCore.QSettings
:returns: The value of the key in the setting.
:rtype: object
Note:
The API for QSettings to get a value is different for PyQt and Qt C++.
In PyQt we can specify the expected type.
See: http://pyqt.sourceforge.net/Docs/PyQt4/qsettings.html#value | [
"Helper",
"function",
"to",
"get",
"a",
"value",
"from",
"settings",
"."
] | 831d60abba919f6d481dc94a8d988cc205130724 | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/utilities/settings.py#L61-L97 | train | 27,197 |
inasafe/inasafe | safe/utilities/settings.py | set_setting | def set_setting(key, value, qsettings=None):
"""Set value to QSettings based on key in InaSAFE scope.
:param key: Unique key for setting.
:type key: basestring
:param value: Value to be saved.
:type value: QVariant
:param qsettings: A custom QSettings to use. If it's not defined, it will
use the default one.
:type qsettings: qgis.PyQt.QtCore.QSettings
"""
full_key = '%s/%s' % (APPLICATION_NAME, key)
set_general_setting(full_key, value, qsettings) | python | def set_setting(key, value, qsettings=None):
"""Set value to QSettings based on key in InaSAFE scope.
:param key: Unique key for setting.
:type key: basestring
:param value: Value to be saved.
:type value: QVariant
:param qsettings: A custom QSettings to use. If it's not defined, it will
use the default one.
:type qsettings: qgis.PyQt.QtCore.QSettings
"""
full_key = '%s/%s' % (APPLICATION_NAME, key)
set_general_setting(full_key, value, qsettings) | [
"def",
"set_setting",
"(",
"key",
",",
"value",
",",
"qsettings",
"=",
"None",
")",
":",
"full_key",
"=",
"'%s/%s'",
"%",
"(",
"APPLICATION_NAME",
",",
"key",
")",
"set_general_setting",
"(",
"full_key",
",",
"value",
",",
"qsettings",
")"
] | Set value to QSettings based on key in InaSAFE scope.
:param key: Unique key for setting.
:type key: basestring
:param value: Value to be saved.
:type value: QVariant
:param qsettings: A custom QSettings to use. If it's not defined, it will
use the default one.
:type qsettings: qgis.PyQt.QtCore.QSettings | [
"Set",
"value",
"to",
"QSettings",
"based",
"on",
"key",
"in",
"InaSAFE",
"scope",
"."
] | 831d60abba919f6d481dc94a8d988cc205130724 | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/utilities/settings.py#L116-L130 | train | 27,198 |
inasafe/inasafe | safe/utilities/settings.py | setting | def setting(key, default=None, expected_type=None, qsettings=None):
"""Helper function to get a value from settings under InaSAFE scope.
:param key: Unique key for setting.
:type key: basestring
:param default: The default value in case of the key is not found or there
is an error.
:type default: basestring, None, boolean, int, float
:param expected_type: The type of object expected.
:type expected_type: type
:param qsettings: A custom QSettings to use. If it's not defined, it will
use the default one.
:type qsettings: qgis.PyQt.QtCore.QSettings
:returns: The value of the key in the setting.
:rtype: object
"""
if default is None:
default = inasafe_default_settings.get(key, None)
full_key = '%s/%s' % (APPLICATION_NAME, key)
return general_setting(full_key, default, expected_type, qsettings) | python | def setting(key, default=None, expected_type=None, qsettings=None):
"""Helper function to get a value from settings under InaSAFE scope.
:param key: Unique key for setting.
:type key: basestring
:param default: The default value in case of the key is not found or there
is an error.
:type default: basestring, None, boolean, int, float
:param expected_type: The type of object expected.
:type expected_type: type
:param qsettings: A custom QSettings to use. If it's not defined, it will
use the default one.
:type qsettings: qgis.PyQt.QtCore.QSettings
:returns: The value of the key in the setting.
:rtype: object
"""
if default is None:
default = inasafe_default_settings.get(key, None)
full_key = '%s/%s' % (APPLICATION_NAME, key)
return general_setting(full_key, default, expected_type, qsettings) | [
"def",
"setting",
"(",
"key",
",",
"default",
"=",
"None",
",",
"expected_type",
"=",
"None",
",",
"qsettings",
"=",
"None",
")",
":",
"if",
"default",
"is",
"None",
":",
"default",
"=",
"inasafe_default_settings",
".",
"get",
"(",
"key",
",",
"None",
... | Helper function to get a value from settings under InaSAFE scope.
:param key: Unique key for setting.
:type key: basestring
:param default: The default value in case of the key is not found or there
is an error.
:type default: basestring, None, boolean, int, float
:param expected_type: The type of object expected.
:type expected_type: type
:param qsettings: A custom QSettings to use. If it's not defined, it will
use the default one.
:type qsettings: qgis.PyQt.QtCore.QSettings
:returns: The value of the key in the setting.
:rtype: object | [
"Helper",
"function",
"to",
"get",
"a",
"value",
"from",
"settings",
"under",
"InaSAFE",
"scope",
"."
] | 831d60abba919f6d481dc94a8d988cc205130724 | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/utilities/settings.py#L133-L156 | train | 27,199 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.