idx int64 0 63k | question stringlengths 53 5.28k | target stringlengths 5 805 |
|---|---|---|
26,500 | def upsert_into ( self , table ) : return SessionContext . session . execute ( insert ( table ) . from_select ( self . c , self , ) . on_conflict_do_nothing ( ) , ) . rowcount | Upsert from a temporarty table into another table . |
26,501 | def configure_key_provider ( graph , key_ids ) : if graph . metadata . testing : provider = StaticMasterKeyProvider ( ) provider . add_master_keys_from_list ( key_ids ) return provider return KMSMasterKeyProvider ( key_ids = key_ids ) | Configure a key provider . |
26,502 | def configure_materials_manager ( graph , key_provider ) : if graph . config . materials_manager . enable_cache : return CachingCryptoMaterialsManager ( cache = LocalCryptoMaterialsCache ( graph . config . materials_manager . cache_capacity ) , master_key_provider = key_provider , max_age = graph . config . materials_m... | Configure a crypto materials manager |
26,503 | def main ( graph ) : args = parse_args ( graph ) if args . drop : drop_all ( graph ) create_all ( graph ) | Create and drop databases . |
26,504 | def get_lattice_type ( cryst ) : lattice_types = [ [ 3 , "Triclinic" ] , [ 16 , "Monoclinic" ] , [ 75 , "Orthorombic" ] , [ 143 , "Tetragonal" ] , [ 168 , "Trigonal" ] , [ 195 , "Hexagonal" ] , [ 231 , "Cubic" ] ] sg = spg . get_spacegroup ( cryst ) m = re . match ( r'([A-Z].*\b)\s*\(([0-9]*)\)' , sg ) sg_name = m . gr... | Find the symmetry of the crystal using spglib symmetry finder . |
26,505 | def get_bulk_modulus ( cryst ) : if getattr ( cryst , 'bm_eos' , None ) is None : raise RuntimeError ( 'Missing B-M EOS data.' ) cryst . bulk_modulus = cryst . bm_eos [ 1 ] return cryst . bulk_modulus | Calculate bulk modulus using the Birch - Murnaghan equation of state . |
26,506 | def get_BM_EOS ( cryst , systems ) : pvdat = array ( [ [ r . get_volume ( ) , get_pressure ( r . get_stress ( ) ) , norm ( r . get_cell ( ) [ : , 0 ] ) , norm ( r . get_cell ( ) [ : , 1 ] ) , norm ( r . get_cell ( ) [ : , 2 ] ) ] for r in systems ] ) . T v1 = min ( pvdat [ 0 ] ) v2 = max ( pvdat [ 0 ] ) p2 = min ( pvda... | Calculate Birch - Murnaghan Equation of State for the crystal . |
26,507 | def get_elementary_deformations ( cryst , n = 5 , d = 2 ) : deform = { "Cubic" : [ [ 0 , 3 ] , regular ] , "Hexagonal" : [ [ 0 , 2 , 3 , 5 ] , hexagonal ] , "Trigonal" : [ [ 0 , 1 , 2 , 3 , 4 , 5 ] , trigonal ] , "Tetragonal" : [ [ 0 , 2 , 3 , 5 ] , tetragonal ] , "Orthorombic" : [ [ 0 , 1 , 2 , 3 , 4 , 5 ] , orthoromb... | Generate elementary deformations for elastic tensor calculation . |
26,508 | def get_cart_deformed_cell ( base_cryst , axis = 0 , size = 1 ) : cryst = Atoms ( base_cryst ) uc = base_cryst . get_cell ( ) s = size / 100.0 L = diag ( ones ( 3 ) ) if axis < 3 : L [ axis , axis ] += s else : if axis == 3 : L [ 1 , 2 ] += s elif axis == 4 : L [ 0 , 2 ] += s else : L [ 0 , 1 ] += s uc = dot ( uc , L )... | Return the cell deformed along one of the cartesian directions |
26,509 | def get_strain ( cryst , refcell = None ) : if refcell is None : refcell = cryst du = cryst . get_cell ( ) - refcell . get_cell ( ) m = refcell . get_cell ( ) m = inv ( m ) u = dot ( m , du ) u = ( u + u . T ) / 2 return array ( [ u [ 0 , 0 ] , u [ 1 , 1 ] , u [ 2 , 2 ] , u [ 2 , 1 ] , u [ 2 , 0 ] , u [ 1 , 0 ] ] ) | Calculate strain tensor in the Voight notation |
26,510 | def work_dir ( path ) : starting_directory = os . getcwd ( ) try : os . chdir ( path ) yield finally : os . chdir ( starting_directory ) | Context menager for executing commands in some working directory . Returns to the previous wd when finished . |
26,511 | def prepare_calc_dir ( self ) : with open ( "vasprun.conf" , "w" ) as f : f . write ( 'NODES="nodes=%s:ppn=%d"\n' % ( self . nodes , self . ppn ) ) f . write ( 'BLOCK=%d\n' % ( self . block , ) ) if self . ncl : f . write ( 'NCL=%d\n' % ( 1 , ) ) | Prepare the calculation directory for VASP execution . This needs to be re - implemented for each local setup . The following code reflects just my particular setup . |
26,512 | def calc_finished ( self ) : if not self . calc_running : return True else : with work_dir ( self . working_dir ) : o = check_output ( [ 'check-job' ] ) if o [ 0 ] in b'R' : return False else : return True | Check if the lockfile is in the calculation directory . It is removed by the script at the end regardless of the success of the calculation . This is totally tied to implementation and you need to implement your own scheme! |
26,513 | def run_calculation ( self , atoms = None , properties = [ 'energy' ] , system_changes = all_changes ) : self . calc . calculate ( self , atoms , properties , system_changes ) self . write_input ( self . atoms , properties , system_changes ) if self . command is None : raise RuntimeError ( 'Please configure Remote calc... | Internal calculation executor . We cannot use FileIOCalculator directly since we need to support remote execution . This calculator is different from others . It prepares the directory launches the remote process and raises the exception to signal that we need to come back for results when the job is finished . |
26,514 | def gen ( ctx , num , lo , hi , size , struct ) : frmt = ctx . parent . params [ 'frmt' ] action = ctx . parent . params [ 'action' ] cryst = ase . io . read ( struct , format = frmt ) fn_tmpl = action if frmt == 'vasp' : fn_tmpl += '_%03d.POSCAR' kwargs = { 'vasp5' : True , 'direct' : True } elif frmt == 'abinit' : fn... | Generate deformed structures |
26,515 | def proc ( ctx , files ) : def calc_reader ( fn , verb ) : if verb : echo ( 'Reading: {:<60s}\r' . format ( fn ) , nl = False , err = True ) return ase . io . read ( fn ) action = ctx . parent . params [ 'action' ] systems = [ calc_reader ( calc , verbose ) for calc in files ] if verbose : echo ( '' , err = True ) if a... | Process calculated structures |
26,516 | def save_model ( self , request , entry , form , change ) : context = RequestContext ( request ) try : content = render_placeholder ( entry . content_placeholder , context ) entry . content = content or '' except KeyError : entry . content = '' super ( EntryPlaceholderAdmin , self ) . save_model ( request , entry , for... | Fill the content field with the interpretation of the placeholder |
26,517 | def get_nodes ( self , request ) : nodes = [ ] archives = [ ] attributes = { 'hidden' : HIDE_ENTRY_MENU } for entry in Entry . published . all ( ) : year = entry . creation_date . strftime ( '%Y' ) month = entry . creation_date . strftime ( '%m' ) month_text = format ( entry . creation_date , 'b' ) . capitalize ( ) day... | Return menu s node for entries |
26,518 | def get_nodes ( self , request ) : nodes = [ ] nodes . append ( NavigationNode ( _ ( 'Categories' ) , reverse ( 'zinnia:category_list' ) , 'categories' ) ) for category in Category . objects . all ( ) : nodes . append ( NavigationNode ( category . title , category . get_absolute_url ( ) , category . pk , 'categories' )... | Return menu s node for categories |
26,519 | def get_nodes ( self , request ) : nodes = [ ] nodes . append ( NavigationNode ( _ ( 'Authors' ) , reverse ( 'zinnia:author_list' ) , 'authors' ) ) for author in Author . published . all ( ) : nodes . append ( NavigationNode ( author . __str__ ( ) , author . get_absolute_url ( ) , author . pk , 'authors' ) ) return nod... | Return menu s node for authors |
26,520 | def get_nodes ( self , request ) : nodes = [ ] nodes . append ( NavigationNode ( _ ( 'Tags' ) , reverse ( 'zinnia:tag_list' ) , 'tags' ) ) for tag in tags_published ( ) : nodes . append ( NavigationNode ( tag . name , reverse ( 'zinnia:tag_detail' , args = [ tag . name ] ) , tag . pk , 'tags' ) ) return nodes | Return menu s node for tags |
26,521 | def modify ( self , request , nodes , namespace , root_id , post_cut , breadcrumb ) : if breadcrumb : return nodes for node in nodes : if node . attr . get ( 'hidden' ) : node . visible = False return nodes | Modify nodes of a menu |
26,522 | def acquire_context ( self ) : frame = None request = None try : for f in inspect . stack ( ) [ 1 : ] : frame = f [ 0 ] args , varargs , keywords , alocals = inspect . getargvalues ( frame ) if not request and 'request' in args : request = alocals [ 'request' ] if 'context' in args : return alocals [ 'context' ] finall... | Inspect the stack to acquire the current context used to render the placeholder . I m really sorry for this but if you have a better way you are welcome ! |
26,523 | def get_boto_ses_connection ( ) : access_key_id = getattr ( settings , 'CUCUMBER_SES_ACCESS_KEY_ID' , getattr ( settings , 'AWS_ACCESS_KEY_ID' , None ) ) access_key = getattr ( settings , 'CUCUMBER_SES_SECRET_ACCESS_KEY' , getattr ( settings , 'AWS_SECRET_ACCESS_KEY' , None ) ) region_name = getattr ( settings , 'CUCUM... | Shortcut for instantiating and returning a boto SESConnection object . |
26,524 | def run ( self , from_email , recipients , message ) : self . _open_ses_conn ( ) try : self . connection . send_raw_email ( source = from_email , destinations = recipients , raw_message = dkim_sign ( message ) , ) except SESAddressBlacklistedError , exc : logger . warning ( 'Attempted to email a blacklisted user: %s' %... | This does the dirty work . Connects to Amazon SES via boto and fires off the message . |
26,525 | def handle ( self , * args , ** options ) : conn = get_boto_ses_connection ( ) self . _print_quota ( conn ) self . _print_daily_stats ( conn ) | Renders the output by piecing together a few methods that do the dirty work . |
26,526 | def _print_quota ( self , conn ) : quota = conn . get_send_quota ( ) quota = quota [ 'GetSendQuotaResponse' ] [ 'GetSendQuotaResult' ] print "--- SES Quota ---" print " 24 Hour Quota: %s" % quota [ 'Max24HourSend' ] print " Sent (Last 24 hours): %s" % quota [ 'SentLast24Hours' ] print " Max sending rate: %s/sec" % q... | Prints some basic quota statistics . |
26,527 | def sample ( self , bqm , init_solution = None , tenure = None , scale_factor = 1 , timeout = 20 , num_reads = 1 ) : if init_solution is not None : if not isinstance ( init_solution , dimod . SampleSet ) : raise TypeError ( "'init_solution' should be a 'dimod.SampleSet' instance" ) if len ( init_solution . record ) < 1... | Run a tabu search on a given binary quadratic model . |
26,528 | def upload_from_url ( self , url ) : self . check_token ( ) params = { 'fetchUrl' : url } r = requests . get ( FETCH_URL_ENDPOINT , params = params ) if r . status_code != 200 : raise GfycatClientError ( 'Error fetching the URL' , r . status_code ) response = r . json ( ) if 'error' in response : raise GfycatClientErro... | Upload a GIF from a URL . |
26,529 | def upload_from_file ( self , filename ) : key = str ( uuid . uuid4 ( ) ) [ : 8 ] form = [ ( 'key' , key ) , ( 'acl' , ACL ) , ( 'AWSAccessKeyId' , AWS_ACCESS_KEY_ID ) , ( 'success_action_status' , SUCCESS_ACTION_STATUS ) , ( 'signature' , SIGNATURE ) , ( 'Content-Type' , CONTENT_TYPE ) , ( 'policy' , POLICY ) ] data =... | Upload a local file to Gfycat |
26,530 | def uploaded_file_info ( self , key ) : r = requests . get ( FILE_UPLOAD_STATUS_ENDPOINT + key ) if r . status_code != 200 : raise GfycatClientError ( 'Unable to check the status' , r . status_code ) return r . json ( ) | Get information about an uploaded GIF . |
26,531 | def query_gfy ( self , gfyname ) : self . check_token ( ) r = requests . get ( QUERY_ENDPOINT + gfyname , headers = self . headers ) response = r . json ( ) if r . status_code != 200 and not ERROR_KEY in response : raise GfycatClientError ( 'Bad response from Gfycat' , r . status_code ) elif ERROR_KEY in response : rai... | Query a gfy name for URLs and more information . |
26,532 | def check_link ( self , link ) : r = requests . get ( CHECK_LINK_ENDPOINT + link ) if r . status_code != 200 : raise GfycatClientError ( 'Unable to check the link' , r . status_code ) return r . json ( ) | Check if a link has been already converted . |
26,533 | def get_token ( self ) : payload = { 'grant_type' : 'client_credentials' , 'client_id' : self . client_id , 'client_secret' : self . client_secret } r = requests . post ( OAUTH_ENDPOINT , data = json . dumps ( payload ) , headers = { 'content-type' : 'application/json' } ) response = r . json ( ) if r . status_code != ... | Gets the authorization token |
26,534 | def dict ( self ) : metadata = { } properties = { } for name , prop in list ( self . properties . items ( ) ) : properties [ name ] = prop . dict metadata [ 'properties' ] = properties return metadata | dictionary representation of the metadata . |
26,535 | def json ( self ) : json_dumps = json . dumps ( self . dict , indent = 2 , sort_keys = True , separators = ( ',' , ': ' ) , cls = MetadataEncoder ) if not json_dumps . endswith ( '\n' ) : json_dumps += '\n' return json_dumps | json representation of the metadata . |
26,536 | def _read_json_file ( self ) : with open ( self . json_uri ) as metadata_file : try : metadata = json . load ( metadata_file ) return metadata except ValueError : message = tr ( 'the file %s does not appear to be valid JSON' ) message = message % self . json_uri raise MetadataReadError ( message ) | read metadata from a json file . |
26,537 | def _read_json_db ( self ) : try : metadata_str = self . db_io . read_metadata_from_uri ( self . layer_uri , 'json' ) except HashNotFoundError : return { } try : metadata = json . loads ( metadata_str ) return metadata except ValueError : message = tr ( 'the file DB entry for %s does not appear to be ' 'valid JSON' ) m... | read metadata from a json string stored in a DB . |
26,538 | def _read_xml_file ( self ) : root = ElementTree . parse ( self . xml_uri ) root . getroot ( ) return root | read metadata from an xml file . |
26,539 | def _read_xml_db ( self ) : try : metadata_str = self . db_io . read_metadata_from_uri ( self . layer_uri , 'xml' ) root = ElementTree . fromstring ( metadata_str ) return root except HashNotFoundError : return None | read metadata from an xml string stored in a DB . |
26,540 | def set ( self , name , value , xml_path ) : xml_type = xml_path . split ( '/' ) [ - 1 ] try : property_class = TYPE_CONVERSIONS [ xml_type ] except KeyError : raise KeyError ( 'The xml type %s is not supported yet' % xml_type ) try : metadata_property = property_class ( name , value , xml_path ) self . _properties [ n... | Create a new metadata property . |
26,541 | def write_to_file ( self , destination_path ) : file_format = os . path . splitext ( destination_path ) [ 1 ] [ 1 : ] metadata = self . get_writable_metadata ( file_format ) with open ( destination_path , 'w' , encoding = 'utf-8' ) as f : f . write ( metadata ) return metadata | Writes the metadata json or xml to a file . |
26,542 | def get_writable_metadata ( self , file_format ) : if file_format == 'json' : metadata = self . json elif file_format == 'xml' : metadata = self . xml else : raise TypeError ( 'The requested file type (%s) is not yet supported' % file_format ) return metadata | Convert the metadata to a writable form . |
26,543 | def read_from_ancillary_file ( self , custom_xml = None ) : if custom_xml and os . path . isfile ( self . xml_uri ) : self . read_xml ( ) else : if not self . read_json ( ) : self . read_xml ( ) | try to read xml and json from existing files or db . |
26,544 | def update_from_dict ( self , keywords ) : for key , value in list ( keywords . items ( ) ) : setattr ( self , key , value ) | Set properties of metadata using key and value from keywords |
26,545 | def accept ( self ) : input_layer = self . layer . currentLayer ( ) output_path = self . output_form . text ( ) radius = self . get_classification ( ) input_layer . keywords = { 'inasafe_fields' : { } } self . output_layer = multi_buffering ( input_layer , radius ) if output_path : self . output_directory , self . outp... | Process the layer for multi buffering and generate a new layer . |
26,546 | def on_directory_button_tool_clicked ( self ) : input_path = self . layer . currentLayer ( ) . source ( ) input_directory , self . output_filename = os . path . split ( input_path ) file_extension = os . path . splitext ( self . output_filename ) [ 1 ] self . output_filename = os . path . splitext ( self . output_filen... | Autoconnect slot activated when directory button is clicked . |
26,547 | def get_output_from_input ( self ) : input_path = self . layer . currentLayer ( ) . source ( ) output_path = ( os . path . splitext ( input_path ) [ 0 ] + '_multi_buffer' + os . path . splitext ( input_path ) [ 1 ] ) self . output_form . setText ( output_path ) | Populate output form with default output path based on input layer . |
26,548 | def populate_hazard_classification ( self ) : new_class = { 'value' : self . radius_form . value ( ) , 'name' : self . class_form . text ( ) } self . classification . append ( new_class ) self . classification = sorted ( self . classification , key = itemgetter ( 'value' ) ) self . hazard_class_form . clear ( ) for ite... | Populate hazard classification on hazard class form . |
26,549 | def remove_selected_classification ( self ) : removed_classes = self . hazard_class_form . selectedItems ( ) current_item = self . hazard_class_form . currentItem ( ) removed_index = self . hazard_class_form . indexFromItem ( current_item ) del self . classification [ removed_index . row ( ) ] for item in removed_class... | Remove selected item on hazard class form . |
26,550 | def get_classification ( self ) : classification_dictionary = { } for item in self . classification : classification_dictionary [ item [ 'value' ] ] = item [ 'name' ] classification_dictionary = OrderedDict ( sorted ( classification_dictionary . items ( ) ) ) return classification_dictionary | Get all hazard class created by user . |
26,551 | def directory_button_status ( self ) : if self . layer . currentLayer ( ) : self . directory_button . setEnabled ( True ) else : self . directory_button . setEnabled ( False ) | Function to enable or disable directory button . |
26,552 | def add_class_button_status ( self ) : if self . class_form . text ( ) and self . radius_form . value ( ) >= 0 : self . add_class_button . setEnabled ( True ) else : self . add_class_button . setEnabled ( False ) | Function to enable or disable add class button . |
26,553 | def ok_button_status ( self ) : if not self . layer . currentLayer ( ) : self . button_box . button ( QtWidgets . QDialogButtonBox . Ok ) . setEnabled ( False ) elif ( self . hazard_class_form . count ( ) > 0 and self . layer . currentLayer ( ) . name ( ) and len ( self . output_form . text ( ) ) >= 0 ) : self . button... | Function to enable or disable OK button . |
26,554 | def help_toggled ( self , flag ) : if flag : self . help_button . setText ( self . tr ( 'Hide Help' ) ) self . show_help ( ) else : self . help_button . setText ( self . tr ( 'Show Help' ) ) self . hide_help ( ) | Show or hide the help tab in the stacked widget . |
26,555 | def convert_mmi_data ( grid_xml_path , title , source , output_path = None , algorithm = None , algorithm_filename_flag = True , smoothing_method = NONE_SMOOTHING , smooth_sigma = 0.9 , extra_keywords = None ) : LOGGER . debug ( grid_xml_path ) LOGGER . debug ( output_path ) if output_path is not None : output_dir , ou... | Convenience function to convert a single file . |
26,556 | def extract_date_time ( self , the_time_stamp ) : date_tokens = the_time_stamp [ 0 : 10 ] . split ( '-' ) self . year = int ( date_tokens [ 0 ] ) self . month = int ( date_tokens [ 1 ] ) self . day = int ( date_tokens [ 2 ] ) time_tokens = the_time_stamp [ 11 : 19 ] . split ( ':' ) self . hour = int ( time_tokens [ 0 ]... | Extract the parts of a date given a timestamp as per below example . |
26,557 | def grid_file_path ( self ) : if os . path . isfile ( self . grid_xml_path ) : return self . grid_xml_path else : raise GridXmlFileNotFoundError | Validate that grid file path points to a file . |
26,558 | def mmi_to_delimited_text ( self ) : delimited_text = 'lon,lat,mmi\n' for row in self . mmi_data : delimited_text += '%s,%s,%s\n' % ( row [ 0 ] , row [ 1 ] , row [ 2 ] ) return delimited_text | Return the mmi data as a delimited test string . |
26,559 | def mmi_to_delimited_file ( self , force_flag = True ) : LOGGER . debug ( 'mmi_to_delimited_text requested.' ) csv_path = os . path . join ( self . output_dir , 'mmi.csv' ) if os . path . exists ( csv_path ) and force_flag is not True : return csv_path csv_file = open ( csv_path , 'w' ) csv_file . write ( self . mmi_to... | Save mmi_data to delimited text file suitable for gdal_grid . |
26,560 | def mmi_to_vrt ( self , force_flag = True ) : LOGGER . debug ( 'mmi_to_vrt requested.' ) vrt_path = os . path . join ( self . output_dir , self . output_basename + '.vrt' ) if os . path . exists ( vrt_path ) and force_flag is not True : return vrt_path csv_path = self . mmi_to_delimited_file ( True ) vrt_string = ( '<O... | Save the mmi_data to an ogr vrt text file . |
26,561 | def _run_command ( self , command ) : try : my_result = call ( command , shell = True ) del my_result except CalledProcessError as e : LOGGER . exception ( 'Running command failed %s' % command ) message = ( 'Error while executing the following shell ' 'command: %s\nError message: %s' % ( command , str ( e ) ) ) if sys... | Run a command and raise any error as needed . |
26,562 | def mmi_to_raster ( self , force_flag = False , algorithm = USE_ASCII ) : LOGGER . debug ( 'mmi_to_raster requested.' ) if algorithm is None : algorithm = USE_ASCII if self . algorithm_name : tif_path = os . path . join ( self . output_dir , '%s-%s.tif' % ( self . output_basename , algorithm ) ) else : tif_path = os . ... | Convert the grid . xml s mmi column to a raster using gdal_grid . |
26,563 | def mmi_to_shapefile ( self , force_flag = False ) : LOGGER . debug ( 'mmi_to_shapefile requested.' ) shp_path = os . path . join ( self . output_dir , '%s-points.shp' % self . output_basename ) if os . path . exists ( shp_path ) and force_flag is not True : return shp_path vrt_path = self . mmi_to_vrt ( force_flag ) b... | Convert grid . xml s mmi column to a vector shp file using ogr2ogr . |
26,564 | def create_keyword_file ( self , algorithm ) : keyword_io = KeywordIO ( ) mmi_default_classes = default_classification_thresholds ( earthquake_mmi_scale ) mmi_default_threshold = { earthquake_mmi_scale [ 'key' ] : { 'active' : True , 'classes' : mmi_default_classes } } generic_default_classes = default_classification_t... | Create keyword file for the raster file created . |
26,565 | def mmi_to_ascii ( self , force_flag = False ) : ascii_path = os . path . join ( self . output_dir , '%s.asc' % self . output_basename ) if os . path . exists ( ascii_path ) and force_flag is not True : return ascii_path cell_size = ( self . x_maximum - self . x_minimum ) / ( self . rows - 1 ) asc_file = open ( ascii_p... | Convert grid . xml mmi column to a ascii raster file . |
26,566 | def set_widgets ( self ) : if self . parent . aggregation_layer : aggr = self . parent . aggregation_layer . name ( ) else : aggr = self . tr ( 'no aggregation' ) html = self . tr ( 'Please ensure the following information ' 'is correct and press Run.' ) html += '<br/><table cellspacing="4">' html += ( '<tr>' ' <td><b... | Set widgets on the Summary tab . |
26,567 | def inasafe_analysis_summary_field_value ( field , feature , parent ) : _ = feature , parent project_context_scope = QgsExpressionContextUtils . projectScope ( QgsProject . instance ( ) ) registry = QgsProject . instance ( ) key = provenance_layer_analysis_impacted_id [ 'provenance_key' ] if not project_context_scope .... | Retrieve a value from a field in the analysis summary layer . |
26,568 | def inasafe_sub_analysis_summary_field_value ( exposure_key , field , feature , parent ) : _ = feature , parent project_context_scope = QgsExpressionContextUtils . projectScope ( QgsProject . instance ( ) ) project = QgsProject . instance ( ) key = ( '{provenance}__{exposure}' ) . format ( provenance = provenance_multi... | Retrieve a value from field in the specified exposure analysis layer . |
26,569 | def inasafe_exposure_summary_field_values ( field , feature , parent ) : _ = feature , parent layer = exposure_summary_layer ( ) if not layer : return None index = layer . fields ( ) . lookupField ( field ) if index < 0 : return None values = [ ] for feat in layer . getFeatures ( ) : value = feat [ index ] values . app... | Retrieve all values from a field in the exposure summary layer . |
26,570 | def inasafe_place_value_name ( number , feature , parent ) : _ = feature , parent if number is None : return None rounded_number = round_affected_number ( number , use_rounding = True , use_population_rounding = True ) value , unit = denomination ( rounded_number , 1000 ) if not unit : return None else : return unit [ ... | Given a number it will return the place value name . |
26,571 | def inasafe_place_value_coefficient ( number , feature , parent ) : _ = feature , parent if number >= 0 : rounded_number = round_affected_number ( number , use_rounding = True , use_population_rounding = True ) min_number = 1000 value , unit = denomination ( rounded_number , min_number ) if number < min_number : rounde... | Given a number it will return the coefficient of the place value name . |
26,572 | def inasafe_place_value_percentage ( number , total , feature , parent ) : _ = feature , parent if number < 0 : return None percentage_format = '{percentage}%' percentage = round ( ( float ( number ) / float ( total ) ) * 100 , 1 ) return percentage_format . format ( percentage = percentage ) | Given a number and total it will return the percentage of the number to the total . |
26,573 | def beautify_date ( inasafe_time , feature , parent ) : _ = feature , parent datetime_object = parse ( inasafe_time ) date = datetime_object . strftime ( '%Y-%m-%d' ) return date | Given an InaSAFE analysis time it will convert it to a date with year - month - date format . |
26,574 | def hazard_extra_keyword ( keyword , feature , parent ) : _ = feature , parent hazard_layer_path = QgsExpressionContextUtils . projectScope ( QgsProject . instance ( ) ) . variable ( 'hazard_layer' ) hazard_layer = load_layer ( hazard_layer_path ) [ 0 ] keywords = KeywordIO . read_keywords ( hazard_layer ) extra_keywor... | Given a keyword it will return the value of the keyword from the hazard layer s extra keywords . |
26,575 | def to_html ( self ) : if self . items is None : return else : html = '<ol%s>\n' % self . html_attributes ( ) for item in self . items : html += '<li>%s</li>\n' % item . to_html ( ) html += '</ol>' return html | Render a Text MessageElement as html |
26,576 | def _check_value_mapping ( layer , exposure_key = None ) : index = layer . fields ( ) . lookupField ( exposure_type_field [ 'field_name' ] ) unique_exposure = layer . uniqueValues ( index ) if layer . keywords [ 'layer_purpose' ] == layer_purpose_hazard [ 'key' ] : if not exposure_key : message = tr ( 'Hazard value map... | Loop over the exposure type field and check if the value map is correct . |
26,577 | def clean_inasafe_fields ( layer ) : fields = [ ] if layer . keywords [ 'layer_purpose' ] == layer_purpose_exposure [ 'key' ] : fields = get_fields ( layer . keywords [ 'layer_purpose' ] , layer . keywords [ 'exposure' ] ) elif layer . keywords [ 'layer_purpose' ] == layer_purpose_hazard [ 'key' ] : fields = get_fields... | Clean inasafe_fields based on keywords . |
26,578 | def _size_is_needed ( layer ) : exposure = layer . keywords . get ( 'exposure' ) if not exposure : return False indivisible_exposure_keys = [ f [ 'key' ] for f in indivisible_exposure ] if exposure in indivisible_exposure_keys : return False if layer . geometryType ( ) == QgsWkbTypes . PointGeometry : return False fiel... | Checker if we need the size field . |
26,579 | def _remove_features ( layer ) : layer_purpose = layer . keywords [ 'layer_purpose' ] layer_subcategory = layer . keywords . get ( layer_purpose ) compulsory_field = get_compulsory_fields ( layer_purpose , layer_subcategory ) inasafe_fields = layer . keywords [ 'inasafe_fields' ] field_names = inasafe_fields . get ( co... | Remove features which do not have information for InaSAFE or an invalid geometry . |
26,580 | def _add_id_column ( layer ) : layer_purpose = layer . keywords [ 'layer_purpose' ] mapping = { layer_purpose_exposure [ 'key' ] : exposure_id_field , layer_purpose_hazard [ 'key' ] : hazard_id_field , layer_purpose_aggregation [ 'key' ] : aggregation_id_field } has_id_column = False for layer_type , field in list ( ma... | Add an ID column if it s not present in the attribute table . |
26,581 | def _add_default_exposure_class ( layer ) : layer . startEditing ( ) field = create_field_from_definition ( exposure_class_field ) layer . keywords [ 'inasafe_fields' ] [ exposure_class_field [ 'key' ] ] = ( exposure_class_field [ 'field_name' ] ) layer . addAttribute ( field ) index = layer . fields ( ) . lookupField ... | The layer doesn t have an exposure class we need to add it . |
26,582 | def sum_fields ( layer , output_field_key , input_fields ) : field_definition = definition ( output_field_key ) output_field_name = field_definition [ 'field_name' ] if len ( input_fields ) == 1 : if input_fields [ 0 ] != output_field_name : to_rename = { input_fields [ 0 ] : output_field_name } copy_fields ( layer , t... | Sum the value of input_fields and put it as output_field . |
26,583 | def get_needs_provenance ( parameters ) : if 'minimum needs' not in parameters : return None needs = parameters [ 'minimum needs' ] provenance = [ p for p in needs if p . name == tr ( 'Provenance' ) ] if provenance : return provenance [ 0 ] return None | Get the provenance of minimum needs . |
26,584 | def load ( self ) : self . minimum_needs = self . settings . value ( 'MinimumNeeds' ) if not self . minimum_needs or self . minimum_needs == '' : profiles = self . get_profiles ( ) if len ( profiles ) == 1 : profile = self . get_profiles ( ) [ 0 ] self . load_profile ( profile ) else : self . minimum_needs = self . _de... | Load the minimum needs . |
26,585 | def load_profile ( self , profile ) : profile_path = os . path . join ( self . root_directory , 'minimum_needs' , profile + '.json' ) self . read_from_file ( profile_path ) | Load a specific profile into the current minimum needs . |
26,586 | def save_profile ( self , profile ) : profile = profile . replace ( '.json' , '' ) profile_path = os . path . join ( self . root_directory , 'minimum_needs' , profile + '.json' ) self . write_to_file ( profile_path ) | Save the current minimum needs into a new profile . |
26,587 | def get_profiles ( self , overwrite = False ) : def sort_by_locale ( unsorted_profiles , locale ) : if locale is None : return unsorted_profiles locale = '_%s' % locale [ : 2 ] profiles_our_locale = [ ] profiles_remaining = [ ] for profile_name in unsorted_profiles : if locale in profile_name : profiles_our_locale . ap... | Get all the minimum needs profiles . |
26,588 | def get_needs_parameters ( self ) : parameters = [ ] for resource in self . minimum_needs [ 'resources' ] : parameter = ResourceParameter ( ) parameter . name = resource [ 'Resource name' ] parameter . help_text = resource [ 'Resource description' ] parameter . frequency = resource [ 'Frequency' ] parameter . descripti... | Get the minimum needs resources in parameter format |
26,589 | def format_sentence ( sentence , resource ) : sentence = sentence . split ( '{{' ) updated_sentence = sentence [ 0 ] . rstrip ( ) for part in sentence [ 1 : ] : replace , keep = part . split ( '}}' ) replace = replace . strip ( ) updated_sentence = "%s %s%s" % ( updated_sentence , resource [ replace ] , keep ) return u... | Populate the placeholders in the sentence . |
26,590 | def remove_profile ( self , profile ) : self . remove_file ( os . path . join ( self . root_directory , 'minimum_needs' , profile + '.json' ) ) | Remove a profile . |
26,591 | def tr ( text , context = '@default' ) : if type ( text ) != str : text = str ( text ) translated_text = QCoreApplication . translate ( context , text ) if text . count ( '%' ) == translated_text . count ( '%' ) : return translated_text else : content = ( 'There is a problem in the translation text.\n' 'The original te... | We define a tr function alias here since the utilities implementation below is not a class and does not inherit from QObject . |
26,592 | def locale ( qsetting = '' ) : override_flag = QSettings ( qsetting ) . value ( 'locale/overrideFlag' , True , type = bool ) default = 'en_US' if override_flag : locale_name = QSettings ( qsetting ) . value ( 'locale/userLocale' , default , type = str ) else : locale_name = QLocale . system ( ) . name ( ) if locale_nam... | Get the name of the currently active locale . |
26,593 | def update_band_description ( self ) : self . clear_further_steps ( ) selected_band = self . selected_band ( ) statistics = self . parent . layer . dataProvider ( ) . bandStatistics ( selected_band , QgsRasterBandStats . All , self . parent . layer . extent ( ) , 0 ) band_description = tr ( 'This band contains data fro... | Helper to update band description . |
26,594 | def selected_band ( self ) : item = self . lstBands . currentItem ( ) return item . data ( QtCore . Qt . UserRole ) | Obtain the layer mode selected by user . |
26,595 | def merge_dictionaries ( base_dict , extra_dict ) : new_dict = base_dict . copy ( ) new_dict . update ( extra_dict ) return new_dict | merge two dictionaries . |
26,596 | def read_property_from_xml ( root , path ) : element = root . find ( path , XML_NS ) try : return element . text . strip ( ' \t\n\r' ) except AttributeError : return None | Get the text from an XML property . |
26,597 | def north_arrow ( self , north_arrow_path ) : if isinstance ( north_arrow_path , str ) and os . path . exists ( north_arrow_path ) : self . _north_arrow = north_arrow_path else : self . _north_arrow = default_north_arrow_path ( ) | Set image that will be used as north arrow in reports . |
26,598 | def organisation_logo ( self , logo ) : if isinstance ( logo , str ) and os . path . exists ( logo ) : self . _organisation_logo = logo else : self . _organisation_logo = supporters_logo_path ( ) | Set image that will be used as organisation logo in reports . |
26,599 | def disclaimer ( self , text ) : if not isinstance ( text , str ) : self . _disclaimer = disclaimer ( ) else : self . _disclaimer = text | Set text that will be used as disclaimer in reports . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.