idx int64 0 251k | question stringlengths 53 3.53k | target stringlengths 5 1.23k | len_question int64 20 893 | len_target int64 3 238 |
|---|---|---|---|---|
26,800 | def on_lstClassifications_itemSelectionChanged ( self ) : self . clear_further_steps ( ) classification = self . selected_classification ( ) # Exit if no selection if not classification : return # Set description label self . lblDescribeClassification . setText ( classification [ "description" ] ) # Enable the next button self . parent . pbnNext . setEnabled ( True ) | Update classification description label and unlock the Next button . | 87 | 10 |
26,801 | def selected_classification ( self ) : item = self . lstClassifications . currentItem ( ) try : return definition ( item . data ( QtCore . Qt . UserRole ) ) except ( AttributeError , NameError ) : return None | Obtain the classification selected by user . | 52 | 8 |
26,802 | def set_widgets ( self ) : self . clear_further_steps ( ) purpose = self . parent . step_kw_purpose . selected_purpose ( ) [ 'name' ] subcategory = self . parent . step_kw_subcategory . selected_subcategory ( ) [ 'name' ] self . lstClassifications . clear ( ) self . lblDescribeClassification . setText ( '' ) self . lblSelectClassification . setText ( classification_question % ( subcategory , purpose ) ) classifications = self . classifications_for_layer ( ) for classification in classifications : if not isinstance ( classification , dict ) : classification = definition ( classification ) item = QListWidgetItem ( classification [ 'name' ] , self . lstClassifications ) item . setData ( QtCore . Qt . UserRole , classification [ 'key' ] ) self . lstClassifications . addItem ( item ) # Set values based on existing keywords (if already assigned) classification_keyword = self . parent . get_existing_keyword ( 'classification' ) if classification_keyword : classifications = [ ] for index in range ( self . lstClassifications . count ( ) ) : item = self . lstClassifications . item ( index ) classifications . append ( item . data ( QtCore . Qt . UserRole ) ) if classification_keyword in classifications : self . lstClassifications . setCurrentRow ( classifications . index ( classification_keyword ) ) self . auto_select_one_item ( self . lstClassifications ) | Set widgets on the Classification tab . | 340 | 7 |
26,803 | def siblings_files ( path ) : file_basename , extension = splitext ( path ) main_extension = extension . lower ( ) files = { } if extension . lower ( ) in list ( extension_siblings . keys ( ) ) : for text_extension in list ( extension_siblings [ main_extension ] . keys ( ) ) : if isfile ( file_basename + text_extension ) : files [ file_basename + text_extension ] = ( extension_siblings [ main_extension ] [ text_extension ] ) if len ( files ) > 0 : mime_base_file = extension_siblings [ main_extension ] [ main_extension ] else : mime_base_file = None return files , mime_base_file | Return a list of sibling files available . | 174 | 8 |
26,804 | def pretty_print_post ( req ) : print ( ( '{}\n{}\n{}\n\n{}' . format ( '-----------START-----------' , req . method + ' ' + req . url , '\n' . join ( '{}: {}' . format ( k , v ) for k , v in list ( req . headers . items ( ) ) ) , req . body , ) ) ) | Helper to print a prepared query . Useful to debug a POST query . | 92 | 14 |
26,805 | def login_user ( server , login , password ) : login_url = urljoin ( server , login_url_prefix ) # Start the web session session = requests . session ( ) result = session . get ( login_url ) # Check if the request ok if not result . ok : message = ( tr ( 'Request failed to {geonode_url}, got status code {status_code} ' 'and reason {request_reason}' ) . format ( geonode_url = server , status_code = result . status_code , request_reason = result . reason ) ) raise GeoNodeInstanceError ( message ) # Take the CSRF token login_form_regexp = ( "<input type='hidden' name='csrfmiddlewaretoken' value='(.*)' />" ) expression_compiled = re . compile ( login_form_regexp ) match = expression_compiled . search ( result . text ) csrf_token = match . groups ( ) [ 0 ] payload = { 'username' : login , 'password' : password , 'csrfmiddlewaretoken' : csrf_token , } # Make the login result = session . post ( login_url , data = payload , headers = dict ( referer = login_url ) ) # Check the result url to check if the login success if result . url == login_url : message = tr ( 'Failed to login to GeoNode at {geonode_url}' ) . format ( geonode_url = server ) raise GeoNodeLoginError ( message ) return session | Get the login session . | 336 | 5 |
26,806 | def upload ( server , session , base_file , charset = 'UTF-8' ) : file_ext = os . path . splitext ( base_file ) [ 1 ] is_geojson = file_ext in [ '.geojson' , '.json' ] original_sibling_files , _ = siblings_files ( base_file ) if is_geojson : # base_file = os.path.splitext(base_file)[0] # create temp shapefile convert_geojson_to_shapefile ( base_file ) base_file = os . path . splitext ( base_file ) [ 0 ] + '.shp' upload_url = urljoin ( server , upload_url_prefix ) result = session . get ( upload_url ) # Get the upload CSRF token expression = re . compile ( 'csrf_token(\s*)=(\s*)"([a-zA-Z0-9]*?)",' ) match = expression . search ( result . text ) csrf_token = match . groups ( ) [ 2 ] # Start the data dict payload = { 'charset' : charset , 'permissions' : ( '{"users":{"AnonymousUser":' '["view_resourcebase","download_resourcebase"]},"groups":{}}' ) } headers = dict ( ) headers [ 'referer' ] = upload_url headers [ 'X-CSRFToken' ] = csrf_token files , mime = siblings_files ( base_file ) if len ( files ) < 1 : raise RuntimeError ( tr ( 'The base layer is not recognised.' ) ) name_file = split ( base_file ) [ 1 ] multiple_files = [ ( 'base_file' , ( name_file , open ( base_file , 'rb' ) , mime ) ) , ] for sibling , mime in list ( files . items ( ) ) : if sibling != base_file : name_param = splitext ( sibling ) [ 1 ] [ 1 : ] name_file = split ( sibling ) [ 1 ] open_file = ( name_file , open ( sibling , 'rb' ) , mime ) definition = ( '{}_file' . format ( name_param ) , open_file ) multiple_files . append ( definition ) # For debug upload_request = requests . Request ( 'POST' , upload_url , data = payload , files = multiple_files , headers = headers ) prepared_request = session . prepare_request ( upload_request ) # For debug # pretty_print_post(prepared_request) result = session . send ( prepared_request ) # Clean up shapefile and its sibling friends if is_geojson : for filename in files . keys ( ) : if filename not in original_sibling_files : try : os . remove ( filename ) except OSError : pass if result . ok : result = json . loads ( result . content ) full_url = server + result [ 'url' ] result [ 'full_url' ] = full_url return result else : message = ( tr ( 'Failed to upload layer. Got HTTP Status Code {status_code} and ' 'the reason is {reason}' ) . format ( status_code = result . status_code , reason = result . reason ) ) raise GeoNodeLayerUploadError ( message ) | Push a layer to a Geonode instance . | 734 | 10 |
26,807 | def add_logging_handler_once ( logger , handler ) : class_name = handler . __class__ . __name__ for logger_handler in logger . handlers : if logger_handler . __class__ . __name__ == class_name : return False logger . addHandler ( handler ) return True | A helper to add a handler to a logger ensuring there are no duplicates . | 65 | 16 |
26,808 | def emit ( self , record ) : try : # Check logging.LogRecord properties for lots of other goodies # like line number etc. you can get from the log message. QgsMessageLog . logMessage ( record . getMessage ( ) , 'InaSAFE' , 0 ) except MemoryError : message = tr ( 'Due to memory limitations on this machine, InaSAFE can not ' 'handle the full log' ) print ( message ) QgsMessageLog . logMessage ( message , 'InaSAFE' , 0 ) | Try to log the message to QGIS if available otherwise do nothing . | 114 | 15 |
26,809 | def initialize_processing ( ) : need_initialize = False needed_algorithms = [ 'native:clip' , 'gdal:cliprasterbyextent' , 'native:union' , 'native:intersection' ] if not QgsApplication . processingRegistry ( ) . algorithms ( ) : need_initialize = True if not need_initialize : for needed_algorithm in needed_algorithms : if not QgsApplication . processingRegistry ( ) . algorithmById ( needed_algorithm ) : need_initialize = True break if need_initialize : QgsApplication . processingRegistry ( ) . addProvider ( QgsNativeAlgorithms ( ) ) processing . Processing . initialize ( ) | Initializes processing if it s not already been done | 155 | 10 |
26,810 | def create_processing_context ( feedback ) : context = QgsProcessingContext ( ) context . setFeedback ( feedback ) context . setProject ( QgsProject . instance ( ) ) # skip Processing geometry checks - Inasafe has its own geometry validation # routines which have already been used context . setInvalidGeometryCheck ( QgsFeatureRequest . GeometryNoCheck ) return context | Creates a default processing context | 81 | 6 |
26,811 | def add_layer ( self , layer , layer_name , save_style = False ) : if self . _use_index : layer_name = '%s-%s' % ( self . _index , layer_name ) self . _index += 1 if self . layer_uri ( layer_name ) : return False , tr ( 'The layer already exists in the datastore.' ) if isinstance ( layer , QgsRasterLayer ) : result = self . _add_raster_layer ( layer , layer_name , save_style ) else : if layer . wkbType ( ) == QgsWkbTypes . NoGeometry : result = self . _add_tabular_layer ( layer , layer_name , save_style ) else : result = self . _add_vector_layer ( layer , layer_name , save_style ) if result [ 0 ] : LOGGER . info ( 'Layer saved {layer_name}' . format ( layer_name = result [ 1 ] ) ) try : layer . keywords real_layer = self . layer ( result [ 1 ] ) if isinstance ( real_layer , bool ) : message = ( '{name} was not found in the datastore or the ' 'layer was not valid.' . format ( name = result [ 1 ] ) ) LOGGER . debug ( message ) return False , message KeywordIO ( ) . write_keywords ( real_layer , layer . keywords ) except AttributeError : pass return result | Add a layer to the datastore . | 321 | 9 |
26,812 | def layer ( self , layer_name ) : uri = self . layer_uri ( layer_name ) layer = QgsVectorLayer ( uri , layer_name , 'ogr' ) if not layer . isValid ( ) : layer = QgsRasterLayer ( uri , layer_name ) if not layer . isValid ( ) : return False monkey_patch_keywords ( layer ) return layer | Get QGIS layer . | 88 | 6 |
26,813 | def layer_keyword ( self , keyword , value ) : for layer in sorted ( self . layers ( ) , reverse = True ) : qgis_layer = self . layer ( layer ) if qgis_layer . keywords . get ( keyword ) == value : return qgis_layer return None | Get a layer according to a keyword and its value . | 65 | 11 |
26,814 | def purposes_for_layer ( layer_geometry_key ) : return_value = [ ] for layer_purpose in layer_purposes : layer_geometry_keys = [ i [ 'key' ] for i in layer_purpose [ 'allowed_geometries' ] ] if layer_geometry_key in layer_geometry_keys : return_value . append ( layer_purpose [ 'key' ] ) return sorted ( return_value ) | Get purposes of a layer geometry id . | 98 | 8 |
26,815 | def hazards_for_layer ( layer_geometry_key ) : result = [ ] for hazard in hazard_all : if layer_geometry_key in hazard . get ( 'allowed_geometries' ) : result . append ( hazard ) return sorted ( result , key = lambda k : k [ 'key' ] ) | Get hazard categories form layer_geometry_key . | 70 | 11 |
26,816 | def exposures_for_layer ( layer_geometry_key ) : result = [ ] for exposure in exposure_all : if layer_geometry_key in exposure . get ( 'allowed_geometries' ) : result . append ( exposure ) return sorted ( result , key = lambda k : k [ 'key' ] ) | Get hazard categories form layer_geometry_key | 70 | 10 |
26,817 | def get_layer_modes ( subcategory ) : layer_modes = definition ( subcategory ) [ 'layer_modes' ] return sorted ( layer_modes , key = lambda k : k [ 'key' ] ) | Return all sorted layer modes from exposure or hazard . | 50 | 10 |
26,818 | def hazard_units ( hazard ) : units = definition ( hazard ) [ 'continuous_hazard_units' ] return sorted ( units , key = lambda k : k [ 'key' ] ) | Helper to get unit of a hazard . | 41 | 8 |
26,819 | def exposure_units ( exposure ) : units = definition ( exposure ) [ 'units' ] return sorted ( units , key = lambda k : k [ 'key' ] ) | Helper to get unit of an exposure . | 36 | 8 |
26,820 | def get_classifications ( subcategory_key ) : classifications = definition ( subcategory_key ) [ 'classifications' ] return sorted ( classifications , key = lambda k : k [ 'key' ] ) | Get hazard or exposure classifications . | 46 | 7 |
26,821 | def get_fields ( layer_purpose , layer_subcategory = None , replace_null = None , in_group = True ) : fields_for_purpose = [ ] if layer_purpose == layer_purpose_exposure [ 'key' ] : if layer_subcategory : subcategory = definition ( layer_subcategory ) fields_for_purpose += subcategory [ 'compulsory_fields' ] fields_for_purpose += subcategory [ 'fields' ] fields_for_purpose += subcategory [ 'extra_fields' ] else : fields_for_purpose = deepcopy ( exposure_fields ) elif layer_purpose == layer_purpose_hazard [ 'key' ] : if layer_subcategory : subcategory = definition ( layer_subcategory ) fields_for_purpose += subcategory [ 'compulsory_fields' ] fields_for_purpose += subcategory [ 'fields' ] fields_for_purpose += subcategory [ 'extra_fields' ] else : fields_for_purpose = deepcopy ( hazard_fields ) elif layer_purpose == layer_purpose_aggregation [ 'key' ] : fields_for_purpose = deepcopy ( aggregation_fields ) elif layer_purpose == layer_purpose_exposure_summary [ 'key' ] : fields_for_purpose = deepcopy ( impact_fields ) if in_group : field_groups = get_field_groups ( layer_purpose , layer_subcategory ) fields_for_purpose += fields_in_field_groups ( field_groups ) if isinstance ( replace_null , bool ) : fields_for_purpose = [ f for f in fields_for_purpose if f . get ( 'replace_null' ) == replace_null ] return fields_for_purpose else : return fields_for_purpose | Get all field based on the layer purpose . | 386 | 9 |
26,822 | def get_compulsory_fields ( layer_purpose , layer_subcategory = None ) : if not layer_subcategory : if layer_purpose == 'hazard' : return hazard_value_field elif layer_purpose == 'exposure' : return exposure_type_field elif layer_purpose == 'aggregation' : return aggregation_name_field else : return None else : return definition ( layer_subcategory ) . get ( 'compulsory_fields' ) [ 0 ] | Get compulsory field based on layer_purpose and layer_subcategory | 105 | 13 |
26,823 | def get_non_compulsory_fields ( layer_purpose , layer_subcategory = None ) : all_fields = get_fields ( layer_purpose , layer_subcategory , replace_null = False ) compulsory_field = get_compulsory_fields ( layer_purpose , layer_subcategory ) if compulsory_field in all_fields : all_fields . remove ( compulsory_field ) return all_fields | Get non compulsory field based on layer_purpose and layer_subcategory . | 90 | 15 |
26,824 | def get_name ( key ) : definition_dict = definition ( key ) if definition_dict : return definition_dict . get ( 'name' , key ) # Else, return the keyword return key | Given a keyword try to get the name of it . | 42 | 11 |
26,825 | def get_class_name ( class_key , classification_key ) : classification = definition ( classification_key ) for the_class in classification [ 'classes' ] : if the_class . get ( 'key' ) == class_key : return the_class . get ( 'name' , class_key ) return class_key | Helper to get class name from a class_key of a classification . | 71 | 14 |
26,826 | def get_allowed_geometries ( layer_purpose_key ) : preferred_order = [ 'point' , 'line' , 'polygon' , 'raster' ] allowed_geometries = set ( ) all_layer_type = [ ] if layer_purpose_key == layer_purpose_hazard [ 'key' ] : all_layer_type = hazard_all elif layer_purpose_key == layer_purpose_exposure [ 'key' ] : all_layer_type = exposure_all for layer in all_layer_type : for allowed_geometry in layer [ 'allowed_geometries' ] : allowed_geometries . add ( allowed_geometry ) allowed_geometries = list ( allowed_geometries ) allowed_geometries_definition = [ ] for allowed_geometry in allowed_geometries : allowed_geometries_definition . append ( definition ( allowed_geometry ) ) # Adapted from http://stackoverflow.com/a/15650556/1198772 order_dict = { color : index for index , color in enumerate ( preferred_order ) } allowed_geometries_definition . sort ( key = lambda x : order_dict [ x [ "key" ] ] ) return allowed_geometries_definition | Helper function to get all possible geometry | 282 | 7 |
26,827 | def all_default_fields ( ) : default_fields = [ ] for item in dir ( fields ) : if not item . startswith ( "__" ) : var = getattr ( definitions , item ) if isinstance ( var , dict ) : if var . get ( 'replace_null' , False ) : default_fields . append ( var ) return default_fields | Helper to retrieve all fields which has default value . | 80 | 10 |
26,828 | def default_classification_thresholds ( classification , unit = None ) : thresholds = { } for hazard_class in classification [ 'classes' ] : if isinstance ( hazard_class [ 'numeric_default_min' ] , dict ) : min_value = hazard_class [ 'numeric_default_min' ] [ unit ] else : min_value = hazard_class [ 'numeric_default_min' ] if isinstance ( hazard_class [ 'numeric_default_max' ] , dict ) : max_value = hazard_class [ 'numeric_default_max' ] [ unit ] else : max_value = hazard_class [ 'numeric_default_max' ] thresholds [ hazard_class [ 'key' ] ] = [ min_value , max_value ] return thresholds | Helper to get default thresholds from classification and unit . | 176 | 10 |
26,829 | def default_classification_value_maps ( classification ) : value_maps = { } for hazard_class in classification [ 'classes' ] : value_maps [ hazard_class [ 'key' ] ] = hazard_class . get ( 'string_defaults' , [ ] ) return value_maps | Helper to get default value maps from classification . | 65 | 9 |
26,830 | def get_field_groups ( layer_purpose , layer_subcategory = None ) : layer_purpose_dict = definition ( layer_purpose ) if not layer_purpose_dict : return [ ] field_groups = deepcopy ( layer_purpose_dict . get ( 'field_groups' , [ ] ) ) if layer_purpose in [ layer_purpose_exposure [ 'key' ] , layer_purpose_hazard [ 'key' ] ] : if layer_subcategory : subcategory = definition ( layer_subcategory ) if 'field_groups' in subcategory : field_groups += deepcopy ( subcategory [ 'field_groups' ] ) return field_groups | Obtain list of field groups from layer purpose and subcategory . | 144 | 13 |
26,831 | def override_component_template ( component , template_path ) : copy_component = deepcopy ( component ) template_directory , template_filename = split ( template_path ) file_name , file_format = splitext ( template_filename ) if file_format [ 1 : ] != ( QgisComposerComponentsMetadata . OutputFormat . QPT ) or ( not exists ( template_path ) ) : return copy_component # we do the import here to avoid circular import when starting # up the plugin from safe . definitions . reports . components import ( map_report_component_boilerplate ) custom_template_component = deepcopy ( map_report_component_boilerplate ) # we need to update several items in this component pdf_output_file = '{file_name}.pdf' . format ( file_name = file_name ) qpt_output_file = '{file_name}.qpt' . format ( file_name = file_name ) custom_template_component [ 'key' ] = file_name custom_template_component [ 'template' ] = template_path custom_template_component [ 'output_path' ] [ 'template' ] = qpt_output_file custom_template_component [ 'output_path' ] [ 'map' ] = pdf_output_file # we need to update the orientation of the custom template with open ( custom_template_component [ 'template' ] ) as ( template_file ) : template_content = template_file . read ( ) document = QDomDocument ( ) document . setContent ( template_content ) root_element = document . namedItem ( 'Composer' ) composition_element = root_element . namedItem ( 'Composition' ) all_orientations = [ landscape_map_report_description , portrait_map_report_description ] orientation = None if isinstance ( root_element , QDomNode ) : paper_width = composition_element . attributes ( ) . namedItem ( 'paperWidth' ) . nodeValue ( ) paper_height = composition_element . attributes ( ) . namedItem ( 'paperHeight' ) . nodeValue ( ) for _orientation in all_orientations : if _orientation [ 'width' ] == int ( paper_width ) and ( _orientation [ 'height' ] == int ( paper_height ) ) : orientation = _orientation [ 'orientation' ] break # By default, the component is landscape oriented, So if we found that # the custom template is portrait, we need to delete the information about # orientation in the component because in the report metadata, if there is # no specification about the orientation, then they will set it # to portrait. if orientation == portrait_map_report_description [ 'orientation' ] : custom_template_component [ 'orientation' ] = orientation del custom_template_component [ 'page_width' ] del custom_template_component [ 'page_height' ] copy_component [ 'components' ] = [ custom_template_component ] return copy_component | Override a default component with a new component with given template . | 658 | 12 |
26,832 | def update_template_component ( component , custom_template_dir = None , hazard = None , exposure = None ) : copy_component = deepcopy ( component ) # get the default template component from the original map report component default_component_keys = [ ] for component in copy_component [ 'components' ] : default_component_keys . append ( component [ 'key' ] ) if not custom_template_dir : # noinspection PyArgumentList custom_template_dir = join ( QgsApplication . qgisSettingsDirPath ( ) , 'inasafe' ) for component in copy_component [ 'components' ] : if not component . get ( 'template' ) : continue template_format = splitext ( component [ 'template' ] ) [ - 1 ] [ 1 : ] if template_format != QgisComposerComponentsMetadata . OutputFormat . QPT : continue qpt_file_name = component [ 'template' ] . split ( '/' ) [ - 1 ] custom_qpt_path = join ( custom_template_dir , qpt_file_name ) if exists ( custom_qpt_path ) : component [ 'template' ] = custom_qpt_path # we want to check if there is hazard-exposure specific template available # in user's custom template directory if exists ( custom_template_dir ) and hazard and exposure : for filename in listdir ( custom_template_dir ) : file_name , file_format = splitext ( filename ) if file_format [ 1 : ] != ( QgisComposerComponentsMetadata . OutputFormat . QPT ) : continue if hazard [ 'key' ] in file_name and exposure [ 'key' ] in file_name : # we do the import here to avoid circular import when starting # up the plugin from safe . definitions . reports . components import ( map_report_component_boilerplate ) hazard_exposure_component = deepcopy ( map_report_component_boilerplate ) # we need to update several items in this component pdf_output_file = '{file_name}.pdf' . format ( file_name = file_name ) qpt_output_file = '{file_name}.qpt' . format ( file_name = file_name ) hazard_exposure_component [ 'key' ] = file_name hazard_exposure_component [ 'template' ] = join ( custom_template_dir , filename ) hazard_exposure_component [ 'output_path' ] [ 'template' ] = ( qpt_output_file ) hazard_exposure_component [ 'output_path' ] [ 'map' ] = ( pdf_output_file ) # add this hazard-exposure component to the returned component copy_component [ 'components' ] . append ( hazard_exposure_component ) # remove the original template component because we want to # override it using this new hazard-exposure template component new_component = [ component for component in copy_component [ 'components' ] if component [ 'key' ] not in default_component_keys ] copy_component [ 'components' ] = new_component return copy_component | Get a component based on custom qpt if exists | 691 | 10 |
26,833 | def get_displacement_rate ( hazard , classification , hazard_class , qsettings = None ) : is_affected_value = is_affected ( hazard , classification , hazard_class , qsettings ) if is_affected_value == not_exposed_class [ 'key' ] : return 0 # Just to make it clear elif not is_affected_value : return 0 preference_data = setting ( 'population_preference' , default = generate_default_profile ( ) , qsettings = qsettings ) # Use default from the default profile default_profile = generate_default_profile ( ) default_displacement_rate_value = default_profile . get ( hazard , { } ) . get ( classification , { } ) . get ( hazard_class , { } ) . get ( 'displacement_rate' , 0 ) # noinspection PyUnresolvedReferences return preference_data . get ( hazard , { } ) . get ( classification , { } ) . get ( hazard_class , { } ) . get ( 'displacement_rate' , default_displacement_rate_value ) | Get displacement rate for hazard in classification in hazard class . | 241 | 11 |
26,834 | def is_affected ( hazard , classification , hazard_class , qsettings = None ) : preference_data = setting ( 'population_preference' , default = generate_default_profile ( ) , qsettings = qsettings ) # Use default from the default profile default_profile = generate_default_profile ( ) default_affected_value = default_profile . get ( hazard , { } ) . get ( classification , { } ) . get ( hazard_class , { } ) . get ( 'affected' , not_exposed_class [ 'key' ] ) # noinspection PyUnresolvedReferences return preference_data . get ( hazard , { } ) . get ( classification , { } ) . get ( hazard_class , { } ) . get ( 'affected' , default_affected_value ) | Get affected flag for hazard in classification in hazard class . | 172 | 11 |
26,835 | def safe_dir ( sub_dir = None ) : safe_relative_path = os . path . join ( os . path . dirname ( __file__ ) , '../' ) return os . path . abspath ( os . path . join ( safe_relative_path , sub_dir ) ) | Absolute path from safe package directory . | 65 | 8 |
26,836 | def temp_dir ( sub_dir = 'work' ) : user = getpass . getuser ( ) . replace ( ' ' , '_' ) current_date = date . today ( ) date_string = current_date . isoformat ( ) if 'INASAFE_WORK_DIR' in os . environ : new_directory = os . environ [ 'INASAFE_WORK_DIR' ] else : # Following 4 lines are a workaround for tempfile.tempdir() # unreliabilty handle , filename = mkstemp ( ) os . close ( handle ) new_directory = os . path . dirname ( filename ) os . remove ( filename ) path = os . path . join ( new_directory , 'inasafe' , date_string , user , sub_dir ) if not os . path . exists ( path ) : # Ensure that the dir is world writable # Umask sets the new mask and returns the old old_mask = os . umask ( 0000 ) os . makedirs ( path , 0o777 ) # Reinstate the old mask for tmp os . umask ( old_mask ) return path | Obtain the temporary working directory for the operating system . | 246 | 11 |
26,837 | def unique_filename ( * * kwargs ) : if 'dir' not in kwargs : path = temp_dir ( 'impacts' ) kwargs [ 'dir' ] = path else : path = temp_dir ( kwargs [ 'dir' ] ) kwargs [ 'dir' ] = path if not os . path . exists ( kwargs [ 'dir' ] ) : # Ensure that the dir mask won't conflict with the mode # Umask sets the new mask and returns the old umask = os . umask ( 0000 ) # Ensure that the dir is world writable by explicitly setting mode os . makedirs ( kwargs [ 'dir' ] , 0o777 ) # Reinstate the old mask for tmp dir os . umask ( umask ) # Now we have the working dir set up go on and return the filename handle , filename = mkstemp ( * * kwargs ) # Need to close it using the file handle first for windows! os . close ( handle ) try : os . remove ( filename ) except OSError : pass return filename | Create new filename guaranteed not to exist previously | 235 | 8 |
26,838 | def get_free_memory ( ) : if 'win32' in sys . platform : # windows return get_free_memory_win ( ) elif 'linux' in sys . platform : # linux return get_free_memory_linux ( ) elif 'darwin' in sys . platform : # mac return get_free_memory_osx ( ) | Return current free memory on the machine . | 77 | 8 |
26,839 | def get_free_memory_win ( ) : stat = MEMORYSTATUSEX ( ) ctypes . windll . kernel32 . GlobalMemoryStatusEx ( ctypes . byref ( stat ) ) return int ( stat . ullAvailPhys / 1024 / 1024 ) | Return current free memory on the machine for windows . | 58 | 10 |
26,840 | def get_free_memory_linux ( ) : try : p = Popen ( 'free -m' , shell = True , stdout = PIPE , encoding = 'utf8' ) stdout_string = p . communicate ( ) [ 0 ] . split ( '\n' ) [ 2 ] except OSError : raise OSError stdout_list = stdout_string . split ( ' ' ) stdout_list = [ x for x in stdout_list if x != '' ] return int ( stdout_list [ 3 ] ) | Return current free memory on the machine for linux . | 122 | 10 |
26,841 | def get_free_memory_osx ( ) : try : p = Popen ( 'echo -e "\n$(top -l 1 | awk \'/PhysMem/\';)\n"' , shell = True , stdout = PIPE , encoding = 'utf8' ) stdout_string = p . communicate ( ) [ 0 ] . split ( '\n' ) [ 1 ] # e.g. output (its a single line) OSX 10.9 Mavericks # PhysMem: 6854M used (994M wired), 1332M unused. # output on Mountain lion # PhysMem: 1491M wired, 3032M active, 1933M inactive, # 6456M used, 1735M free. except OSError : raise OSError platform_version = platform . mac_ver ( ) [ 0 ] # Might get '10.9.1' so strop off the last no parts = platform_version . split ( '.' ) platform_version = parts [ 0 ] + parts [ 1 ] # We make version a int by concatenating the two parts # so that we can successfully determine that 10.10 (release version) # is greater than e.g. 10.8 (release version) # 1010 vs 108 platform_version = int ( platform_version ) if platform_version > 108 : stdout_list = stdout_string . split ( ',' ) unused = stdout_list [ 1 ] . replace ( 'M unused' , '' ) . replace ( ' ' , '' ) unused = unused . replace ( '.' , '' ) return int ( unused ) else : stdout_list = stdout_string . split ( ',' ) inactive = stdout_list [ 2 ] . replace ( 'M inactive' , '' ) . replace ( ' ' , '' ) free = stdout_list [ 4 ] . replace ( 'M free.' , '' ) . replace ( ' ' , '' ) return int ( inactive ) + int ( free ) | Return current free memory on the machine for mac os . | 427 | 11 |
26,842 | def humanize_min_max ( min_value , max_value , interval ) : current_interval = max_value - min_value if interval > 1 : # print 'case 1. Current interval : ', current_interval humanize_min_value = add_separators ( int ( python2_round ( min_value ) ) ) humanize_max_value = add_separators ( int ( python2_round ( max_value ) ) ) else : # print 'case 2. Current interval : ', current_interval humanize_min_value = format_decimal ( current_interval , min_value ) humanize_max_value = format_decimal ( current_interval , max_value ) return humanize_min_value , humanize_max_value | Return humanize value format for max and min . | 172 | 10 |
26,843 | def format_decimal ( interval , value ) : interval = get_significant_decimal ( interval ) if isinstance ( interval , Integral ) or isinstance ( value , Integral ) : return add_separators ( int ( value ) ) if interval != interval : # nan return str ( value ) if value != value : # nan return str ( value ) decimal_places = len ( str ( interval ) . split ( '.' ) [ 1 ] ) my_number_int = str ( value ) . split ( '.' ) [ 0 ] my_number_decimal = str ( value ) . split ( '.' ) [ 1 ] [ : decimal_places ] if len ( set ( my_number_decimal ) ) == 1 and my_number_decimal [ - 1 ] == '0' : return my_number_int formatted_decimal = ( add_separators ( int ( my_number_int ) ) + decimal_separator ( ) + my_number_decimal ) return formatted_decimal | Return formatted decimal according to interval decimal place | 218 | 8 |
26,844 | def get_significant_decimal ( my_decimal ) : if isinstance ( my_decimal , Integral ) : return my_decimal if my_decimal != my_decimal : # nan return my_decimal my_int_part = str ( my_decimal ) . split ( '.' ) [ 0 ] my_decimal_part = str ( my_decimal ) . split ( '.' ) [ 1 ] first_not_zero = 0 for i in range ( len ( my_decimal_part ) ) : if my_decimal_part [ i ] == '0' : continue else : first_not_zero = i break my_truncated_decimal = my_decimal_part [ : first_not_zero + 3 ] # rounding my_leftover_number = my_decimal_part [ : first_not_zero + 3 : ] my_leftover_number = int ( float ( '0.' + my_leftover_number ) ) round_up = False if my_leftover_number == 1 : round_up = True my_truncated = float ( my_int_part + '.' + my_truncated_decimal ) if round_up : my_bonus = 1 * 10 ^ ( - ( first_not_zero + 4 ) ) my_truncated += my_bonus return my_truncated | Return a truncated decimal by last three digit after leading zero . | 306 | 13 |
26,845 | def humanize_class ( my_classes ) : min_value = 0 if min_value - my_classes [ 0 ] == 0 : if len ( my_classes ) == 1 : return [ ( '0' , '0' ) ] else : return humanize_class ( my_classes [ 1 : ] ) humanize_classes = [ ] interval = my_classes [ - 1 ] - my_classes [ - 2 ] for max_value in my_classes : humanize_classes . append ( humanize_min_max ( min_value , max_value , interval ) ) min_value = max_value try : if humanize_classes [ - 1 ] [ 0 ] == humanize_classes [ - 1 ] [ - 1 ] : return unhumanize_class ( my_classes ) except IndexError : continue return humanize_classes | Return humanize interval of an array . | 182 | 8 |
26,846 | def unhumanize_class ( my_classes ) : result = [ ] interval = my_classes [ - 1 ] - my_classes [ - 2 ] min_value = 0 for max_value in my_classes : result . append ( ( format_decimal ( interval , min_value ) , format_decimal ( interval , max_value ) ) ) min_value = max_value return result | Return class as interval without formatting . | 86 | 7 |
26,847 | def unhumanize_number ( number ) : try : number = number . replace ( thousand_separator ( ) , '' ) number = int ( float ( number ) ) except ( AttributeError , ValueError ) : pass return number | Return number without formatting . | 49 | 5 |
26,848 | def get_utm_zone ( longitude ) : zone = int ( ( math . floor ( ( longitude + 180.0 ) / 6.0 ) + 1 ) % 60 ) if zone == 0 : zone = 60 return zone | Return utm zone . | 49 | 5 |
26,849 | def get_utm_epsg ( longitude , latitude , crs = None ) : if crs is None or crs . authid ( ) == 'EPSG:4326' : epsg = 32600 if latitude < 0.0 : epsg += 100 epsg += get_utm_zone ( longitude ) return epsg else : epsg_4326 = QgsCoordinateReferenceSystem ( 'EPSG:4326' ) transform = QgsCoordinateTransform ( crs , epsg_4326 , QgsProject . instance ( ) ) geom = QgsGeometry . fromPointXY ( QgsPointXY ( longitude , latitude ) ) geom . transform ( transform ) point = geom . asPoint ( ) # The point is now in 4326, we can call the function again. return get_utm_epsg ( point . x ( ) , point . y ( ) ) | Return epsg code of the utm zone according to X Y coordinates . | 203 | 16 |
26,850 | def color_ramp ( number_of_colour ) : if number_of_colour < 1 : raise Exception ( 'The number of colours should be > 0' ) colors = [ ] if number_of_colour == 1 : hue_interval = 1 else : hue_interval = 1.0 / ( number_of_colour - 1 ) for i in range ( number_of_colour ) : hue = ( i * hue_interval ) / 3 light = 127.5 saturation = - 1.007905138339921 rgb = colorsys . hls_to_rgb ( hue , light , saturation ) hex_color = '#%02x%02x%02x' % ( int ( rgb [ 0 ] ) , int ( rgb [ 1 ] ) , int ( rgb [ 2 ] ) ) colors . append ( hex_color ) return colors | Generate list of color in hexadecimal . | 187 | 11 |
26,851 | def romanise ( number ) : if number is None : return '' roman_list = [ '0' , 'I' , 'II' , 'III' , 'IV' , 'V' , 'VI' , 'VII' , 'VIII' , 'IX' , 'X' , 'XI' , 'XII' ] try : roman = roman_list [ int ( number ) ] except ValueError : return None return roman | Return the roman numeral for a number . | 100 | 10 |
26,852 | def add_to_list ( my_list , my_element ) : if isinstance ( my_element , list ) : for element in my_element : my_list = add_to_list ( my_list , element ) else : if my_element not in my_list : my_list . append ( my_element ) return my_list | Helper function to add new my_element to my_list based on its type . | 76 | 17 |
26,853 | def action_checklist_extractor ( impact_report , component_metadata ) : context = { } provenance = impact_report . impact_function . provenance extra_args = component_metadata . extra_args context [ 'component_key' ] = component_metadata . key context [ 'header' ] = resolve_from_dictionary ( extra_args , 'header' ) context [ 'items' ] = provenance [ 'action_checklist' ] return context | Extracting action checklist of the exposure layer . | 101 | 10 |
26,854 | def filterAcceptsRow ( self , source_row , source_parent ) : source_index = self . sourceModel ( ) . index ( source_row , 0 , source_parent ) item = self . sourceModel ( ) . dataItem ( source_index ) if item . metaObject ( ) . className ( ) not in [ 'QgsPGRootItem' , 'QgsPGConnectionItem' , 'QgsPGSchemaItem' , 'QgsPGLayerItem' , 'QgsFavoritesItem' , 'QgsDirectoryItem' , 'QgsLayerItem' , 'QgsGdalLayerItem' , 'QgsOgrLayerItem' ] : return False if item . path ( ) . endswith ( '.xml' ) : return False return True | The filter method | 168 | 3 |
26,855 | def save_metadata ( self ) : metadata = self . field_mapping_widget . get_field_mapping ( ) for key , value in list ( metadata [ 'fields' ] . items ( ) ) : # Delete the key if it's set to None if key in self . metadata [ 'inasafe_default_values' ] : self . metadata [ 'inasafe_default_values' ] . pop ( key ) if value is None or value == [ ] : if key in self . metadata [ 'inasafe_fields' ] : self . metadata [ 'inasafe_fields' ] . pop ( key ) else : self . metadata [ 'inasafe_fields' ] [ key ] = value for key , value in list ( metadata [ 'values' ] . items ( ) ) : # Delete the key if it's set to None if key in self . metadata [ 'inasafe_fields' ] : self . metadata [ 'inasafe_fields' ] . pop ( key ) if value is None : if key in self . metadata [ 'inasafe_default_values' ] : self . metadata [ 'inasafe_default_values' ] . pop ( key ) else : self . metadata [ 'inasafe_default_values' ] [ key ] = value # Save metadata try : self . keyword_io . write_keywords ( layer = self . layer , keywords = self . metadata ) except InaSAFEError as e : error_message = get_error_message ( e ) # noinspection PyCallByClass,PyTypeChecker,PyArgumentList QMessageBox . warning ( self , self . tr ( 'InaSAFE' ) , ( ( self . tr ( 'An error was encountered when saving the following ' 'keywords:\n %s' ) % error_message . to_html ( ) ) ) ) # Update setting fir recent value if self . metadata . get ( 'inasafe_default_values' ) : for key , value in list ( self . metadata [ 'inasafe_default_values' ] . items ( ) ) : set_inasafe_default_value_qsetting ( self . setting , key , RECENT , value ) | Save metadata based on the field mapping state . | 469 | 9 |
26,856 | def add_impact_layers_to_canvas ( impact_function , group = None , iface = None ) : layers = impact_function . outputs name = impact_function . name if group : group_analysis = group else : # noinspection PyArgumentList root = QgsProject . instance ( ) . layerTreeRoot ( ) group_analysis = root . insertGroup ( 0 , name ) group_analysis . setItemVisibilityChecked ( True ) group_analysis . setExpanded ( group is None ) for layer in layers : # noinspection PyArgumentList QgsProject . instance ( ) . addMapLayer ( layer , False ) layer_node = group_analysis . addLayer ( layer ) # set layer title if any try : title = layer . keywords [ 'title' ] if qgis_version ( ) >= 21800 : layer . setName ( title ) else : layer . setLayerName ( title ) except KeyError : pass visible_layers = [ impact_function . impact . id ( ) ] print_atlas = setting ( 'print_atlas_report' , False , bool ) if print_atlas : visible_layers . append ( impact_function . aggregation_summary . id ( ) ) # Let's enable only the more detailed layer. See #2925 if layer . id ( ) in visible_layers : layer_node . setItemVisibilityChecked ( True ) else : layer_node . setItemVisibilityChecked ( False ) # we need to set analysis_impacted as an active layer because we need # to get all qgis variables that we need from this layer for # infographic. if iface : iface . setActiveLayer ( impact_function . analysis_impacted ) | Helper method to add impact layer to QGIS from impact function . | 375 | 14 |
26,857 | def add_debug_layers_to_canvas ( impact_function ) : name = 'DEBUG %s' % impact_function . name root = QgsProject . instance ( ) . layerTreeRoot ( ) group_debug = root . insertGroup ( 0 , name ) group_debug . setItemVisibilityChecked ( False ) group_debug . setExpanded ( False ) hazard_keywords = impact_function . provenance [ 'hazard_keywords' ] exposure_keywords = impact_function . provenance [ 'exposure_keywords' ] # Let's style the hazard class in each layers. # noinspection PyBroadException try : classification = active_classification ( hazard_keywords , exposure_keywords [ 'exposure' ] ) classification = definition ( classification ) classes = OrderedDict ( ) for f in reversed ( classification [ 'classes' ] ) : classes [ f [ 'key' ] ] = ( f [ 'color' ] , f [ 'name' ] ) hazard_class = hazard_class_field [ 'key' ] except BaseException : # We might not have a classification. But this is the debug group so # let's not raise a new exception. classification = None datastore = impact_function . datastore for layer in datastore . layers ( ) : qgis_layer = datastore . layer ( layer ) if not isinstance ( qgis_layer , QgsMapLayer ) : continue QgsProject . instance ( ) . addMapLayer ( qgis_layer , False ) layer_node = group_debug . insertLayer ( 0 , qgis_layer ) layer_node . setItemVisibilityChecked ( False ) layer_node . setExpanded ( False ) # Let's style layers which have a geometry and have # hazard_class if qgis_layer . type ( ) == QgsMapLayer . VectorLayer : if qgis_layer . geometryType ( ) not in [ QgsWkbTypes . NullGeometry , QgsWkbTypes . UnknownGeometry ] and classification : # noqa if qgis_layer . keywords [ 'inasafe_fields' ] . get ( hazard_class ) : hazard_class_style ( qgis_layer , classes , True ) | Helper method to add debug layers to QGIS from impact function . | 491 | 14 |
26,858 | def add_layers_to_canvas_with_custom_orders ( order , impact_function , iface = None ) : root = QgsProject . instance ( ) . layerTreeRoot ( ) # Make all layers hidden. for child in root . children ( ) : child . setItemVisibilityChecked ( False ) group_analysis = root . insertGroup ( 0 , impact_function . name ) group_analysis . setItemVisibilityChecked ( True ) group_analysis . setCustomProperty ( MULTI_EXPOSURE_ANALYSIS_FLAG , True ) # Insert layers in the good order in the group. for layer_definition in order : if layer_definition [ 0 ] == FROM_CANVAS [ 'key' ] : style = QDomDocument ( ) style . setContent ( layer_definition [ 3 ] ) layer = load_layer ( layer_definition [ 2 ] , layer_definition [ 1 ] ) [ 0 ] layer . importNamedStyle ( style ) QgsProject . instance ( ) . addMapLayer ( layer , False ) layer_node = group_analysis . addLayer ( layer ) layer_node . setItemVisibilityChecked ( True ) else : if layer_definition [ 2 ] == impact_function . name : for layer in impact_function . outputs : if layer . keywords [ 'layer_purpose' ] == layer_definition [ 1 ] : QgsProject . instance ( ) . addMapLayer ( layer , False ) layer_node = group_analysis . addLayer ( layer ) layer_node . setItemVisibilityChecked ( True ) try : title = layer . keywords [ 'title' ] if qgis_version ( ) >= 21800 : layer . setName ( title ) else : layer . setLayerName ( title ) except KeyError : pass break else : for sub_impact_function in impact_function . impact_functions : # Iterate over each sub impact function used in the # multi exposure analysis. if sub_impact_function . name == layer_definition [ 2 ] : for layer in sub_impact_function . outputs : purpose = layer_definition [ 1 ] if layer . keywords [ 'layer_purpose' ] == purpose : QgsProject . instance ( ) . addMapLayer ( layer , False ) layer_node = group_analysis . addLayer ( layer ) layer_node . setItemVisibilityChecked ( True ) try : title = layer . keywords [ 'title' ] if qgis_version ( ) >= 21800 : layer . setName ( title ) else : layer . setLayerName ( title ) except KeyError : pass break if iface : iface . setActiveLayer ( impact_function . analysis_impacted ) | Helper to add layers to the map canvas following a specific order . | 580 | 13 |
26,859 | def add_layer_to_canvas ( layer , name ) : if qgis_version ( ) >= 21800 : layer . setName ( name ) else : layer . setLayerName ( name ) QgsProject . instance ( ) . addMapLayer ( layer , False ) | Helper method to add layer to QGIS . | 60 | 10 |
26,860 | def summarize_result ( exposure_summary ) : summarization_dicts = { } summarizer_flags = { } # for summarizer_field in summarizer_fields: for key , summary_rule in list ( summary_rules . items ( ) ) : input_field = summary_rule [ 'input_field' ] if exposure_summary . fields ( ) . lookupField ( input_field [ 'field_name' ] ) == - 1 : summarizer_flags [ key ] = False else : summarizer_flags [ key ] = True summarization_dicts [ key ] = { } for feature in exposure_summary . getFeatures ( ) : exposure_class_name = feature [ exposure_class_field [ 'field_name' ] ] # for summarizer_field in summarizer_fields: for key , summary_rule in list ( summary_rules . items ( ) ) : input_field = summary_rule [ 'input_field' ] case_field = summary_rule [ 'case_field' ] case_value = feature [ case_field [ 'field_name' ] ] flag = summarizer_flags [ key ] if not flag : continue if case_value in summary_rule [ 'case_values' ] : if exposure_class_name not in summarization_dicts [ key ] : summarization_dicts [ key ] [ exposure_class_name ] = 0 value = feature [ input_field [ 'field_name' ] ] if isinstance ( value , Number ) : summarization_dicts [ key ] [ exposure_class_name ] += value return summarization_dicts | Extract result based on summarizer field value and sum by exposure type . | 346 | 15 |
26,861 | def prettify_xml ( xml_str ) : parsed_xml = parseString ( get_string ( xml_str ) ) pretty_xml = '\n' . join ( [ line for line in parsed_xml . toprettyxml ( indent = ' ' * 2 ) . split ( '\n' ) if line . strip ( ) ] ) if not pretty_xml . endswith ( '\n' ) : pretty_xml += '\n' return pretty_xml | returns prettified XML without blank lines | 102 | 8 |
26,862 | def serialize_dictionary ( dictionary ) : string_value = { } for k , v in list ( dictionary . items ( ) ) : if isinstance ( v , QUrl ) : string_value [ k ] = v . toString ( ) elif isinstance ( v , ( QDate , QDateTime ) ) : string_value [ k ] = v . toString ( Qt . ISODate ) elif isinstance ( v , datetime ) : string_value [ k ] = v . isoformat ( ) elif isinstance ( v , date ) : string_value [ k ] = v . isoformat ( ) elif isinstance ( v , dict ) : # Recursive call string_value [ k ] = serialize_dictionary ( v ) else : string_value [ k ] = v return string_value | Function to stringify a dictionary recursively . | 178 | 10 |
26,863 | def create_virtual_aggregation ( geometry , crs ) : fields = [ create_field_from_definition ( aggregation_id_field ) , create_field_from_definition ( aggregation_name_field ) ] aggregation_layer = create_memory_layer ( 'aggregation' , QgsWkbTypes . PolygonGeometry , crs , fields ) aggregation_layer . startEditing ( ) feature = QgsFeature ( ) feature . setGeometry ( geometry ) feature . setAttributes ( [ 1 , tr ( 'Entire Area' ) ] ) aggregation_layer . addFeature ( feature ) aggregation_layer . commitChanges ( ) # Generate aggregation keywords aggregation_layer . keywords [ 'layer_purpose' ] = ( layer_purpose_aggregation [ 'key' ] ) aggregation_layer . keywords [ 'title' ] = 'aggr_from_bbox' aggregation_layer . keywords [ inasafe_keyword_version_key ] = ( inasafe_keyword_version ) aggregation_layer . keywords [ 'inasafe_fields' ] = { aggregation_id_field [ 'key' ] : aggregation_id_field [ 'field_name' ] , aggregation_name_field [ 'key' ] : aggregation_name_field [ 'field_name' ] } # We will fill default values later, according to the exposure. aggregation_layer . keywords [ 'inasafe_default_values' ] = { } return aggregation_layer | Function to create aggregation layer based on extent . | 314 | 9 |
26,864 | def create_analysis_layer ( analysis_extent , crs , name ) : fields = [ create_field_from_definition ( analysis_name_field ) ] analysis_layer = create_memory_layer ( 'analysis' , QgsWkbTypes . PolygonGeometry , crs , fields ) analysis_layer . startEditing ( ) feature = QgsFeature ( ) # noinspection PyCallByClass,PyArgumentList,PyTypeChecker feature . setGeometry ( analysis_extent ) feature . setAttributes ( [ name ] ) analysis_layer . addFeature ( feature ) analysis_layer . commitChanges ( ) # Generate analysis keywords analysis_layer . keywords [ 'layer_purpose' ] = ( layer_purpose_analysis_impacted [ 'key' ] ) analysis_layer . keywords [ 'title' ] = 'analysis' analysis_layer . keywords [ inasafe_keyword_version_key ] = ( inasafe_keyword_version ) analysis_layer . keywords [ 'inasafe_fields' ] = { analysis_name_field [ 'key' ] : analysis_name_field [ 'field_name' ] } return analysis_layer | Create the analysis layer . | 255 | 5 |
26,865 | def create_profile_layer ( profiling ) : fields = [ create_field_from_definition ( profiling_function_field ) , create_field_from_definition ( profiling_time_field ) ] if setting ( key = 'memory_profile' , expected_type = bool ) : fields . append ( create_field_from_definition ( profiling_memory_field ) ) tabular = create_memory_layer ( 'profiling' , QgsWkbTypes . NullGeometry , fields = fields ) # Generate profiling keywords tabular . keywords [ 'layer_purpose' ] = layer_purpose_profiling [ 'key' ] tabular . keywords [ 'title' ] = layer_purpose_profiling [ 'name' ] if qgis_version ( ) >= 21800 : tabular . setName ( tabular . keywords [ 'title' ] ) else : tabular . setLayerName ( tabular . keywords [ 'title' ] ) tabular . keywords [ 'inasafe_fields' ] = { profiling_function_field [ 'key' ] : profiling_function_field [ 'field_name' ] , profiling_time_field [ 'key' ] : profiling_time_field [ 'field_name' ] , } if setting ( key = 'memory_profile' , expected_type = bool ) : tabular . keywords [ 'inasafe_fields' ] [ profiling_memory_field [ 'key' ] ] = profiling_memory_field [ 'field_name' ] tabular . keywords [ inasafe_keyword_version_key ] = ( inasafe_keyword_version ) table = profiling . to_text ( ) . splitlines ( ) [ 3 : ] tabular . startEditing ( ) for line in table : feature = QgsFeature ( ) items = line . split ( ', ' ) time = items [ 1 ] . replace ( '-' , '' ) if setting ( key = 'memory_profile' , expected_type = bool ) : memory = items [ 2 ] . replace ( '-' , '' ) feature . setAttributes ( [ items [ 0 ] , time , memory ] ) else : feature . setAttributes ( [ items [ 0 ] , time ] ) tabular . addFeature ( feature ) tabular . commitChanges ( ) return tabular | Create a tabular layer with the profiling . | 492 | 9 |
26,866 | def create_valid_aggregation ( layer ) : cleaned = create_memory_layer ( 'aggregation' , layer . geometryType ( ) , layer . crs ( ) , layer . fields ( ) ) # We transfer keywords to the output. cleaned . keywords = layer . keywords try : use_selected_only = layer . use_selected_features_only except AttributeError : use_selected_only = False cleaned . use_selected_features_only = use_selected_only copy_layer ( layer , cleaned ) return cleaned | Create a local copy of the aggregation layer and try to make it valid . | 113 | 15 |
26,867 | def stop_capture_coordinates ( self ) : self . extent_dialog . _populate_coordinates ( ) self . extent_dialog . canvas . setMapTool ( self . extent_dialog . previous_map_tool ) self . parent . show ( ) | Exit the coordinate capture mode . | 60 | 6 |
26,868 | def write_extent ( self ) : self . extent_dialog . accept ( ) self . extent_dialog . clear_extent . disconnect ( self . parent . dock . extent . clear_user_analysis_extent ) self . extent_dialog . extent_defined . disconnect ( self . parent . dock . define_user_analysis_extent ) self . extent_dialog . capture_button . clicked . disconnect ( self . start_capture_coordinates ) self . extent_dialog . tool . rectangle_created . disconnect ( self . stop_capture_coordinates ) | After the extent selection save the extent and disconnect signals . | 128 | 11 |
26,869 | def set_widgets ( self ) : self . extent_dialog = ExtentSelectorDialog ( self . parent . iface , self . parent . iface . mainWindow ( ) , extent = self . parent . dock . extent . user_extent , crs = self . parent . dock . extent . crs ) self . extent_dialog . tool . rectangle_created . disconnect ( self . extent_dialog . stop_capture ) self . extent_dialog . clear_extent . connect ( self . parent . dock . extent . clear_user_analysis_extent ) self . extent_dialog . extent_defined . connect ( self . parent . dock . define_user_analysis_extent ) self . extent_dialog . capture_button . clicked . connect ( self . start_capture_coordinates ) self . extent_dialog . tool . rectangle_created . connect ( self . stop_capture_coordinates ) self . extent_dialog . label . setText ( tr ( 'Please specify extent of your analysis:' ) ) if self . swExtent : self . swExtent . hide ( ) self . swExtent = self . extent_dialog . main_stacked_widget self . layoutAnalysisExtent . addWidget ( self . swExtent ) | Set widgets on the Extent tab . | 281 | 8 |
26,870 | def clip_by_extent ( layer , extent ) : parameters = dict ( ) # noinspection PyBroadException try : output_layer_name = quick_clip_steps [ 'output_layer_name' ] output_layer_name = output_layer_name % layer . keywords [ 'layer_purpose' ] output_raster = unique_filename ( suffix = '.tif' , dir = temp_dir ( ) ) # We make one pixel size buffer on the extent to cover every pixels. # See https://github.com/inasafe/inasafe/issues/3655 pixel_size_x = layer . rasterUnitsPerPixelX ( ) pixel_size_y = layer . rasterUnitsPerPixelY ( ) buffer_size = max ( pixel_size_x , pixel_size_y ) extent = extent . buffered ( buffer_size ) if is_raster_y_inverted ( layer ) : # The raster is Y inverted. We need to switch Y min and Y max. bbox = [ str ( extent . xMinimum ( ) ) , str ( extent . xMaximum ( ) ) , str ( extent . yMaximum ( ) ) , str ( extent . yMinimum ( ) ) ] else : # The raster is normal. bbox = [ str ( extent . xMinimum ( ) ) , str ( extent . xMaximum ( ) ) , str ( extent . yMinimum ( ) ) , str ( extent . yMaximum ( ) ) ] # These values are all from the processing algorithm. # https://github.com/qgis/QGIS/blob/master/python/plugins/processing/ # algs/gdal/ClipByExtent.py # Please read the file to know these parameters. parameters [ 'INPUT' ] = layer . source ( ) parameters [ 'NO_DATA' ] = '' parameters [ 'PROJWIN' ] = ',' . join ( bbox ) parameters [ 'DATA_TYPE' ] = 5 parameters [ 'COMPRESS' ] = 4 parameters [ 'JPEGCOMPRESSION' ] = 75 parameters [ 'ZLEVEL' ] = 6 parameters [ 'PREDICTOR' ] = 1 parameters [ 'TILED' ] = False parameters [ 'BIGTIFF' ] = 0 parameters [ 'TFW' ] = False parameters [ 'EXTRA' ] = '' parameters [ 'OUTPUT' ] = output_raster initialize_processing ( ) feedback = create_processing_feedback ( ) context = create_processing_context ( feedback = feedback ) result = processing . run ( "gdal:cliprasterbyextent" , parameters , context = context ) if result is None : raise ProcessingInstallationError clipped = QgsRasterLayer ( result [ 'OUTPUT' ] , output_layer_name ) # We transfer keywords to the output. clipped . keywords = layer . keywords . copy ( ) clipped . keywords [ 'title' ] = output_layer_name check_layer ( clipped ) except Exception as e : # This step clip_raster_by_extent was nice to speedup the analysis. # As we got an exception because the layer is invalid, we are not going # to stop the analysis. We will return the original raster layer. # It will take more processing time until we clip the vector layer. # Check https://github.com/inasafe/inasafe/issues/4026 why we got some # exceptions with this step. LOGGER . exception ( parameters ) LOGGER . exception ( 'Error from QGIS clip raster by extent. Please check the QGIS ' 'logs too !' ) LOGGER . info ( 'Even if we got an exception, we are continuing the analysis. The ' 'layer was not clipped.' ) LOGGER . exception ( str ( e ) ) LOGGER . exception ( get_error_message ( e ) . to_text ( ) ) clipped = layer return clipped | Clip a raster using a bounding box using processing . | 841 | 13 |
26,871 | def get_elements ( nodelist ) : element_list = [ ] for node in nodelist : if node . nodeType == Node . ELEMENT_NODE : element_list . append ( node ) return element_list | Return list of nodes that are ELEMENT_NODE | 48 | 11 |
26,872 | def get_text ( nodelist ) : s = '' for node in nodelist : if node . nodeType == Node . TEXT_NODE : s += node . nodeValue + ', ' if len ( s ) > 0 : s = s [ : - 2 ] return s | Return a concatenation of text fields from list of nodes | 58 | 12 |
26,873 | def xml2object ( xml , verbose = False ) : # FIXME - can we allow xml to be string? # This would depend on minidom's parse function # Input tests if isinstance ( xml , basestring ) : fid = open ( xml ) else : fid = xml try : dom = parse ( fid ) except Exception as e : # Throw filename into dom exception msg = 'XML file "%s" could not be parsed.\n' % fid . name msg += 'Error message from parser: "%s"' % str ( e ) raise Exception , msg try : xml_object = dom2object ( dom ) except Exception as e : msg = 'Could not convert %s into XML object.\n' % fid . name msg += str ( e ) raise Exception , msg return xml_object | Generate XML object model from XML file or XML text | 171 | 11 |
26,874 | def dom2object ( node ) : value = [ ] textnode_encountered = None for n in node . childNodes : if n . nodeType == 3 : # Child is a text element - omit the dom tag #text and # go straight to the text value. # Note - only the last text value will be recorded msg = 'Text element has child nodes - this shouldn\'t happen' verify ( len ( n . childNodes ) == 0 , msg ) x = n . nodeValue . strip ( ) if len ( x ) == 0 : # Skip empty text children continue textnode_encountered = value = x else : # XML element if textnode_encountered is not None : msg = 'A text node was followed by a non-text tag. This is not allowed.\n' msg += 'Offending text node: "%s" ' % str ( textnode_encountered ) msg += 'was followed by node named: "<%s>"' % str ( n . nodeName ) raise Exception , msg value . append ( dom2object ( n ) ) # Deal with empty elements if len ( value ) == 0 : value = '' if node . nodeType == 9 : # Root node (document) tag = None else : # Normal XML node tag = node . nodeName X = XML_element ( tag = tag , value = value ) return X | Convert DOM representation to XML_object hierarchy . | 293 | 10 |
26,875 | def pretty_print ( self , indent = 0 ) : s = tab = ' ' * indent s += '%s: ' % self . tag if isinstance ( self . value , basestring ) : s += self . value else : s += '\n' for e in self . value : s += e . pretty_print ( indent + 4 ) s += '\n' return s | Print the document without tags using indentation | 84 | 8 |
26,876 | def on_lstHazardCategories_itemSelectionChanged ( self ) : self . clear_further_steps ( ) # Set widgets hazard_category = self . selected_hazard_category ( ) # Exit if no selection if not hazard_category : return # Set description label self . lblDescribeHazardCategory . setText ( hazard_category [ "description" ] ) # Enable the next button self . parent . pbnNext . setEnabled ( True ) | Update hazard category description label . | 100 | 6 |
26,877 | def selected_hazard_category ( self ) : item = self . lstHazardCategories . currentItem ( ) try : return definition ( item . data ( QtCore . Qt . UserRole ) ) except ( AttributeError , NameError ) : return None | Obtain the hazard category selected by user . | 55 | 9 |
26,878 | def set_widgets ( self ) : self . clear_further_steps ( ) # Set widgets self . lstHazardCategories . clear ( ) self . lblDescribeHazardCategory . setText ( '' ) self . lblSelectHazardCategory . setText ( hazard_category_question ) hazard_categories = self . hazard_categories_for_layer ( ) for hazard_category in hazard_categories : if not isinstance ( hazard_category , dict ) : # noinspection PyTypeChecker hazard_category = definition ( hazard_category ) # noinspection PyTypeChecker item = QListWidgetItem ( hazard_category [ 'name' ] , self . lstHazardCategories ) # noinspection PyTypeChecker item . setData ( QtCore . Qt . UserRole , hazard_category [ 'key' ] ) self . lstHazardCategories . addItem ( item ) # Set values based on existing keywords (if already assigned) category_keyword = self . parent . get_existing_keyword ( 'hazard_category' ) if category_keyword : categories = [ ] for index in range ( self . lstHazardCategories . count ( ) ) : item = self . lstHazardCategories . item ( index ) categories . append ( item . data ( QtCore . Qt . UserRole ) ) if category_keyword in categories : self . lstHazardCategories . setCurrentRow ( categories . index ( category_keyword ) ) self . auto_select_one_item ( self . lstHazardCategories ) | Set widgets on the Hazard Category tab . | 346 | 8 |
26,879 | def polygonize ( layer ) : output_layer_name = polygonize_steps [ 'output_layer_name' ] output_layer_name = output_layer_name % layer . keywords [ 'layer_purpose' ] gdal_layer_name = polygonize_steps [ 'gdal_layer_name' ] if layer . keywords . get ( 'layer_purpose' ) == 'exposure' : output_field = exposure_type_field else : output_field = hazard_value_field input_raster = gdal . Open ( layer . source ( ) , gdal . GA_ReadOnly ) srs = osr . SpatialReference ( ) srs . ImportFromWkt ( input_raster . GetProjectionRef ( ) ) temporary_dir = temp_dir ( sub_dir = 'pre-process' ) out_shapefile = unique_filename ( suffix = '-%s.shp' % output_layer_name , dir = temporary_dir ) driver = ogr . GetDriverByName ( "ESRI Shapefile" ) destination = driver . CreateDataSource ( out_shapefile ) output_layer = destination . CreateLayer ( gdal_layer_name , srs ) # We have no other way to use a shapefile. We need only the first 10 chars. field_name = output_field [ 'field_name' ] [ 0 : 10 ] fd = ogr . FieldDefn ( field_name , ogr . OFTInteger ) output_layer . CreateField ( fd ) active_band = layer . keywords . get ( 'active_band' , 1 ) input_band = input_raster . GetRasterBand ( active_band ) # Fixme : add our own callback to Polygonize gdal . Polygonize ( input_band , None , output_layer , 0 , [ ] , callback = None ) destination . Destroy ( ) vector_layer = QgsVectorLayer ( out_shapefile , output_layer_name , 'ogr' ) # Let's remove polygons which were no data request = QgsFeatureRequest ( ) expression = '"%s" = %s' % ( field_name , no_data_value ) request . setFilterExpression ( expression ) vector_layer . startEditing ( ) for feature in vector_layer . getFeatures ( request ) : vector_layer . deleteFeature ( feature . id ( ) ) vector_layer . commitChanges ( ) # We transfer keywords to the output. vector_layer . keywords = layer . keywords . copy ( ) vector_layer . keywords [ layer_geometry [ 'key' ] ] = layer_geometry_polygon [ 'key' ] vector_layer . keywords [ 'title' ] = output_layer_name # We just polygonized the raster layer. inasafe_fields do not exist. vector_layer . keywords [ 'inasafe_fields' ] = { output_field [ 'key' ] : field_name } check_layer ( vector_layer ) return vector_layer | Polygonize a raster layer into a vector layer using GDAL . | 658 | 15 |
26,880 | def value ( self , value ) : # For custom value if value not in self . options : if len ( self . labels ) == len ( self . options ) : self . options [ - 1 ] = value else : self . options . append ( value ) self . _value = value | Setter for value . | 60 | 5 |
26,881 | def mmi_ramp_roman ( raster_layer ) : items = [ ] sorted_mmi_scale = sorted ( earthquake_mmi_scale [ 'classes' ] , key = itemgetter ( 'value' ) ) for class_max in sorted_mmi_scale : colour = class_max [ 'color' ] label = '%s' % class_max [ 'key' ] ramp_item = QgsColorRampShader . ColorRampItem ( class_max [ 'value' ] , colour , label ) items . append ( ramp_item ) raster_shader = QgsRasterShader ( ) ramp_shader = QgsColorRampShader ( ) ramp_shader . setColorRampType ( QgsColorRampShader . Interpolated ) ramp_shader . setColorRampItemList ( items ) raster_shader . setRasterShaderFunction ( ramp_shader ) band = 1 renderer = QgsSingleBandPseudoColorRenderer ( raster_layer . dataProvider ( ) , band , raster_shader ) raster_layer . setRenderer ( renderer ) | Generate an mmi ramp using range of 1 - 10 on roman . | 258 | 16 |
26,882 | def load_layer_from_registry ( layer_path ) : # reload the layer in case the layer path has no provider information the_layer = load_layer ( layer_path ) [ 0 ] layers = QgsProject . instance ( ) . mapLayers ( ) for _ , layer in list ( layers . items ( ) ) : if full_layer_uri ( layer ) == full_layer_uri ( the_layer ) : monkey_patch_keywords ( layer ) return layer return the_layer | Helper method to load a layer from registry if its already there . | 108 | 13 |
26,883 | def reclassify_value ( one_value , ranges ) : if ( one_value is None or ( hasattr ( one_value , 'isNull' ) and one_value . isNull ( ) ) ) : return None for threshold_id , threshold in list ( ranges . items ( ) ) : value_min = threshold [ 0 ] value_max = threshold [ 1 ] # If, eg [0, 0], the one_value must be equal to 0. if value_min == value_max and value_max == one_value : return threshold_id # If, eg [None, 0], the one_value must be less or equal than 0. if value_min is None and one_value <= value_max : return threshold_id # If, eg [0, None], the one_value must be greater than 0. if value_max is None and one_value > value_min : return threshold_id # If, eg [0, 1], the one_value must be # between 0 excluded and 1 included. if value_min is not None and ( value_min < one_value <= value_max ) : return threshold_id return None | This function will return the classified value according to ranges . | 250 | 11 |
26,884 | def decode_full_layer_uri ( full_layer_uri_string ) : if not full_layer_uri_string : return None , None split = full_layer_uri_string . split ( '|qgis_provider=' ) if len ( split ) == 1 : return split [ 0 ] , None else : return split | Decode the full layer URI . | 73 | 7 |
26,885 | def load_layer ( full_layer_uri_string , name = None , provider = None ) : if provider : # Cool ! layer_path = full_layer_uri_string else : # Let's check if the driver is included in the path layer_path , provider = decode_full_layer_uri ( full_layer_uri_string ) if not provider : # Let's try to check if it's file based and look for a extension if '|' in layer_path : clean_uri = layer_path . split ( '|' ) [ 0 ] else : clean_uri = layer_path is_file_based = os . path . exists ( clean_uri ) if is_file_based : # Extract basename and absolute path file_name = os . path . split ( layer_path ) [ - 1 ] # If path was absolute extension = os . path . splitext ( file_name ) [ 1 ] if extension in OGR_EXTENSIONS : provider = 'ogr' elif extension in GDAL_EXTENSIONS : provider = 'gdal' else : provider = None if not provider : layer = load_layer_without_provider ( layer_path ) else : layer = load_layer_with_provider ( layer_path , provider ) if not layer or not layer . isValid ( ) : message = 'Layer "%s" is not valid' % layer_path LOGGER . debug ( message ) raise InvalidLayerError ( message ) # Define the name if not name : source = layer . source ( ) if '|' in source : clean_uri = source . split ( '|' ) [ 0 ] else : clean_uri = source is_file_based = os . path . exists ( clean_uri ) if is_file_based : # Extract basename and absolute path file_name = os . path . split ( layer_path ) [ - 1 ] # If path was absolute name = os . path . splitext ( file_name ) [ 0 ] else : # Might be a DB, take the DB name source = QgsDataSourceUri ( source ) name = source . table ( ) if not name : name = 'default' if qgis_version ( ) >= 21800 : layer . setName ( name ) else : layer . setLayerName ( name ) # update the layer keywords monkey_patch_keywords ( layer ) layer_purpose = layer . keywords . get ( 'layer_purpose' ) return layer , layer_purpose | Helper to load and return a single QGIS layer based on our layer URI . | 536 | 17 |
26,886 | def load_layer_with_provider ( layer_uri , provider , layer_name = 'tmp' ) : if provider in RASTER_DRIVERS : return QgsRasterLayer ( layer_uri , layer_name , provider ) elif provider in VECTOR_DRIVERS : return QgsVectorLayer ( layer_uri , layer_name , provider ) else : return None | Load a layer with a specific driver . | 83 | 8 |
26,887 | def load_layer_without_provider ( layer_uri , layer_name = 'tmp' ) : # Let's try the most common vector driver layer = QgsVectorLayer ( layer_uri , layer_name , VECTOR_DRIVERS [ 0 ] ) if layer . isValid ( ) : return layer # Let's try the most common raster driver layer = QgsRasterLayer ( layer_uri , layer_name , RASTER_DRIVERS [ 0 ] ) if layer . isValid ( ) : return layer # Then try all other drivers for driver in VECTOR_DRIVERS [ 1 : ] : if driver == 'delimitedtext' : # Explicitly use URI with delimiter or tests fail in Windows. TS. layer = QgsVectorLayer ( 'file:///%s?delimiter=,' % layer_uri , layer_name , driver ) if layer . isValid ( ) : return layer layer = QgsVectorLayer ( layer_uri , layer_name , driver ) if layer . isValid ( ) : return layer for driver in RASTER_DRIVERS [ 1 : ] : layer = QgsRasterLayer ( layer_uri , layer_name , driver ) if layer . isValid ( ) : return layer return None | Helper to load a layer when don t know the driver . | 270 | 12 |
26,888 | def clip ( layer_to_clip , mask_layer ) : output_layer_name = clip_steps [ 'output_layer_name' ] output_layer_name = output_layer_name % ( layer_to_clip . keywords [ 'layer_purpose' ] ) parameters = { 'INPUT' : layer_to_clip , 'OVERLAY' : mask_layer , 'OUTPUT' : 'memory:' } # TODO implement callback through QgsProcessingFeedback object initialize_processing ( ) feedback = create_processing_feedback ( ) context = create_processing_context ( feedback = feedback ) result = processing . run ( 'native:clip' , parameters , context = context ) if result is None : raise ProcessingInstallationError clipped = result [ 'OUTPUT' ] clipped . setName ( output_layer_name ) clipped . keywords = layer_to_clip . keywords . copy ( ) clipped . keywords [ 'title' ] = output_layer_name check_layer ( clipped ) return clipped | Clip a vector layer with another . | 219 | 8 |
26,889 | def download ( feature_type , output_base_path , extent , progress_dialog = None , server_url = None ) : if not server_url : server_url = PRODUCTION_SERVER # preparing necessary data min_longitude = extent [ 0 ] min_latitude = extent [ 1 ] max_longitude = extent [ 2 ] max_latitude = extent [ 3 ] box = ( '{min_longitude},{min_latitude},{max_longitude},' '{max_latitude}' ) . format ( min_longitude = min_longitude , min_latitude = min_latitude , max_longitude = max_longitude , max_latitude = max_latitude ) url = ( '{url_osm_prefix}' '{feature_type}' '{url_osm_suffix}?' 'bbox={box}&' 'qgis_version={qgis}&' 'lang={lang}&' 'inasafe_version={inasafe_version}' . format ( url_osm_prefix = server_url , feature_type = feature_type , url_osm_suffix = URL_OSM_SUFFIX , box = box , qgis = qgis_version ( ) , lang = locale ( ) , inasafe_version = get_version ( ) ) ) path = tempfile . mktemp ( '.shp.zip' ) # download and extract it fetch_zip ( url , path , feature_type , progress_dialog ) extract_zip ( path , output_base_path ) if progress_dialog : progress_dialog . done ( QDialog . Accepted ) | Download shapefiles from Kartoza server . | 372 | 9 |
26,890 | def fetch_zip ( url , output_path , feature_type , progress_dialog = None ) : LOGGER . debug ( 'Downloading file from URL: %s' % url ) LOGGER . debug ( 'Downloading to: %s' % output_path ) if progress_dialog : progress_dialog . show ( ) # Infinite progress bar when the server is fetching data. # The progress bar will be updated with the file size later. progress_dialog . setMaximum ( 0 ) progress_dialog . setMinimum ( 0 ) progress_dialog . setValue ( 0 ) # Get a pretty label from feature_type, but not translatable label_feature_type = feature_type . replace ( '-' , ' ' ) label_text = tr ( 'Fetching %s' % label_feature_type ) progress_dialog . setLabelText ( label_text ) # Download Process downloader = FileDownloader ( url , output_path , progress_dialog ) try : result = downloader . download ( ) except IOError as ex : raise IOError ( ex ) if result [ 0 ] is not True : _ , error_message = result if result [ 0 ] == QNetworkReply . OperationCanceledError : raise CanceledImportDialogError ( error_message ) else : raise DownloadError ( error_message ) | Download zip containing shp file and write to output_path . | 289 | 13 |
26,891 | def extract_zip ( zip_path , destination_base_path ) : handle = open ( zip_path , 'rb' ) zip_file = zipfile . ZipFile ( handle ) for name in zip_file . namelist ( ) : extension = os . path . splitext ( name ) [ 1 ] output_final_path = '%s%s' % ( destination_base_path , extension ) output_file = open ( output_final_path , 'wb' ) output_file . write ( zip_file . read ( name ) ) output_file . close ( ) handle . close ( ) | Extract different extensions to the destination base path . | 133 | 10 |
26,892 | def get_question_text ( constant ) : if constant in dir ( safe . gui . tools . wizard . wizard_strings ) : return getattr ( safe . gui . tools . wizard . wizard_strings , constant ) else : return '<b>MISSING CONSTANT: %s</b>' % constant | Find a constant by name and return its value . | 68 | 10 |
26,893 | def layers_intersect ( layer_a , layer_b ) : extent_a = layer_a . extent ( ) extent_b = layer_b . extent ( ) if layer_a . crs ( ) != layer_b . crs ( ) : coord_transform = QgsCoordinateTransform ( layer_a . crs ( ) , layer_b . crs ( ) , QgsProject . instance ( ) ) extent_b = ( coord_transform . transform ( extent_b , QgsCoordinateTransform . ReverseTransform ) ) return extent_a . intersects ( extent_b ) | Check if extents of two layers intersect . | 129 | 9 |
26,894 | def get_inasafe_default_value_fields ( qsetting , field_key ) : labels = [ tr ( 'Global (%s)' ) , tr ( 'Do not report' ) , tr ( 'Custom' ) ] values = [ get_inasafe_default_value_qsetting ( qsetting , GLOBAL , field_key ) , None , get_inasafe_default_value_qsetting ( qsetting , RECENT , field_key ) ] return labels , values | Obtain default value for a field with default value . | 104 | 11 |
26,895 | def clear_layout ( layout ) : # Different platform has different treatment # If InaSAFE running on Windows or Linux # Adapted from http://stackoverflow.com/a/9383780 if layout is not None : while layout . count ( ) : item = layout . takeAt ( 0 ) widget = item . widget ( ) if widget is not None : # Remove the widget from layout widget . close ( ) widget . deleteLater ( ) else : clear_layout ( item . layout ( ) ) # Remove the item from layout layout . removeItem ( item ) del item | Clear layout content . | 122 | 4 |
26,896 | def skip_inasafe_field ( layer , inasafe_fields ) : # Iterate through all inasafe fields for inasafe_field in inasafe_fields : for field in layer . fields ( ) : # Check the field type if isinstance ( inasafe_field [ 'type' ] , list ) : if field . type ( ) in inasafe_field [ 'type' ] : return False else : if field . type ( ) == inasafe_field [ 'type' ] : return False return True | Check if it possible to skip inasafe field step . | 115 | 12 |
26,897 | def get_image_path ( definition ) : path = resources_path ( 'img' , 'wizard' , 'keyword-subcategory-%s.svg' % definition [ 'key' ] ) if os . path . exists ( path ) : return path else : return not_set_image_path | Helper to get path of image from a definition in resource directory . | 68 | 13 |
26,898 | def recompute_counts ( layer ) : output_layer_name = recompute_counts_steps [ 'output_layer_name' ] fields = layer . keywords [ 'inasafe_fields' ] if size_field [ 'key' ] not in fields : # noinspection PyTypeChecker msg = '%s not found in %s' % ( size_field [ 'key' ] , layer . keywords [ 'title' ] ) raise InvalidKeywordsForProcessingAlgorithm ( msg ) indexes = [ ] absolute_field_keys = [ f [ 'key' ] for f in count_fields ] for field , field_name in list ( fields . items ( ) ) : if field in absolute_field_keys and field != size_field [ 'key' ] : indexes . append ( layer . fields ( ) . lookupField ( field_name ) ) LOGGER . info ( 'We detected the count {field_name}, we will recompute the ' 'count according to the new size.' . format ( field_name = field_name ) ) if not len ( indexes ) : msg = 'Absolute field not found in the layer %s' % ( layer . keywords [ 'title' ] ) raise InvalidKeywordsForProcessingAlgorithm ( msg ) size_field_name = fields [ size_field [ 'key' ] ] size_field_index = layer . fields ( ) . lookupField ( size_field_name ) layer . startEditing ( ) exposure_key = layer . keywords [ 'exposure_keywords' ] [ 'exposure' ] size_calculator = SizeCalculator ( layer . crs ( ) , layer . geometryType ( ) , exposure_key ) for feature in layer . getFeatures ( ) : old_size = feature [ size_field_name ] new_size = size ( size_calculator = size_calculator , geometry = feature . geometry ( ) ) layer . changeAttributeValue ( feature . id ( ) , size_field_index , new_size ) # Cross multiplication for each field for index in indexes : old_count = feature [ index ] try : new_value = new_size * old_count / old_size except TypeError : new_value = '' except ZeroDivisionError : new_value = 0 layer . changeAttributeValue ( feature . id ( ) , index , new_value ) layer . commitChanges ( ) layer . keywords [ 'title' ] = output_layer_name check_layer ( layer ) return layer | Recompute counts according to the size field and the new size . | 540 | 14 |
26,899 | def multi_exposure_aggregation_summary ( aggregation , intermediate_layers ) : target_index_field_name = ( aggregation . keywords [ 'inasafe_fields' ] [ aggregation_id_field [ 'key' ] ] ) aggregation . startEditing ( ) request = QgsFeatureRequest ( ) request . setFlags ( QgsFeatureRequest . NoGeometry ) for layer in intermediate_layers : source_fields = layer . keywords [ 'inasafe_fields' ] exposure = layer . keywords [ 'exposure_keywords' ] [ 'exposure' ] unique_exposure = read_dynamic_inasafe_field ( source_fields , affected_exposure_count_field , [ total_affected_field ] ) field_map = { } for exposure_class in unique_exposure : field = create_field_from_definition ( exposure_affected_exposure_type_count_field , name = exposure , sub_name = exposure_class ) aggregation . addAttribute ( field ) source_field_index = layer . fields ( ) . lookupField ( affected_exposure_count_field [ 'field_name' ] % exposure_class ) target_field_index = aggregation . fields ( ) . lookupField ( field . name ( ) ) field_map [ source_field_index ] = target_field_index # Total affected field field = create_field_from_definition ( exposure_total_not_affected_field , exposure ) aggregation . addAttribute ( field ) source_field_index = layer . fields ( ) . lookupField ( total_affected_field [ 'field_name' ] ) target_field_index = aggregation . fields ( ) . lookupField ( field . name ( ) ) field_map [ source_field_index ] = target_field_index # Get Aggregation ID from original feature index = ( layer . fields ( ) . lookupField ( source_fields [ aggregation_id_field [ 'key' ] ] ) ) for source_feature in layer . getFeatures ( request ) : target_expression = QgsFeatureRequest ( ) target_expression . setFlags ( QgsFeatureRequest . NoGeometry ) expression = '\"{field_name}\" = {id_value}' . format ( field_name = target_index_field_name , id_value = source_feature [ index ] ) target_expression . setFilterExpression ( expression ) iterator = aggregation . getFeatures ( target_expression ) target_feature = next ( iterator ) # It must return only 1 feature. for source_field , target_field in list ( field_map . items ( ) ) : aggregation . changeAttributeValue ( target_feature . id ( ) , target_field , source_feature [ source_field ] ) try : next ( iterator ) except StopIteration : # Everything is fine, it's normal. pass else : # This should never happen ! IDs are duplicated in the # aggregation layer. raise Exception ( 'Aggregation IDs are duplicated in the aggregation layer. ' 'We can\'t make any joins.' ) aggregation . commitChanges ( ) aggregation . keywords [ 'title' ] = ( layer_purpose_aggregation_summary [ 'multi_exposure_name' ] ) aggregation . keywords [ 'layer_purpose' ] = ( layer_purpose_aggregation_summary [ 'key' ] ) # Set up the extra keywords so everyone knows it's a # multi exposure analysis result. extra_keywords = { extra_keyword_analysis_type [ 'key' ] : MULTI_EXPOSURE_ANALYSIS_FLAG } aggregation . keywords [ 'extra_keywords' ] = extra_keywords if qgis_version ( ) >= 21600 : aggregation . setName ( aggregation . keywords [ 'title' ] ) else : aggregation . setLayerName ( aggregation . keywords [ 'title' ] ) return aggregation | Merge intermediate aggregations into one aggregation summary . | 832 | 10 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.