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/report/impact_report.py
ImpactReport.output_folder
def output_folder(self, value): """Output folder path for the rendering. :param value: output folder path :type value: str """ self._output_folder = value if not os.path.exists(self._output_folder): os.makedirs(self._output_folder)
python
def output_folder(self, value): """Output folder path for the rendering. :param value: output folder path :type value: str """ self._output_folder = value if not os.path.exists(self._output_folder): os.makedirs(self._output_folder)
[ "def", "output_folder", "(", "self", ",", "value", ")", ":", "self", ".", "_output_folder", "=", "value", "if", "not", "os", ".", "path", ".", "exists", "(", "self", ".", "_output_folder", ")", ":", "os", ".", "makedirs", "(", "self", ".", "_output_fol...
Output folder path for the rendering. :param value: output folder path :type value: str
[ "Output", "folder", "path", "for", "the", "rendering", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/report/impact_report.py#L368-L376
train
26,600
inasafe/inasafe
safe/report/impact_report.py
ImpactReport._check_layer_count
def _check_layer_count(self, layer): """Check for the validity of the layer. :param layer: QGIS layer :type layer: qgis.core.QgsVectorLayer :return: """ if layer: if not layer.isValid(): raise ImpactReport.LayerException('Layer is not valid') if isinstance(layer, QgsRasterLayer): # can't check feature count of raster layer return feature_count = len([f for f in layer.getFeatures()]) if feature_count == 0: raise ImpactReport.LayerException( 'Layer contains no features')
python
def _check_layer_count(self, layer): """Check for the validity of the layer. :param layer: QGIS layer :type layer: qgis.core.QgsVectorLayer :return: """ if layer: if not layer.isValid(): raise ImpactReport.LayerException('Layer is not valid') if isinstance(layer, QgsRasterLayer): # can't check feature count of raster layer return feature_count = len([f for f in layer.getFeatures()]) if feature_count == 0: raise ImpactReport.LayerException( 'Layer contains no features')
[ "def", "_check_layer_count", "(", "self", ",", "layer", ")", ":", "if", "layer", ":", "if", "not", "layer", ".", "isValid", "(", ")", ":", "raise", "ImpactReport", ".", "LayerException", "(", "'Layer is not valid'", ")", "if", "isinstance", "(", "layer", "...
Check for the validity of the layer. :param layer: QGIS layer :type layer: qgis.core.QgsVectorLayer :return:
[ "Check", "for", "the", "validity", "of", "the", "layer", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/report/impact_report.py#L455-L471
train
26,601
inasafe/inasafe
safe/report/impact_report.py
ImpactReport.map_title
def map_title(self): """Get the map title from the layer keywords if possible. :returns: None on error, otherwise the title. :rtype: None, str """ # noinspection PyBroadException try: title = self._keyword_io.read_keywords( self.impact, 'map_title') return title except KeywordNotFoundError: return None except Exception: # pylint: disable=broad-except return None
python
def map_title(self): """Get the map title from the layer keywords if possible. :returns: None on error, otherwise the title. :rtype: None, str """ # noinspection PyBroadException try: title = self._keyword_io.read_keywords( self.impact, 'map_title') return title except KeywordNotFoundError: return None except Exception: # pylint: disable=broad-except return None
[ "def", "map_title", "(", "self", ")", ":", "# noinspection PyBroadException", "try", ":", "title", "=", "self", ".", "_keyword_io", ".", "read_keywords", "(", "self", ".", "impact", ",", "'map_title'", ")", "return", "title", "except", "KeywordNotFoundError", ":...
Get the map title from the layer keywords if possible. :returns: None on error, otherwise the title. :rtype: None, str
[ "Get", "the", "map", "title", "from", "the", "layer", "keywords", "if", "possible", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/report/impact_report.py#L674-L688
train
26,602
inasafe/inasafe
safe/report/impact_report.py
ImpactReport.map_legend_attributes
def map_legend_attributes(self): """Get the map legend attribute from the layer keywords if possible. :returns: None on error, otherwise the attributes (notes and units). :rtype: None, str """ LOGGER.debug('InaSAFE Map getMapLegendAttributes called') legend_attribute_list = [ 'legend_notes', 'legend_units', 'legend_title'] legend_attribute_dict = {} for legend_attribute in legend_attribute_list: # noinspection PyBroadException try: legend_attribute_dict[legend_attribute] = \ self._keyword_io.read_keywords( self.impact, legend_attribute) except KeywordNotFoundError: pass except Exception: # pylint: disable=broad-except pass return legend_attribute_dict
python
def map_legend_attributes(self): """Get the map legend attribute from the layer keywords if possible. :returns: None on error, otherwise the attributes (notes and units). :rtype: None, str """ LOGGER.debug('InaSAFE Map getMapLegendAttributes called') legend_attribute_list = [ 'legend_notes', 'legend_units', 'legend_title'] legend_attribute_dict = {} for legend_attribute in legend_attribute_list: # noinspection PyBroadException try: legend_attribute_dict[legend_attribute] = \ self._keyword_io.read_keywords( self.impact, legend_attribute) except KeywordNotFoundError: pass except Exception: # pylint: disable=broad-except pass return legend_attribute_dict
[ "def", "map_legend_attributes", "(", "self", ")", ":", "LOGGER", ".", "debug", "(", "'InaSAFE Map getMapLegendAttributes called'", ")", "legend_attribute_list", "=", "[", "'legend_notes'", ",", "'legend_units'", ",", "'legend_title'", "]", "legend_attribute_dict", "=", ...
Get the map legend attribute from the layer keywords if possible. :returns: None on error, otherwise the attributes (notes and units). :rtype: None, str
[ "Get", "the", "map", "legend", "attribute", "from", "the", "layer", "keywords", "if", "possible", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/report/impact_report.py#L691-L713
train
26,603
inasafe/inasafe
safe/datastore/geopackage.py
GeoPackage._vector_layers
def _vector_layers(self): """Return a list of vector layers available. :return: List of vector layers available in the geopackage. :rtype: list .. versionadded:: 4.0 """ layers = [] vector_datasource = self.vector_driver.Open( self.uri.absoluteFilePath()) if vector_datasource: for i in range(vector_datasource.GetLayerCount()): layers.append(vector_datasource.GetLayer(i).GetName()) return layers
python
def _vector_layers(self): """Return a list of vector layers available. :return: List of vector layers available in the geopackage. :rtype: list .. versionadded:: 4.0 """ layers = [] vector_datasource = self.vector_driver.Open( self.uri.absoluteFilePath()) if vector_datasource: for i in range(vector_datasource.GetLayerCount()): layers.append(vector_datasource.GetLayer(i).GetName()) return layers
[ "def", "_vector_layers", "(", "self", ")", ":", "layers", "=", "[", "]", "vector_datasource", "=", "self", ".", "vector_driver", ".", "Open", "(", "self", ".", "uri", ".", "absoluteFilePath", "(", ")", ")", "if", "vector_datasource", ":", "for", "i", "in...
Return a list of vector layers available. :return: List of vector layers available in the geopackage. :rtype: list .. versionadded:: 4.0
[ "Return", "a", "list", "of", "vector", "layers", "available", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/datastore/geopackage.py#L103-L117
train
26,604
inasafe/inasafe
safe/datastore/geopackage.py
GeoPackage._raster_layers
def _raster_layers(self): """Return a list of raster layers available. :return: List of raster layers available in the geopackage. :rtype: list .. versionadded:: 4.0 """ layers = [] raster_datasource = gdal.Open(self.uri.absoluteFilePath()) if raster_datasource: subdatasets = raster_datasource.GetSubDatasets() if len(subdatasets) == 0: metadata = raster_datasource.GetMetadata() layers.append(metadata['IDENTIFIER']) else: for subdataset in subdatasets: layers.append(subdataset[0].split(':')[2]) return layers
python
def _raster_layers(self): """Return a list of raster layers available. :return: List of raster layers available in the geopackage. :rtype: list .. versionadded:: 4.0 """ layers = [] raster_datasource = gdal.Open(self.uri.absoluteFilePath()) if raster_datasource: subdatasets = raster_datasource.GetSubDatasets() if len(subdatasets) == 0: metadata = raster_datasource.GetMetadata() layers.append(metadata['IDENTIFIER']) else: for subdataset in subdatasets: layers.append(subdataset[0].split(':')[2]) return layers
[ "def", "_raster_layers", "(", "self", ")", ":", "layers", "=", "[", "]", "raster_datasource", "=", "gdal", ".", "Open", "(", "self", ".", "uri", ".", "absoluteFilePath", "(", ")", ")", "if", "raster_datasource", ":", "subdatasets", "=", "raster_datasource", ...
Return a list of raster layers available. :return: List of raster layers available in the geopackage. :rtype: list .. versionadded:: 4.0
[ "Return", "a", "list", "of", "raster", "layers", "available", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/datastore/geopackage.py#L119-L139
train
26,605
inasafe/inasafe
safe/datastore/geopackage.py
GeoPackage._add_vector_layer
def _add_vector_layer(self, vector_layer, layer_name, save_style=False): """Add a vector layer to the geopackage. :param vector_layer: The layer to add. :type vector_layer: QgsVectorLayer :param layer_name: The name of the layer in the datastore. :type layer_name: str :param save_style: If we have to save a QML too. Default to False. Not implemented in geopackage ! :type save_style: bool :returns: A two-tuple. The first element will be True if we could add the layer to the datastore. The second element will be the layer name which has been used or the error message. :rtype: (bool, str) .. versionadded:: 4.0 """ # Fixme # if not self.is_writable(): # return False, 'The destination is not writable.' geometry = QGIS_OGR_GEOMETRY_MAP[vector_layer.wkbType()] spatial_reference = osr.SpatialReference() qgis_spatial_reference = vector_layer.crs().authid() # Use 4326 as default if the spatial reference is not found epsg = 4326 epsg_string = qgis_spatial_reference if epsg_string: epsg = int(epsg_string.split(':')[1]) spatial_reference.ImportFromEPSG(epsg) vector_datasource = self.vector_driver.Open( self.uri.absoluteFilePath(), True) vector_datasource.CreateLayer(layer_name, spatial_reference, geometry) uri = '{}|layerid=0'.format(self.uri.absoluteFilePath()) vector_layer = QgsVectorLayer(uri, layer_name, 'ogr') data_provider = vector_layer.dataProvider() for feature in vector_layer.getFeatures(): data_provider.addFeatures([feature]) return True, layer_name
python
def _add_vector_layer(self, vector_layer, layer_name, save_style=False): """Add a vector layer to the geopackage. :param vector_layer: The layer to add. :type vector_layer: QgsVectorLayer :param layer_name: The name of the layer in the datastore. :type layer_name: str :param save_style: If we have to save a QML too. Default to False. Not implemented in geopackage ! :type save_style: bool :returns: A two-tuple. The first element will be True if we could add the layer to the datastore. The second element will be the layer name which has been used or the error message. :rtype: (bool, str) .. versionadded:: 4.0 """ # Fixme # if not self.is_writable(): # return False, 'The destination is not writable.' geometry = QGIS_OGR_GEOMETRY_MAP[vector_layer.wkbType()] spatial_reference = osr.SpatialReference() qgis_spatial_reference = vector_layer.crs().authid() # Use 4326 as default if the spatial reference is not found epsg = 4326 epsg_string = qgis_spatial_reference if epsg_string: epsg = int(epsg_string.split(':')[1]) spatial_reference.ImportFromEPSG(epsg) vector_datasource = self.vector_driver.Open( self.uri.absoluteFilePath(), True) vector_datasource.CreateLayer(layer_name, spatial_reference, geometry) uri = '{}|layerid=0'.format(self.uri.absoluteFilePath()) vector_layer = QgsVectorLayer(uri, layer_name, 'ogr') data_provider = vector_layer.dataProvider() for feature in vector_layer.getFeatures(): data_provider.addFeatures([feature]) return True, layer_name
[ "def", "_add_vector_layer", "(", "self", ",", "vector_layer", ",", "layer_name", ",", "save_style", "=", "False", ")", ":", "# Fixme", "# if not self.is_writable():", "# return False, 'The destination is not writable.'", "geometry", "=", "QGIS_OGR_GEOMETRY_MAP", "[", "ve...
Add a vector layer to the geopackage. :param vector_layer: The layer to add. :type vector_layer: QgsVectorLayer :param layer_name: The name of the layer in the datastore. :type layer_name: str :param save_style: If we have to save a QML too. Default to False. Not implemented in geopackage ! :type save_style: bool :returns: A two-tuple. The first element will be True if we could add the layer to the datastore. The second element will be the layer name which has been used or the error message. :rtype: (bool, str) .. versionadded:: 4.0
[ "Add", "a", "vector", "layer", "to", "the", "geopackage", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/datastore/geopackage.py#L182-L228
train
26,606
inasafe/inasafe
safe/datastore/geopackage.py
GeoPackage._add_tabular_layer
def _add_tabular_layer(self, tabular_layer, layer_name, save_style=False): """Add a tabular layer to the geopackage. :param tabular_layer: The layer to add. :type tabular_layer: QgsVectorLayer :param layer_name: The name of the layer in the datastore. :type layer_name: str :param save_style: If we have to save a QML too. Default to False. Not implemented in geopackage ! :type save_style: bool :returns: A two-tuple. The first element will be True if we could add the layer to the datastore. The second element will be the layer name which has been used or the error message. :rtype: (bool, str) .. versionadded:: 4.0 """ return self._add_vector_layer(tabular_layer, layer_name, save_style)
python
def _add_tabular_layer(self, tabular_layer, layer_name, save_style=False): """Add a tabular layer to the geopackage. :param tabular_layer: The layer to add. :type tabular_layer: QgsVectorLayer :param layer_name: The name of the layer in the datastore. :type layer_name: str :param save_style: If we have to save a QML too. Default to False. Not implemented in geopackage ! :type save_style: bool :returns: A two-tuple. The first element will be True if we could add the layer to the datastore. The second element will be the layer name which has been used or the error message. :rtype: (bool, str) .. versionadded:: 4.0 """ return self._add_vector_layer(tabular_layer, layer_name, save_style)
[ "def", "_add_tabular_layer", "(", "self", ",", "tabular_layer", ",", "layer_name", ",", "save_style", "=", "False", ")", ":", "return", "self", ".", "_add_vector_layer", "(", "tabular_layer", ",", "layer_name", ",", "save_style", ")" ]
Add a tabular layer to the geopackage. :param tabular_layer: The layer to add. :type tabular_layer: QgsVectorLayer :param layer_name: The name of the layer in the datastore. :type layer_name: str :param save_style: If we have to save a QML too. Default to False. Not implemented in geopackage ! :type save_style: bool :returns: A two-tuple. The first element will be True if we could add the layer to the datastore. The second element will be the layer name which has been used or the error message. :rtype: (bool, str) .. versionadded:: 4.0
[ "Add", "a", "tabular", "layer", "to", "the", "geopackage", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/datastore/geopackage.py#L275-L295
train
26,607
inasafe/inasafe
safe/gui/tools/wizard/step_fc20_hazlayer_from_canvas.py
StepFcHazLayerFromCanvas.selected_canvas_hazlayer
def selected_canvas_hazlayer(self): """Obtain the canvas layer selected by user. :returns: The currently selected map layer in the list. :rtype: QgsMapLayer """ if self.lstCanvasHazLayers.selectedItems(): item = self.lstCanvasHazLayers.currentItem() else: return None try: layer_id = item.data(Qt.UserRole) except (AttributeError, NameError): layer_id = None # noinspection PyArgumentList layer = QgsProject.instance().mapLayer(layer_id) return layer
python
def selected_canvas_hazlayer(self): """Obtain the canvas layer selected by user. :returns: The currently selected map layer in the list. :rtype: QgsMapLayer """ if self.lstCanvasHazLayers.selectedItems(): item = self.lstCanvasHazLayers.currentItem() else: return None try: layer_id = item.data(Qt.UserRole) except (AttributeError, NameError): layer_id = None # noinspection PyArgumentList layer = QgsProject.instance().mapLayer(layer_id) return layer
[ "def", "selected_canvas_hazlayer", "(", "self", ")", ":", "if", "self", ".", "lstCanvasHazLayers", ".", "selectedItems", "(", ")", ":", "item", "=", "self", ".", "lstCanvasHazLayers", ".", "currentItem", "(", ")", "else", ":", "return", "None", "try", ":", ...
Obtain the canvas layer selected by user. :returns: The currently selected map layer in the list. :rtype: QgsMapLayer
[ "Obtain", "the", "canvas", "layer", "selected", "by", "user", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/tools/wizard/step_fc20_hazlayer_from_canvas.py#L72-L90
train
26,608
inasafe/inasafe
safe/gui/tools/wizard/step_fc20_hazlayer_from_canvas.py
StepFcHazLayerFromCanvas.list_compatible_canvas_layers
def list_compatible_canvas_layers(self): """Fill the list widget with compatible layers. :returns: Metadata of found layers. :rtype: list of dicts """ italic_font = QFont() italic_font.setItalic(True) list_widget = self.lstCanvasHazLayers # Add compatible layers list_widget.clear() for layer in self.parent.get_compatible_canvas_layers('hazard'): item = QListWidgetItem(layer['name'], list_widget) item.setData(Qt.UserRole, layer['id']) if not layer['keywords']: item.setFont(italic_font) list_widget.addItem(item)
python
def list_compatible_canvas_layers(self): """Fill the list widget with compatible layers. :returns: Metadata of found layers. :rtype: list of dicts """ italic_font = QFont() italic_font.setItalic(True) list_widget = self.lstCanvasHazLayers # Add compatible layers list_widget.clear() for layer in self.parent.get_compatible_canvas_layers('hazard'): item = QListWidgetItem(layer['name'], list_widget) item.setData(Qt.UserRole, layer['id']) if not layer['keywords']: item.setFont(italic_font) list_widget.addItem(item)
[ "def", "list_compatible_canvas_layers", "(", "self", ")", ":", "italic_font", "=", "QFont", "(", ")", "italic_font", ".", "setItalic", "(", "True", ")", "list_widget", "=", "self", ".", "lstCanvasHazLayers", "# Add compatible layers", "list_widget", ".", "clear", ...
Fill the list widget with compatible layers. :returns: Metadata of found layers. :rtype: list of dicts
[ "Fill", "the", "list", "widget", "with", "compatible", "layers", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/tools/wizard/step_fc20_hazlayer_from_canvas.py#L92-L108
train
26,609
inasafe/inasafe
safe/gui/tools/wizard/step_fc20_hazlayer_from_canvas.py
StepFcHazLayerFromCanvas.set_widgets
def set_widgets(self): """Set widgets on the Hazard Layer From TOC tab.""" # The list is already populated in the previous step, but now we # need to do it again in case we're back from the Keyword Wizard. # First, preserve self.parent.layer before clearing the list last_layer = self.parent.layer and self.parent.layer.id() or None self.lblDescribeCanvasHazLayer.clear() self.list_compatible_canvas_layers() self.auto_select_one_item(self.lstCanvasHazLayers) # Try to select the last_layer, if found: if last_layer: layers = [] for index in range(self.lstCanvasHazLayers.count()): item = self.lstCanvasHazLayers.item(index) layers += [item.data(Qt.UserRole)] if last_layer in layers: self.lstCanvasHazLayers.setCurrentRow(layers.index(last_layer)) # Set icon hazard = self.parent.step_fc_functions1.selected_value( layer_purpose_hazard['key']) icon_path = get_image_path(hazard) self.lblIconIFCWHazardFromCanvas.setPixmap(QPixmap(icon_path))
python
def set_widgets(self): """Set widgets on the Hazard Layer From TOC tab.""" # The list is already populated in the previous step, but now we # need to do it again in case we're back from the Keyword Wizard. # First, preserve self.parent.layer before clearing the list last_layer = self.parent.layer and self.parent.layer.id() or None self.lblDescribeCanvasHazLayer.clear() self.list_compatible_canvas_layers() self.auto_select_one_item(self.lstCanvasHazLayers) # Try to select the last_layer, if found: if last_layer: layers = [] for index in range(self.lstCanvasHazLayers.count()): item = self.lstCanvasHazLayers.item(index) layers += [item.data(Qt.UserRole)] if last_layer in layers: self.lstCanvasHazLayers.setCurrentRow(layers.index(last_layer)) # Set icon hazard = self.parent.step_fc_functions1.selected_value( layer_purpose_hazard['key']) icon_path = get_image_path(hazard) self.lblIconIFCWHazardFromCanvas.setPixmap(QPixmap(icon_path))
[ "def", "set_widgets", "(", "self", ")", ":", "# The list is already populated in the previous step, but now we", "# need to do it again in case we're back from the Keyword Wizard.", "# First, preserve self.parent.layer before clearing the list", "last_layer", "=", "self", ".", "parent", ...
Set widgets on the Hazard Layer From TOC tab.
[ "Set", "widgets", "on", "the", "Hazard", "Layer", "From", "TOC", "tab", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/tools/wizard/step_fc20_hazlayer_from_canvas.py#L110-L132
train
26,610
inasafe/inasafe
safe/impact_function/impact_function.py
ImpactFunction.performance_log_message
def performance_log_message(self): """Return the profiling log as a message.""" message = m.Message() table = m.Table(style_class='table table-condensed table-striped') row = m.Row() row.add(m.Cell(tr('Function'), header=True)) row.add(m.Cell(tr('Time'), header=True)) if setting(key='memory_profile', expected_type=bool): row.add(m.Cell(tr('Memory'), header=True)) table.add(row) if self.performance_log is None: message.add(table) return message indent = -1 def display_tree(tree, space): space += 1 new_row = m.Row() # This is a kind of hack to display the tree with indentation text = '|' text += '*' * space if tree.children: text += '\ ' else: text += '| ' text += tree.__str__() busy = tr('Busy') new_row.add(m.Cell(text)) time = tree.elapsed_time if time is None: time = busy new_row.add(m.Cell(time)) if setting(key='memory_profile', expected_type=bool): memory_used = tree.memory_used if memory_used is None: memory_used = busy new_row.add(m.Cell(memory_used)) table.add(new_row) if tree.children: for child in tree.children: display_tree(child, space) space -= 1 # noinspection PyTypeChecker display_tree(self.performance_log, indent) message.add(table) return message
python
def performance_log_message(self): """Return the profiling log as a message.""" message = m.Message() table = m.Table(style_class='table table-condensed table-striped') row = m.Row() row.add(m.Cell(tr('Function'), header=True)) row.add(m.Cell(tr('Time'), header=True)) if setting(key='memory_profile', expected_type=bool): row.add(m.Cell(tr('Memory'), header=True)) table.add(row) if self.performance_log is None: message.add(table) return message indent = -1 def display_tree(tree, space): space += 1 new_row = m.Row() # This is a kind of hack to display the tree with indentation text = '|' text += '*' * space if tree.children: text += '\ ' else: text += '| ' text += tree.__str__() busy = tr('Busy') new_row.add(m.Cell(text)) time = tree.elapsed_time if time is None: time = busy new_row.add(m.Cell(time)) if setting(key='memory_profile', expected_type=bool): memory_used = tree.memory_used if memory_used is None: memory_used = busy new_row.add(m.Cell(memory_used)) table.add(new_row) if tree.children: for child in tree.children: display_tree(child, space) space -= 1 # noinspection PyTypeChecker display_tree(self.performance_log, indent) message.add(table) return message
[ "def", "performance_log_message", "(", "self", ")", ":", "message", "=", "m", ".", "Message", "(", ")", "table", "=", "m", ".", "Table", "(", "style_class", "=", "'table table-condensed table-striped'", ")", "row", "=", "m", ".", "Row", "(", ")", "row", ...
Return the profiling log as a message.
[ "Return", "the", "profiling", "log", "as", "a", "message", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/impact_function/impact_function.py#L461-L513
train
26,611
inasafe/inasafe
safe/impact_function/impact_function.py
ImpactFunction.requested_extent
def requested_extent(self, extent): """Setter for extent property. :param extent: Analysis boundaries expressed as a QgsRectangle. The extent CRS should match the crs property of this IF instance. :type extent: QgsRectangle """ if isinstance(extent, QgsRectangle): self._requested_extent = extent self._is_ready = False else: raise InvalidExtentError('%s is not a valid extent.' % extent)
python
def requested_extent(self, extent): """Setter for extent property. :param extent: Analysis boundaries expressed as a QgsRectangle. The extent CRS should match the crs property of this IF instance. :type extent: QgsRectangle """ if isinstance(extent, QgsRectangle): self._requested_extent = extent self._is_ready = False else: raise InvalidExtentError('%s is not a valid extent.' % extent)
[ "def", "requested_extent", "(", "self", ",", "extent", ")", ":", "if", "isinstance", "(", "extent", ",", "QgsRectangle", ")", ":", "self", ".", "_requested_extent", "=", "extent", "self", ".", "_is_ready", "=", "False", "else", ":", "raise", "InvalidExtentEr...
Setter for extent property. :param extent: Analysis boundaries expressed as a QgsRectangle. The extent CRS should match the crs property of this IF instance. :type extent: QgsRectangle
[ "Setter", "for", "extent", "property", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/impact_function/impact_function.py#L748-L760
train
26,612
inasafe/inasafe
safe/impact_function/impact_function.py
ImpactFunction.crs
def crs(self, crs): """Setter for extent_crs property. :param crs: The coordinate reference system for the analysis boundary. :type crs: QgsCoordinateReferenceSystem """ if isinstance(crs, QgsCoordinateReferenceSystem): self._crs = crs self._is_ready = False else: raise InvalidExtentError('%s is not a valid CRS object.' % crs)
python
def crs(self, crs): """Setter for extent_crs property. :param crs: The coordinate reference system for the analysis boundary. :type crs: QgsCoordinateReferenceSystem """ if isinstance(crs, QgsCoordinateReferenceSystem): self._crs = crs self._is_ready = False else: raise InvalidExtentError('%s is not a valid CRS object.' % crs)
[ "def", "crs", "(", "self", ",", "crs", ")", ":", "if", "isinstance", "(", "crs", ",", "QgsCoordinateReferenceSystem", ")", ":", "self", ".", "_crs", "=", "crs", "self", ".", "_is_ready", "=", "False", "else", ":", "raise", "InvalidExtentError", "(", "'%s...
Setter for extent_crs property. :param crs: The coordinate reference system for the analysis boundary. :type crs: QgsCoordinateReferenceSystem
[ "Setter", "for", "extent_crs", "property", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/impact_function/impact_function.py#L775-L785
train
26,613
inasafe/inasafe
safe/impact_function/impact_function.py
ImpactFunction.datastore
def datastore(self, datastore): """Setter for the datastore. :param datastore: The datastore. :type datastore: DataStore """ if isinstance(datastore, DataStore): self._datastore = datastore else: raise Exception('%s is not a valid datastore.' % datastore)
python
def datastore(self, datastore): """Setter for the datastore. :param datastore: The datastore. :type datastore: DataStore """ if isinstance(datastore, DataStore): self._datastore = datastore else: raise Exception('%s is not a valid datastore.' % datastore)
[ "def", "datastore", "(", "self", ",", "datastore", ")", ":", "if", "isinstance", "(", "datastore", ",", "DataStore", ")", ":", "self", ".", "_datastore", "=", "datastore", "else", ":", "raise", "Exception", "(", "'%s is not a valid datastore.'", "%", "datastor...
Setter for the datastore. :param datastore: The datastore. :type datastore: DataStore
[ "Setter", "for", "the", "datastore", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/impact_function/impact_function.py#L806-L815
train
26,614
inasafe/inasafe
safe/impact_function/impact_function.py
ImpactFunction.duration
def duration(self): """The duration of running the impact function in seconds. Return 0 if the start or end datetime is None. :return: The duration. :rtype: float """ if self.end_datetime is None or self.start_datetime is None: return 0 return (self.end_datetime - self.start_datetime).total_seconds()
python
def duration(self): """The duration of running the impact function in seconds. Return 0 if the start or end datetime is None. :return: The duration. :rtype: float """ if self.end_datetime is None or self.start_datetime is None: return 0 return (self.end_datetime - self.start_datetime).total_seconds()
[ "def", "duration", "(", "self", ")", ":", "if", "self", ".", "end_datetime", "is", "None", "or", "self", ".", "start_datetime", "is", "None", ":", "return", "0", "return", "(", "self", ".", "end_datetime", "-", "self", ".", "start_datetime", ")", ".", ...
The duration of running the impact function in seconds. Return 0 if the start or end datetime is None. :return: The duration. :rtype: float
[ "The", "duration", "of", "running", "the", "impact", "function", "in", "seconds", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/impact_function/impact_function.py#L854-L864
train
26,615
inasafe/inasafe
safe/impact_function/impact_function.py
ImpactFunction.console_progress_callback
def console_progress_callback(current, maximum, message=None): """Simple console based callback implementation for tests. :param current: Current progress. :type current: int :param maximum: Maximum range (point at which task is complete. :type maximum: int :param message: Optional message dictionary to containing content we can display to the user. See safe.definitions.analysis_steps for an example of the expected format :type message: dict """ # noinspection PyChainedComparisons if maximum > 1000 and current % 1000 != 0 and current != maximum: return if message is not None: LOGGER.info(message['description']) LOGGER.info('Task progress: %i of %i' % (current, maximum))
python
def console_progress_callback(current, maximum, message=None): """Simple console based callback implementation for tests. :param current: Current progress. :type current: int :param maximum: Maximum range (point at which task is complete. :type maximum: int :param message: Optional message dictionary to containing content we can display to the user. See safe.definitions.analysis_steps for an example of the expected format :type message: dict """ # noinspection PyChainedComparisons if maximum > 1000 and current % 1000 != 0 and current != maximum: return if message is not None: LOGGER.info(message['description']) LOGGER.info('Task progress: %i of %i' % (current, maximum))
[ "def", "console_progress_callback", "(", "current", ",", "maximum", ",", "message", "=", "None", ")", ":", "# noinspection PyChainedComparisons", "if", "maximum", ">", "1000", "and", "current", "%", "1000", "!=", "0", "and", "current", "!=", "maximum", ":", "r...
Simple console based callback implementation for tests. :param current: Current progress. :type current: int :param maximum: Maximum range (point at which task is complete. :type maximum: int :param message: Optional message dictionary to containing content we can display to the user. See safe.definitions.analysis_steps for an example of the expected format :type message: dict
[ "Simple", "console", "based", "callback", "implementation", "for", "tests", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/impact_function/impact_function.py#L909-L928
train
26,616
inasafe/inasafe
safe/impact_function/impact_function.py
ImpactFunction.set_state_process
def set_state_process(self, context, process): """Method to append process for a context in the IF state. :param context: It can be a layer purpose or a section (impact function, post processor). :type context: str, unicode :param process: A text explain the process. :type process: str, unicode """ LOGGER.info('%s: %s' % (context, process)) self.state[context]["process"].append(process)
python
def set_state_process(self, context, process): """Method to append process for a context in the IF state. :param context: It can be a layer purpose or a section (impact function, post processor). :type context: str, unicode :param process: A text explain the process. :type process: str, unicode """ LOGGER.info('%s: %s' % (context, process)) self.state[context]["process"].append(process)
[ "def", "set_state_process", "(", "self", ",", "context", ",", "process", ")", ":", "LOGGER", ".", "info", "(", "'%s: %s'", "%", "(", "context", ",", "process", ")", ")", "self", ".", "state", "[", "context", "]", "[", "\"process\"", "]", ".", "append",...
Method to append process for a context in the IF state. :param context: It can be a layer purpose or a section (impact function, post processor). :type context: str, unicode :param process: A text explain the process. :type process: str, unicode
[ "Method", "to", "append", "process", "for", "a", "context", "in", "the", "IF", "state", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/impact_function/impact_function.py#L959-L970
train
26,617
inasafe/inasafe
safe/impact_function/impact_function.py
ImpactFunction.set_state_info
def set_state_info(self, context, key, value): """Method to add information for a context in the IF state. :param context: It can be a layer purpose or a section (impact function, post processor). :type context: str, unicode :param key: A key for the information, e.g. algorithm. :type key: str, unicode :param value: The value of the information. E.g point :type value: str, unicode, int, float, bool, list, dict """ LOGGER.info('%s: %s: %s' % (context, key, value)) self.state[context]["info"][key] = value
python
def set_state_info(self, context, key, value): """Method to add information for a context in the IF state. :param context: It can be a layer purpose or a section (impact function, post processor). :type context: str, unicode :param key: A key for the information, e.g. algorithm. :type key: str, unicode :param value: The value of the information. E.g point :type value: str, unicode, int, float, bool, list, dict """ LOGGER.info('%s: %s: %s' % (context, key, value)) self.state[context]["info"][key] = value
[ "def", "set_state_info", "(", "self", ",", "context", ",", "key", ",", "value", ")", ":", "LOGGER", ".", "info", "(", "'%s: %s: %s'", "%", "(", "context", ",", "key", ",", "value", ")", ")", "self", ".", "state", "[", "context", "]", "[", "\"info\"",...
Method to add information for a context in the IF state. :param context: It can be a layer purpose or a section (impact function, post processor). :type context: str, unicode :param key: A key for the information, e.g. algorithm. :type key: str, unicode :param value: The value of the information. E.g point :type value: str, unicode, int, float, bool, list, dict
[ "Method", "to", "add", "information", "for", "a", "context", "in", "the", "IF", "state", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/impact_function/impact_function.py#L972-L986
train
26,618
inasafe/inasafe
safe/impact_function/impact_function.py
ImpactFunction.debug_layer
def debug_layer(self, layer, check_fields=True, add_to_datastore=None): """Write the layer produced to the datastore if debug mode is on. :param layer: The QGIS layer to check and save. :type layer: QgsMapLayer :param check_fields: Boolean to check or not inasafe_fields. By default, it's true. :type check_fields: bool :param add_to_datastore: Boolean if we need to store the layer. This parameter will overwrite the debug mode behaviour. Default to None, we usually let debug mode choose for us. :param add_to_datastore: bool :return: The name of the layer added in the datastore. :rtype: basestring """ # This one checks the memory layer. check_layer(layer, has_geometry=None) if isinstance(layer, QgsVectorLayer) and check_fields: is_geojson = '.geojson' in layer.source().lower() if layer.featureCount() == 0 and is_geojson: # https://issues.qgis.org/issues/18370 # We can't check a geojson file with 0 feature. pass else: check_inasafe_fields(layer) # Be careful, add_to_datastore can be None, True or False. # None means we let debug_mode to choose for us. # If add_to_datastore is not None, we do not care about debug_mode. if isinstance(add_to_datastore, bool) and add_to_datastore: save_layer = True elif isinstance(add_to_datastore, bool) and not add_to_datastore: save_layer = False elif self.debug_mode: save_layer = True else: save_layer = False if save_layer: result, name = self.datastore.add_layer( layer, layer.keywords['title']) if not result: raise Exception( 'Something went wrong with the datastore : {error_message}' .format(error_message=name)) if self.debug_mode: # This one checks the GeoJSON file. We noticed some difference # between checking a memory layer and a file based layer. check_layer(self.datastore.layer(name)) return name
python
def debug_layer(self, layer, check_fields=True, add_to_datastore=None): """Write the layer produced to the datastore if debug mode is on. :param layer: The QGIS layer to check and save. :type layer: QgsMapLayer :param check_fields: Boolean to check or not inasafe_fields. By default, it's true. :type check_fields: bool :param add_to_datastore: Boolean if we need to store the layer. This parameter will overwrite the debug mode behaviour. Default to None, we usually let debug mode choose for us. :param add_to_datastore: bool :return: The name of the layer added in the datastore. :rtype: basestring """ # This one checks the memory layer. check_layer(layer, has_geometry=None) if isinstance(layer, QgsVectorLayer) and check_fields: is_geojson = '.geojson' in layer.source().lower() if layer.featureCount() == 0 and is_geojson: # https://issues.qgis.org/issues/18370 # We can't check a geojson file with 0 feature. pass else: check_inasafe_fields(layer) # Be careful, add_to_datastore can be None, True or False. # None means we let debug_mode to choose for us. # If add_to_datastore is not None, we do not care about debug_mode. if isinstance(add_to_datastore, bool) and add_to_datastore: save_layer = True elif isinstance(add_to_datastore, bool) and not add_to_datastore: save_layer = False elif self.debug_mode: save_layer = True else: save_layer = False if save_layer: result, name = self.datastore.add_layer( layer, layer.keywords['title']) if not result: raise Exception( 'Something went wrong with the datastore : {error_message}' .format(error_message=name)) if self.debug_mode: # This one checks the GeoJSON file. We noticed some difference # between checking a memory layer and a file based layer. check_layer(self.datastore.layer(name)) return name
[ "def", "debug_layer", "(", "self", ",", "layer", ",", "check_fields", "=", "True", ",", "add_to_datastore", "=", "None", ")", ":", "# This one checks the memory layer.", "check_layer", "(", "layer", ",", "has_geometry", "=", "None", ")", "if", "isinstance", "(",...
Write the layer produced to the datastore if debug mode is on. :param layer: The QGIS layer to check and save. :type layer: QgsMapLayer :param check_fields: Boolean to check or not inasafe_fields. By default, it's true. :type check_fields: bool :param add_to_datastore: Boolean if we need to store the layer. This parameter will overwrite the debug mode behaviour. Default to None, we usually let debug mode choose for us. :param add_to_datastore: bool :return: The name of the layer added in the datastore. :rtype: basestring
[ "Write", "the", "layer", "produced", "to", "the", "datastore", "if", "debug", "mode", "is", "on", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/impact_function/impact_function.py#L1369-L1423
train
26,619
inasafe/inasafe
safe/impact_function/impact_function.py
ImpactFunction.pre_process
def pre_process(self): """Run every pre-processors. Preprocessors are creating new layers with a specific layer_purpose. This layer is added then to the datastore. :return: Nothing """ LOGGER.info('ANALYSIS : Pre processing') for pre_processor in self._preprocessors: layer = pre_processor['process']['function'](self) purpose = pre_processor['output'].get('value')['key'] save_style = pre_processor['output'].get('save_style', False) result, name = self.datastore.add_layer(layer, purpose, save_style) if not result: raise Exception( tr('Something went wrong with the datastore : ' '{error_message}').format(error_message=name)) layer = self.datastore.layer(name) self._preprocessors_layers[purpose] = layer self.debug_layer(layer, add_to_datastore=False) self.set_state_process('pre_processor', pre_processor['name']) LOGGER.info('{name} : Running'.format(name=pre_processor['name']))
python
def pre_process(self): """Run every pre-processors. Preprocessors are creating new layers with a specific layer_purpose. This layer is added then to the datastore. :return: Nothing """ LOGGER.info('ANALYSIS : Pre processing') for pre_processor in self._preprocessors: layer = pre_processor['process']['function'](self) purpose = pre_processor['output'].get('value')['key'] save_style = pre_processor['output'].get('save_style', False) result, name = self.datastore.add_layer(layer, purpose, save_style) if not result: raise Exception( tr('Something went wrong with the datastore : ' '{error_message}').format(error_message=name)) layer = self.datastore.layer(name) self._preprocessors_layers[purpose] = layer self.debug_layer(layer, add_to_datastore=False) self.set_state_process('pre_processor', pre_processor['name']) LOGGER.info('{name} : Running'.format(name=pre_processor['name']))
[ "def", "pre_process", "(", "self", ")", ":", "LOGGER", ".", "info", "(", "'ANALYSIS : Pre processing'", ")", "for", "pre_processor", "in", "self", ".", "_preprocessors", ":", "layer", "=", "pre_processor", "[", "'process'", "]", "[", "'function'", "]", "(", ...
Run every pre-processors. Preprocessors are creating new layers with a specific layer_purpose. This layer is added then to the datastore. :return: Nothing
[ "Run", "every", "pre", "-", "processors", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/impact_function/impact_function.py#L1878-L1902
train
26,620
inasafe/inasafe
safe/impact_function/impact_function.py
ImpactFunction.hazard_preparation
def hazard_preparation(self): """This function is doing the hazard preparation.""" LOGGER.info('ANALYSIS : Hazard preparation') use_same_projection = ( self.hazard.crs().authid() == self._crs.authid()) self.set_state_info( 'hazard', 'use_same_projection_as_aggregation', use_same_projection) if is_raster_layer(self.hazard): extent = self._analysis_impacted.extent() if not use_same_projection: transform = QgsCoordinateTransform( self._crs, self.hazard.crs(), QgsProject.instance()) extent = transform.transform(extent) self.set_state_process( 'hazard', 'Clip raster by analysis bounding box') # noinspection PyTypeChecker self.hazard = clip_by_extent(self.hazard, extent) self.debug_layer(self.hazard) if self.hazard.keywords.get('layer_mode') == 'continuous': self.set_state_process( 'hazard', 'Classify continuous raster hazard') # noinspection PyTypeChecker self.hazard = reclassify_raster( self.hazard, self.exposure.keywords['exposure']) self.debug_layer(self.hazard) self.set_state_process( 'hazard', 'Polygonize classified raster hazard') # noinspection PyTypeChecker self.hazard = polygonize(self.hazard) self.debug_layer(self.hazard) if not use_same_projection: self.set_state_process( 'hazard', 'Reproject hazard layer to aggregation CRS') # noinspection PyTypeChecker self.hazard = reproject(self.hazard, self._crs) self.debug_layer(self.hazard, check_fields=False) self.set_state_process( 'hazard', 'Clip and mask hazard polygons with the analysis layer') self.hazard = clip(self.hazard, self._analysis_impacted) self.debug_layer(self.hazard, check_fields=False) self.set_state_process( 'hazard', 'Cleaning the vector hazard attribute table') # noinspection PyTypeChecker self.hazard = prepare_vector_layer(self.hazard) self.debug_layer(self.hazard) if self.hazard.keywords.get('layer_mode') == 'continuous': # If the layer is continuous, we update the original data to the # inasafe hazard class. self.set_state_process( 'hazard', 'Classify continuous hazard and assign class names') self.hazard = reclassify_vector( self.hazard, self.exposure.keywords['exposure']) self.debug_layer(self.hazard) else: # However, if it's a classified dataset, we only transpose the # value map using inasafe hazard classes. self.set_state_process( 'hazard', 'Assign classes based on value map') self.hazard = update_value_map( self.hazard, self.exposure.keywords['exposure']) self.debug_layer(self.hazard)
python
def hazard_preparation(self): """This function is doing the hazard preparation.""" LOGGER.info('ANALYSIS : Hazard preparation') use_same_projection = ( self.hazard.crs().authid() == self._crs.authid()) self.set_state_info( 'hazard', 'use_same_projection_as_aggregation', use_same_projection) if is_raster_layer(self.hazard): extent = self._analysis_impacted.extent() if not use_same_projection: transform = QgsCoordinateTransform( self._crs, self.hazard.crs(), QgsProject.instance()) extent = transform.transform(extent) self.set_state_process( 'hazard', 'Clip raster by analysis bounding box') # noinspection PyTypeChecker self.hazard = clip_by_extent(self.hazard, extent) self.debug_layer(self.hazard) if self.hazard.keywords.get('layer_mode') == 'continuous': self.set_state_process( 'hazard', 'Classify continuous raster hazard') # noinspection PyTypeChecker self.hazard = reclassify_raster( self.hazard, self.exposure.keywords['exposure']) self.debug_layer(self.hazard) self.set_state_process( 'hazard', 'Polygonize classified raster hazard') # noinspection PyTypeChecker self.hazard = polygonize(self.hazard) self.debug_layer(self.hazard) if not use_same_projection: self.set_state_process( 'hazard', 'Reproject hazard layer to aggregation CRS') # noinspection PyTypeChecker self.hazard = reproject(self.hazard, self._crs) self.debug_layer(self.hazard, check_fields=False) self.set_state_process( 'hazard', 'Clip and mask hazard polygons with the analysis layer') self.hazard = clip(self.hazard, self._analysis_impacted) self.debug_layer(self.hazard, check_fields=False) self.set_state_process( 'hazard', 'Cleaning the vector hazard attribute table') # noinspection PyTypeChecker self.hazard = prepare_vector_layer(self.hazard) self.debug_layer(self.hazard) if self.hazard.keywords.get('layer_mode') == 'continuous': # If the layer is continuous, we update the original data to the # inasafe hazard class. self.set_state_process( 'hazard', 'Classify continuous hazard and assign class names') self.hazard = reclassify_vector( self.hazard, self.exposure.keywords['exposure']) self.debug_layer(self.hazard) else: # However, if it's a classified dataset, we only transpose the # value map using inasafe hazard classes. self.set_state_process( 'hazard', 'Assign classes based on value map') self.hazard = update_value_map( self.hazard, self.exposure.keywords['exposure']) self.debug_layer(self.hazard)
[ "def", "hazard_preparation", "(", "self", ")", ":", "LOGGER", ".", "info", "(", "'ANALYSIS : Hazard preparation'", ")", "use_same_projection", "=", "(", "self", ".", "hazard", ".", "crs", "(", ")", ".", "authid", "(", ")", "==", "self", ".", "_crs", ".", ...
This function is doing the hazard preparation.
[ "This", "function", "is", "doing", "the", "hazard", "preparation", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/impact_function/impact_function.py#L2129-L2205
train
26,621
inasafe/inasafe
safe/impact_function/impact_function.py
ImpactFunction.aggregate_hazard_preparation
def aggregate_hazard_preparation(self): """This function is doing the aggregate hazard layer. It will prepare the aggregate layer and intersect hazard polygons with aggregation areas and assign hazard class. """ LOGGER.info('ANALYSIS : Aggregate hazard preparation') self.set_state_process('hazard', 'Make hazard layer valid') self.hazard = clean_layer(self.hazard) self.debug_layer(self.hazard) self.set_state_process( 'aggregation', 'Union hazard polygons with aggregation areas and assign ' 'hazard class') self._aggregate_hazard_impacted = union(self.hazard, self.aggregation) self.debug_layer(self._aggregate_hazard_impacted)
python
def aggregate_hazard_preparation(self): """This function is doing the aggregate hazard layer. It will prepare the aggregate layer and intersect hazard polygons with aggregation areas and assign hazard class. """ LOGGER.info('ANALYSIS : Aggregate hazard preparation') self.set_state_process('hazard', 'Make hazard layer valid') self.hazard = clean_layer(self.hazard) self.debug_layer(self.hazard) self.set_state_process( 'aggregation', 'Union hazard polygons with aggregation areas and assign ' 'hazard class') self._aggregate_hazard_impacted = union(self.hazard, self.aggregation) self.debug_layer(self._aggregate_hazard_impacted)
[ "def", "aggregate_hazard_preparation", "(", "self", ")", ":", "LOGGER", ".", "info", "(", "'ANALYSIS : Aggregate hazard preparation'", ")", "self", ".", "set_state_process", "(", "'hazard'", ",", "'Make hazard layer valid'", ")", "self", ".", "hazard", "=", "clean_lay...
This function is doing the aggregate hazard layer. It will prepare the aggregate layer and intersect hazard polygons with aggregation areas and assign hazard class.
[ "This", "function", "is", "doing", "the", "aggregate", "hazard", "layer", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/impact_function/impact_function.py#L2208-L2224
train
26,622
inasafe/inasafe
safe/impact_function/impact_function.py
ImpactFunction.exposure_preparation
def exposure_preparation(self): """This function is doing the exposure preparation.""" LOGGER.info('ANALYSIS : Exposure preparation') use_same_projection = ( self.exposure.crs().authid() == self._crs.authid()) self.set_state_info( 'exposure', 'use_same_projection_as_aggregation', use_same_projection) if is_raster_layer(self.exposure): if self.exposure.keywords.get('layer_mode') == 'continuous': if self.exposure.keywords.get('exposure_unit') == 'density': self.set_state_process( 'exposure', 'Calculate counts per cell') # Todo, Need to write this algorithm. # We don't do any other process to a continuous raster. return else: self.set_state_process( 'exposure', 'Polygonise classified raster exposure') # noinspection PyTypeChecker self.exposure = polygonize(self.exposure) self.debug_layer(self.exposure) # We may need to add the size of the original feature. So don't want to # split the feature yet. if use_same_projection: mask = self._analysis_impacted else: mask = reproject(self._analysis_impacted, self.exposure.crs()) self.set_state_process('exposure', 'Smart clip') self.exposure = smart_clip(self.exposure, mask) self.debug_layer(self.exposure, check_fields=False) self.set_state_process( 'exposure', 'Cleaning the vector exposure attribute table') # noinspection PyTypeChecker self.exposure = prepare_vector_layer(self.exposure) self.debug_layer(self.exposure) if not use_same_projection: self.set_state_process( 'exposure', 'Reproject exposure layer to aggregation CRS') # noinspection PyTypeChecker self.exposure = reproject( self.exposure, self._crs) self.debug_layer(self.exposure) self.set_state_process('exposure', 'Compute ratios from counts') self.exposure = from_counts_to_ratios(self.exposure) self.debug_layer(self.exposure) exposure = self.exposure.keywords.get('exposure') geometry = self.exposure.geometryType() indivisible_keys = [f['key'] for f in indivisible_exposure] if exposure not in indivisible_keys and geometry != \ QgsWkbTypes.PointGeometry: # We can now split features because the `prepare_vector_layer` # might have added the size field. self.set_state_process( 'exposure', 'Clip the exposure layer with the analysis layer') self.exposure = clip(self.exposure, self._analysis_impacted) self.debug_layer(self.exposure) self.set_state_process('exposure', 'Add default values') self.exposure = add_default_values(self.exposure) self.debug_layer(self.exposure) fields = self.exposure.keywords['inasafe_fields'] if exposure_class_field['key'] not in fields: self.set_state_process( 'exposure', 'Assign classes based on value map') self.exposure = update_value_map(self.exposure) self.debug_layer(self.exposure)
python
def exposure_preparation(self): """This function is doing the exposure preparation.""" LOGGER.info('ANALYSIS : Exposure preparation') use_same_projection = ( self.exposure.crs().authid() == self._crs.authid()) self.set_state_info( 'exposure', 'use_same_projection_as_aggregation', use_same_projection) if is_raster_layer(self.exposure): if self.exposure.keywords.get('layer_mode') == 'continuous': if self.exposure.keywords.get('exposure_unit') == 'density': self.set_state_process( 'exposure', 'Calculate counts per cell') # Todo, Need to write this algorithm. # We don't do any other process to a continuous raster. return else: self.set_state_process( 'exposure', 'Polygonise classified raster exposure') # noinspection PyTypeChecker self.exposure = polygonize(self.exposure) self.debug_layer(self.exposure) # We may need to add the size of the original feature. So don't want to # split the feature yet. if use_same_projection: mask = self._analysis_impacted else: mask = reproject(self._analysis_impacted, self.exposure.crs()) self.set_state_process('exposure', 'Smart clip') self.exposure = smart_clip(self.exposure, mask) self.debug_layer(self.exposure, check_fields=False) self.set_state_process( 'exposure', 'Cleaning the vector exposure attribute table') # noinspection PyTypeChecker self.exposure = prepare_vector_layer(self.exposure) self.debug_layer(self.exposure) if not use_same_projection: self.set_state_process( 'exposure', 'Reproject exposure layer to aggregation CRS') # noinspection PyTypeChecker self.exposure = reproject( self.exposure, self._crs) self.debug_layer(self.exposure) self.set_state_process('exposure', 'Compute ratios from counts') self.exposure = from_counts_to_ratios(self.exposure) self.debug_layer(self.exposure) exposure = self.exposure.keywords.get('exposure') geometry = self.exposure.geometryType() indivisible_keys = [f['key'] for f in indivisible_exposure] if exposure not in indivisible_keys and geometry != \ QgsWkbTypes.PointGeometry: # We can now split features because the `prepare_vector_layer` # might have added the size field. self.set_state_process( 'exposure', 'Clip the exposure layer with the analysis layer') self.exposure = clip(self.exposure, self._analysis_impacted) self.debug_layer(self.exposure) self.set_state_process('exposure', 'Add default values') self.exposure = add_default_values(self.exposure) self.debug_layer(self.exposure) fields = self.exposure.keywords['inasafe_fields'] if exposure_class_field['key'] not in fields: self.set_state_process( 'exposure', 'Assign classes based on value map') self.exposure = update_value_map(self.exposure) self.debug_layer(self.exposure)
[ "def", "exposure_preparation", "(", "self", ")", ":", "LOGGER", ".", "info", "(", "'ANALYSIS : Exposure preparation'", ")", "use_same_projection", "=", "(", "self", ".", "exposure", ".", "crs", "(", ")", ".", "authid", "(", ")", "==", "self", ".", "_crs", ...
This function is doing the exposure preparation.
[ "This", "function", "is", "doing", "the", "exposure", "preparation", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/impact_function/impact_function.py#L2227-L2307
train
26,623
inasafe/inasafe
safe/impact_function/impact_function.py
ImpactFunction.intersect_exposure_and_aggregate_hazard
def intersect_exposure_and_aggregate_hazard(self): """This function intersects the exposure with the aggregate hazard. If the the exposure is a continuous raster exposure, this function will set the aggregate hazard layer. However, this function will set the impact layer. """ LOGGER.info('ANALYSIS : Intersect Exposure and Aggregate Hazard') if is_raster_layer(self.exposure): self.set_state_process( 'impact function', 'Zonal stats between exposure and aggregate hazard') # Be careful, our own zonal stats will take care of different # projections between the two layers. We don't want to reproject # rasters. # noinspection PyTypeChecker self._aggregate_hazard_impacted = zonal_stats( self.exposure, self._aggregate_hazard_impacted) self.debug_layer(self._aggregate_hazard_impacted) self.set_state_process('impact function', 'Add default values') self._aggregate_hazard_impacted = add_default_values( self._aggregate_hazard_impacted) self.debug_layer(self._aggregate_hazard_impacted) # I know it's redundant, it's just to be sure that we don't have # any impact layer for that IF. self._exposure_summary = None else: indivisible_keys = [f['key'] for f in indivisible_exposure] geometry = self.exposure.geometryType() exposure = self.exposure.keywords.get('exposure') is_divisible = exposure not in indivisible_keys if geometry in [ QgsWkbTypes.LineGeometry, QgsWkbTypes.PolygonGeometry] and is_divisible: self.set_state_process( 'exposure', 'Make exposure layer valid') self._exposure = clean_layer(self.exposure) self.debug_layer(self.exposure) self.set_state_process( 'impact function', 'Make aggregate hazard layer valid') self._aggregate_hazard_impacted = clean_layer( self._aggregate_hazard_impacted) self.debug_layer(self._aggregate_hazard_impacted) self.set_state_process( 'impact function', 'Intersect divisible features with the aggregate hazard') self._exposure_summary = intersection( self._exposure, self._aggregate_hazard_impacted) self.debug_layer(self._exposure_summary) # If the layer has the size field, it means we need to # recompute counts based on the old and new size. fields = self._exposure_summary.keywords['inasafe_fields'] if size_field['key'] in fields: self.set_state_process( 'impact function', 'Recompute counts') LOGGER.info( 'InaSAFE will not use these counts, as we have ratios ' 'since the exposure preparation step.') self._exposure_summary = recompute_counts( self._exposure_summary) self.debug_layer(self._exposure_summary) else: self.set_state_process( 'impact function', 'Highest class of hazard is assigned to the exposure') self._exposure_summary = assign_highest_value( self._exposure, self._aggregate_hazard_impacted) self.debug_layer(self._exposure_summary) # set title using definition # the title will be overwritten anyway by standard title # set this as fallback. self._exposure_summary.keywords['title'] = ( layer_purpose_exposure_summary['name']) if qgis_version() >= 21800: self._exposure_summary.setName( self._exposure_summary.keywords['title']) else: self._exposure_summary.setLayerName( self._exposure_summary.keywords['title'])
python
def intersect_exposure_and_aggregate_hazard(self): """This function intersects the exposure with the aggregate hazard. If the the exposure is a continuous raster exposure, this function will set the aggregate hazard layer. However, this function will set the impact layer. """ LOGGER.info('ANALYSIS : Intersect Exposure and Aggregate Hazard') if is_raster_layer(self.exposure): self.set_state_process( 'impact function', 'Zonal stats between exposure and aggregate hazard') # Be careful, our own zonal stats will take care of different # projections between the two layers. We don't want to reproject # rasters. # noinspection PyTypeChecker self._aggregate_hazard_impacted = zonal_stats( self.exposure, self._aggregate_hazard_impacted) self.debug_layer(self._aggregate_hazard_impacted) self.set_state_process('impact function', 'Add default values') self._aggregate_hazard_impacted = add_default_values( self._aggregate_hazard_impacted) self.debug_layer(self._aggregate_hazard_impacted) # I know it's redundant, it's just to be sure that we don't have # any impact layer for that IF. self._exposure_summary = None else: indivisible_keys = [f['key'] for f in indivisible_exposure] geometry = self.exposure.geometryType() exposure = self.exposure.keywords.get('exposure') is_divisible = exposure not in indivisible_keys if geometry in [ QgsWkbTypes.LineGeometry, QgsWkbTypes.PolygonGeometry] and is_divisible: self.set_state_process( 'exposure', 'Make exposure layer valid') self._exposure = clean_layer(self.exposure) self.debug_layer(self.exposure) self.set_state_process( 'impact function', 'Make aggregate hazard layer valid') self._aggregate_hazard_impacted = clean_layer( self._aggregate_hazard_impacted) self.debug_layer(self._aggregate_hazard_impacted) self.set_state_process( 'impact function', 'Intersect divisible features with the aggregate hazard') self._exposure_summary = intersection( self._exposure, self._aggregate_hazard_impacted) self.debug_layer(self._exposure_summary) # If the layer has the size field, it means we need to # recompute counts based on the old and new size. fields = self._exposure_summary.keywords['inasafe_fields'] if size_field['key'] in fields: self.set_state_process( 'impact function', 'Recompute counts') LOGGER.info( 'InaSAFE will not use these counts, as we have ratios ' 'since the exposure preparation step.') self._exposure_summary = recompute_counts( self._exposure_summary) self.debug_layer(self._exposure_summary) else: self.set_state_process( 'impact function', 'Highest class of hazard is assigned to the exposure') self._exposure_summary = assign_highest_value( self._exposure, self._aggregate_hazard_impacted) self.debug_layer(self._exposure_summary) # set title using definition # the title will be overwritten anyway by standard title # set this as fallback. self._exposure_summary.keywords['title'] = ( layer_purpose_exposure_summary['name']) if qgis_version() >= 21800: self._exposure_summary.setName( self._exposure_summary.keywords['title']) else: self._exposure_summary.setLayerName( self._exposure_summary.keywords['title'])
[ "def", "intersect_exposure_and_aggregate_hazard", "(", "self", ")", ":", "LOGGER", ".", "info", "(", "'ANALYSIS : Intersect Exposure and Aggregate Hazard'", ")", "if", "is_raster_layer", "(", "self", ".", "exposure", ")", ":", "self", ".", "set_state_process", "(", "'...
This function intersects the exposure with the aggregate hazard. If the the exposure is a continuous raster exposure, this function will set the aggregate hazard layer. However, this function will set the impact layer.
[ "This", "function", "intersects", "the", "exposure", "with", "the", "aggregate", "hazard", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/impact_function/impact_function.py#L2310-L2400
train
26,624
inasafe/inasafe
safe/impact_function/impact_function.py
ImpactFunction.post_process
def post_process(self, layer): """More process after getting the impact layer with data. :param layer: The vector layer to use for post processing. :type layer: QgsVectorLayer """ LOGGER.info('ANALYSIS : Post processing') # Set the layer title purpose = layer.keywords['layer_purpose'] if purpose != layer_purpose_aggregation_summary['key']: # On an aggregation layer, the default title does make any sense. layer_title(layer) for post_processor in post_processors: run, run_message = should_run(layer.keywords, post_processor) if run: valid, message = enough_input(layer, post_processor['input']) name = post_processor['name'] if valid: valid, message = run_single_post_processor( layer, post_processor) if valid: self.set_state_process('post_processor', name) message = '{name} : Running'.format(name=name) LOGGER.info(message) else: # message = u'{name} : Could not run : {reason}'.format( # name=name, reason=message) # LOGGER.info(message) pass else: # LOGGER.info(run_message) pass self.debug_layer(layer, add_to_datastore=False)
python
def post_process(self, layer): """More process after getting the impact layer with data. :param layer: The vector layer to use for post processing. :type layer: QgsVectorLayer """ LOGGER.info('ANALYSIS : Post processing') # Set the layer title purpose = layer.keywords['layer_purpose'] if purpose != layer_purpose_aggregation_summary['key']: # On an aggregation layer, the default title does make any sense. layer_title(layer) for post_processor in post_processors: run, run_message = should_run(layer.keywords, post_processor) if run: valid, message = enough_input(layer, post_processor['input']) name = post_processor['name'] if valid: valid, message = run_single_post_processor( layer, post_processor) if valid: self.set_state_process('post_processor', name) message = '{name} : Running'.format(name=name) LOGGER.info(message) else: # message = u'{name} : Could not run : {reason}'.format( # name=name, reason=message) # LOGGER.info(message) pass else: # LOGGER.info(run_message) pass self.debug_layer(layer, add_to_datastore=False)
[ "def", "post_process", "(", "self", ",", "layer", ")", ":", "LOGGER", ".", "info", "(", "'ANALYSIS : Post processing'", ")", "# Set the layer title", "purpose", "=", "layer", ".", "keywords", "[", "'layer_purpose'", "]", "if", "purpose", "!=", "layer_purpose_aggre...
More process after getting the impact layer with data. :param layer: The vector layer to use for post processing. :type layer: QgsVectorLayer
[ "More", "process", "after", "getting", "the", "impact", "layer", "with", "data", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/impact_function/impact_function.py#L2403-L2439
train
26,625
inasafe/inasafe
safe/impact_function/impact_function.py
ImpactFunction.summary_calculation
def summary_calculation(self): """Do the summary calculation. We do not check layers here, we will check them in the next step. """ LOGGER.info('ANALYSIS : Summary calculation') if is_vector_layer(self._exposure_summary): # With continuous exposure, we don't have an exposure summary layer self.set_state_process( 'impact function', 'Aggregate the impact summary') self._aggregate_hazard_impacted = aggregate_hazard_summary( self.exposure_summary, self._aggregate_hazard_impacted) self.debug_layer(self._exposure_summary, add_to_datastore=False) self.set_state_process( 'impact function', 'Aggregate the aggregation summary') self._aggregation_summary = aggregation_summary( self._aggregate_hazard_impacted, self.aggregation) self.debug_layer( self._aggregation_summary, add_to_datastore=False) self.set_state_process( 'impact function', 'Aggregate the analysis summary') self._analysis_impacted = analysis_summary( self._aggregate_hazard_impacted, self._analysis_impacted) self.debug_layer(self._analysis_impacted) if self._exposure.keywords.get('classification'): self.set_state_process( 'impact function', 'Build the exposure summary table') self._exposure_summary_table = exposure_summary_table( self._aggregate_hazard_impacted, self._exposure_summary) self.debug_layer( self._exposure_summary_table, add_to_datastore=False)
python
def summary_calculation(self): """Do the summary calculation. We do not check layers here, we will check them in the next step. """ LOGGER.info('ANALYSIS : Summary calculation') if is_vector_layer(self._exposure_summary): # With continuous exposure, we don't have an exposure summary layer self.set_state_process( 'impact function', 'Aggregate the impact summary') self._aggregate_hazard_impacted = aggregate_hazard_summary( self.exposure_summary, self._aggregate_hazard_impacted) self.debug_layer(self._exposure_summary, add_to_datastore=False) self.set_state_process( 'impact function', 'Aggregate the aggregation summary') self._aggregation_summary = aggregation_summary( self._aggregate_hazard_impacted, self.aggregation) self.debug_layer( self._aggregation_summary, add_to_datastore=False) self.set_state_process( 'impact function', 'Aggregate the analysis summary') self._analysis_impacted = analysis_summary( self._aggregate_hazard_impacted, self._analysis_impacted) self.debug_layer(self._analysis_impacted) if self._exposure.keywords.get('classification'): self.set_state_process( 'impact function', 'Build the exposure summary table') self._exposure_summary_table = exposure_summary_table( self._aggregate_hazard_impacted, self._exposure_summary) self.debug_layer( self._exposure_summary_table, add_to_datastore=False)
[ "def", "summary_calculation", "(", "self", ")", ":", "LOGGER", ".", "info", "(", "'ANALYSIS : Summary calculation'", ")", "if", "is_vector_layer", "(", "self", ".", "_exposure_summary", ")", ":", "# With continuous exposure, we don't have an exposure summary layer", "self",...
Do the summary calculation. We do not check layers here, we will check them in the next step.
[ "Do", "the", "summary", "calculation", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/impact_function/impact_function.py#L2442-L2476
train
26,626
inasafe/inasafe
safe/impact_function/impact_function.py
ImpactFunction.style
def style(self): """Function to apply some styles to the layers.""" LOGGER.info('ANALYSIS : Styling') classes = generate_classified_legend( self.analysis_impacted, self.exposure, self.hazard, self.use_rounding, self.debug_mode) # Let's style layers which have a geometry and have hazard_class hazard_class = hazard_class_field['key'] for layer in self._outputs(): without_geometries = [ QgsWkbTypes.NullGeometry, QgsWkbTypes.UnknownGeometry] if layer.geometryType() not in without_geometries: display_not_exposed = False if layer == self.impact or self.debug_mode: display_not_exposed = True if layer.keywords['inasafe_fields'].get(hazard_class): hazard_class_style(layer, classes, display_not_exposed) # Let's style the aggregation and analysis layer. simple_polygon_without_brush( self.aggregation_summary, aggregation_width, aggregation_color) simple_polygon_without_brush( self.analysis_impacted, analysis_width, analysis_color) # Styling is finished, save them as QML for layer in self._outputs(): layer.saveDefaultStyle()
python
def style(self): """Function to apply some styles to the layers.""" LOGGER.info('ANALYSIS : Styling') classes = generate_classified_legend( self.analysis_impacted, self.exposure, self.hazard, self.use_rounding, self.debug_mode) # Let's style layers which have a geometry and have hazard_class hazard_class = hazard_class_field['key'] for layer in self._outputs(): without_geometries = [ QgsWkbTypes.NullGeometry, QgsWkbTypes.UnknownGeometry] if layer.geometryType() not in without_geometries: display_not_exposed = False if layer == self.impact or self.debug_mode: display_not_exposed = True if layer.keywords['inasafe_fields'].get(hazard_class): hazard_class_style(layer, classes, display_not_exposed) # Let's style the aggregation and analysis layer. simple_polygon_without_brush( self.aggregation_summary, aggregation_width, aggregation_color) simple_polygon_without_brush( self.analysis_impacted, analysis_width, analysis_color) # Styling is finished, save them as QML for layer in self._outputs(): layer.saveDefaultStyle()
[ "def", "style", "(", "self", ")", ":", "LOGGER", ".", "info", "(", "'ANALYSIS : Styling'", ")", "classes", "=", "generate_classified_legend", "(", "self", ".", "analysis_impacted", ",", "self", ".", "exposure", ",", "self", ".", "hazard", ",", "self", ".", ...
Function to apply some styles to the layers.
[ "Function", "to", "apply", "some", "styles", "to", "the", "layers", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/impact_function/impact_function.py#L2478-L2510
train
26,627
inasafe/inasafe
safe/impact_function/impact_function.py
ImpactFunction.exposure_notes
def exposure_notes(self): """Get the exposure specific notes defined in definitions. This method will do a lookup in definitions and return the exposure definition specific notes dictionary. This is a helper function to make it easy to get exposure specific notes from the definitions metadata. .. versionadded:: 3.5 :returns: A list like e.g. safe.definitions.exposure_land_cover[ 'notes'] :rtype: list, None """ notes = [] exposure = definition(self.exposure.keywords.get('exposure')) if 'notes' in exposure: notes += exposure['notes'] if self.exposure.keywords['layer_mode'] == 'classified': if 'classified_notes' in exposure: notes += exposure['classified_notes'] if self.exposure.keywords['layer_mode'] == 'continuous': if 'continuous_notes' in exposure: notes += exposure['continuous_notes'] return notes
python
def exposure_notes(self): """Get the exposure specific notes defined in definitions. This method will do a lookup in definitions and return the exposure definition specific notes dictionary. This is a helper function to make it easy to get exposure specific notes from the definitions metadata. .. versionadded:: 3.5 :returns: A list like e.g. safe.definitions.exposure_land_cover[ 'notes'] :rtype: list, None """ notes = [] exposure = definition(self.exposure.keywords.get('exposure')) if 'notes' in exposure: notes += exposure['notes'] if self.exposure.keywords['layer_mode'] == 'classified': if 'classified_notes' in exposure: notes += exposure['classified_notes'] if self.exposure.keywords['layer_mode'] == 'continuous': if 'continuous_notes' in exposure: notes += exposure['continuous_notes'] return notes
[ "def", "exposure_notes", "(", "self", ")", ":", "notes", "=", "[", "]", "exposure", "=", "definition", "(", "self", ".", "exposure", ".", "keywords", ".", "get", "(", "'exposure'", ")", ")", "if", "'notes'", "in", "exposure", ":", "notes", "+=", "expos...
Get the exposure specific notes defined in definitions. This method will do a lookup in definitions and return the exposure definition specific notes dictionary. This is a helper function to make it easy to get exposure specific notes from the definitions metadata. .. versionadded:: 3.5 :returns: A list like e.g. safe.definitions.exposure_land_cover[ 'notes'] :rtype: list, None
[ "Get", "the", "exposure", "specific", "notes", "defined", "in", "definitions", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/impact_function/impact_function.py#L2607-L2632
train
26,628
inasafe/inasafe
safe/impact_function/impact_function.py
ImpactFunction.hazard_notes
def hazard_notes(self): """Get the hazard specific notes defined in definitions. This method will do a lookup in definitions and return the hazard definition specific notes dictionary. This is a helper function to make it easy to get hazard specific notes from the definitions metadata. .. versionadded:: 3.5 :returns: A list like e.g. safe.definitions.hazard_land_cover[ 'notes'] :rtype: list, None """ notes = [] hazard = definition(self.hazard.keywords.get('hazard')) if 'notes' in hazard: notes += hazard['notes'] if self.hazard.keywords['layer_mode'] == 'classified': if 'classified_notes' in hazard: notes += hazard['classified_notes'] if self.hazard.keywords['layer_mode'] == 'continuous': if 'continuous_notes' in hazard: notes += hazard['continuous_notes'] if self.hazard.keywords['hazard_category'] == 'single_event': if 'single_event_notes' in hazard: notes += hazard['single_event_notes'] if self.hazard.keywords['hazard_category'] == 'multiple_event': if 'multi_event_notes' in hazard: notes += hazard['multi_event_notes'] return notes
python
def hazard_notes(self): """Get the hazard specific notes defined in definitions. This method will do a lookup in definitions and return the hazard definition specific notes dictionary. This is a helper function to make it easy to get hazard specific notes from the definitions metadata. .. versionadded:: 3.5 :returns: A list like e.g. safe.definitions.hazard_land_cover[ 'notes'] :rtype: list, None """ notes = [] hazard = definition(self.hazard.keywords.get('hazard')) if 'notes' in hazard: notes += hazard['notes'] if self.hazard.keywords['layer_mode'] == 'classified': if 'classified_notes' in hazard: notes += hazard['classified_notes'] if self.hazard.keywords['layer_mode'] == 'continuous': if 'continuous_notes' in hazard: notes += hazard['continuous_notes'] if self.hazard.keywords['hazard_category'] == 'single_event': if 'single_event_notes' in hazard: notes += hazard['single_event_notes'] if self.hazard.keywords['hazard_category'] == 'multiple_event': if 'multi_event_notes' in hazard: notes += hazard['multi_event_notes'] return notes
[ "def", "hazard_notes", "(", "self", ")", ":", "notes", "=", "[", "]", "hazard", "=", "definition", "(", "self", ".", "hazard", ".", "keywords", ".", "get", "(", "'hazard'", ")", ")", "if", "'notes'", "in", "hazard", ":", "notes", "+=", "hazard", "[",...
Get the hazard specific notes defined in definitions. This method will do a lookup in definitions and return the hazard definition specific notes dictionary. This is a helper function to make it easy to get hazard specific notes from the definitions metadata. .. versionadded:: 3.5 :returns: A list like e.g. safe.definitions.hazard_land_cover[ 'notes'] :rtype: list, None
[ "Get", "the", "hazard", "specific", "notes", "defined", "in", "definitions", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/impact_function/impact_function.py#L2634-L2666
train
26,629
inasafe/inasafe
safe/impact_function/impact_function.py
ImpactFunction.notes
def notes(self): """Return the notes section of the report. .. versionadded:: 3.5 :return: The notes that should be attached to this impact report. :rtype: list """ fields = [] # Notes still to be defined for ASH # include any generic exposure specific notes from definitions fields = fields + self.exposure_notes() # include any generic hazard specific notes from definitions fields = fields + self.hazard_notes() # include any hazard/exposure notes from definitions exposure = definition(self.exposure.keywords.get('exposure')) hazard = definition(self.hazard.keywords.get('hazard')) fields.extend(specific_notes(hazard, exposure)) if self._earthquake_function is not None: # Get notes specific to the fatality model for fatality_model in EARTHQUAKE_FUNCTIONS: if fatality_model['key'] == self._earthquake_function: fields.extend(fatality_model.get('notes', [])) return fields
python
def notes(self): """Return the notes section of the report. .. versionadded:: 3.5 :return: The notes that should be attached to this impact report. :rtype: list """ fields = [] # Notes still to be defined for ASH # include any generic exposure specific notes from definitions fields = fields + self.exposure_notes() # include any generic hazard specific notes from definitions fields = fields + self.hazard_notes() # include any hazard/exposure notes from definitions exposure = definition(self.exposure.keywords.get('exposure')) hazard = definition(self.hazard.keywords.get('hazard')) fields.extend(specific_notes(hazard, exposure)) if self._earthquake_function is not None: # Get notes specific to the fatality model for fatality_model in EARTHQUAKE_FUNCTIONS: if fatality_model['key'] == self._earthquake_function: fields.extend(fatality_model.get('notes', [])) return fields
[ "def", "notes", "(", "self", ")", ":", "fields", "=", "[", "]", "# Notes still to be defined for ASH", "# include any generic exposure specific notes from definitions", "fields", "=", "fields", "+", "self", ".", "exposure_notes", "(", ")", "# include any generic hazard spec...
Return the notes section of the report. .. versionadded:: 3.5 :return: The notes that should be attached to this impact report. :rtype: list
[ "Return", "the", "notes", "section", "of", "the", "report", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/impact_function/impact_function.py#L2668-L2693
train
26,630
inasafe/inasafe
safe/impact_function/impact_function.py
ImpactFunction.action_checklist
def action_checklist(self): """Return the list of action check list dictionary. :return: The list of action check list dictionary. :rtype: list """ actions = [] exposure = definition(self.exposure.keywords.get('exposure')) actions.extend(exposure.get('actions')) hazard = definition(self.hazard.keywords.get('hazard')) actions.extend(hazard.get('actions')) actions.extend(specific_actions(hazard, exposure)) return actions
python
def action_checklist(self): """Return the list of action check list dictionary. :return: The list of action check list dictionary. :rtype: list """ actions = [] exposure = definition(self.exposure.keywords.get('exposure')) actions.extend(exposure.get('actions')) hazard = definition(self.hazard.keywords.get('hazard')) actions.extend(hazard.get('actions')) actions.extend(specific_actions(hazard, exposure)) return actions
[ "def", "action_checklist", "(", "self", ")", ":", "actions", "=", "[", "]", "exposure", "=", "definition", "(", "self", ".", "exposure", ".", "keywords", ".", "get", "(", "'exposure'", ")", ")", "actions", ".", "extend", "(", "exposure", ".", "get", "(...
Return the list of action check list dictionary. :return: The list of action check list dictionary. :rtype: list
[ "Return", "the", "list", "of", "action", "check", "list", "dictionary", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/impact_function/impact_function.py#L2695-L2709
train
26,631
inasafe/inasafe
safe/utilities/memory_checker.py
memory_error
def memory_error(): """Display an error when there is not enough memory.""" warning_heading = m.Heading( tr('Memory issue'), **WARNING_STYLE) warning_message = tr( 'There is not enough free memory to run this analysis.') suggestion_heading = m.Heading( tr('Suggestion'), **SUGGESTION_STYLE) suggestion = tr( 'Try zooming in to a smaller area or using a raster layer with a ' 'coarser resolution to speed up execution and reduce memory ' 'requirements. You could also try adding more RAM to your computer.') message = m.Message() message.add(warning_heading) message.add(warning_message) message.add(suggestion_heading) message.add(suggestion) send_static_message(dispatcher.Anonymous, message)
python
def memory_error(): """Display an error when there is not enough memory.""" warning_heading = m.Heading( tr('Memory issue'), **WARNING_STYLE) warning_message = tr( 'There is not enough free memory to run this analysis.') suggestion_heading = m.Heading( tr('Suggestion'), **SUGGESTION_STYLE) suggestion = tr( 'Try zooming in to a smaller area or using a raster layer with a ' 'coarser resolution to speed up execution and reduce memory ' 'requirements. You could also try adding more RAM to your computer.') message = m.Message() message.add(warning_heading) message.add(warning_message) message.add(suggestion_heading) message.add(suggestion) send_static_message(dispatcher.Anonymous, message)
[ "def", "memory_error", "(", ")", ":", "warning_heading", "=", "m", ".", "Heading", "(", "tr", "(", "'Memory issue'", ")", ",", "*", "*", "WARNING_STYLE", ")", "warning_message", "=", "tr", "(", "'There is not enough free memory to run this analysis.'", ")", "sugge...
Display an error when there is not enough memory.
[ "Display", "an", "error", "when", "there", "is", "not", "enough", "memory", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/utilities/memory_checker.py#L162-L180
train
26,632
inasafe/inasafe
scripts/create_api_docs.py
create_top_level_index_entry
def create_top_level_index_entry(title, max_depth, subtitles): """Function for creating a text entry in index.rst for its content. :param title : Title for the content. :type title: str :param max_depth : Value for max_depth in the top level index content. :type max_depth: int :param subtitles : list of subtitles that is available. :type subtitles: list :return: A text for the content of top level index. :rtype: str """ return_text = title + '\n' dash = '-' * len(title) + '\n' return_text += dash + '\n' return_text += '.. toctree::' + '\n' return_text += ' :maxdepth: ' + str(max_depth) + '\n\n' for subtitle in subtitles: return_text += ' ' + subtitle + '\n\n' return return_text
python
def create_top_level_index_entry(title, max_depth, subtitles): """Function for creating a text entry in index.rst for its content. :param title : Title for the content. :type title: str :param max_depth : Value for max_depth in the top level index content. :type max_depth: int :param subtitles : list of subtitles that is available. :type subtitles: list :return: A text for the content of top level index. :rtype: str """ return_text = title + '\n' dash = '-' * len(title) + '\n' return_text += dash + '\n' return_text += '.. toctree::' + '\n' return_text += ' :maxdepth: ' + str(max_depth) + '\n\n' for subtitle in subtitles: return_text += ' ' + subtitle + '\n\n' return return_text
[ "def", "create_top_level_index_entry", "(", "title", ",", "max_depth", ",", "subtitles", ")", ":", "return_text", "=", "title", "+", "'\\n'", "dash", "=", "'-'", "*", "len", "(", "title", ")", "+", "'\\n'", "return_text", "+=", "dash", "+", "'\\n'", "retur...
Function for creating a text entry in index.rst for its content. :param title : Title for the content. :type title: str :param max_depth : Value for max_depth in the top level index content. :type max_depth: int :param subtitles : list of subtitles that is available. :type subtitles: list :return: A text for the content of top level index. :rtype: str
[ "Function", "for", "creating", "a", "text", "entry", "in", "index", ".", "rst", "for", "its", "content", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/scripts/create_api_docs.py#L24-L49
train
26,633
inasafe/inasafe
scripts/create_api_docs.py
create_package_level_rst_index_file
def create_package_level_rst_index_file( package_name, max_depth, modules, inner_packages=None): """Function for creating text for index for a package. :param package_name: name of the package :type package_name: str :param max_depth: Value for max_depth in the index file. :type max_depth: int :param modules: list of module in the package. :type modules: list :return: A text for the content of the index file. :rtype: str """ if inner_packages is None: inner_packages = [] return_text = 'Package::' + package_name dash = '=' * len(return_text) return_text += '\n' + dash + '\n\n' return_text += '.. toctree::' + '\n' return_text += ' :maxdepth: ' + str(max_depth) + '\n\n' upper_package = package_name.split('.')[-1] for module in modules: if module in EXCLUDED_PACKAGES: continue return_text += ' ' + upper_package + os.sep + module[:-3] + '\n' for inner_package in inner_packages: if inner_package in EXCLUDED_PACKAGES: continue return_text += ' ' + upper_package + os.sep + inner_package + '\n' return return_text
python
def create_package_level_rst_index_file( package_name, max_depth, modules, inner_packages=None): """Function for creating text for index for a package. :param package_name: name of the package :type package_name: str :param max_depth: Value for max_depth in the index file. :type max_depth: int :param modules: list of module in the package. :type modules: list :return: A text for the content of the index file. :rtype: str """ if inner_packages is None: inner_packages = [] return_text = 'Package::' + package_name dash = '=' * len(return_text) return_text += '\n' + dash + '\n\n' return_text += '.. toctree::' + '\n' return_text += ' :maxdepth: ' + str(max_depth) + '\n\n' upper_package = package_name.split('.')[-1] for module in modules: if module in EXCLUDED_PACKAGES: continue return_text += ' ' + upper_package + os.sep + module[:-3] + '\n' for inner_package in inner_packages: if inner_package in EXCLUDED_PACKAGES: continue return_text += ' ' + upper_package + os.sep + inner_package + '\n' return return_text
[ "def", "create_package_level_rst_index_file", "(", "package_name", ",", "max_depth", ",", "modules", ",", "inner_packages", "=", "None", ")", ":", "if", "inner_packages", "is", "None", ":", "inner_packages", "=", "[", "]", "return_text", "=", "'Package::'", "+", ...
Function for creating text for index for a package. :param package_name: name of the package :type package_name: str :param max_depth: Value for max_depth in the index file. :type max_depth: int :param modules: list of module in the package. :type modules: list :return: A text for the content of the index file. :rtype: str
[ "Function", "for", "creating", "text", "for", "index", "for", "a", "package", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/scripts/create_api_docs.py#L52-L85
train
26,634
inasafe/inasafe
scripts/create_api_docs.py
create_module_rst_file
def create_module_rst_file(module_name): """Function for creating content in each .rst file for a module. :param module_name: name of the module. :type module_name: str :returns: A content for auto module. :rtype: str """ return_text = 'Module: ' + module_name dash = '=' * len(return_text) return_text += '\n' + dash + '\n\n' return_text += '.. automodule:: ' + module_name + '\n' return_text += ' :members:\n\n' return return_text
python
def create_module_rst_file(module_name): """Function for creating content in each .rst file for a module. :param module_name: name of the module. :type module_name: str :returns: A content for auto module. :rtype: str """ return_text = 'Module: ' + module_name dash = '=' * len(return_text) return_text += '\n' + dash + '\n\n' return_text += '.. automodule:: ' + module_name + '\n' return_text += ' :members:\n\n' return return_text
[ "def", "create_module_rst_file", "(", "module_name", ")", ":", "return_text", "=", "'Module: '", "+", "module_name", "dash", "=", "'='", "*", "len", "(", "return_text", ")", "return_text", "+=", "'\\n'", "+", "dash", "+", "'\\n\\n'", "return_text", "+=", "'.....
Function for creating content in each .rst file for a module. :param module_name: name of the module. :type module_name: str :returns: A content for auto module. :rtype: str
[ "Function", "for", "creating", "content", "in", "each", ".", "rst", "file", "for", "a", "module", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/scripts/create_api_docs.py#L88-L104
train
26,635
inasafe/inasafe
scripts/create_api_docs.py
write_rst_file
def write_rst_file(file_directory, file_name, content): """Shorter procedure for creating rst file. :param file_directory: Directory of the filename. :type file_directory: str :param file_name: Name of the file. :type file_name: str :param content: The content of the file. :type content: str """ create_dirs(os.path.split(os.path.join(file_directory, file_name))[0]) try: fl = open(os.path.join(file_directory, file_name + '.rst'), 'w+') fl.write(content) fl.close() except Exception as e: print(('Creating %s failed' % os.path.join( file_directory, file_name + '.rst'), e))
python
def write_rst_file(file_directory, file_name, content): """Shorter procedure for creating rst file. :param file_directory: Directory of the filename. :type file_directory: str :param file_name: Name of the file. :type file_name: str :param content: The content of the file. :type content: str """ create_dirs(os.path.split(os.path.join(file_directory, file_name))[0]) try: fl = open(os.path.join(file_directory, file_name + '.rst'), 'w+') fl.write(content) fl.close() except Exception as e: print(('Creating %s failed' % os.path.join( file_directory, file_name + '.rst'), e))
[ "def", "write_rst_file", "(", "file_directory", ",", "file_name", ",", "content", ")", ":", "create_dirs", "(", "os", ".", "path", ".", "split", "(", "os", ".", "path", ".", "join", "(", "file_directory", ",", "file_name", ")", ")", "[", "0", "]", ")",...
Shorter procedure for creating rst file. :param file_directory: Directory of the filename. :type file_directory: str :param file_name: Name of the file. :type file_name: str :param content: The content of the file. :type content: str
[ "Shorter", "procedure", "for", "creating", "rst", "file", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/scripts/create_api_docs.py#L113-L133
train
26,636
inasafe/inasafe
scripts/create_api_docs.py
get_python_files_from_list
def get_python_files_from_list(files, excluded_files=None): """Return list of python file from files, without excluded files. :param files: List of files. :type files: list :param excluded_files: List of excluded file names. :type excluded_files: list, None :returns: List of python file without the excluded file, not started with test. :rtype: list """ if excluded_files is None: excluded_files = ['__init__.py'] python_files = [] for fl in files: if (fl.endswith('.py') and fl not in excluded_files and not fl.startswith('test')): python_files.append(fl) return python_files
python
def get_python_files_from_list(files, excluded_files=None): """Return list of python file from files, without excluded files. :param files: List of files. :type files: list :param excluded_files: List of excluded file names. :type excluded_files: list, None :returns: List of python file without the excluded file, not started with test. :rtype: list """ if excluded_files is None: excluded_files = ['__init__.py'] python_files = [] for fl in files: if (fl.endswith('.py') and fl not in excluded_files and not fl.startswith('test')): python_files.append(fl) return python_files
[ "def", "get_python_files_from_list", "(", "files", ",", "excluded_files", "=", "None", ")", ":", "if", "excluded_files", "is", "None", ":", "excluded_files", "=", "[", "'__init__.py'", "]", "python_files", "=", "[", "]", "for", "fl", "in", "files", ":", "if"...
Return list of python file from files, without excluded files. :param files: List of files. :type files: list :param excluded_files: List of excluded file names. :type excluded_files: list, None :returns: List of python file without the excluded file, not started with test. :rtype: list
[ "Return", "list", "of", "python", "file", "from", "files", "without", "excluded", "files", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/scripts/create_api_docs.py#L136-L158
train
26,637
inasafe/inasafe
scripts/create_api_docs.py
get_inasafe_code_path
def get_inasafe_code_path(custom_inasafe_path=None): """Determine the path to inasafe location. :param custom_inasafe_path: Custom inasafe project location. :type custom_inasafe_path: str :returns: Path to inasafe source code. :rtype: str """ inasafe_code_path = os.path.abspath( os.path.join(os.path.dirname(__file__), '..')) if custom_inasafe_path is not None: inasafe_code_path = custom_inasafe_path return inasafe_code_path
python
def get_inasafe_code_path(custom_inasafe_path=None): """Determine the path to inasafe location. :param custom_inasafe_path: Custom inasafe project location. :type custom_inasafe_path: str :returns: Path to inasafe source code. :rtype: str """ inasafe_code_path = os.path.abspath( os.path.join(os.path.dirname(__file__), '..')) if custom_inasafe_path is not None: inasafe_code_path = custom_inasafe_path return inasafe_code_path
[ "def", "get_inasafe_code_path", "(", "custom_inasafe_path", "=", "None", ")", ":", "inasafe_code_path", "=", "os", ".", "path", ".", "abspath", "(", "os", ".", "path", ".", "join", "(", "os", ".", "path", ".", "dirname", "(", "__file__", ")", ",", "'..'"...
Determine the path to inasafe location. :param custom_inasafe_path: Custom inasafe project location. :type custom_inasafe_path: str :returns: Path to inasafe source code. :rtype: str
[ "Determine", "the", "path", "to", "inasafe", "location", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/scripts/create_api_docs.py#L185-L200
train
26,638
inasafe/inasafe
scripts/create_api_docs.py
clean_api_docs_dirs
def clean_api_docs_dirs(): """Empty previous api-docs directory. :returns: Path to api-docs directory. :rtype: str """ inasafe_docs_path = os.path.abspath( os.path.join( os.path.dirname(__file__), '..', 'docs', 'api-docs')) if os.path.exists(inasafe_docs_path): rmtree(inasafe_docs_path) create_dirs(inasafe_docs_path) return inasafe_docs_path
python
def clean_api_docs_dirs(): """Empty previous api-docs directory. :returns: Path to api-docs directory. :rtype: str """ inasafe_docs_path = os.path.abspath( os.path.join( os.path.dirname(__file__), '..', 'docs', 'api-docs')) if os.path.exists(inasafe_docs_path): rmtree(inasafe_docs_path) create_dirs(inasafe_docs_path) return inasafe_docs_path
[ "def", "clean_api_docs_dirs", "(", ")", ":", "inasafe_docs_path", "=", "os", ".", "path", ".", "abspath", "(", "os", ".", "path", ".", "join", "(", "os", ".", "path", ".", "dirname", "(", "__file__", ")", ",", "'..'", ",", "'docs'", ",", "'api-docs'", ...
Empty previous api-docs directory. :returns: Path to api-docs directory. :rtype: str
[ "Empty", "previous", "api", "-", "docs", "directory", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/scripts/create_api_docs.py#L203-L215
train
26,639
inasafe/inasafe
scripts/create_api_docs.py
create_api_docs
def create_api_docs(code_path, api_docs_path, max_depth=2): """Function for generating .rst file for all .py file in dir_path folder. :param code_path: Path of the source code. :type code_path: str :param api_docs_path: Path of the api documentation directory. :type api_docs_path: str :param max_depth: Maximum depth for the index. :type max_depth: int """ base_path = os.path.split(code_path)[0] for package, subpackages, candidate_files in os.walk(code_path): # Checking __init__.py file if '__init__.py' not in candidate_files: continue # Creating directory for the package package_relative_path = package.replace(base_path + os.sep, '') index_package_path = os.path.join( api_docs_path, package_relative_path) # calculate dir one up from package to store the index in index_base_path, package_base_name = os.path.split(index_package_path) if package_base_name in EXCLUDED_PACKAGES: continue full_package_name = package_relative_path.replace(os.sep, '.') new_rst_dir = os.path.join(api_docs_path, package_relative_path) create_dirs(new_rst_dir) # Create index_file for the directory modules = get_python_files_from_list(candidate_files) index_file_text = create_package_level_rst_index_file( package_name=full_package_name, max_depth=max_depth, modules=modules, inner_packages=subpackages) write_rst_file( file_directory=index_base_path, file_name=package_base_name, content=index_file_text) # Creating .rst file for each .py file for module in modules: module = module[:-3] # strip .py off the end py_module_text = create_module_rst_file( '%s.%s' % (full_package_name, module)) write_rst_file( file_directory=new_rst_dir, file_name=module, content=py_module_text)
python
def create_api_docs(code_path, api_docs_path, max_depth=2): """Function for generating .rst file for all .py file in dir_path folder. :param code_path: Path of the source code. :type code_path: str :param api_docs_path: Path of the api documentation directory. :type api_docs_path: str :param max_depth: Maximum depth for the index. :type max_depth: int """ base_path = os.path.split(code_path)[0] for package, subpackages, candidate_files in os.walk(code_path): # Checking __init__.py file if '__init__.py' not in candidate_files: continue # Creating directory for the package package_relative_path = package.replace(base_path + os.sep, '') index_package_path = os.path.join( api_docs_path, package_relative_path) # calculate dir one up from package to store the index in index_base_path, package_base_name = os.path.split(index_package_path) if package_base_name in EXCLUDED_PACKAGES: continue full_package_name = package_relative_path.replace(os.sep, '.') new_rst_dir = os.path.join(api_docs_path, package_relative_path) create_dirs(new_rst_dir) # Create index_file for the directory modules = get_python_files_from_list(candidate_files) index_file_text = create_package_level_rst_index_file( package_name=full_package_name, max_depth=max_depth, modules=modules, inner_packages=subpackages) write_rst_file( file_directory=index_base_path, file_name=package_base_name, content=index_file_text) # Creating .rst file for each .py file for module in modules: module = module[:-3] # strip .py off the end py_module_text = create_module_rst_file( '%s.%s' % (full_package_name, module)) write_rst_file( file_directory=new_rst_dir, file_name=module, content=py_module_text)
[ "def", "create_api_docs", "(", "code_path", ",", "api_docs_path", ",", "max_depth", "=", "2", ")", ":", "base_path", "=", "os", ".", "path", ".", "split", "(", "code_path", ")", "[", "0", "]", "for", "package", ",", "subpackages", ",", "candidate_files", ...
Function for generating .rst file for all .py file in dir_path folder. :param code_path: Path of the source code. :type code_path: str :param api_docs_path: Path of the api documentation directory. :type api_docs_path: str :param max_depth: Maximum depth for the index. :type max_depth: int
[ "Function", "for", "generating", ".", "rst", "file", "for", "all", ".", "py", "file", "in", "dir_path", "folder", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/scripts/create_api_docs.py#L218-L270
train
26,640
inasafe/inasafe
safe/gui/tools/wizard/step_kw47_default_inasafe_fields.py
StepKwDefaultInaSAFEFields.get_inasafe_fields
def get_inasafe_fields(self): """Return inasafe fields from the current wizard state. :returns: Dictionary of key and value from InaSAFE Fields. :rtype: dict """ inasafe_fields = {} parameters = self.parameter_container.get_parameters(True) for parameter in parameters: if not parameter.value == no_field: inasafe_fields[parameter.guid] = parameter.value return inasafe_fields
python
def get_inasafe_fields(self): """Return inasafe fields from the current wizard state. :returns: Dictionary of key and value from InaSAFE Fields. :rtype: dict """ inasafe_fields = {} parameters = self.parameter_container.get_parameters(True) for parameter in parameters: if not parameter.value == no_field: inasafe_fields[parameter.guid] = parameter.value return inasafe_fields
[ "def", "get_inasafe_fields", "(", "self", ")", ":", "inasafe_fields", "=", "{", "}", "parameters", "=", "self", ".", "parameter_container", ".", "get_parameters", "(", "True", ")", "for", "parameter", "in", "parameters", ":", "if", "not", "parameter", ".", "...
Return inasafe fields from the current wizard state. :returns: Dictionary of key and value from InaSAFE Fields. :rtype: dict
[ "Return", "inasafe", "fields", "from", "the", "current", "wizard", "state", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/tools/wizard/step_kw47_default_inasafe_fields.py#L195-L207
train
26,641
inasafe/inasafe
safe/gui/tools/wizard/step_kw47_default_inasafe_fields.py
StepKwDefaultInaSAFEFields.get_inasafe_default_values
def get_inasafe_default_values(self): """Return inasafe default from the current wizard state. :returns: Dictionary of key and value from InaSAFE Default Values. :rtype: dict """ inasafe_default_values = {} parameters = self.parameter_container.get_parameters(True) for parameter in parameters: if parameter.default is not None: inasafe_default_values[parameter.guid] = parameter.default return inasafe_default_values
python
def get_inasafe_default_values(self): """Return inasafe default from the current wizard state. :returns: Dictionary of key and value from InaSAFE Default Values. :rtype: dict """ inasafe_default_values = {} parameters = self.parameter_container.get_parameters(True) for parameter in parameters: if parameter.default is not None: inasafe_default_values[parameter.guid] = parameter.default return inasafe_default_values
[ "def", "get_inasafe_default_values", "(", "self", ")", ":", "inasafe_default_values", "=", "{", "}", "parameters", "=", "self", ".", "parameter_container", ".", "get_parameters", "(", "True", ")", "for", "parameter", "in", "parameters", ":", "if", "parameter", "...
Return inasafe default from the current wizard state. :returns: Dictionary of key and value from InaSAFE Default Values. :rtype: dict
[ "Return", "inasafe", "default", "from", "the", "current", "wizard", "state", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/tools/wizard/step_kw47_default_inasafe_fields.py#L209-L221
train
26,642
inasafe/inasafe
safe/gui/tools/help/function_options_help.py
function_options_help
def function_options_help(): """Help message for Function 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 function_options_help(): """Help message for Function 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", "function_options_help", "(", ")", ":", "message", "=", "m", ".", "Message", "(", ")", "message", ".", "add", "(", "m", ".", "Brand", "(", ")", ")", "message", ".", "add", "(", "heading", "(", ")", ")", "message", ".", "add", "(", "content",...
Help message for Function options Dialog. .. versionadded:: 3.2.1 :returns: A message object containing helpful information. :rtype: messaging.message.Message
[ "Help", "message", "for", "Function", "options", "Dialog", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/tools/help/function_options_help.py#L18-L31
train
26,643
inasafe/inasafe
safe/utilities/rounding.py
format_number
def format_number( x, use_rounding=True, is_population=False, coefficient=1): """Format a number according to the standards. :param x: A number to be formatted in a locale friendly way. :type x: int :param use_rounding: Flag to enable a rounding. :type use_rounding: bool :param is_population: Flag if the number is population. It needs to be used with enable_rounding. :type is_population: bool :param coefficient: Divide the result after the rounding. :type coefficient:float :returns: A locale friendly formatted string e.g. 1,000,0000.00 representing the original x. If a ValueError exception occurs, x is simply returned. :rtype: basestring """ if use_rounding: x = rounding(x, is_population) x //= coefficient number = add_separators(x) return number
python
def format_number( x, use_rounding=True, is_population=False, coefficient=1): """Format a number according to the standards. :param x: A number to be formatted in a locale friendly way. :type x: int :param use_rounding: Flag to enable a rounding. :type use_rounding: bool :param is_population: Flag if the number is population. It needs to be used with enable_rounding. :type is_population: bool :param coefficient: Divide the result after the rounding. :type coefficient:float :returns: A locale friendly formatted string e.g. 1,000,0000.00 representing the original x. If a ValueError exception occurs, x is simply returned. :rtype: basestring """ if use_rounding: x = rounding(x, is_population) x //= coefficient number = add_separators(x) return number
[ "def", "format_number", "(", "x", ",", "use_rounding", "=", "True", ",", "is_population", "=", "False", ",", "coefficient", "=", "1", ")", ":", "if", "use_rounding", ":", "x", "=", "rounding", "(", "x", ",", "is_population", ")", "x", "//=", "coefficient...
Format a number according to the standards. :param x: A number to be formatted in a locale friendly way. :type x: int :param use_rounding: Flag to enable a rounding. :type use_rounding: bool :param is_population: Flag if the number is population. It needs to be used with enable_rounding. :type is_population: bool :param coefficient: Divide the result after the rounding. :type coefficient:float :returns: A locale friendly formatted string e.g. 1,000,0000.00 representing the original x. If a ValueError exception occurs, x is simply returned. :rtype: basestring
[ "Format", "a", "number", "according", "to", "the", "standards", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/utilities/rounding.py#L17-L45
train
26,644
inasafe/inasafe
safe/utilities/rounding.py
add_separators
def add_separators(x): """Format integer with separator between thousands. :param x: A number to be formatted in a locale friendly way. :type x: int :returns: A locale friendly formatted string e.g. 1,000,0000.00 representing the original x. If a ValueError exception occurs, x is simply returned. :rtype: basestring From http:// stackoverflow.com/questions/5513615/add-thousands-separators-to-a-number Instead use this: http://docs.python.org/library/string.html#formatspec """ try: s = '{0:,}'.format(x) # s = '{0:n}'.format(x) # n means locale aware (read up on this) # see issue #526 except ValueError: return x # Quick solution for the moment if locale() in ['id', 'fr']: # Replace commas with the correct thousand separator. s = s.replace(',', thousand_separator()) return s
python
def add_separators(x): """Format integer with separator between thousands. :param x: A number to be formatted in a locale friendly way. :type x: int :returns: A locale friendly formatted string e.g. 1,000,0000.00 representing the original x. If a ValueError exception occurs, x is simply returned. :rtype: basestring From http:// stackoverflow.com/questions/5513615/add-thousands-separators-to-a-number Instead use this: http://docs.python.org/library/string.html#formatspec """ try: s = '{0:,}'.format(x) # s = '{0:n}'.format(x) # n means locale aware (read up on this) # see issue #526 except ValueError: return x # Quick solution for the moment if locale() in ['id', 'fr']: # Replace commas with the correct thousand separator. s = s.replace(',', thousand_separator()) return s
[ "def", "add_separators", "(", "x", ")", ":", "try", ":", "s", "=", "'{0:,}'", ".", "format", "(", "x", ")", "# s = '{0:n}'.format(x) # n means locale aware (read up on this)", "# see issue #526", "except", "ValueError", ":", "return", "x", "# Quick solution for the mom...
Format integer with separator between thousands. :param x: A number to be formatted in a locale friendly way. :type x: int :returns: A locale friendly formatted string e.g. 1,000,0000.00 representing the original x. If a ValueError exception occurs, x is simply returned. :rtype: basestring From http:// stackoverflow.com/questions/5513615/add-thousands-separators-to-a-number Instead use this: http://docs.python.org/library/string.html#formatspec
[ "Format", "integer", "with", "separator", "between", "thousands", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/utilities/rounding.py#L48-L76
train
26,645
inasafe/inasafe
safe/utilities/rounding.py
round_affected_number
def round_affected_number( number, use_rounding=False, use_population_rounding=False): """Tries to convert and round the number. Rounded using population rounding rule. :param number: number represented as string or float :type number: str, float :param use_rounding: flag to enable rounding :type use_rounding: bool :param use_population_rounding: flag to enable population rounding scheme :type use_population_rounding: bool :return: rounded number """ decimal_number = float(number) rounded_number = int(ceil(decimal_number)) if use_rounding and use_population_rounding: # if uses population rounding return rounding(rounded_number, use_population_rounding) elif use_rounding: return rounded_number return decimal_number
python
def round_affected_number( number, use_rounding=False, use_population_rounding=False): """Tries to convert and round the number. Rounded using population rounding rule. :param number: number represented as string or float :type number: str, float :param use_rounding: flag to enable rounding :type use_rounding: bool :param use_population_rounding: flag to enable population rounding scheme :type use_population_rounding: bool :return: rounded number """ decimal_number = float(number) rounded_number = int(ceil(decimal_number)) if use_rounding and use_population_rounding: # if uses population rounding return rounding(rounded_number, use_population_rounding) elif use_rounding: return rounded_number return decimal_number
[ "def", "round_affected_number", "(", "number", ",", "use_rounding", "=", "False", ",", "use_population_rounding", "=", "False", ")", ":", "decimal_number", "=", "float", "(", "number", ")", "rounded_number", "=", "int", "(", "ceil", "(", "decimal_number", ")", ...
Tries to convert and round the number. Rounded using population rounding rule. :param number: number represented as string or float :type number: str, float :param use_rounding: flag to enable rounding :type use_rounding: bool :param use_population_rounding: flag to enable population rounding scheme :type use_population_rounding: bool :return: rounded number
[ "Tries", "to", "convert", "and", "round", "the", "number", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/utilities/rounding.py#L112-L139
train
26,646
inasafe/inasafe
safe/utilities/rounding.py
rounding_full
def rounding_full(number, is_population=False): """This function performs a rigorous rounding. :param number: The amount to round. :type number: int, float :param is_population: If we should use the population rounding rule, #4062. :type is_population: bool :returns: result and rounding bracket. :rtype: (int, int) """ if number < 1000 and not is_population: rounding_number = 1 # See ticket #4062 elif number < 1000 and is_population: rounding_number = 10 elif number < 100000: rounding_number = 100 else: rounding_number = 1000 number = int(rounding_number * ceil(float(number) / rounding_number)) return number, rounding_number
python
def rounding_full(number, is_population=False): """This function performs a rigorous rounding. :param number: The amount to round. :type number: int, float :param is_population: If we should use the population rounding rule, #4062. :type is_population: bool :returns: result and rounding bracket. :rtype: (int, int) """ if number < 1000 and not is_population: rounding_number = 1 # See ticket #4062 elif number < 1000 and is_population: rounding_number = 10 elif number < 100000: rounding_number = 100 else: rounding_number = 1000 number = int(rounding_number * ceil(float(number) / rounding_number)) return number, rounding_number
[ "def", "rounding_full", "(", "number", ",", "is_population", "=", "False", ")", ":", "if", "number", "<", "1000", "and", "not", "is_population", ":", "rounding_number", "=", "1", "# See ticket #4062", "elif", "number", "<", "1000", "and", "is_population", ":",...
This function performs a rigorous rounding. :param number: The amount to round. :type number: int, float :param is_population: If we should use the population rounding rule, #4062. :type is_population: bool :returns: result and rounding bracket. :rtype: (int, int)
[ "This", "function", "performs", "a", "rigorous", "rounding", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/utilities/rounding.py#L142-L163
train
26,647
inasafe/inasafe
safe/utilities/rounding.py
convert_unit
def convert_unit(number, input_unit, expected_unit): """A helper to convert the unit. :param number: The number to update. :type number: int :param input_unit: The unit of the number. :type input_unit: safe.definitions.units :param expected_unit: The expected output unit. :type expected_unit: safe.definitions.units :return: The new number in the expected unit. :rtype: int """ for mapping in unit_mapping: if input_unit == mapping[0] and expected_unit == mapping[1]: return number * mapping[2] if input_unit == mapping[1] and expected_unit == mapping[0]: return number / mapping[2] return None
python
def convert_unit(number, input_unit, expected_unit): """A helper to convert the unit. :param number: The number to update. :type number: int :param input_unit: The unit of the number. :type input_unit: safe.definitions.units :param expected_unit: The expected output unit. :type expected_unit: safe.definitions.units :return: The new number in the expected unit. :rtype: int """ for mapping in unit_mapping: if input_unit == mapping[0] and expected_unit == mapping[1]: return number * mapping[2] if input_unit == mapping[1] and expected_unit == mapping[0]: return number / mapping[2] return None
[ "def", "convert_unit", "(", "number", ",", "input_unit", ",", "expected_unit", ")", ":", "for", "mapping", "in", "unit_mapping", ":", "if", "input_unit", "==", "mapping", "[", "0", "]", "and", "expected_unit", "==", "mapping", "[", "1", "]", ":", "return",...
A helper to convert the unit. :param number: The number to update. :type number: int :param input_unit: The unit of the number. :type input_unit: safe.definitions.units :param expected_unit: The expected output unit. :type expected_unit: safe.definitions.units :return: The new number in the expected unit. :rtype: int
[ "A", "helper", "to", "convert", "the", "unit", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/utilities/rounding.py#L181-L202
train
26,648
inasafe/inasafe
safe/utilities/rounding.py
coefficient_between_units
def coefficient_between_units(unit_a, unit_b): """A helper to get the coefficient between two units. :param unit_a: The first unit. :type unit_a: safe.definitions.units :param unit_b: The second unit. :type unit_b: safe.definitions.units :return: The coefficient between these two units. :rtype: float """ for mapping in unit_mapping: if unit_a == mapping[0] and unit_b == mapping[1]: return mapping[2] if unit_a == mapping[1] and unit_b == mapping[0]: return 1 / mapping[2] return None
python
def coefficient_between_units(unit_a, unit_b): """A helper to get the coefficient between two units. :param unit_a: The first unit. :type unit_a: safe.definitions.units :param unit_b: The second unit. :type unit_b: safe.definitions.units :return: The coefficient between these two units. :rtype: float """ for mapping in unit_mapping: if unit_a == mapping[0] and unit_b == mapping[1]: return mapping[2] if unit_a == mapping[1] and unit_b == mapping[0]: return 1 / mapping[2] return None
[ "def", "coefficient_between_units", "(", "unit_a", ",", "unit_b", ")", ":", "for", "mapping", "in", "unit_mapping", ":", "if", "unit_a", "==", "mapping", "[", "0", "]", "and", "unit_b", "==", "mapping", "[", "1", "]", ":", "return", "mapping", "[", "2", ...
A helper to get the coefficient between two units. :param unit_a: The first unit. :type unit_a: safe.definitions.units :param unit_b: The second unit. :type unit_b: safe.definitions.units :return: The coefficient between these two units. :rtype: float
[ "A", "helper", "to", "get", "the", "coefficient", "between", "two", "units", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/utilities/rounding.py#L205-L223
train
26,649
inasafe/inasafe
safe/utilities/rounding.py
fatalities_range
def fatalities_range(number): """A helper to return fatalities as a range of number. See https://github.com/inasafe/inasafe/issues/3666#issuecomment-283565297 :param number: The exact number. Will be converted as a range. :type number: int, float :return: The range of the number. :rtype: str """ range_format = '{min_range} - {max_range}' more_than_format = '> {min_range}' ranges = [ [0, 100], [100, 1000], [1000, 10000], [10000, 100000], [100000, float('inf')] ] for r in ranges: min_range = r[0] max_range = r[1] if max_range == float('inf'): return more_than_format.format( min_range=add_separators(min_range)) elif min_range <= number <= max_range: return range_format.format( min_range=add_separators(min_range), max_range=add_separators(max_range))
python
def fatalities_range(number): """A helper to return fatalities as a range of number. See https://github.com/inasafe/inasafe/issues/3666#issuecomment-283565297 :param number: The exact number. Will be converted as a range. :type number: int, float :return: The range of the number. :rtype: str """ range_format = '{min_range} - {max_range}' more_than_format = '> {min_range}' ranges = [ [0, 100], [100, 1000], [1000, 10000], [10000, 100000], [100000, float('inf')] ] for r in ranges: min_range = r[0] max_range = r[1] if max_range == float('inf'): return more_than_format.format( min_range=add_separators(min_range)) elif min_range <= number <= max_range: return range_format.format( min_range=add_separators(min_range), max_range=add_separators(max_range))
[ "def", "fatalities_range", "(", "number", ")", ":", "range_format", "=", "'{min_range} - {max_range}'", "more_than_format", "=", "'> {min_range}'", "ranges", "=", "[", "[", "0", ",", "100", "]", ",", "[", "100", ",", "1000", "]", ",", "[", "1000", ",", "10...
A helper to return fatalities as a range of number. See https://github.com/inasafe/inasafe/issues/3666#issuecomment-283565297 :param number: The exact number. Will be converted as a range. :type number: int, float :return: The range of the number. :rtype: str
[ "A", "helper", "to", "return", "fatalities", "as", "a", "range", "of", "number", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/utilities/rounding.py#L226-L256
train
26,650
inasafe/inasafe
safe/utilities/rounding.py
html_scientific_notation_rate
def html_scientific_notation_rate(rate): """Helper for convert decimal rate using scientific notation. For example we want to show the very detail value of fatality rate because it might be a very small number. :param rate: Rate value :type rate: float :return: Rate value with html tag to show the exponent :rtype: str """ precision = '%.3f' if rate * 100 > 0: decimal_rate = Decimal(precision % (rate * 100)) if decimal_rate == Decimal((precision % 0)): decimal_rate = Decimal(str(rate * 100)) else: decimal_rate = Decimal(str(rate * 100)) if decimal_rate.as_tuple().exponent >= -3: rate_percentage = str(decimal_rate) else: rate = '%.2E' % decimal_rate html_rate = rate.split('E') # we use html tag to show exponent html_rate[1] = '10<sup>{exponent}</sup>'.format( exponent=html_rate[1]) html_rate.insert(1, 'x') rate_percentage = ''.join(html_rate) return rate_percentage
python
def html_scientific_notation_rate(rate): """Helper for convert decimal rate using scientific notation. For example we want to show the very detail value of fatality rate because it might be a very small number. :param rate: Rate value :type rate: float :return: Rate value with html tag to show the exponent :rtype: str """ precision = '%.3f' if rate * 100 > 0: decimal_rate = Decimal(precision % (rate * 100)) if decimal_rate == Decimal((precision % 0)): decimal_rate = Decimal(str(rate * 100)) else: decimal_rate = Decimal(str(rate * 100)) if decimal_rate.as_tuple().exponent >= -3: rate_percentage = str(decimal_rate) else: rate = '%.2E' % decimal_rate html_rate = rate.split('E') # we use html tag to show exponent html_rate[1] = '10<sup>{exponent}</sup>'.format( exponent=html_rate[1]) html_rate.insert(1, 'x') rate_percentage = ''.join(html_rate) return rate_percentage
[ "def", "html_scientific_notation_rate", "(", "rate", ")", ":", "precision", "=", "'%.3f'", "if", "rate", "*", "100", ">", "0", ":", "decimal_rate", "=", "Decimal", "(", "precision", "%", "(", "rate", "*", "100", ")", ")", "if", "decimal_rate", "==", "Dec...
Helper for convert decimal rate using scientific notation. For example we want to show the very detail value of fatality rate because it might be a very small number. :param rate: Rate value :type rate: float :return: Rate value with html tag to show the exponent :rtype: str
[ "Helper", "for", "convert", "decimal", "rate", "using", "scientific", "notation", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/utilities/rounding.py#L259-L288
train
26,651
inasafe/inasafe
safe/utilities/rounding.py
denomination
def denomination(value, min_nominal=None): """Return the denomination of a number. :param value: The value. :type value: int :param min_nominal: Minimum value of denomination eg: 1000, 100. :type min_nominal: int :return: The new value and the denomination as a unit definition. :rtype: tuple(int, safe.unit.definition) """ if value is None or (hasattr(value, 'isNull') and value.isNull()): return None, None if not value: return value, None if abs(value) == list(nominal_mapping.keys())[0] and not min_nominal: return 1 * value, nominal_mapping[list(nominal_mapping.keys())[0]] # we need minimum value of denomination because we don't want to show # '2 ones', '3 tens', etc. index = 0 if min_nominal: index = int(ceil(log(min_nominal, 10))) iterator = list(zip(list(nominal_mapping.keys())[ index:], list(nominal_mapping.keys())[index + 1:])) for min_value, max_value in iterator: if min_value <= abs(value) < max_value: return float(value) / min_value, nominal_mapping[min_value] elif abs(value) < min_value: return float(value), None max_value = list(nominal_mapping.keys())[-1] new_value = float(value) / max_value new_unit = nominal_mapping[list(nominal_mapping.keys())[-1]] return new_value, new_unit
python
def denomination(value, min_nominal=None): """Return the denomination of a number. :param value: The value. :type value: int :param min_nominal: Minimum value of denomination eg: 1000, 100. :type min_nominal: int :return: The new value and the denomination as a unit definition. :rtype: tuple(int, safe.unit.definition) """ if value is None or (hasattr(value, 'isNull') and value.isNull()): return None, None if not value: return value, None if abs(value) == list(nominal_mapping.keys())[0] and not min_nominal: return 1 * value, nominal_mapping[list(nominal_mapping.keys())[0]] # we need minimum value of denomination because we don't want to show # '2 ones', '3 tens', etc. index = 0 if min_nominal: index = int(ceil(log(min_nominal, 10))) iterator = list(zip(list(nominal_mapping.keys())[ index:], list(nominal_mapping.keys())[index + 1:])) for min_value, max_value in iterator: if min_value <= abs(value) < max_value: return float(value) / min_value, nominal_mapping[min_value] elif abs(value) < min_value: return float(value), None max_value = list(nominal_mapping.keys())[-1] new_value = float(value) / max_value new_unit = nominal_mapping[list(nominal_mapping.keys())[-1]] return new_value, new_unit
[ "def", "denomination", "(", "value", ",", "min_nominal", "=", "None", ")", ":", "if", "value", "is", "None", "or", "(", "hasattr", "(", "value", ",", "'isNull'", ")", "and", "value", ".", "isNull", "(", ")", ")", ":", "return", "None", ",", "None", ...
Return the denomination of a number. :param value: The value. :type value: int :param min_nominal: Minimum value of denomination eg: 1000, 100. :type min_nominal: int :return: The new value and the denomination as a unit definition. :rtype: tuple(int, safe.unit.definition)
[ "Return", "the", "denomination", "of", "a", "number", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/utilities/rounding.py#L291-L330
train
26,652
inasafe/inasafe
safe/report/expressions/map_report.py
legend_title_header_element
def legend_title_header_element(feature, parent): """Retrieve legend title header string from definitions.""" _ = feature, parent # NOQA header = legend_title_header['string_format'] return header.capitalize()
python
def legend_title_header_element(feature, parent): """Retrieve legend title header string from definitions.""" _ = feature, parent # NOQA header = legend_title_header['string_format'] return header.capitalize()
[ "def", "legend_title_header_element", "(", "feature", ",", "parent", ")", ":", "_", "=", "feature", ",", "parent", "# NOQA", "header", "=", "legend_title_header", "[", "'string_format'", "]", "return", "header", ".", "capitalize", "(", ")" ]
Retrieve legend title header string from definitions.
[ "Retrieve", "legend", "title", "header", "string", "from", "definitions", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/report/expressions/map_report.py#L85-L89
train
26,653
inasafe/inasafe
safe/report/expressions/map_report.py
exposure_summary_layer
def exposure_summary_layer(): """Helper method for retrieving exposure summary layer. If the analysis is multi-exposure, then it will return the exposure summary layer from place exposure analysis. """ project_context_scope = QgsExpressionContextUtils.projectScope( QgsProject.instance()) project = QgsProject.instance() key = provenance_layer_analysis_impacted_id['provenance_key'] analysis_summary_layer = project.mapLayer( project_context_scope.variable(key)) if not analysis_summary_layer: key = provenance_layer_analysis_impacted['provenance_key'] if project_context_scope.hasVariable(key): analysis_summary_layer = load_layer( project_context_scope.variable(key))[0] if not analysis_summary_layer: return None keywords = KeywordIO.read_keywords(analysis_summary_layer) extra_keywords = keywords.get(property_extra_keywords['key'], {}) is_multi_exposure = extra_keywords.get(extra_keyword_analysis_type['key']) key = provenance_layer_exposure_summary_id['provenance_key'] if is_multi_exposure: key = ('{provenance}__{exposure}').format( provenance=provenance_multi_exposure_summary_layers_id[ 'provenance_key'], exposure=exposure_place['key']) if not project_context_scope.hasVariable(key): return None exposure_summary_layer = project.mapLayer( project_context_scope.variable(key)) if not exposure_summary_layer: key = provenance_layer_exposure_summary['provenance_key'] if is_multi_exposure: key = ('{provenance}__{exposure}').format( provenance=provenance_multi_exposure_summary_layers[ 'provenance_key'], exposure=exposure_place['key']) if project_context_scope.hasVariable(key): exposure_summary_layer = load_layer( project_context_scope.variable(key))[0] else: return None return exposure_summary_layer
python
def exposure_summary_layer(): """Helper method for retrieving exposure summary layer. If the analysis is multi-exposure, then it will return the exposure summary layer from place exposure analysis. """ project_context_scope = QgsExpressionContextUtils.projectScope( QgsProject.instance()) project = QgsProject.instance() key = provenance_layer_analysis_impacted_id['provenance_key'] analysis_summary_layer = project.mapLayer( project_context_scope.variable(key)) if not analysis_summary_layer: key = provenance_layer_analysis_impacted['provenance_key'] if project_context_scope.hasVariable(key): analysis_summary_layer = load_layer( project_context_scope.variable(key))[0] if not analysis_summary_layer: return None keywords = KeywordIO.read_keywords(analysis_summary_layer) extra_keywords = keywords.get(property_extra_keywords['key'], {}) is_multi_exposure = extra_keywords.get(extra_keyword_analysis_type['key']) key = provenance_layer_exposure_summary_id['provenance_key'] if is_multi_exposure: key = ('{provenance}__{exposure}').format( provenance=provenance_multi_exposure_summary_layers_id[ 'provenance_key'], exposure=exposure_place['key']) if not project_context_scope.hasVariable(key): return None exposure_summary_layer = project.mapLayer( project_context_scope.variable(key)) if not exposure_summary_layer: key = provenance_layer_exposure_summary['provenance_key'] if is_multi_exposure: key = ('{provenance}__{exposure}').format( provenance=provenance_multi_exposure_summary_layers[ 'provenance_key'], exposure=exposure_place['key']) if project_context_scope.hasVariable(key): exposure_summary_layer = load_layer( project_context_scope.variable(key))[0] else: return None return exposure_summary_layer
[ "def", "exposure_summary_layer", "(", ")", ":", "project_context_scope", "=", "QgsExpressionContextUtils", ".", "projectScope", "(", "QgsProject", ".", "instance", "(", ")", ")", "project", "=", "QgsProject", ".", "instance", "(", ")", "key", "=", "provenance_laye...
Helper method for retrieving exposure summary layer. If the analysis is multi-exposure, then it will return the exposure summary layer from place exposure analysis.
[ "Helper", "method", "for", "retrieving", "exposure", "summary", "layer", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/report/expressions/map_report.py#L92-L142
train
26,654
inasafe/inasafe
safe/report/expressions/map_report.py
distance_to_nearest_place
def distance_to_nearest_place(feature, parent): """If the impact layer has a distance field, it will return the distance to the nearest place in metres. e.g. distance_to_nearest_place() -> 1234 """ _ = feature, parent # NOQA layer = exposure_summary_layer() if not layer: return None index = layer.fields().lookupField( distance_field['field_name']) if index < 0: return None feature = next(layer.getFeatures()) return feature[index]
python
def distance_to_nearest_place(feature, parent): """If the impact layer has a distance field, it will return the distance to the nearest place in metres. e.g. distance_to_nearest_place() -> 1234 """ _ = feature, parent # NOQA layer = exposure_summary_layer() if not layer: return None index = layer.fields().lookupField( distance_field['field_name']) if index < 0: return None feature = next(layer.getFeatures()) return feature[index]
[ "def", "distance_to_nearest_place", "(", "feature", ",", "parent", ")", ":", "_", "=", "feature", ",", "parent", "# NOQA", "layer", "=", "exposure_summary_layer", "(", ")", "if", "not", "layer", ":", "return", "None", "index", "=", "layer", ".", "fields", ...
If the impact layer has a distance field, it will return the distance to the nearest place in metres. e.g. distance_to_nearest_place() -> 1234
[ "If", "the", "impact", "layer", "has", "a", "distance", "field", "it", "will", "return", "the", "distance", "to", "the", "nearest", "place", "in", "metres", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/report/expressions/map_report.py#L157-L175
train
26,655
inasafe/inasafe
safe/report/expressions/map_report.py
direction_to_nearest_place
def direction_to_nearest_place(feature, parent): """If the impact layer has a distance field, it will return the direction to the nearest place. e.g. direction_to_nearest_place() -> NW """ _ = feature, parent # NOQA layer = exposure_summary_layer() if not layer: return None index = layer.fields().lookupField( direction_field['field_name']) if index < 0: return None feature = next(layer.getFeatures()) return feature[index]
python
def direction_to_nearest_place(feature, parent): """If the impact layer has a distance field, it will return the direction to the nearest place. e.g. direction_to_nearest_place() -> NW """ _ = feature, parent # NOQA layer = exposure_summary_layer() if not layer: return None index = layer.fields().lookupField( direction_field['field_name']) if index < 0: return None feature = next(layer.getFeatures()) return feature[index]
[ "def", "direction_to_nearest_place", "(", "feature", ",", "parent", ")", ":", "_", "=", "feature", ",", "parent", "# NOQA", "layer", "=", "exposure_summary_layer", "(", ")", "if", "not", "layer", ":", "return", "None", "index", "=", "layer", ".", "fields", ...
If the impact layer has a distance field, it will return the direction to the nearest place. e.g. direction_to_nearest_place() -> NW
[ "If", "the", "impact", "layer", "has", "a", "distance", "field", "it", "will", "return", "the", "direction", "to", "the", "nearest", "place", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/report/expressions/map_report.py#L190-L208
train
26,656
inasafe/inasafe
safe/report/expressions/map_report.py
bearing_to_nearest_place
def bearing_to_nearest_place(feature, parent): """If the impact layer has a distance field, it will return the bearing to the nearest place in degrees. e.g. bearing_to_nearest_place() -> 280 """ _ = feature, parent # NOQA layer = exposure_summary_layer() if not layer: return None index = layer.fields().lookupField( bearing_field['field_name']) if index < 0: return None feature = next(layer.getFeatures()) return feature[index]
python
def bearing_to_nearest_place(feature, parent): """If the impact layer has a distance field, it will return the bearing to the nearest place in degrees. e.g. bearing_to_nearest_place() -> 280 """ _ = feature, parent # NOQA layer = exposure_summary_layer() if not layer: return None index = layer.fields().lookupField( bearing_field['field_name']) if index < 0: return None feature = next(layer.getFeatures()) return feature[index]
[ "def", "bearing_to_nearest_place", "(", "feature", ",", "parent", ")", ":", "_", "=", "feature", ",", "parent", "# NOQA", "layer", "=", "exposure_summary_layer", "(", ")", "if", "not", "layer", ":", "return", "None", "index", "=", "layer", ".", "fields", "...
If the impact layer has a distance field, it will return the bearing to the nearest place in degrees. e.g. bearing_to_nearest_place() -> 280
[ "If", "the", "impact", "layer", "has", "a", "distance", "field", "it", "will", "return", "the", "bearing", "to", "the", "nearest", "place", "in", "degrees", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/report/expressions/map_report.py#L223-L241
train
26,657
inasafe/inasafe
safe/report/expressions/map_report.py
name_of_the_nearest_place
def name_of_the_nearest_place(feature, parent): """If the impact layer has a distance field, it will return the name of the nearest place. e.g. name_of_the_nearest_place() -> Tokyo """ _ = feature, parent # NOQA layer = exposure_summary_layer() if not layer: return None index = layer.fields().lookupField( exposure_name_field['field_name']) if index < 0: return None feature = next(layer.getFeatures()) return feature[index]
python
def name_of_the_nearest_place(feature, parent): """If the impact layer has a distance field, it will return the name of the nearest place. e.g. name_of_the_nearest_place() -> Tokyo """ _ = feature, parent # NOQA layer = exposure_summary_layer() if not layer: return None index = layer.fields().lookupField( exposure_name_field['field_name']) if index < 0: return None feature = next(layer.getFeatures()) return feature[index]
[ "def", "name_of_the_nearest_place", "(", "feature", ",", "parent", ")", ":", "_", "=", "feature", ",", "parent", "# NOQA", "layer", "=", "exposure_summary_layer", "(", ")", "if", "not", "layer", ":", "return", "None", "index", "=", "layer", ".", "fields", ...
If the impact layer has a distance field, it will return the name of the nearest place. e.g. name_of_the_nearest_place() -> Tokyo
[ "If", "the", "impact", "layer", "has", "a", "distance", "field", "it", "will", "return", "the", "name", "of", "the", "nearest", "place", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/report/expressions/map_report.py#L256-L274
train
26,658
inasafe/inasafe
safe/report/expressions/map_report.py
disclaimer_title_header_element
def disclaimer_title_header_element(feature, parent): """Retrieve disclaimer title header string from definitions.""" _ = feature, parent # NOQA header = disclaimer_title_header['string_format'] return header.capitalize()
python
def disclaimer_title_header_element(feature, parent): """Retrieve disclaimer title header string from definitions.""" _ = feature, parent # NOQA header = disclaimer_title_header['string_format'] return header.capitalize()
[ "def", "disclaimer_title_header_element", "(", "feature", ",", "parent", ")", ":", "_", "=", "feature", ",", "parent", "# NOQA", "header", "=", "disclaimer_title_header", "[", "'string_format'", "]", "return", "header", ".", "capitalize", "(", ")" ]
Retrieve disclaimer title header string from definitions.
[ "Retrieve", "disclaimer", "title", "header", "string", "from", "definitions", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/report/expressions/map_report.py#L288-L292
train
26,659
inasafe/inasafe
safe/report/expressions/map_report.py
information_title_header_element
def information_title_header_element(feature, parent): """Retrieve information title header string from definitions.""" _ = feature, parent # NOQA header = information_title_header['string_format'] return header.capitalize()
python
def information_title_header_element(feature, parent): """Retrieve information title header string from definitions.""" _ = feature, parent # NOQA header = information_title_header['string_format'] return header.capitalize()
[ "def", "information_title_header_element", "(", "feature", ",", "parent", ")", ":", "_", "=", "feature", ",", "parent", "# NOQA", "header", "=", "information_title_header", "[", "'string_format'", "]", "return", "header", ".", "capitalize", "(", ")" ]
Retrieve information title header string from definitions.
[ "Retrieve", "information", "title", "header", "string", "from", "definitions", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/report/expressions/map_report.py#L323-L327
train
26,660
inasafe/inasafe
safe/report/expressions/map_report.py
time_title_header_element
def time_title_header_element(feature, parent): """Retrieve time title header string from definitions.""" _ = feature, parent # NOQA header = time_title_header['string_format'] return header.capitalize()
python
def time_title_header_element(feature, parent): """Retrieve time title header string from definitions.""" _ = feature, parent # NOQA header = time_title_header['string_format'] return header.capitalize()
[ "def", "time_title_header_element", "(", "feature", ",", "parent", ")", ":", "_", "=", "feature", ",", "parent", "# NOQA", "header", "=", "time_title_header", "[", "'string_format'", "]", "return", "header", ".", "capitalize", "(", ")" ]
Retrieve time title header string from definitions.
[ "Retrieve", "time", "title", "header", "string", "from", "definitions", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/report/expressions/map_report.py#L341-L345
train
26,661
inasafe/inasafe
safe/report/expressions/map_report.py
caution_title_header_element
def caution_title_header_element(feature, parent): """Retrieve caution title header string from definitions.""" _ = feature, parent # NOQA header = caution_title_header['string_format'] return header.capitalize()
python
def caution_title_header_element(feature, parent): """Retrieve caution title header string from definitions.""" _ = feature, parent # NOQA header = caution_title_header['string_format'] return header.capitalize()
[ "def", "caution_title_header_element", "(", "feature", ",", "parent", ")", ":", "_", "=", "feature", ",", "parent", "# NOQA", "header", "=", "caution_title_header", "[", "'string_format'", "]", "return", "header", ".", "capitalize", "(", ")" ]
Retrieve caution title header string from definitions.
[ "Retrieve", "caution", "title", "header", "string", "from", "definitions", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/report/expressions/map_report.py#L359-L363
train
26,662
inasafe/inasafe
safe/report/expressions/map_report.py
source_title_header_element
def source_title_header_element(feature, parent): """Retrieve source title header string from definitions.""" _ = feature, parent # NOQA header = source_title_header['string_format'] return header.capitalize()
python
def source_title_header_element(feature, parent): """Retrieve source title header string from definitions.""" _ = feature, parent # NOQA header = source_title_header['string_format'] return header.capitalize()
[ "def", "source_title_header_element", "(", "feature", ",", "parent", ")", ":", "_", "=", "feature", ",", "parent", "# NOQA", "header", "=", "source_title_header", "[", "'string_format'", "]", "return", "header", ".", "capitalize", "(", ")" ]
Retrieve source title header string from definitions.
[ "Retrieve", "source", "title", "header", "string", "from", "definitions", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/report/expressions/map_report.py#L395-L399
train
26,663
inasafe/inasafe
safe/report/expressions/map_report.py
analysis_title_header_element
def analysis_title_header_element(feature, parent): """Retrieve analysis title header string from definitions.""" _ = feature, parent # NOQA header = analysis_title_header['string_format'] return header.capitalize()
python
def analysis_title_header_element(feature, parent): """Retrieve analysis title header string from definitions.""" _ = feature, parent # NOQA header = analysis_title_header['string_format'] return header.capitalize()
[ "def", "analysis_title_header_element", "(", "feature", ",", "parent", ")", ":", "_", "=", "feature", ",", "parent", "# NOQA", "header", "=", "analysis_title_header", "[", "'string_format'", "]", "return", "header", ".", "capitalize", "(", ")" ]
Retrieve analysis title header string from definitions.
[ "Retrieve", "analysis", "title", "header", "string", "from", "definitions", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/report/expressions/map_report.py#L413-L417
train
26,664
inasafe/inasafe
safe/report/expressions/map_report.py
version_title_header_element
def version_title_header_element(feature, parent): """Retrieve version title header string from definitions.""" _ = feature, parent # NOQA header = version_title_header['string_format'] return header.capitalize()
python
def version_title_header_element(feature, parent): """Retrieve version title header string from definitions.""" _ = feature, parent # NOQA header = version_title_header['string_format'] return header.capitalize()
[ "def", "version_title_header_element", "(", "feature", ",", "parent", ")", ":", "_", "=", "feature", ",", "parent", "# NOQA", "header", "=", "version_title_header", "[", "'string_format'", "]", "return", "header", ".", "capitalize", "(", ")" ]
Retrieve version title header string from definitions.
[ "Retrieve", "version", "title", "header", "string", "from", "definitions", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/report/expressions/map_report.py#L431-L435
train
26,665
inasafe/inasafe
safe/report/expressions/map_report.py
crs_text_element
def crs_text_element(crs, feature, parent): """Retrieve coordinate reference system text string from definitions. Example usage: crs_text_element('EPSG:3857'). """ _ = feature, parent # NOQA crs_definition = QgsCoordinateReferenceSystem(crs) crs_description = crs_definition.description() text = crs_text['string_format'].format(crs=crs_description) return text
python
def crs_text_element(crs, feature, parent): """Retrieve coordinate reference system text string from definitions. Example usage: crs_text_element('EPSG:3857'). """ _ = feature, parent # NOQA crs_definition = QgsCoordinateReferenceSystem(crs) crs_description = crs_definition.description() text = crs_text['string_format'].format(crs=crs_description) return text
[ "def", "crs_text_element", "(", "crs", ",", "feature", ",", "parent", ")", ":", "_", "=", "feature", ",", "parent", "# NOQA", "crs_definition", "=", "QgsCoordinateReferenceSystem", "(", "crs", ")", "crs_description", "=", "crs_definition", ".", "description", "(...
Retrieve coordinate reference system text string from definitions. Example usage: crs_text_element('EPSG:3857').
[ "Retrieve", "coordinate", "reference", "system", "text", "string", "from", "definitions", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/report/expressions/map_report.py#L468-L477
train
26,666
inasafe/inasafe
safe/report/expressions/map_report.py
north_arrow_path
def north_arrow_path(feature, parent): """Retrieve the full path of default north arrow logo.""" _ = feature, parent # NOQA north_arrow_file = setting(inasafe_north_arrow_path['setting_key']) if os.path.exists(north_arrow_file): return north_arrow_file else: LOGGER.info( 'The custom north arrow is not found in {north_arrow_file}. ' 'Default north arrow will be used.').format( north_arrow_file=north_arrow_file) return inasafe_default_settings['north_arrow_path']
python
def north_arrow_path(feature, parent): """Retrieve the full path of default north arrow logo.""" _ = feature, parent # NOQA north_arrow_file = setting(inasafe_north_arrow_path['setting_key']) if os.path.exists(north_arrow_file): return north_arrow_file else: LOGGER.info( 'The custom north arrow is not found in {north_arrow_file}. ' 'Default north arrow will be used.').format( north_arrow_file=north_arrow_file) return inasafe_default_settings['north_arrow_path']
[ "def", "north_arrow_path", "(", "feature", ",", "parent", ")", ":", "_", "=", "feature", ",", "parent", "# NOQA", "north_arrow_file", "=", "setting", "(", "inasafe_north_arrow_path", "[", "'setting_key'", "]", ")", "if", "os", ".", "path", ".", "exists", "("...
Retrieve the full path of default north arrow logo.
[ "Retrieve", "the", "full", "path", "of", "default", "north", "arrow", "logo", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/report/expressions/map_report.py#L563-L575
train
26,667
inasafe/inasafe
safe/report/expressions/map_report.py
organisation_logo_path
def organisation_logo_path(feature, parent): """Retrieve the full path of used specified organisation logo.""" _ = feature, parent # NOQA organisation_logo_file = setting( inasafe_organisation_logo_path['setting_key']) if os.path.exists(organisation_logo_file): return organisation_logo_file else: LOGGER.info( 'The custom organisation logo is not found in {logo_path}. ' 'Default organisation logo will be used.').format( logo_path=organisation_logo_file) return inasafe_default_settings['organisation_logo_path']
python
def organisation_logo_path(feature, parent): """Retrieve the full path of used specified organisation logo.""" _ = feature, parent # NOQA organisation_logo_file = setting( inasafe_organisation_logo_path['setting_key']) if os.path.exists(organisation_logo_file): return organisation_logo_file else: LOGGER.info( 'The custom organisation logo is not found in {logo_path}. ' 'Default organisation logo will be used.').format( logo_path=organisation_logo_file) return inasafe_default_settings['organisation_logo_path']
[ "def", "organisation_logo_path", "(", "feature", ",", "parent", ")", ":", "_", "=", "feature", ",", "parent", "# NOQA", "organisation_logo_file", "=", "setting", "(", "inasafe_organisation_logo_path", "[", "'setting_key'", "]", ")", "if", "os", ".", "path", ".",...
Retrieve the full path of used specified organisation logo.
[ "Retrieve", "the", "full", "path", "of", "used", "specified", "organisation", "logo", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/report/expressions/map_report.py#L591-L603
train
26,668
inasafe/inasafe
safe/gui/tools/help/multi_buffer_help.py
multi_buffer_help
def multi_buffer_help(): """Help message for multi buffer dialog. .. versionadded:: 4.0.0 :returns: A message object containing helpful information. :rtype: messaging.message.Message """ message = m.Message() message.add(m.Brand()) message.add(heading()) message.add(content()) return message
python
def multi_buffer_help(): """Help message for multi buffer dialog. .. versionadded:: 4.0.0 :returns: A message object containing helpful information. :rtype: messaging.message.Message """ message = m.Message() message.add(m.Brand()) message.add(heading()) message.add(content()) return message
[ "def", "multi_buffer_help", "(", ")", ":", "message", "=", "m", ".", "Message", "(", ")", "message", ".", "add", "(", "m", ".", "Brand", "(", ")", ")", "message", ".", "add", "(", "heading", "(", ")", ")", "message", ".", "add", "(", "content", "...
Help message for multi buffer dialog. .. versionadded:: 4.0.0 :returns: A message object containing helpful information. :rtype: messaging.message.Message
[ "Help", "message", "for", "multi", "buffer", "dialog", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/tools/help/multi_buffer_help.py#L12-L24
train
26,669
inasafe/inasafe
safe/processors/post_processor_functions.py
multiply
def multiply(**kwargs): """Simple postprocessor where we multiply the input values. :param kwargs: Dictionary of values to multiply :type kwargs: dict :return: The result. :rtype: float """ result = 1 for i in list(kwargs.values()): if not i: # If one value is null, we return null. return i result *= i return result
python
def multiply(**kwargs): """Simple postprocessor where we multiply the input values. :param kwargs: Dictionary of values to multiply :type kwargs: dict :return: The result. :rtype: float """ result = 1 for i in list(kwargs.values()): if not i: # If one value is null, we return null. return i result *= i return result
[ "def", "multiply", "(", "*", "*", "kwargs", ")", ":", "result", "=", "1", "for", "i", "in", "list", "(", "kwargs", ".", "values", "(", ")", ")", ":", "if", "not", "i", ":", "# If one value is null, we return null.", "return", "i", "result", "*=", "i", ...
Simple postprocessor where we multiply the input values. :param kwargs: Dictionary of values to multiply :type kwargs: dict :return: The result. :rtype: float
[ "Simple", "postprocessor", "where", "we", "multiply", "the", "input", "values", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/processors/post_processor_functions.py#L29-L44
train
26,670
inasafe/inasafe
safe/processors/post_processor_functions.py
calculate_distance
def calculate_distance( distance_calculator, place_geometry, latitude, longitude, earthquake_hazard=None, place_exposure=None): """Simple postprocessor where we compute the distance between two points. :param distance_calculator: The size calculator. :type distance_calculator: safe.gis.vector.tools.SizeCalculator :param latitude: The latitude to use. :type latitude: float :param longitude: The longitude to use. :type longitude: float :param place_geometry: Geometry of place. :type place_geometry: QgsGeometry :param earthquake_hazard: The hazard to use. :type earthquake_hazard: str :param place_exposure: The exposure to use. :type place_exposure: str :return: distance :rtype: float """ _ = earthquake_hazard, place_exposure # NOQA epicenter = QgsPointXY(longitude, latitude) place_point = place_geometry.asPoint() distance = distance_calculator.measure_distance(epicenter, place_point) return distance
python
def calculate_distance( distance_calculator, place_geometry, latitude, longitude, earthquake_hazard=None, place_exposure=None): """Simple postprocessor where we compute the distance between two points. :param distance_calculator: The size calculator. :type distance_calculator: safe.gis.vector.tools.SizeCalculator :param latitude: The latitude to use. :type latitude: float :param longitude: The longitude to use. :type longitude: float :param place_geometry: Geometry of place. :type place_geometry: QgsGeometry :param earthquake_hazard: The hazard to use. :type earthquake_hazard: str :param place_exposure: The exposure to use. :type place_exposure: str :return: distance :rtype: float """ _ = earthquake_hazard, place_exposure # NOQA epicenter = QgsPointXY(longitude, latitude) place_point = place_geometry.asPoint() distance = distance_calculator.measure_distance(epicenter, place_point) return distance
[ "def", "calculate_distance", "(", "distance_calculator", ",", "place_geometry", ",", "latitude", ",", "longitude", ",", "earthquake_hazard", "=", "None", ",", "place_exposure", "=", "None", ")", ":", "_", "=", "earthquake_hazard", ",", "place_exposure", "# NOQA", ...
Simple postprocessor where we compute the distance between two points. :param distance_calculator: The size calculator. :type distance_calculator: safe.gis.vector.tools.SizeCalculator :param latitude: The latitude to use. :type latitude: float :param longitude: The longitude to use. :type longitude: float :param place_geometry: Geometry of place. :type place_geometry: QgsGeometry :param earthquake_hazard: The hazard to use. :type earthquake_hazard: str :param place_exposure: The exposure to use. :type place_exposure: str :return: distance :rtype: float
[ "Simple", "postprocessor", "where", "we", "compute", "the", "distance", "between", "two", "points", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/processors/post_processor_functions.py#L62-L97
train
26,671
inasafe/inasafe
safe/processors/post_processor_functions.py
calculate_bearing
def calculate_bearing( place_geometry, latitude, longitude, earthquake_hazard=None, place_exposure=None ): """Simple postprocessor where we compute the bearing angle between two points. :param place_geometry: Geometry of place. :type place_geometry: QgsGeometry :param latitude: The latitude to use. :type latitude: float :param longitude: The longitude to use. :type longitude: float :param earthquake_hazard: The hazard to use. :type earthquake_hazard: str :param place_exposure: The exposure to use. :type place_exposure: str :return: Bearing angle :rtype: float """ _ = earthquake_hazard, place_exposure # NOQA epicenter = QgsPointXY(longitude, latitude) place_point = place_geometry.asPoint() bearing = place_point.azimuth(epicenter) return bearing
python
def calculate_bearing( place_geometry, latitude, longitude, earthquake_hazard=None, place_exposure=None ): """Simple postprocessor where we compute the bearing angle between two points. :param place_geometry: Geometry of place. :type place_geometry: QgsGeometry :param latitude: The latitude to use. :type latitude: float :param longitude: The longitude to use. :type longitude: float :param earthquake_hazard: The hazard to use. :type earthquake_hazard: str :param place_exposure: The exposure to use. :type place_exposure: str :return: Bearing angle :rtype: float """ _ = earthquake_hazard, place_exposure # NOQA epicenter = QgsPointXY(longitude, latitude) place_point = place_geometry.asPoint() bearing = place_point.azimuth(epicenter) return bearing
[ "def", "calculate_bearing", "(", "place_geometry", ",", "latitude", ",", "longitude", ",", "earthquake_hazard", "=", "None", ",", "place_exposure", "=", "None", ")", ":", "_", "=", "earthquake_hazard", ",", "place_exposure", "# NOQA", "epicenter", "=", "QgsPointXY...
Simple postprocessor where we compute the bearing angle between two points. :param place_geometry: Geometry of place. :type place_geometry: QgsGeometry :param latitude: The latitude to use. :type latitude: float :param longitude: The longitude to use. :type longitude: float :param earthquake_hazard: The hazard to use. :type earthquake_hazard: str :param place_exposure: The exposure to use. :type place_exposure: str :return: Bearing angle :rtype: float
[ "Simple", "postprocessor", "where", "we", "compute", "the", "bearing", "angle", "between", "two", "points", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/processors/post_processor_functions.py#L100-L133
train
26,672
inasafe/inasafe
safe/processors/post_processor_functions.py
calculate_cardinality
def calculate_cardinality( angle, earthquake_hazard=None, place_exposure=None ): """Simple postprocessor where we compute the cardinality of an angle. :param angle: Bearing angle. :type angle: float :param earthquake_hazard: The hazard to use. :type earthquake_hazard: str :param place_exposure: The exposure to use. :type place_exposure: str :return: Cardinality text. :rtype: str """ # this method could still be improved later, since the acquisition interval # is a bit strange, i.e the input angle of 22.499° will return `N` even # though 22.5° is the direction for `NNE` _ = earthquake_hazard, place_exposure # NOQA direction_list = tr( 'N,NNE,NE,ENE,E,ESE,SE,SSE,S,SSW,SW,WSW,W,WNW,NW,NNW' ).split(',') bearing = float(angle) direction_count = len(direction_list) direction_interval = 360. / direction_count index = int(floor(bearing / direction_interval)) index %= direction_count return direction_list[index]
python
def calculate_cardinality( angle, earthquake_hazard=None, place_exposure=None ): """Simple postprocessor where we compute the cardinality of an angle. :param angle: Bearing angle. :type angle: float :param earthquake_hazard: The hazard to use. :type earthquake_hazard: str :param place_exposure: The exposure to use. :type place_exposure: str :return: Cardinality text. :rtype: str """ # this method could still be improved later, since the acquisition interval # is a bit strange, i.e the input angle of 22.499° will return `N` even # though 22.5° is the direction for `NNE` _ = earthquake_hazard, place_exposure # NOQA direction_list = tr( 'N,NNE,NE,ENE,E,ESE,SE,SSE,S,SSW,SW,WSW,W,WNW,NW,NNW' ).split(',') bearing = float(angle) direction_count = len(direction_list) direction_interval = 360. / direction_count index = int(floor(bearing / direction_interval)) index %= direction_count return direction_list[index]
[ "def", "calculate_cardinality", "(", "angle", ",", "earthquake_hazard", "=", "None", ",", "place_exposure", "=", "None", ")", ":", "# this method could still be improved later, since the acquisition interval", "# is a bit strange, i.e the input angle of 22.499° will return `N` even", ...
Simple postprocessor where we compute the cardinality of an angle. :param angle: Bearing angle. :type angle: float :param earthquake_hazard: The hazard to use. :type earthquake_hazard: str :param place_exposure: The exposure to use. :type place_exposure: str :return: Cardinality text. :rtype: str
[ "Simple", "postprocessor", "where", "we", "compute", "the", "cardinality", "of", "an", "angle", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/processors/post_processor_functions.py#L136-L169
train
26,673
inasafe/inasafe
safe/processors/post_processor_functions.py
post_processor_affected_function
def post_processor_affected_function( exposure=None, hazard=None, classification=None, hazard_class=None): """Private function used in the affected postprocessor. It returns a boolean if it's affected or not, or not exposed. :param exposure: The exposure to use. :type exposure: str :param hazard: The hazard to use. :type hazard: str :param classification: The hazard classification to use. :type classification: str :param hazard_class: The hazard class of the feature. :type hazard_class: str :return: If this hazard class is affected or not. It can be `not exposed`. The not exposed value returned is the key defined in `hazard_classification.py` at the top of the file. :rtype: bool,'not exposed' """ if exposure == exposure_population['key']: affected = is_affected( hazard, classification, hazard_class) else: classes = None for hazard in hazard_classes_all: if hazard['key'] == classification: classes = hazard['classes'] break for the_class in classes: if the_class['key'] == hazard_class: affected = the_class['affected'] break else: affected = not_exposed_class['key'] return affected
python
def post_processor_affected_function( exposure=None, hazard=None, classification=None, hazard_class=None): """Private function used in the affected postprocessor. It returns a boolean if it's affected or not, or not exposed. :param exposure: The exposure to use. :type exposure: str :param hazard: The hazard to use. :type hazard: str :param classification: The hazard classification to use. :type classification: str :param hazard_class: The hazard class of the feature. :type hazard_class: str :return: If this hazard class is affected or not. It can be `not exposed`. The not exposed value returned is the key defined in `hazard_classification.py` at the top of the file. :rtype: bool,'not exposed' """ if exposure == exposure_population['key']: affected = is_affected( hazard, classification, hazard_class) else: classes = None for hazard in hazard_classes_all: if hazard['key'] == classification: classes = hazard['classes'] break for the_class in classes: if the_class['key'] == hazard_class: affected = the_class['affected'] break else: affected = not_exposed_class['key'] return affected
[ "def", "post_processor_affected_function", "(", "exposure", "=", "None", ",", "hazard", "=", "None", ",", "classification", "=", "None", ",", "hazard_class", "=", "None", ")", ":", "if", "exposure", "==", "exposure_population", "[", "'key'", "]", ":", "affecte...
Private function used in the affected postprocessor. It returns a boolean if it's affected or not, or not exposed. :param exposure: The exposure to use. :type exposure: str :param hazard: The hazard to use. :type hazard: str :param classification: The hazard classification to use. :type classification: str :param hazard_class: The hazard class of the feature. :type hazard_class: str :return: If this hazard class is affected or not. It can be `not exposed`. The not exposed value returned is the key defined in `hazard_classification.py` at the top of the file. :rtype: bool,'not exposed'
[ "Private", "function", "used", "in", "the", "affected", "postprocessor", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/processors/post_processor_functions.py#L173-L213
train
26,674
inasafe/inasafe
safe/processors/post_processor_functions.py
post_processor_population_displacement_function
def post_processor_population_displacement_function( hazard=None, classification=None, hazard_class=None, population=None): """Private function used in the displacement postprocessor. :param hazard: The hazard to use. :type hazard: str :param classification: The hazard classification to use. :type classification: str :param hazard_class: The hazard class of the feature. :type hazard_class: str :param population: We don't use this value here. It's only used for condition for the postprocessor to run. :type population: float, int :return: The displacement ratio for a given hazard class. :rtype: float """ _ = population # NOQA return get_displacement_rate(hazard, classification, hazard_class)
python
def post_processor_population_displacement_function( hazard=None, classification=None, hazard_class=None, population=None): """Private function used in the displacement postprocessor. :param hazard: The hazard to use. :type hazard: str :param classification: The hazard classification to use. :type classification: str :param hazard_class: The hazard class of the feature. :type hazard_class: str :param population: We don't use this value here. It's only used for condition for the postprocessor to run. :type population: float, int :return: The displacement ratio for a given hazard class. :rtype: float """ _ = population # NOQA return get_displacement_rate(hazard, classification, hazard_class)
[ "def", "post_processor_population_displacement_function", "(", "hazard", "=", "None", ",", "classification", "=", "None", ",", "hazard_class", "=", "None", ",", "population", "=", "None", ")", ":", "_", "=", "population", "# NOQA", "return", "get_displacement_rate",...
Private function used in the displacement postprocessor. :param hazard: The hazard to use. :type hazard: str :param classification: The hazard classification to use. :type classification: str :param hazard_class: The hazard class of the feature. :type hazard_class: str :param population: We don't use this value here. It's only used for condition for the postprocessor to run. :type population: float, int :return: The displacement ratio for a given hazard class. :rtype: float
[ "Private", "function", "used", "in", "the", "displacement", "postprocessor", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/processors/post_processor_functions.py#L216-L238
train
26,675
inasafe/inasafe
safe/processors/post_processor_functions.py
post_processor_population_fatality_function
def post_processor_population_fatality_function( classification=None, hazard_class=None, population=None): """Private function used in the fatality postprocessor. :param classification: The hazard classification to use. :type classification: str :param hazard_class: The hazard class of the feature. :type hazard_class: str :param population: We don't use this value here. It's only used for condition for the postprocessor to run. :type population: float, int :return: The displacement ratio for a given hazard class. :rtype: float """ _ = population # NOQA for hazard in hazard_classes_all: if hazard['key'] == classification: classification = hazard['classes'] break for hazard_class_def in classification: if hazard_class_def['key'] == hazard_class: displaced_ratio = hazard_class_def.get('fatality_rate', 0.0) if displaced_ratio is None: displaced_ratio = 0.0 # We need to cast it to float to make it works. return float(displaced_ratio) return 0.0
python
def post_processor_population_fatality_function( classification=None, hazard_class=None, population=None): """Private function used in the fatality postprocessor. :param classification: The hazard classification to use. :type classification: str :param hazard_class: The hazard class of the feature. :type hazard_class: str :param population: We don't use this value here. It's only used for condition for the postprocessor to run. :type population: float, int :return: The displacement ratio for a given hazard class. :rtype: float """ _ = population # NOQA for hazard in hazard_classes_all: if hazard['key'] == classification: classification = hazard['classes'] break for hazard_class_def in classification: if hazard_class_def['key'] == hazard_class: displaced_ratio = hazard_class_def.get('fatality_rate', 0.0) if displaced_ratio is None: displaced_ratio = 0.0 # We need to cast it to float to make it works. return float(displaced_ratio) return 0.0
[ "def", "post_processor_population_fatality_function", "(", "classification", "=", "None", ",", "hazard_class", "=", "None", ",", "population", "=", "None", ")", ":", "_", "=", "population", "# NOQA", "for", "hazard", "in", "hazard_classes_all", ":", "if", "hazard"...
Private function used in the fatality postprocessor. :param classification: The hazard classification to use. :type classification: str :param hazard_class: The hazard class of the feature. :type hazard_class: str :param population: We don't use this value here. It's only used for condition for the postprocessor to run. :type population: float, int :return: The displacement ratio for a given hazard class. :rtype: float
[ "Private", "function", "used", "in", "the", "fatality", "postprocessor", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/processors/post_processor_functions.py#L241-L272
train
26,676
inasafe/inasafe
safe/utilities/metadata.py
append_ISO19115_keywords
def append_ISO19115_keywords(keywords): """Append ISO19115 from setting to keywords. :param keywords: The keywords destination. :type keywords: dict """ # Map setting's key and metadata key ISO19115_mapping = { 'ISO19115_ORGANIZATION': 'organisation', 'ISO19115_URL': 'url', 'ISO19115_EMAIL': 'email', 'ISO19115_LICENSE': 'license' } ISO19115_keywords = {} # Getting value from setting. for key, value in list(ISO19115_mapping.items()): ISO19115_keywords[value] = setting(key, expected_type=str) keywords.update(ISO19115_keywords)
python
def append_ISO19115_keywords(keywords): """Append ISO19115 from setting to keywords. :param keywords: The keywords destination. :type keywords: dict """ # Map setting's key and metadata key ISO19115_mapping = { 'ISO19115_ORGANIZATION': 'organisation', 'ISO19115_URL': 'url', 'ISO19115_EMAIL': 'email', 'ISO19115_LICENSE': 'license' } ISO19115_keywords = {} # Getting value from setting. for key, value in list(ISO19115_mapping.items()): ISO19115_keywords[value] = setting(key, expected_type=str) keywords.update(ISO19115_keywords)
[ "def", "append_ISO19115_keywords", "(", "keywords", ")", ":", "# Map setting's key and metadata key", "ISO19115_mapping", "=", "{", "'ISO19115_ORGANIZATION'", ":", "'organisation'", ",", "'ISO19115_URL'", ":", "'url'", ",", "'ISO19115_EMAIL'", ":", "'email'", ",", "'ISO19...
Append ISO19115 from setting to keywords. :param keywords: The keywords destination. :type keywords: dict
[ "Append", "ISO19115", "from", "setting", "to", "keywords", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/utilities/metadata.py#L112-L129
train
26,677
inasafe/inasafe
safe/utilities/metadata.py
write_iso19115_metadata
def write_iso19115_metadata(layer_uri, keywords, version_35=False): """Create metadata object from a layer path and keywords dictionary. This function will save these keywords to the file system or the database. :param version_35: If we write keywords version 3.5. Default to False. :type version_35: bool :param layer_uri: Uri to layer. :type layer_uri: basestring :param keywords: Dictionary of keywords. :type keywords: dict """ active_metadata_classes = METADATA_CLASSES if version_35: active_metadata_classes = METADATA_CLASSES35 if 'layer_purpose' in keywords: if keywords['layer_purpose'] in active_metadata_classes: metadata = active_metadata_classes[ keywords['layer_purpose']](layer_uri) else: LOGGER.info( 'The layer purpose is not supported explicitly. It will use ' 'generic metadata. The layer purpose is %s' % keywords['layer_purpose']) if version_35: metadata = GenericLayerMetadata35(layer_uri) else: metadata = GenericLayerMetadata(layer_uri) else: if version_35: metadata = GenericLayerMetadata35(layer_uri) else: metadata = GenericLayerMetadata(layer_uri) metadata.update_from_dict(keywords) # Always set keyword_version to the latest one. if not version_35: metadata.update_from_dict({'keyword_version': inasafe_keyword_version}) if metadata.layer_is_file_based: xml_file_path = os.path.splitext(layer_uri)[0] + '.xml' metadata.write_to_file(xml_file_path) else: metadata.write_to_db() return metadata
python
def write_iso19115_metadata(layer_uri, keywords, version_35=False): """Create metadata object from a layer path and keywords dictionary. This function will save these keywords to the file system or the database. :param version_35: If we write keywords version 3.5. Default to False. :type version_35: bool :param layer_uri: Uri to layer. :type layer_uri: basestring :param keywords: Dictionary of keywords. :type keywords: dict """ active_metadata_classes = METADATA_CLASSES if version_35: active_metadata_classes = METADATA_CLASSES35 if 'layer_purpose' in keywords: if keywords['layer_purpose'] in active_metadata_classes: metadata = active_metadata_classes[ keywords['layer_purpose']](layer_uri) else: LOGGER.info( 'The layer purpose is not supported explicitly. It will use ' 'generic metadata. The layer purpose is %s' % keywords['layer_purpose']) if version_35: metadata = GenericLayerMetadata35(layer_uri) else: metadata = GenericLayerMetadata(layer_uri) else: if version_35: metadata = GenericLayerMetadata35(layer_uri) else: metadata = GenericLayerMetadata(layer_uri) metadata.update_from_dict(keywords) # Always set keyword_version to the latest one. if not version_35: metadata.update_from_dict({'keyword_version': inasafe_keyword_version}) if metadata.layer_is_file_based: xml_file_path = os.path.splitext(layer_uri)[0] + '.xml' metadata.write_to_file(xml_file_path) else: metadata.write_to_db() return metadata
[ "def", "write_iso19115_metadata", "(", "layer_uri", ",", "keywords", ",", "version_35", "=", "False", ")", ":", "active_metadata_classes", "=", "METADATA_CLASSES", "if", "version_35", ":", "active_metadata_classes", "=", "METADATA_CLASSES35", "if", "'layer_purpose'", "i...
Create metadata object from a layer path and keywords dictionary. This function will save these keywords to the file system or the database. :param version_35: If we write keywords version 3.5. Default to False. :type version_35: bool :param layer_uri: Uri to layer. :type layer_uri: basestring :param keywords: Dictionary of keywords. :type keywords: dict
[ "Create", "metadata", "object", "from", "a", "layer", "path", "and", "keywords", "dictionary", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/utilities/metadata.py#L132-L180
train
26,678
inasafe/inasafe
safe/utilities/metadata.py
read_iso19115_metadata
def read_iso19115_metadata(layer_uri, keyword=None, version_35=False): """Retrieve keywords from a metadata object :param layer_uri: Uri to layer. :type layer_uri: basestring :param keyword: The key of keyword that want to be read. If None, return all keywords in dictionary. :type keyword: basestring :returns: Dictionary of keywords or value of key as string. :rtype: dict, basestring """ xml_uri = os.path.splitext(layer_uri)[0] + '.xml' # Remove the prefix for local file. For example csv. file_prefix = 'file:' if xml_uri.startswith(file_prefix): xml_uri = xml_uri[len(file_prefix):] if not os.path.exists(xml_uri): xml_uri = None if not xml_uri and os.path.exists(layer_uri): message = 'Layer based file but no xml file.\n' message += 'Layer path: %s.' % layer_uri raise NoKeywordsFoundError(message) if version_35: metadata = GenericLayerMetadata35(layer_uri, xml_uri) else: metadata = GenericLayerMetadata(layer_uri, xml_uri) active_metadata_classes = METADATA_CLASSES if version_35: active_metadata_classes = METADATA_CLASSES35 if metadata.layer_purpose in active_metadata_classes: metadata = active_metadata_classes[ metadata.layer_purpose](layer_uri, xml_uri) # dictionary comprehension keywords = { x[0]: x[1]['value'] for x in list(metadata.dict['properties'].items()) if x[1]['value'] is not None} if 'keyword_version' not in list(keywords.keys()) and xml_uri: message = 'No keyword version found. Metadata xml file is invalid.\n' message += 'Layer uri: %s\n' % layer_uri message += 'Keywords file: %s\n' % os.path.exists( os.path.splitext(layer_uri)[0] + '.xml') message += 'keywords:\n' for k, v in list(keywords.items()): message += '%s: %s\n' % (k, v) raise MetadataReadError(message) # Get dictionary keywords that has value != None keywords = { x[0]: x[1]['value'] for x in list(metadata.dict['properties'].items()) if x[1]['value'] is not None} if keyword: try: return keywords[keyword] except KeyError: message = 'Keyword with key %s is not found. ' % keyword message += 'Layer path: %s' % layer_uri raise KeywordNotFoundError(message) return keywords
python
def read_iso19115_metadata(layer_uri, keyword=None, version_35=False): """Retrieve keywords from a metadata object :param layer_uri: Uri to layer. :type layer_uri: basestring :param keyword: The key of keyword that want to be read. If None, return all keywords in dictionary. :type keyword: basestring :returns: Dictionary of keywords or value of key as string. :rtype: dict, basestring """ xml_uri = os.path.splitext(layer_uri)[0] + '.xml' # Remove the prefix for local file. For example csv. file_prefix = 'file:' if xml_uri.startswith(file_prefix): xml_uri = xml_uri[len(file_prefix):] if not os.path.exists(xml_uri): xml_uri = None if not xml_uri and os.path.exists(layer_uri): message = 'Layer based file but no xml file.\n' message += 'Layer path: %s.' % layer_uri raise NoKeywordsFoundError(message) if version_35: metadata = GenericLayerMetadata35(layer_uri, xml_uri) else: metadata = GenericLayerMetadata(layer_uri, xml_uri) active_metadata_classes = METADATA_CLASSES if version_35: active_metadata_classes = METADATA_CLASSES35 if metadata.layer_purpose in active_metadata_classes: metadata = active_metadata_classes[ metadata.layer_purpose](layer_uri, xml_uri) # dictionary comprehension keywords = { x[0]: x[1]['value'] for x in list(metadata.dict['properties'].items()) if x[1]['value'] is not None} if 'keyword_version' not in list(keywords.keys()) and xml_uri: message = 'No keyword version found. Metadata xml file is invalid.\n' message += 'Layer uri: %s\n' % layer_uri message += 'Keywords file: %s\n' % os.path.exists( os.path.splitext(layer_uri)[0] + '.xml') message += 'keywords:\n' for k, v in list(keywords.items()): message += '%s: %s\n' % (k, v) raise MetadataReadError(message) # Get dictionary keywords that has value != None keywords = { x[0]: x[1]['value'] for x in list(metadata.dict['properties'].items()) if x[1]['value'] is not None} if keyword: try: return keywords[keyword] except KeyError: message = 'Keyword with key %s is not found. ' % keyword message += 'Layer path: %s' % layer_uri raise KeywordNotFoundError(message) return keywords
[ "def", "read_iso19115_metadata", "(", "layer_uri", ",", "keyword", "=", "None", ",", "version_35", "=", "False", ")", ":", "xml_uri", "=", "os", ".", "path", ".", "splitext", "(", "layer_uri", ")", "[", "0", "]", "+", "'.xml'", "# Remove the prefix for local...
Retrieve keywords from a metadata object :param layer_uri: Uri to layer. :type layer_uri: basestring :param keyword: The key of keyword that want to be read. If None, return all keywords in dictionary. :type keyword: basestring :returns: Dictionary of keywords or value of key as string. :rtype: dict, basestring
[ "Retrieve", "keywords", "from", "a", "metadata", "object" ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/utilities/metadata.py#L183-L247
train
26,679
inasafe/inasafe
safe/utilities/metadata.py
active_classification
def active_classification(keywords, exposure_key): """Helper to retrieve active classification for an exposure. :param keywords: Hazard layer keywords. :type keywords: dict :param exposure_key: The exposure key. :type exposure_key: str :returns: The active classification key. None if there is no active one. :rtype: str """ classifications = None if 'classification' in keywords: return keywords['classification'] if 'layer_mode' in keywords and keywords['layer_mode'] == \ layer_mode_continuous['key']: classifications = keywords['thresholds'].get(exposure_key) elif 'value_maps' in keywords: classifications = keywords['value_maps'].get(exposure_key) if classifications is None: return None for classification, value in list(classifications.items()): if value['active']: return classification return None
python
def active_classification(keywords, exposure_key): """Helper to retrieve active classification for an exposure. :param keywords: Hazard layer keywords. :type keywords: dict :param exposure_key: The exposure key. :type exposure_key: str :returns: The active classification key. None if there is no active one. :rtype: str """ classifications = None if 'classification' in keywords: return keywords['classification'] if 'layer_mode' in keywords and keywords['layer_mode'] == \ layer_mode_continuous['key']: classifications = keywords['thresholds'].get(exposure_key) elif 'value_maps' in keywords: classifications = keywords['value_maps'].get(exposure_key) if classifications is None: return None for classification, value in list(classifications.items()): if value['active']: return classification return None
[ "def", "active_classification", "(", "keywords", ",", "exposure_key", ")", ":", "classifications", "=", "None", "if", "'classification'", "in", "keywords", ":", "return", "keywords", "[", "'classification'", "]", "if", "'layer_mode'", "in", "keywords", "and", "key...
Helper to retrieve active classification for an exposure. :param keywords: Hazard layer keywords. :type keywords: dict :param exposure_key: The exposure key. :type exposure_key: str :returns: The active classification key. None if there is no active one. :rtype: str
[ "Helper", "to", "retrieve", "active", "classification", "for", "an", "exposure", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/utilities/metadata.py#L250-L276
train
26,680
inasafe/inasafe
safe/utilities/metadata.py
active_thresholds_value_maps
def active_thresholds_value_maps(keywords, exposure_key): """Helper to retrieve active value maps or thresholds for an exposure. :param keywords: Hazard layer keywords. :type keywords: dict :param exposure_key: The exposure key. :type exposure_key: str :returns: Active thresholds or value maps. :rtype: dict """ if 'classification' in keywords: if keywords['layer_mode'] == layer_mode_continuous['key']: return keywords['thresholds'] else: return keywords['value_map'] if keywords['layer_mode'] == layer_mode_continuous['key']: classifications = keywords['thresholds'].get(exposure_key) else: classifications = keywords['value_maps'].get(exposure_key) if classifications is None: return None for value in list(classifications.values()): if value['active']: return value['classes'] return None
python
def active_thresholds_value_maps(keywords, exposure_key): """Helper to retrieve active value maps or thresholds for an exposure. :param keywords: Hazard layer keywords. :type keywords: dict :param exposure_key: The exposure key. :type exposure_key: str :returns: Active thresholds or value maps. :rtype: dict """ if 'classification' in keywords: if keywords['layer_mode'] == layer_mode_continuous['key']: return keywords['thresholds'] else: return keywords['value_map'] if keywords['layer_mode'] == layer_mode_continuous['key']: classifications = keywords['thresholds'].get(exposure_key) else: classifications = keywords['value_maps'].get(exposure_key) if classifications is None: return None for value in list(classifications.values()): if value['active']: return value['classes'] return None
[ "def", "active_thresholds_value_maps", "(", "keywords", ",", "exposure_key", ")", ":", "if", "'classification'", "in", "keywords", ":", "if", "keywords", "[", "'layer_mode'", "]", "==", "layer_mode_continuous", "[", "'key'", "]", ":", "return", "keywords", "[", ...
Helper to retrieve active value maps or thresholds for an exposure. :param keywords: Hazard layer keywords. :type keywords: dict :param exposure_key: The exposure key. :type exposure_key: str :returns: Active thresholds or value maps. :rtype: dict
[ "Helper", "to", "retrieve", "active", "value", "maps", "or", "thresholds", "for", "an", "exposure", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/utilities/metadata.py#L279-L305
train
26,681
inasafe/inasafe
safe/utilities/metadata.py
copy_layer_keywords
def copy_layer_keywords(layer_keywords): """Helper to make a deep copy of a layer keywords. :param layer_keywords: A dictionary of layer's keywords. :type layer_keywords: dict :returns: A deep copy of layer keywords. :rtype: dict """ copy_keywords = {} for key, value in list(layer_keywords.items()): if isinstance(value, QUrl): copy_keywords[key] = value.toString() elif isinstance(value, datetime): copy_keywords[key] = value.date().isoformat() elif isinstance(value, QDate): copy_keywords[key] = value.toString(Qt.ISODate) elif isinstance(value, QDateTime): copy_keywords[key] = value.toString(Qt.ISODate) elif isinstance(value, date): copy_keywords[key] = value.isoformat() else: copy_keywords[key] = deepcopy(value) return copy_keywords
python
def copy_layer_keywords(layer_keywords): """Helper to make a deep copy of a layer keywords. :param layer_keywords: A dictionary of layer's keywords. :type layer_keywords: dict :returns: A deep copy of layer keywords. :rtype: dict """ copy_keywords = {} for key, value in list(layer_keywords.items()): if isinstance(value, QUrl): copy_keywords[key] = value.toString() elif isinstance(value, datetime): copy_keywords[key] = value.date().isoformat() elif isinstance(value, QDate): copy_keywords[key] = value.toString(Qt.ISODate) elif isinstance(value, QDateTime): copy_keywords[key] = value.toString(Qt.ISODate) elif isinstance(value, date): copy_keywords[key] = value.isoformat() else: copy_keywords[key] = deepcopy(value) return copy_keywords
[ "def", "copy_layer_keywords", "(", "layer_keywords", ")", ":", "copy_keywords", "=", "{", "}", "for", "key", ",", "value", "in", "list", "(", "layer_keywords", ".", "items", "(", ")", ")", ":", "if", "isinstance", "(", "value", ",", "QUrl", ")", ":", "...
Helper to make a deep copy of a layer keywords. :param layer_keywords: A dictionary of layer's keywords. :type layer_keywords: dict :returns: A deep copy of layer keywords. :rtype: dict
[ "Helper", "to", "make", "a", "deep", "copy", "of", "a", "layer", "keywords", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/utilities/metadata.py#L308-L332
train
26,682
inasafe/inasafe
safe/gui/tools/wizard/step_kw44_fields_mapping.py
StepKwFieldsMapping.set_widgets
def set_widgets(self): """Set widgets on the Field Mapping step.""" on_the_fly_metadata = {} layer_purpose = self.parent.step_kw_purpose.selected_purpose() on_the_fly_metadata['layer_purpose'] = layer_purpose['key'] if layer_purpose != layer_purpose_aggregation: subcategory = self.parent.step_kw_subcategory.\ selected_subcategory() if layer_purpose == layer_purpose_exposure: on_the_fly_metadata['exposure'] = subcategory['key'] if layer_purpose == layer_purpose_hazard: on_the_fly_metadata['hazard'] = subcategory['key'] inasafe_fields = self.parent.get_existing_keyword( 'inasafe_fields') inasafe_default_values = self.parent.get_existing_keyword( 'inasafe_default_values') on_the_fly_metadata['inasafe_fields'] = inasafe_fields on_the_fly_metadata['inasafe_default_values'] = inasafe_default_values self.field_mapping_widget.set_layer( self.parent.layer, on_the_fly_metadata) self.field_mapping_widget.show() self.main_layout.addWidget(self.field_mapping_widget)
python
def set_widgets(self): """Set widgets on the Field Mapping step.""" on_the_fly_metadata = {} layer_purpose = self.parent.step_kw_purpose.selected_purpose() on_the_fly_metadata['layer_purpose'] = layer_purpose['key'] if layer_purpose != layer_purpose_aggregation: subcategory = self.parent.step_kw_subcategory.\ selected_subcategory() if layer_purpose == layer_purpose_exposure: on_the_fly_metadata['exposure'] = subcategory['key'] if layer_purpose == layer_purpose_hazard: on_the_fly_metadata['hazard'] = subcategory['key'] inasafe_fields = self.parent.get_existing_keyword( 'inasafe_fields') inasafe_default_values = self.parent.get_existing_keyword( 'inasafe_default_values') on_the_fly_metadata['inasafe_fields'] = inasafe_fields on_the_fly_metadata['inasafe_default_values'] = inasafe_default_values self.field_mapping_widget.set_layer( self.parent.layer, on_the_fly_metadata) self.field_mapping_widget.show() self.main_layout.addWidget(self.field_mapping_widget)
[ "def", "set_widgets", "(", "self", ")", ":", "on_the_fly_metadata", "=", "{", "}", "layer_purpose", "=", "self", ".", "parent", ".", "step_kw_purpose", ".", "selected_purpose", "(", ")", "on_the_fly_metadata", "[", "'layer_purpose'", "]", "=", "layer_purpose", "...
Set widgets on the Field Mapping step.
[ "Set", "widgets", "on", "the", "Field", "Mapping", "step", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/tools/wizard/step_kw44_fields_mapping.py#L94-L115
train
26,683
inasafe/inasafe
safe/gis/sanity_check.py
check_inasafe_fields
def check_inasafe_fields(layer, keywords_only=False): """Helper to check inasafe_fields. :param layer: The layer to check. :type layer: QgsVectorLayer :param keywords_only: If we should check from the keywords only. False by default, we will check also from the layer. :type keywords_only: bool :return: Return True if the layer is valid. :rtype: bool :raises: Exception with a message if the layer is not correct. """ inasafe_fields = layer.keywords['inasafe_fields'] real_fields = [field.name() for field in layer.fields().toList()] inasafe_fields_flat = [] for value in list(inasafe_fields.values()): if isinstance(value, list): inasafe_fields_flat.extend(value) else: inasafe_fields_flat.append(value) difference = set(inasafe_fields_flat).difference(real_fields) if len(difference): message = tr( 'inasafe_fields has more fields than the layer %s itself : %s' % (layer.keywords['layer_purpose'], difference)) raise InvalidLayerError(message) if keywords_only: # We don't check if it's valid from the layer. The layer may have more # fields than inasafe_fields. return True difference = set(real_fields).difference(inasafe_fields_flat) if len(difference): message = tr( 'The layer %s has more fields than inasafe_fields : %s' % (layer.title(), difference)) raise InvalidLayerError(message) return True
python
def check_inasafe_fields(layer, keywords_only=False): """Helper to check inasafe_fields. :param layer: The layer to check. :type layer: QgsVectorLayer :param keywords_only: If we should check from the keywords only. False by default, we will check also from the layer. :type keywords_only: bool :return: Return True if the layer is valid. :rtype: bool :raises: Exception with a message if the layer is not correct. """ inasafe_fields = layer.keywords['inasafe_fields'] real_fields = [field.name() for field in layer.fields().toList()] inasafe_fields_flat = [] for value in list(inasafe_fields.values()): if isinstance(value, list): inasafe_fields_flat.extend(value) else: inasafe_fields_flat.append(value) difference = set(inasafe_fields_flat).difference(real_fields) if len(difference): message = tr( 'inasafe_fields has more fields than the layer %s itself : %s' % (layer.keywords['layer_purpose'], difference)) raise InvalidLayerError(message) if keywords_only: # We don't check if it's valid from the layer. The layer may have more # fields than inasafe_fields. return True difference = set(real_fields).difference(inasafe_fields_flat) if len(difference): message = tr( 'The layer %s has more fields than inasafe_fields : %s' % (layer.title(), difference)) raise InvalidLayerError(message) return True
[ "def", "check_inasafe_fields", "(", "layer", ",", "keywords_only", "=", "False", ")", ":", "inasafe_fields", "=", "layer", ".", "keywords", "[", "'inasafe_fields'", "]", "real_fields", "=", "[", "field", ".", "name", "(", ")", "for", "field", "in", "layer", ...
Helper to check inasafe_fields. :param layer: The layer to check. :type layer: QgsVectorLayer :param keywords_only: If we should check from the keywords only. False by default, we will check also from the layer. :type keywords_only: bool :return: Return True if the layer is valid. :rtype: bool :raises: Exception with a message if the layer is not correct.
[ "Helper", "to", "check", "inasafe_fields", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gis/sanity_check.py#L17-L62
train
26,684
inasafe/inasafe
safe/gis/sanity_check.py
check_layer
def check_layer(layer, has_geometry=True): """Helper to check layer validity. This function wil; raise InvalidLayerError if the layer is invalid. :param layer: The layer to check. :type layer: QgsMapLayer :param has_geometry: If the layer must have a geometry. True by default. If it's a raster layer, we will no check this parameter. If we do not want to check the geometry type, we can set it to None. :type has_geometry: bool,None :raise: InvalidLayerError :return: Return True if the layer is valid. :rtype: bool """ if is_vector_layer(layer) or is_raster_layer(layer): if not layer.isValid(): raise InvalidLayerError( 'The layer is invalid : %s' % layer.publicSource()) if is_vector_layer(layer): sub_layers = layer.dataProvider().subLayers() if len(sub_layers) > 1: names = ';'.join(sub_layers) source = layer.source() raise InvalidLayerError( tr('The layer should not have many sublayers : {source} : ' '{names}').format(source=source, names=names)) # We only check the geometry if we have at least one feature. if layer.geometryType() == QgsWkbTypes.UnknownGeometry and ( layer.featureCount() != 0): raise InvalidLayerError( tr('The layer has not a valid geometry type.')) if layer.wkbType() == QgsWkbTypes.Unknown and ( layer.featureCount() != 0): raise InvalidLayerError( tr('The layer has not a valid geometry type.')) if isinstance(has_geometry, bool) and layer.featureCount() != 0: if layer.isSpatial() != has_geometry: raise InvalidLayerError( tr('The layer has not a correct geometry type.')) else: raise InvalidLayerError( tr('The layer is neither a raster nor a vector : {type}').format( type=type(layer))) return True
python
def check_layer(layer, has_geometry=True): """Helper to check layer validity. This function wil; raise InvalidLayerError if the layer is invalid. :param layer: The layer to check. :type layer: QgsMapLayer :param has_geometry: If the layer must have a geometry. True by default. If it's a raster layer, we will no check this parameter. If we do not want to check the geometry type, we can set it to None. :type has_geometry: bool,None :raise: InvalidLayerError :return: Return True if the layer is valid. :rtype: bool """ if is_vector_layer(layer) or is_raster_layer(layer): if not layer.isValid(): raise InvalidLayerError( 'The layer is invalid : %s' % layer.publicSource()) if is_vector_layer(layer): sub_layers = layer.dataProvider().subLayers() if len(sub_layers) > 1: names = ';'.join(sub_layers) source = layer.source() raise InvalidLayerError( tr('The layer should not have many sublayers : {source} : ' '{names}').format(source=source, names=names)) # We only check the geometry if we have at least one feature. if layer.geometryType() == QgsWkbTypes.UnknownGeometry and ( layer.featureCount() != 0): raise InvalidLayerError( tr('The layer has not a valid geometry type.')) if layer.wkbType() == QgsWkbTypes.Unknown and ( layer.featureCount() != 0): raise InvalidLayerError( tr('The layer has not a valid geometry type.')) if isinstance(has_geometry, bool) and layer.featureCount() != 0: if layer.isSpatial() != has_geometry: raise InvalidLayerError( tr('The layer has not a correct geometry type.')) else: raise InvalidLayerError( tr('The layer is neither a raster nor a vector : {type}').format( type=type(layer))) return True
[ "def", "check_layer", "(", "layer", ",", "has_geometry", "=", "True", ")", ":", "if", "is_vector_layer", "(", "layer", ")", "or", "is_raster_layer", "(", "layer", ")", ":", "if", "not", "layer", ".", "isValid", "(", ")", ":", "raise", "InvalidLayerError", ...
Helper to check layer validity. This function wil; raise InvalidLayerError if the layer is invalid. :param layer: The layer to check. :type layer: QgsMapLayer :param has_geometry: If the layer must have a geometry. True by default. If it's a raster layer, we will no check this parameter. If we do not want to check the geometry type, we can set it to None. :type has_geometry: bool,None :raise: InvalidLayerError :return: Return True if the layer is valid. :rtype: bool
[ "Helper", "to", "check", "layer", "validity", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gis/sanity_check.py#L65-L120
train
26,685
inasafe/inasafe
safe/defaults.py
default_provenance
def default_provenance(): """The provenance for the default values. :return: default provenance. :rtype: str """ field = TextParameter() field.name = tr('Provenance') field.description = tr('The provenance of minimum needs') field.value = 'The minimum needs are based on BNPB Perka 7/2008.' return field
python
def default_provenance(): """The provenance for the default values. :return: default provenance. :rtype: str """ field = TextParameter() field.name = tr('Provenance') field.description = tr('The provenance of minimum needs') field.value = 'The minimum needs are based on BNPB Perka 7/2008.' return field
[ "def", "default_provenance", "(", ")", ":", "field", "=", "TextParameter", "(", ")", "field", ".", "name", "=", "tr", "(", "'Provenance'", ")", "field", ".", "description", "=", "tr", "(", "'The provenance of minimum needs'", ")", "field", ".", "value", "=",...
The provenance for the default values. :return: default provenance. :rtype: str
[ "The", "provenance", "for", "the", "default", "values", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/defaults.py#L18-L28
train
26,686
inasafe/inasafe
safe/gui/tools/peta_bencana_dialog.py
PetaBencanaDialog.accept
def accept(self): """Do PetaBencana download and display it in QGIS. .. versionadded: 3.3 """ self.save_state() try: self.require_directory() except CanceledImportDialogError: return QgsApplication.instance().setOverrideCursor( QtGui.QCursor(QtCore.Qt.WaitCursor) ) source = self.define_url() # save the file as json first name = 'jakarta_flood.json' output_directory = self.output_directory.text() output_prefix = self.filename_prefix.text() overwrite = self.overwrite_flag.isChecked() date_stamp_flag = self.include_date_flag.isChecked() output_base_file_path = self.get_output_base_path( output_directory, output_prefix, date_stamp_flag, name, overwrite) title = self.tr("Can't access API") try: self.download(source, output_base_file_path) # Open downloaded file as QgsMapLayer options = QgsVectorLayer.LayerOptions(False) layer = QgsVectorLayer( output_base_file_path, 'flood', 'ogr', options) except Exception as e: disable_busy_cursor() QMessageBox.critical(self, title, str(e)) return self.time_stamp = time.strftime('%d-%b-%Y %H:%M:%S') # Now save as shp name = 'jakarta_flood.shp' output_base_file_path = self.get_output_base_path( output_directory, output_prefix, date_stamp_flag, name, overwrite) QgsVectorFileWriter.writeAsVectorFormat( layer, output_base_file_path, 'CP1250', QgsCoordinateTransform(), 'ESRI Shapefile') # Get rid of the GeoJSON layer and rather use local shp del layer self.copy_style(output_base_file_path) self.copy_keywords(output_base_file_path) layer = self.add_flooded_field(output_base_file_path) # check if the layer has feature or not if layer.featureCount() <= 0: city = self.city_combo_box.currentText() message = self.tr( 'There are no floods data available on {city} ' 'at this time.').format(city=city) display_warning_message_box( self, self.tr('No data'), message) disable_busy_cursor() else: # add the layer to the map project = QgsProject.instance() project.addMapLayer(layer) disable_busy_cursor() self.done(QDialog.Accepted)
python
def accept(self): """Do PetaBencana download and display it in QGIS. .. versionadded: 3.3 """ self.save_state() try: self.require_directory() except CanceledImportDialogError: return QgsApplication.instance().setOverrideCursor( QtGui.QCursor(QtCore.Qt.WaitCursor) ) source = self.define_url() # save the file as json first name = 'jakarta_flood.json' output_directory = self.output_directory.text() output_prefix = self.filename_prefix.text() overwrite = self.overwrite_flag.isChecked() date_stamp_flag = self.include_date_flag.isChecked() output_base_file_path = self.get_output_base_path( output_directory, output_prefix, date_stamp_flag, name, overwrite) title = self.tr("Can't access API") try: self.download(source, output_base_file_path) # Open downloaded file as QgsMapLayer options = QgsVectorLayer.LayerOptions(False) layer = QgsVectorLayer( output_base_file_path, 'flood', 'ogr', options) except Exception as e: disable_busy_cursor() QMessageBox.critical(self, title, str(e)) return self.time_stamp = time.strftime('%d-%b-%Y %H:%M:%S') # Now save as shp name = 'jakarta_flood.shp' output_base_file_path = self.get_output_base_path( output_directory, output_prefix, date_stamp_flag, name, overwrite) QgsVectorFileWriter.writeAsVectorFormat( layer, output_base_file_path, 'CP1250', QgsCoordinateTransform(), 'ESRI Shapefile') # Get rid of the GeoJSON layer and rather use local shp del layer self.copy_style(output_base_file_path) self.copy_keywords(output_base_file_path) layer = self.add_flooded_field(output_base_file_path) # check if the layer has feature or not if layer.featureCount() <= 0: city = self.city_combo_box.currentText() message = self.tr( 'There are no floods data available on {city} ' 'at this time.').format(city=city) display_warning_message_box( self, self.tr('No data'), message) disable_busy_cursor() else: # add the layer to the map project = QgsProject.instance() project.addMapLayer(layer) disable_busy_cursor() self.done(QDialog.Accepted)
[ "def", "accept", "(", "self", ")", ":", "self", ".", "save_state", "(", ")", "try", ":", "self", ".", "require_directory", "(", ")", "except", "CanceledImportDialogError", ":", "return", "QgsApplication", ".", "instance", "(", ")", ".", "setOverrideCursor", ...
Do PetaBencana download and display it in QGIS. .. versionadded: 3.3
[ "Do", "PetaBencana", "download", "and", "display", "it", "in", "QGIS", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/tools/peta_bencana_dialog.py#L205-L288
train
26,687
inasafe/inasafe
safe/gui/tools/peta_bencana_dialog.py
PetaBencanaDialog.add_flooded_field
def add_flooded_field(self, shapefile_path): """Create the layer from the local shp adding the flooded field. .. versionadded:: 3.3 Use this method to add a calculated field to a shapefile. The shapefile should have a field called 'count' containing the number of flood reports for the field. The field values will be set to 0 if the count field is < 1, otherwise it will be set to 1. :param shapefile_path: Path to the shapefile that will have the flooded field added. :type shapefile_path: basestring :return: A vector layer with the flooded field added. :rtype: QgsVectorLayer """ layer = QgsVectorLayer( shapefile_path, self.tr('Jakarta Floods'), 'ogr') # Add a calculated field indicating if a poly is flooded or not # from qgis.PyQt.QtCore import QVariant layer.startEditing() # Add field with integer from 0 to 4 which represents the flood # class. Its the same as 'state' field except that is being treated # as a string. # This is used for cartography flood_class_field = QgsField('floodclass', QVariant.Int) layer.addAttribute(flood_class_field) layer.commitChanges() layer.startEditing() flood_class_idx = layer.fields().lookupField('floodclass') flood_class_expression = QgsExpression('to_int(state)') context = QgsExpressionContext() context.setFields(layer.fields()) flood_class_expression.prepare(context) # Add field with boolean flag to say if the area is flooded # This is used by the impact function flooded_field = QgsField('flooded', QVariant.Int) layer.dataProvider().addAttributes([flooded_field]) layer.commitChanges() layer.startEditing() flooded_idx = layer.fields().lookupField('flooded') flood_flag_expression = QgsExpression('state > 0') flood_flag_expression.prepare(context) for feature in layer.getFeatures(): context.setFeature(feature) feature[flood_class_idx] = flood_class_expression.evaluate(context) feature[flooded_idx] = flood_flag_expression.evaluate(context) layer.updateFeature(feature) layer.commitChanges() return layer
python
def add_flooded_field(self, shapefile_path): """Create the layer from the local shp adding the flooded field. .. versionadded:: 3.3 Use this method to add a calculated field to a shapefile. The shapefile should have a field called 'count' containing the number of flood reports for the field. The field values will be set to 0 if the count field is < 1, otherwise it will be set to 1. :param shapefile_path: Path to the shapefile that will have the flooded field added. :type shapefile_path: basestring :return: A vector layer with the flooded field added. :rtype: QgsVectorLayer """ layer = QgsVectorLayer( shapefile_path, self.tr('Jakarta Floods'), 'ogr') # Add a calculated field indicating if a poly is flooded or not # from qgis.PyQt.QtCore import QVariant layer.startEditing() # Add field with integer from 0 to 4 which represents the flood # class. Its the same as 'state' field except that is being treated # as a string. # This is used for cartography flood_class_field = QgsField('floodclass', QVariant.Int) layer.addAttribute(flood_class_field) layer.commitChanges() layer.startEditing() flood_class_idx = layer.fields().lookupField('floodclass') flood_class_expression = QgsExpression('to_int(state)') context = QgsExpressionContext() context.setFields(layer.fields()) flood_class_expression.prepare(context) # Add field with boolean flag to say if the area is flooded # This is used by the impact function flooded_field = QgsField('flooded', QVariant.Int) layer.dataProvider().addAttributes([flooded_field]) layer.commitChanges() layer.startEditing() flooded_idx = layer.fields().lookupField('flooded') flood_flag_expression = QgsExpression('state > 0') flood_flag_expression.prepare(context) for feature in layer.getFeatures(): context.setFeature(feature) feature[flood_class_idx] = flood_class_expression.evaluate(context) feature[flooded_idx] = flood_flag_expression.evaluate(context) layer.updateFeature(feature) layer.commitChanges() return layer
[ "def", "add_flooded_field", "(", "self", ",", "shapefile_path", ")", ":", "layer", "=", "QgsVectorLayer", "(", "shapefile_path", ",", "self", ".", "tr", "(", "'Jakarta Floods'", ")", ",", "'ogr'", ")", "# Add a calculated field indicating if a poly is flooded or not", ...
Create the layer from the local shp adding the flooded field. .. versionadded:: 3.3 Use this method to add a calculated field to a shapefile. The shapefile should have a field called 'count' containing the number of flood reports for the field. The field values will be set to 0 if the count field is < 1, otherwise it will be set to 1. :param shapefile_path: Path to the shapefile that will have the flooded field added. :type shapefile_path: basestring :return: A vector layer with the flooded field added. :rtype: QgsVectorLayer
[ "Create", "the", "layer", "from", "the", "local", "shp", "adding", "the", "flooded", "field", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/tools/peta_bencana_dialog.py#L290-L341
train
26,688
inasafe/inasafe
safe/gui/tools/peta_bencana_dialog.py
PetaBencanaDialog.copy_keywords
def copy_keywords(self, shapefile_path): """Copy keywords from the OSM resource directory to the output path. .. versionadded: 3.3 In addition to copying the template, tokens within the template will be replaced with new values for the date token and title token. :param shapefile_path: Path to the shapefile that will have the flooded field added. :type shapefile_path: basestring """ source_xml_path = resources_path('petabencana', 'flood-keywords.xml') output_xml_path = shapefile_path.replace('shp', 'xml') LOGGER.info('Copying xml to: %s' % output_xml_path) title_token = '[TITLE]' new_title = self.tr('Jakarta Floods - %s' % self.time_stamp) date_token = '[DATE]' new_date = self.time_stamp with open(source_xml_path) as source_file, \ open(output_xml_path, 'w') as output_file: for line in source_file: line = line.replace(date_token, new_date) line = line.replace(title_token, new_title) output_file.write(line)
python
def copy_keywords(self, shapefile_path): """Copy keywords from the OSM resource directory to the output path. .. versionadded: 3.3 In addition to copying the template, tokens within the template will be replaced with new values for the date token and title token. :param shapefile_path: Path to the shapefile that will have the flooded field added. :type shapefile_path: basestring """ source_xml_path = resources_path('petabencana', 'flood-keywords.xml') output_xml_path = shapefile_path.replace('shp', 'xml') LOGGER.info('Copying xml to: %s' % output_xml_path) title_token = '[TITLE]' new_title = self.tr('Jakarta Floods - %s' % self.time_stamp) date_token = '[DATE]' new_date = self.time_stamp with open(source_xml_path) as source_file, \ open(output_xml_path, 'w') as output_file: for line in source_file: line = line.replace(date_token, new_date) line = line.replace(title_token, new_title) output_file.write(line)
[ "def", "copy_keywords", "(", "self", ",", "shapefile_path", ")", ":", "source_xml_path", "=", "resources_path", "(", "'petabencana'", ",", "'flood-keywords.xml'", ")", "output_xml_path", "=", "shapefile_path", ".", "replace", "(", "'shp'", ",", "'xml'", ")", "LOGG...
Copy keywords from the OSM resource directory to the output path. .. versionadded: 3.3 In addition to copying the template, tokens within the template will be replaced with new values for the date token and title token. :param shapefile_path: Path to the shapefile that will have the flooded field added. :type shapefile_path: basestring
[ "Copy", "keywords", "from", "the", "OSM", "resource", "directory", "to", "the", "output", "path", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/tools/peta_bencana_dialog.py#L343-L369
train
26,689
inasafe/inasafe
safe/gui/tools/peta_bencana_dialog.py
PetaBencanaDialog.copy_style
def copy_style(shapefile_path): """Copy style from the OSM resource directory to the output path. .. versionadded: 3.3 :param shapefile_path: Path to the shapefile that should get the path added. :type shapefile_path: basestring """ source_qml_path = resources_path('petabencana', 'flood-style.qml') output_qml_path = shapefile_path.replace('shp', 'qml') LOGGER.info('Copying qml to: %s' % output_qml_path) copy(source_qml_path, output_qml_path)
python
def copy_style(shapefile_path): """Copy style from the OSM resource directory to the output path. .. versionadded: 3.3 :param shapefile_path: Path to the shapefile that should get the path added. :type shapefile_path: basestring """ source_qml_path = resources_path('petabencana', 'flood-style.qml') output_qml_path = shapefile_path.replace('shp', 'qml') LOGGER.info('Copying qml to: %s' % output_qml_path) copy(source_qml_path, output_qml_path)
[ "def", "copy_style", "(", "shapefile_path", ")", ":", "source_qml_path", "=", "resources_path", "(", "'petabencana'", ",", "'flood-style.qml'", ")", "output_qml_path", "=", "shapefile_path", ".", "replace", "(", "'shp'", ",", "'qml'", ")", "LOGGER", ".", "info", ...
Copy style from the OSM resource directory to the output path. .. versionadded: 3.3 :param shapefile_path: Path to the shapefile that should get the path added. :type shapefile_path: basestring
[ "Copy", "style", "from", "the", "OSM", "resource", "directory", "to", "the", "output", "path", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/tools/peta_bencana_dialog.py#L372-L384
train
26,690
inasafe/inasafe
safe/gui/tools/peta_bencana_dialog.py
PetaBencanaDialog.download
def download(self, url, output_path): """Download file from API url and write to output path. :param url: URL of the API. :type url: str :param output_path: Path of output file, :type output_path: str """ request_failed_message = self.tr( "Can't access PetaBencana API: {source}").format( source=url) downloader = FileDownloader(url, output_path) result, message = downloader.download() if not result: display_warning_message_box( self, self.tr('Download error'), self.tr(request_failed_message + '\n' + message)) if result == QNetworkReply.OperationCanceledError: display_warning_message_box( self, self.tr('Download error'), self.tr(message))
python
def download(self, url, output_path): """Download file from API url and write to output path. :param url: URL of the API. :type url: str :param output_path: Path of output file, :type output_path: str """ request_failed_message = self.tr( "Can't access PetaBencana API: {source}").format( source=url) downloader = FileDownloader(url, output_path) result, message = downloader.download() if not result: display_warning_message_box( self, self.tr('Download error'), self.tr(request_failed_message + '\n' + message)) if result == QNetworkReply.OperationCanceledError: display_warning_message_box( self, self.tr('Download error'), self.tr(message))
[ "def", "download", "(", "self", ",", "url", ",", "output_path", ")", ":", "request_failed_message", "=", "self", ".", "tr", "(", "\"Can't access PetaBencana API: {source}\"", ")", ".", "format", "(", "source", "=", "url", ")", "downloader", "=", "FileDownloader"...
Download file from API url and write to output path. :param url: URL of the API. :type url: str :param output_path: Path of output file, :type output_path: str
[ "Download", "file", "from", "API", "url", "and", "write", "to", "output", "path", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/tools/peta_bencana_dialog.py#L546-L570
train
26,691
inasafe/inasafe
safe/gui/tools/peta_bencana_dialog.py
PetaBencanaDialog.populate_combo_box
def populate_combo_box(self): """Populate combobox for selecting city.""" if self.radio_button_production.isChecked(): self.source = production_api['url'] available_data = production_api['available_data'] else: self.source = development_api['url'] available_data = development_api['available_data'] self.city_combo_box.clear() for index, data in enumerate(available_data): self.city_combo_box.addItem(data['name']) self.city_combo_box.setItemData( index, data['code'], Qt.UserRole)
python
def populate_combo_box(self): """Populate combobox for selecting city.""" if self.radio_button_production.isChecked(): self.source = production_api['url'] available_data = production_api['available_data'] else: self.source = development_api['url'] available_data = development_api['available_data'] self.city_combo_box.clear() for index, data in enumerate(available_data): self.city_combo_box.addItem(data['name']) self.city_combo_box.setItemData( index, data['code'], Qt.UserRole)
[ "def", "populate_combo_box", "(", "self", ")", ":", "if", "self", ".", "radio_button_production", ".", "isChecked", "(", ")", ":", "self", ".", "source", "=", "production_api", "[", "'url'", "]", "available_data", "=", "production_api", "[", "'available_data'", ...
Populate combobox for selecting city.
[ "Populate", "combobox", "for", "selecting", "city", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/tools/peta_bencana_dialog.py#L594-L608
train
26,692
inasafe/inasafe
safe/gui/tools/peta_bencana_dialog.py
PetaBencanaDialog.define_url
def define_url(self): """Define API url based on which source is selected. :return: Valid url of selected source. :rtype: str """ current_index = self.city_combo_box.currentIndex() city_code = self.city_combo_box.itemData(current_index, Qt.UserRole) source = (self.source).format(city_code=city_code) return source
python
def define_url(self): """Define API url based on which source is selected. :return: Valid url of selected source. :rtype: str """ current_index = self.city_combo_box.currentIndex() city_code = self.city_combo_box.itemData(current_index, Qt.UserRole) source = (self.source).format(city_code=city_code) return source
[ "def", "define_url", "(", "self", ")", ":", "current_index", "=", "self", ".", "city_combo_box", ".", "currentIndex", "(", ")", "city_code", "=", "self", ".", "city_combo_box", ".", "itemData", "(", "current_index", ",", "Qt", ".", "UserRole", ")", "source",...
Define API url based on which source is selected. :return: Valid url of selected source. :rtype: str
[ "Define", "API", "url", "based", "on", "which", "source", "is", "selected", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/tools/peta_bencana_dialog.py#L610-L619
train
26,693
inasafe/inasafe
safe/report/extractors/analysis_provenance_details.py
analysis_provenance_details_simplified_extractor
def analysis_provenance_details_simplified_extractor( impact_report, component_metadata): """Extracting simplified version of provenance details of layers. This extractor will produce provenance details which will be displayed in the main report. :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 default_source = resolve_from_dictionary( extra_args, ['defaults', 'source']) default_reference = resolve_from_dictionary( extra_args, ['defaults', 'reference']) provenance_format_args = resolve_from_dictionary( extra_args, 'provenance_format') hazard_keywords = impact_report.impact_function.provenance[ 'hazard_keywords'] header = resolve_from_dictionary( provenance_format_args, 'hazard_header') provenance_format = resolve_from_dictionary( provenance_format_args, 'hazard_format') hazard_provenance = { 'header': header, 'provenance': provenance_format.format( layer_name=hazard_keywords.get('title'), source=QgsDataSourceUri.removePassword( decode_full_layer_uri(hazard_keywords.get('source'))[0] or default_source)) } exposure_keywords = impact_report.impact_function.provenance[ 'exposure_keywords'] header = resolve_from_dictionary( provenance_format_args, 'exposure_header') provenance_format = resolve_from_dictionary( provenance_format_args, 'exposure_format') exposure_provenance = { 'header': header, 'provenance': provenance_format.format( layer_name=exposure_keywords.get('title'), source=QgsDataSourceUri.removePassword( decode_full_layer_uri(exposure_keywords.get('source'))[0] or default_source)) } aggregation_keywords = impact_report.impact_function.provenance[ 'aggregation_keywords'] header = resolve_from_dictionary( provenance_format_args, 'aggregation_header') provenance_format = resolve_from_dictionary( provenance_format_args, 'aggregation_format') # only if aggregation layer used if aggregation_keywords: provenance_string = provenance_format.format( layer_name=aggregation_keywords.get('title'), source=QgsDataSourceUri.removePassword( decode_full_layer_uri(aggregation_keywords.get('source'))[0] or default_source)) else: aggregation_not_used = resolve_from_dictionary( extra_args, ['defaults', 'aggregation_not_used']) provenance_string = aggregation_not_used aggregation_provenance = { 'header': header, 'provenance': provenance_string } impact_function_name = impact_report.impact_function.name header = resolve_from_dictionary( provenance_format_args, 'impact_function_header') provenance_format = resolve_from_dictionary( provenance_format_args, 'impact_function_format') impact_function_provenance = { 'header': header, 'provenance': provenance_format.format( impact_function_name=impact_function_name, reference=default_reference) } provenance_detail = OrderedDict() provenance_detail['hazard'] = hazard_provenance provenance_detail['exposure'] = exposure_provenance provenance_detail['aggregation'] = aggregation_provenance provenance_detail['impact_function'] = impact_function_provenance analysis_details_header = resolve_from_dictionary( extra_args, ['header', 'analysis_detail']) context['component_key'] = component_metadata.key context.update({ 'header': analysis_details_header, 'details': provenance_detail }) return context
python
def analysis_provenance_details_simplified_extractor( impact_report, component_metadata): """Extracting simplified version of provenance details of layers. This extractor will produce provenance details which will be displayed in the main report. :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 default_source = resolve_from_dictionary( extra_args, ['defaults', 'source']) default_reference = resolve_from_dictionary( extra_args, ['defaults', 'reference']) provenance_format_args = resolve_from_dictionary( extra_args, 'provenance_format') hazard_keywords = impact_report.impact_function.provenance[ 'hazard_keywords'] header = resolve_from_dictionary( provenance_format_args, 'hazard_header') provenance_format = resolve_from_dictionary( provenance_format_args, 'hazard_format') hazard_provenance = { 'header': header, 'provenance': provenance_format.format( layer_name=hazard_keywords.get('title'), source=QgsDataSourceUri.removePassword( decode_full_layer_uri(hazard_keywords.get('source'))[0] or default_source)) } exposure_keywords = impact_report.impact_function.provenance[ 'exposure_keywords'] header = resolve_from_dictionary( provenance_format_args, 'exposure_header') provenance_format = resolve_from_dictionary( provenance_format_args, 'exposure_format') exposure_provenance = { 'header': header, 'provenance': provenance_format.format( layer_name=exposure_keywords.get('title'), source=QgsDataSourceUri.removePassword( decode_full_layer_uri(exposure_keywords.get('source'))[0] or default_source)) } aggregation_keywords = impact_report.impact_function.provenance[ 'aggregation_keywords'] header = resolve_from_dictionary( provenance_format_args, 'aggregation_header') provenance_format = resolve_from_dictionary( provenance_format_args, 'aggregation_format') # only if aggregation layer used if aggregation_keywords: provenance_string = provenance_format.format( layer_name=aggregation_keywords.get('title'), source=QgsDataSourceUri.removePassword( decode_full_layer_uri(aggregation_keywords.get('source'))[0] or default_source)) else: aggregation_not_used = resolve_from_dictionary( extra_args, ['defaults', 'aggregation_not_used']) provenance_string = aggregation_not_used aggregation_provenance = { 'header': header, 'provenance': provenance_string } impact_function_name = impact_report.impact_function.name header = resolve_from_dictionary( provenance_format_args, 'impact_function_header') provenance_format = resolve_from_dictionary( provenance_format_args, 'impact_function_format') impact_function_provenance = { 'header': header, 'provenance': provenance_format.format( impact_function_name=impact_function_name, reference=default_reference) } provenance_detail = OrderedDict() provenance_detail['hazard'] = hazard_provenance provenance_detail['exposure'] = exposure_provenance provenance_detail['aggregation'] = aggregation_provenance provenance_detail['impact_function'] = impact_function_provenance analysis_details_header = resolve_from_dictionary( extra_args, ['header', 'analysis_detail']) context['component_key'] = component_metadata.key context.update({ 'header': analysis_details_header, 'details': provenance_detail }) return context
[ "def", "analysis_provenance_details_simplified_extractor", "(", "impact_report", ",", "component_metadata", ")", ":", "context", "=", "{", "}", "extra_args", "=", "component_metadata", ".", "extra_args", "default_source", "=", "resolve_from_dictionary", "(", "extra_args", ...
Extracting simplified version of provenance details of layers. This extractor will produce provenance details which will be displayed in the main report. :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", "simplified", "version", "of", "provenance", "details", "of", "layers", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/report/extractors/analysis_provenance_details.py#L228-L339
train
26,694
inasafe/inasafe
safe/report/extractors/analysis_provenance_details.py
analysis_provenance_details_pdf_extractor
def analysis_provenance_details_pdf_extractor( impact_report, component_metadata): """Extracting the main provenance details to its own pdf report. For PDF generations :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.1 """ # QGIS Composer needed certain context to generate the output # - Map Settings # - Substitution maps # - Element settings, such as icon for picture file or image source context = QGISComposerContext() # we only have html elements for this html_frame_elements = [ { 'id': 'analysis-provenance-details-report', 'mode': 'text', 'text': jinja2_output_as_string( impact_report, 'analysis-provenance-details-report'), 'margin_left': 10, 'margin_top': 10, } ] context.html_frame_elements = html_frame_elements return context
python
def analysis_provenance_details_pdf_extractor( impact_report, component_metadata): """Extracting the main provenance details to its own pdf report. For PDF generations :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.1 """ # QGIS Composer needed certain context to generate the output # - Map Settings # - Substitution maps # - Element settings, such as icon for picture file or image source context = QGISComposerContext() # we only have html elements for this html_frame_elements = [ { 'id': 'analysis-provenance-details-report', 'mode': 'text', 'text': jinja2_output_as_string( impact_report, 'analysis-provenance-details-report'), 'margin_left': 10, 'margin_top': 10, } ] context.html_frame_elements = html_frame_elements return context
[ "def", "analysis_provenance_details_pdf_extractor", "(", "impact_report", ",", "component_metadata", ")", ":", "# QGIS Composer needed certain context to generate the output", "# - Map Settings", "# - Substitution maps", "# - Element settings, such as icon for picture file or image source", ...
Extracting the main provenance details to its own pdf report. For PDF generations :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.1
[ "Extracting", "the", "main", "provenance", "details", "to", "its", "own", "pdf", "report", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/report/extractors/analysis_provenance_details.py#L377-L416
train
26,695
inasafe/inasafe
safe/report/extractors/analysis_provenance_details.py
headerize
def headerize(provenances): """Create a header for each keyword. :param provenances: The keywords. :type provenances: dict :return: New keywords with header for every keyword. :rtype: dict """ special_case = { 'Inasafe': 'InaSAFE', 'Qgis': 'QGIS', 'Pyqt': 'PyQt', 'Os': 'OS', 'Gdal': 'GDAL', 'Maps': 'Map' } for key, value in list(provenances.items()): if '_' in key: header = key.replace('_', ' ').title() else: header = key.title() header_list = header.split(' ') proper_word = None proper_word_index = None for index, word in enumerate(header_list): if word in list(special_case.keys()): proper_word = special_case[word] proper_word_index = index if proper_word: header_list[proper_word_index] = proper_word header = ' '.join(header_list) provenances.update( { key: { 'header': '{header} '.format(header=header), 'content': value } }) return provenances
python
def headerize(provenances): """Create a header for each keyword. :param provenances: The keywords. :type provenances: dict :return: New keywords with header for every keyword. :rtype: dict """ special_case = { 'Inasafe': 'InaSAFE', 'Qgis': 'QGIS', 'Pyqt': 'PyQt', 'Os': 'OS', 'Gdal': 'GDAL', 'Maps': 'Map' } for key, value in list(provenances.items()): if '_' in key: header = key.replace('_', ' ').title() else: header = key.title() header_list = header.split(' ') proper_word = None proper_word_index = None for index, word in enumerate(header_list): if word in list(special_case.keys()): proper_word = special_case[word] proper_word_index = index if proper_word: header_list[proper_word_index] = proper_word header = ' '.join(header_list) provenances.update( { key: { 'header': '{header} '.format(header=header), 'content': value } }) return provenances
[ "def", "headerize", "(", "provenances", ")", ":", "special_case", "=", "{", "'Inasafe'", ":", "'InaSAFE'", ",", "'Qgis'", ":", "'QGIS'", ",", "'Pyqt'", ":", "'PyQt'", ",", "'Os'", ":", "'OS'", ",", "'Gdal'", ":", "'GDAL'", ",", "'Maps'", ":", "'Map'", ...
Create a header for each keyword. :param provenances: The keywords. :type provenances: dict :return: New keywords with header for every keyword. :rtype: dict
[ "Create", "a", "header", "for", "each", "keyword", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/report/extractors/analysis_provenance_details.py#L419-L464
train
26,696
inasafe/inasafe
safe/report/extractors/analysis_provenance_details.py
resolve_dict_keywords
def resolve_dict_keywords(keywords): """Replace dictionary content with html. :param keywords: The keywords. :type keywords: dict :return: New keywords with updated content. :rtype: dict """ for keyword in ['value_map', 'inasafe_fields', 'inasafe_default_values']: value = keywords.get(keyword) if value: value = value.get('content') value = KeywordIO._dict_to_row(value).to_html() keywords[keyword]['content'] = value value_maps = keywords.get('value_maps') thresholds = keywords.get('thresholds') if value_maps: value_maps = value_maps.get('content') value_maps = KeywordIO._value_maps_row(value_maps).to_html() keywords['value_maps']['content'] = value_maps if thresholds: thresholds = thresholds.get('content') thresholds = KeywordIO._threshold_to_row(thresholds).to_html() keywords['thresholds']['content'] = thresholds return keywords
python
def resolve_dict_keywords(keywords): """Replace dictionary content with html. :param keywords: The keywords. :type keywords: dict :return: New keywords with updated content. :rtype: dict """ for keyword in ['value_map', 'inasafe_fields', 'inasafe_default_values']: value = keywords.get(keyword) if value: value = value.get('content') value = KeywordIO._dict_to_row(value).to_html() keywords[keyword]['content'] = value value_maps = keywords.get('value_maps') thresholds = keywords.get('thresholds') if value_maps: value_maps = value_maps.get('content') value_maps = KeywordIO._value_maps_row(value_maps).to_html() keywords['value_maps']['content'] = value_maps if thresholds: thresholds = thresholds.get('content') thresholds = KeywordIO._threshold_to_row(thresholds).to_html() keywords['thresholds']['content'] = thresholds return keywords
[ "def", "resolve_dict_keywords", "(", "keywords", ")", ":", "for", "keyword", "in", "[", "'value_map'", ",", "'inasafe_fields'", ",", "'inasafe_default_values'", "]", ":", "value", "=", "keywords", ".", "get", "(", "keyword", ")", "if", "value", ":", "value", ...
Replace dictionary content with html. :param keywords: The keywords. :type keywords: dict :return: New keywords with updated content. :rtype: dict
[ "Replace", "dictionary", "content", "with", "html", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/report/extractors/analysis_provenance_details.py#L467-L495
train
26,697
inasafe/inasafe
safe/report/extractors/analysis_provenance_details.py
sorted_keywords_by_order
def sorted_keywords_by_order(keywords, order): """Sort keywords based on defined order. :param keywords: Keyword to be sorted. :type keywords: dict :param order: Ordered list of key. :type order: list :return: Ordered dictionary based on order list. :rtype: OrderedDict """ # we need to delete item with no value for key, value in list(keywords.items()): if value is None: del keywords[key] ordered_keywords = OrderedDict() for key in order: if key in list(keywords.keys()): ordered_keywords[key] = keywords.get(key) for keyword in keywords: if keyword not in order: ordered_keywords[keyword] = keywords.get(keyword) return ordered_keywords
python
def sorted_keywords_by_order(keywords, order): """Sort keywords based on defined order. :param keywords: Keyword to be sorted. :type keywords: dict :param order: Ordered list of key. :type order: list :return: Ordered dictionary based on order list. :rtype: OrderedDict """ # we need to delete item with no value for key, value in list(keywords.items()): if value is None: del keywords[key] ordered_keywords = OrderedDict() for key in order: if key in list(keywords.keys()): ordered_keywords[key] = keywords.get(key) for keyword in keywords: if keyword not in order: ordered_keywords[keyword] = keywords.get(keyword) return ordered_keywords
[ "def", "sorted_keywords_by_order", "(", "keywords", ",", "order", ")", ":", "# we need to delete item with no value", "for", "key", ",", "value", "in", "list", "(", "keywords", ".", "items", "(", ")", ")", ":", "if", "value", "is", "None", ":", "del", "keywo...
Sort keywords based on defined order. :param keywords: Keyword to be sorted. :type keywords: dict :param order: Ordered list of key. :type order: list :return: Ordered dictionary based on order list. :rtype: OrderedDict
[ "Sort", "keywords", "based", "on", "defined", "order", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/report/extractors/analysis_provenance_details.py#L498-L525
train
26,698
inasafe/inasafe
safe/plugin.py
Plugin.add_action
def add_action(self, action, add_to_toolbar=True, add_to_legend=False): """Add a toolbar icon to the InaSAFE toolbar. :param action: The action that should be added to the toolbar. :type action: QAction :param add_to_toolbar: Flag indicating whether the action should also be added to the InaSAFE toolbar. Defaults to True. :type add_to_toolbar: bool :param add_to_legend: Flag indicating whether the action should also be added to the layer legend menu. Default to False. :type add_to_legend: bool """ # store in the class list of actions for easy plugin unloading self.actions.append(action) self.iface.addPluginToMenu(self.tr('InaSAFE'), action) if add_to_toolbar: self.toolbar.addAction(action) if add_to_legend: # The id is the action name without spaces, tabs ... self.iface.addCustomActionForLayerType( action, self.tr('InaSAFE'), QgsMapLayer.VectorLayer, True) self.iface.addCustomActionForLayerType( action, self.tr('InaSAFE'), QgsMapLayer.RasterLayer, True)
python
def add_action(self, action, add_to_toolbar=True, add_to_legend=False): """Add a toolbar icon to the InaSAFE toolbar. :param action: The action that should be added to the toolbar. :type action: QAction :param add_to_toolbar: Flag indicating whether the action should also be added to the InaSAFE toolbar. Defaults to True. :type add_to_toolbar: bool :param add_to_legend: Flag indicating whether the action should also be added to the layer legend menu. Default to False. :type add_to_legend: bool """ # store in the class list of actions for easy plugin unloading self.actions.append(action) self.iface.addPluginToMenu(self.tr('InaSAFE'), action) if add_to_toolbar: self.toolbar.addAction(action) if add_to_legend: # The id is the action name without spaces, tabs ... self.iface.addCustomActionForLayerType( action, self.tr('InaSAFE'), QgsMapLayer.VectorLayer, True) self.iface.addCustomActionForLayerType( action, self.tr('InaSAFE'), QgsMapLayer.RasterLayer, True)
[ "def", "add_action", "(", "self", ",", "action", ",", "add_to_toolbar", "=", "True", ",", "add_to_legend", "=", "False", ")", ":", "# store in the class list of actions for easy plugin unloading", "self", ".", "actions", ".", "append", "(", "action", ")", "self", ...
Add a toolbar icon to the InaSAFE toolbar. :param action: The action that should be added to the toolbar. :type action: QAction :param add_to_toolbar: Flag indicating whether the action should also be added to the InaSAFE toolbar. Defaults to True. :type add_to_toolbar: bool :param add_to_legend: Flag indicating whether the action should also be added to the layer legend menu. Default to False. :type add_to_legend: bool
[ "Add", "a", "toolbar", "icon", "to", "the", "InaSAFE", "toolbar", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/plugin.py#L138-L168
train
26,699