Exemple #1
0
def networkPreProcessing(bikeNetwork, footNetwork):
    arcpy.Delete_management(
        "C:/Users/Simon/Documents/GitHub/Enrichment/networkPr_update.shp", "")
    bikeNetworkFL = arcpy.CopyFeatures_management(
        bikeNetwork,
        "C:/Users/Simon/Documents/GitHub/Enrichment/bikeNetworkUpdate")
    arcpy.MakeFeatureLayer_management(bikeNetworkFL, "bikeNetworkPr_update")
    expressionBike = """("navigatie" = 'onderdeel van rotonde' OR "navigatie" = 'onderdeel van kruispunt' OR "wegtype" = 'bromfietspad (langs weg)' OR "wegtype" = 'fietspad (langs weg)' OR "wegtype" = 'fietsstraat' OR "wegtype" = 'solitair bromfietspad' OR "wegtype" = 'solitair fietspad' OR "wegtype" = 'voetgangersdoorsteekje' OR "wegtype" = 'voetgangersgebied' OR "wegtype" = 'weg met fiets(suggestie)strook' ) AND "verlichtin" = ' ' OR "verlichtin" = 'beperkt verlicht (bijvoorbeeld alleen bij kruispunten)' OR "verlichtin" = 'goed verlicht' OR "verlichtin" = 'niet verlicht' OR "verlichtin" = 'ONBEKEND'"""
    arcpy.SelectLayerByAttribute_management("bikeNetworkPr_update",
                                            "NEW_SELECTION", expressionBike)
    if int(arcpy.GetCount_management("bikeNetworkPr_update").getOutput(0)) < 0:
        arcpy.DeleteRows_management("bikeNetworkPr_update")

    footNetworkFL = arcpy.CopyFeatures_management(
        footNetwork,
        "C:/Users/Simon/Documents/GitHub/Enrichment/footNetworkUpdate")
    arcpy.MakeFeatureLayer_management(footNetworkFL, "footNetworkPr_update")
    expressionFoot = """VERHARDINGSBREEDTEKLASSE = '< 2 meter' OR VERHARDINGSBREEDTEKLASSE = '2 - 4 meter' AND (TYPEWEG_1 = 'overig' AND (HOOFDVERKEERSGEBRUIK_1 = 'gemengd verkeer' OR HOOFDVERKEERSGEBRUIK_1 = 'voetgangers') AND (VERHARDINGSTYPE = 'half verhard' OR VERHARDINGSTYPE = 'onbekend' OR VERHARDINGSTYPE = 'onverhard'))"""
    arcpy.SelectLayerByAttribute_management("footNetworkPr_update",
                                            "NEW_SELECTION", expressionFoot)
    if int(arcpy.GetCount_management("footNetworkPr_update").getOutput(0)) < 0:
        arcpy.DeleteRows_management("footNetworkPr_update")

    updatedNetworkBike = arcpy.FeatureClassToShapefile_conversion(
        "bikeNetworkPr_update", "C:/Users/Simon/Documents/GitHub/Enrichment/")
    updatedNetworkFoot = arcpy.FeatureClassToShapefile_conversion(
        "footNetworkPr_update", "C:/Users/Simon/Documents/GitHub/Enrichment/")
    arcpy.Delete_management(
        "C:/Users/Simon/Documents/GitHub/Enrichment/networkUpdate.shp",
        "C:/Users/Simon/Documents/GitHub/Enrichment/footNetworkUpdate.shp")
    return updatedNetwork
Exemple #2
0
def limit_cores(pair_tbl, stats_tbl):
    """Limit core pairs based upon climate threshold"""
    pair_vw = "dist_tbvw"
    stats_vw = "stats_tbvw"
    core_id = cc_env.core_fld.upper()

    lm_util.gprint("\nLIMITING CORE PAIRS BASED UPON CLIMATE " "THRESHOLD")

    arcpy.MakeTableView_management(pair_tbl, pair_vw)
    arcpy.MakeTableView_management(stats_tbl, stats_vw)

    # Add basic stats to distance table
    lm_util.gprint("Joining zonal statistics to pairings table")
    add_stats(stats_vw, core_id, "fr", pair_vw, TO_COL)
    add_stats(stats_vw, core_id, "to", pair_vw, FR_COL)

    # Calculate difference of 2 std
    lm_util.gprint("Calculating difference of 2 std")
    diffu_2std = "diffu_2std"
    arcpy.AddField_management(pair_vw, diffu_2std, "Float", "", "", "", "",
                              "NULLABLE")
    arcpy.CalculateField_management(pair_vw, diffu_2std,
                                    "abs(!frumin2std! - !toumin2std!)",
                                    "PYTHON_9.3")

    # Filter distance table based on inputed threshold and delete rows
    lm_util.gprint("Filtering table based on threshold")
    diffu2std_fld = arcpy.AddFieldDelimiters(pair_vw, diffu_2std)
    expression = diffu2std_fld + " <= " + str(cc_env.climate_threshold)
    arcpy.SelectLayerByAttribute_management(pair_vw, "NEW_SELECTION",
                                            expression)
    rows_del = int(arcpy.GetCount_management(pair_vw).getOutput(0))
    if rows_del > 0:
        arcpy.DeleteRows_management(pair_vw)
    lm_util.gprint(str(rows_del) + " rows deleted")
Exemple #3
0
def FC_Exist(FCname, DatasetPath, Template):
    FCpath = os.path.join(DatasetPath, FCname)
    FCtype = arcpy.Describe(Template).shapeType
    if arcpy.Exists(FCpath):
        if Compare_Fields(FCpath, Template):
            arcpy.AddMessage(
                "Feature class, {}, already exists. Clearing records.......".
                format(FCname))
            try:
                arcpy.TruncateTable_management(FCpath)
            except:
                arcpy.DeleteRows_management(FCpath)
        else:
            arcpy.AddMessage(
                "Additional fields have been added since the Feature class, {}, was created. Recreating Feature class......."
                .format(FCname))
            arcpy.Delete_management(FCpath)
            return arcpy.CreateFeatureclass_management(DatasetPath, FCname,
                                                       FCtype, Template,
                                                       "SAME_AS_TEMPLATE",
                                                       "SAME_AS_TEMPLATE",
                                                       Template)
    else:
        arcpy.AddMessage(
            "Feature class, {}, does not exist. Creating now.......".format(
                FCname))
        return arcpy.CreateFeatureclass_management(DatasetPath, FCname, FCtype,
                                                   Template,
                                                   "SAME_AS_TEMPLATE",
                                                   "SAME_AS_TEMPLATE",
                                                   Template)
Exemple #4
0
def update_incidents(mlayer):
    arcpy.DeleteRows_management('Closest Facility\Incidents')
    arcpy.AddLocations_na(network, 'Incidents', mlayer,
                          'Name {} #'.format(_HYBASID), _TOLERANCE, '#',
                          'tracks SHAPE;tracks_ND_Junctions NONE',
                          'MATCH_TO_CLOSEST', 'APPEND', 'NO_SNAP', '5 Meters',
                          'INCLUDE', 'tracks #;tracks_ND_Junctions #')
Exemple #5
0
 def model_catalog_test_data_cleanup(self):
     if self.config.test_flag == "TEST":
         feature_class_list = [
             self.config.model_tracking_sde_path,
             self.config.model_alt_bc_sde_path,
             self.config.model_alt_hydraulic_sde_path,
             self.config.model_alt_hydrologic_sde_path,
             self.config.project_type_sde_path,
             self.config.simulation_sde_path,
             self.config.geometry_nodes_sde_path,
             self.config.geometry_areas_sde_path,
             self.config.geometry_links_sde_path,
             self.config.results_area_sde_path,
             self.config.results_link_sde_path,
             self.config.results_node_sde_path,
             self.config.results_node_flooding_sde_path,
             self.config.storage_sde_path, self.config.director_sde_path
         ]
         for feature_class in feature_class_list:
             try:
                 arcpy.TruncateTable_management(feature_class)
             except:
                 print("unable to truncate, using Delete Rows")
                 arcpy.DeleteRows_management(feature_class)
     else:
         print("Config set to other than TEST, data will not be deleted")
 def run(self):
     area, i = self.parent_tbx.get_selected_area()
     toolbox = self.parent_tbx
     source_x = toolbox.x
     source_y = toolbox.y
     shape = arcpy.Point(source_x, source_y)
     id = area['id_teilflaeche']
     toolbox.update_table('Anbindungspunkte', {'Shape': shape},
                          where='id_teilflaeche={}'.format(id),
                          workspace='FGDB_Verkehr.gdb')
     arcpy.AddMessage(u"initialisiertes Verkehrsaufkommen wird gelöscht")
     self.remove_output()
     # delete pickle file
     pickle_path = self.folders.get_otp_pickle_filename(check=False)
     if os.path.exists(pickle_path):
         os.remove(pickle_path)
         # empty gdb tables
         tn_path = toolbox.folders.get_table('Zielpunkte',
                                             workspace=self._workspace)
         links_path = toolbox.folders.get_table('links',
                                                workspace=self._workspace)
         nodes_path = toolbox.folders.get_table('nodes',
                                                workspace=self._workspace)
         routes_path = toolbox.folders.get_table('Routes',
                                                 workspace=self._workspace)
         tables_to_clear = [tn_path, links_path, nodes_path, routes_path]
         for path in tables_to_clear:
             arcpy.DeleteRows_management(path)
    def parcelFlag(reviewName, reviewType, sourceFC, fieldCalculation,
                   whereClause, outputFC, workspace, parcels, parcelDict):
        reviewLayer = reviewType + '_' + reviewName
        reviewField = 'CODE' if reviewType == zonB else 'OVERLAY_NAME' if reviewType == zonO else reviewName + 'ReviewReason'
        print reviewField

        if '_Buffer' in reviewName:
            print('Buffering')
            arcpy.Buffer_analysis(sourceFC, reviewLayer, '500 Feet')
        else:
            print('Creating Local FC for ' + reviewName)
            arcpy.FeatureClassToFeatureClass_conversion(
                sourceFC, workspace, reviewLayer, whereClause)

        # All FCs except for Zoning are copied to LIGISDB
        if outputFC:
            print('Copying FC to GISLNI')
            arcpy.AddField_management(reviewLayer, reviewField, 'TEXT')
            arcpy.CalculateField_management(reviewLayer, reviewField,
                                            fieldCalculation)
            arcpy.AddField_management(reviewLayer,
                                      'REVIEW_TYPE',
                                      'TEXT',
                                      field_length=2000)
            arcpy.CalculateField_management(reviewLayer, 'REVIEW_TYPE',
                                            '"' + reviewName + '"')
            arcpy.DeleteRows_management(outputFC)
            arcpy.Append_management(reviewLayer, outputFC, 'NO_TEST')

        arcpy.Delete_management(reviewLayer)

        return parcelDict
def loadORACLE():
    now = datetime.datetime.now()
    arcpy.AddMessage('--- Przetwarzanie zasilania Oracle [' +
                     now.strftime("%Y/%m/%d %H:%M:%S") + '] ---')

    #inputs = [baza4Connector+r"\\sde.SDE.ZLOZA_GRANICE", baza4Connector+"\\sde.SDE.ZLOZA_OBSZARY", baza4Connector+"\\sde.SDE.ZLOZA_TERENY", baza4Connector+"\\sde.SDE.OTWORY", baza4Connector+"\\sde.SDE.JASKINIE"]
    inputs = [
        myPath + "\\cbdg_midas_kontury_" + today_ + "\\cbdg_midas_kontury_" +
        today_ + ".shp", myPath + "\\cbdg_midas_obszary_" + today_ +
        "\\cbdg_midas_obszary_" + today_ + ".shp",
        myPath + "\\cbdg_midas_tereny_" + today_ + "\\cbdg_midas_tereny_" +
        today_ + ".shp", myPath + "\\cbdg_otwory\\cbdg_otwory.shp",
        myPath + "midas.gdb\\jaskinieTemp"
    ]
    #temps = [myPath+"oracle2oracle.gdb\\ZLOZA_GRANICE", myPath+"oracle2oracle.gdb\\ZLOZA_OBSZARY", myPath+"oracle2oracle.gdb\\ZLOZA_TERENY", myPath+"oracle2oracle.gdb\\OTWORY", myPath+"oracle2oracle.gdb\\JASKINIE"]
    targets = [
        oracleGISPIG2Connector + "\\GIS_PIG2.ZLOZA_GRANICE",
        oracleGISPIG2Connector + "\\GIS_PIG2.ZLOZA_OBSZARY",
        oracleGISPIG2Connector + "\\GIS_PIG2.ZLOZA_TERENY",
        oracleGISPIG2Connector + "\\GIS_PIG2.OTWORY",
        oracleGISPIG2Connector + "\\GIS_PIG2.JASKINIE"
    ]

    i = 0
    for n in inputs:
        arcpy.AddMessage('  --> Usuwanie danych z ' + targets[i])
        arcpy.DeleteRows_management(targets[i])

        #arcpy.Select_analysis(inputs[i],temps[i],"")
        arcpy.AddMessage('  --> Wybrano obiektow: ' +
                         str(arcpy.GetCount_management(inputs[i])))

        arcpy.AddMessage('  --> Zasilanie danych do ' + targets[i])
        arcpy.Append_management(inputs[i], targets[i], "NO_TEST", "", "")
        i = i + 1
Exemple #9
0
def oracleXY2oracle(sourceLyr, tempName, targetLyr, X, Y):
    now = datetime.datetime.now()
    arcpy.AddMessage('--- Przetwarzanie zasilania Oracle [' +
                     now.strftime("%Y/%m/%d %H:%M:%S") + '] ---')

    inputs = [oracle_hydro_sdo + "\\" + sourceLyr]
    temps = [myPath + "tempGDB.gdb\\" + tempName]
    #targets = [baza4Connector + "\\" + targetLyr]
    targets = [oracle_hydro_sdo + "\\" + targetLyr]
    fieldX = [X]
    fieldY = [Y]
    events = ["tempLyr"]

    i = 0
    for n in inputs:

        arcpy.AddMessage('  --> Kopiowanie tabeli tempTable' + tempName)
        arcpy.TableToTable_conversion(n, myPath + "tempGDB.gdb",
                                      "tempTable" + tempName)

        arcpy.AddMessage('  --> Tworzenie warstwy przestrzennej ' + temps[i])
        arcpy.MakeXYEventLayer_management(
            myPath + "tempGDB.gdb\\tempTable" + tempName, fieldX[i], fieldY[i],
            events[i], spatialRef, "")
        arcpy.FeatureClassToFeatureClass_conversion(events[i],
                                                    myPath + "tempGDB.gdb\\",
                                                    tempName)

        arcpy.AddMessage('  --> Usuwanie danych z ' + targets[i])
        arcpy.DeleteRows_management(targets[i])

        arcpy.AddMessage('  --> Zasilanie danych do ' + targets[i])
        arcpy.Append_management(temps[i], targets[i], "NO_TEST", "", "")

        i = i + 1
Exemple #10
0
def loadGIS_SDO():
    now = datetime.datetime.now()
    arcpy.AddMessage('--- Przetwarzanie zasilania Oracle [' +
                     now.strftime("%Y/%m/%d %H:%M:%S") + '] ---')

    inputs = [
        oracleGISPIG2Connector + "\\GIS_PIG2.ZLOZA_TERENY",
        oracleGISPIG2Connector + "\\GIS_PIG2.ZLOZA_OBSZARY",
        oracleGISPIG2Connector + "\\GIS_PIG2.ZLOZA_GRANICE"
    ]
    targets = [
        oracle_gis_sdo + "\\GIS_SDO.ZLOZA_TERENY",
        oracle_gis_sdo + "\\GIS_SDO.ZLOZA_OBSZARY",
        oracle_gis_sdo + "\\GIS_SDO.ZLOZA_GRANICE"
    ]

    i = 0
    for n in inputs:
        #arcpy.AddMessage('  --> Kopiowanie danych z '+inputs[i])
        #arcpy.CopyFeatures_management(n,temps[i],"","","","")

        arcpy.AddMessage('  --> Usuwanie danych z ' + targets[i])
        arcpy.DeleteRows_management(targets[i])

        arcpy.AddMessage('  --> Zasilanie danych do ' + targets[i])
        arcpy.Append_management(n, targets[i], "NO_TEST", "", "")
        arcpy.AddMessage('  --> OK')
        i = i + 1
Exemple #11
0
def deleteRows(workspace, fClassName, expr):
    # delete rows in feature class
    arcpy.env.workspace = workspace  # keep setting the workspace to force load activities
    tableName = workspace + os.sep + fClassName
    if debug:
        addMessageLocal(tableName)
    retcode = False
    if arcpy.Exists(tableName):
        viewName = fClassName + "_View"
        if arcpy.Exists(viewName):
            arcpy.Delete_management(viewName)  # delete view if it exists

        arcpy.MakeTableView_management(tableName, viewName, expr)
        arcpy.DeleteRows_management(viewName)
        addMessageLocal("Existing " + fClassName + " rows deleted ")
        try:
            arcpy.Delete_management(viewName)  # delete view if it exists
        except:
            addMessageLocal("Could not delete view, continuing...")
        retcode = True
    else:
        addMessageLocal("Feature class " + fClassName +
                        " does not exist, skipping " + fClassName)
        retcode = False
    return retcode
Exemple #12
0
def filterRecords(surveyGDB, now, lastSync):
    '''Filter the records to those that need to be updated'''
    #Note - This excludes new entries that are *after* the timestamp
    #       Depending on how active the survey is, there may have been new submissions
    #           after the start of the script
    #       We put in a max time to ensure consistency in operation from run to run and
    #           table to table
    arcpy.AddMessage('\t-Filtering records to new set')
    arcpy.env.workspace = surveyGDB
    nowText = createTimestampText(now)
    tableList = getSurveyTables(surveyGDB)
    dateField = arcpy.AddFieldDelimiters(surveyGDB, "CreationDate")
    excludeStatement = "CreationDate > date '{1}'".format(dateField, nowText)
    if lastSync != None:
        lastSyncText = createTimestampText(lastSync)
        excludeStatement = excludeStatement + " OR CreationDate <= date '{0}'".format(lastSyncText)
    arcpy.AddMessage('\t\t-{0}'.format(excludeStatement))
    i = 0
    for table in tableList:
        i = i + 1
        thisName = 'filterView{0}'.format(str(i))
        dsc = arcpy.Describe(table)
        if dsc.datatype == u'FeatureClass' or dsc.datatype == u'FeatureLayer':
            arcpy.AddMessage('\t\t{0}'.format('featureclass'))
            arcpy.MakeFeatureLayer_management(table, thisName, excludeStatement)
            arcpy.DeleteFeatures_management(thisName)
        else:
            arcpy.MakeTableView_management(table, thisName, excludeStatement)
            arcpy.DeleteRows_management(thisName)
        arcpy.Delete_management(thisName)
Exemple #13
0
    def filter_source_dataset(self, input_wc):
        """
        If the config table specifies a where_clause to apply as a filter to the source dataset, copy the source
        locally and then delete these rows. This copied dataset becomes the new source
        :param input_wc:
        :return:
        """
        if input_wc:
            logging.info(
                'Starting vector_layer.filter_source_dataset for {0} with wc {1}'
                .format(self.name, input_wc))

            # If we are going to filter the source feature class, copy to a new location before deleting records
            # from it
            out_filename = os.path.splitext(os.path.basename(self.source))[0]
            output_fc = os.path.join(self.scratch_workspace,
                                     out_filename).replace('.', '_') + '.shp'
            arcpy.CopyFeatures_management(self.source, output_fc)

            # Delete records from this copied FC based on the input where clause
            arcpy.MakeFeatureLayer_management(output_fc, "input_fl", input_wc)
            arcpy.DeleteRows_management("input_fl")
            arcpy.Delete_management("input_fl")

            # Set the source to this new fc
            self.source = output_fc

        else:
            pass
Exemple #14
0
 def DME_master_hybrid_data_cleanup(self):
     feature_class_list = [self.config.DME_master_hybrid_sde_path]
     for feature_class in feature_class_list:
         try:
             arcpy.TruncateTable_management(feature_class)
         except:
             print("  unable to truncate, using Delete Rows")
             arcpy.DeleteRows_management(feature_class)
 def deleteSurveyLines(self, FCName, clipLayerName, linePrefix):
     arcpy.AddMessage(
         "Clearing out existing lines from layer: %s with prefix %s" %
         (clipLayerName, linePrefix))
     whereclause = "LINE_PREFIX LIKE '%" + linePrefix + "%'"
     arcpy.SelectLayerByAttribute_management(FCName, "NEW_SELECTION",
                                             whereclause)
     arcpy.DeleteRows_management(FCName)
def delete_append():
    print "deleting old data"
    arcpy.env.workspace = r"C:\Users\astrong\AppData\Roaming\ESRI\Desktop10.3\ArcCatalog\gfw (gfw@localhost).sde"
    fc = 'gfw.gfw.gran_chaco_deforestation'
    arcpy.DeleteRows_management(fc)
    print "appending new data"
    file = r"D:\GIS Data\GFW\temp\gran_chaco_deforestation\gran_chaco_deforestation.shp"
    arcpy.Append_management(file, fc, "TEST", "", "")
    print "new data appended to FC"
Exemple #17
0
def deleteExistingRows(datasets):
    for dataset in datasets:
        name = dataset.getAttributeNode("targetName").nodeValue
        table = os.path.join(gzSupport.workspace, name)
        if arcpy.Exists(table):
            arcpy.DeleteRows_management(table)
            gzSupport.addMessage("Rows deleted from: " + name)
        else:
            gzSupport.addMessage(table + " does not exist")
Exemple #18
0
def deleteExistingRows(datasets):
    # delete existing rows in a dataset
    for dataset in datasets:
        name = dataset.getAttributeNode("targetName").nodeValue
        table = os.path.join(workspace, name)
        if arcpy.Exists(table):
            arcpy.DeleteRows_management(table)
            addMessageLocal("Rows deleted from: " + name)
        else:
            addMessageLocal(table + " does not exist")
Exemple #19
0
def networkPreProcessing(objects):
    arcpy.Delete_management("C:/Users/Simon/Documents/GitHub/Enrichment/networkPr_update.shp")
    networkFL = arcpy.CopyFeatures_management(objects, "C:/Users/Simon/Documents/GitHub/Enrichment/networkUpdate")
    arcpy.MakeFeatureLayer_management(networkFL, "networkPr_update")
    expression = """("navigatie" = 'onderdeel van rotonde' OR "navigatie" = 'onderdeel van kruispunt' OR "wegtype" = 'bromfietspad (langs weg)' OR "wegtype" = 'fietspad (langs weg)' OR "wegtype" = 'fietsstraat' OR "wegtype" = 'solitair bromfietspad' OR "wegtype" = 'solitair fietspad' OR "wegtype" = 'voetgangersdoorsteekje' OR "wegtype" = 'voetgangersgebied' OR "wegtype" = 'weg met fiets(suggestie)strook' ) AND "verlichtin" = ' ' OR "verlichtin" = 'beperkt verlicht (bijvoorbeeld alleen bij kruispunten)' OR "verlichtin" = 'goed verlicht' OR "verlichtin" = 'niet verlicht' OR "verlichtin" = 'ONBEKEND'"""
    arcpy.SelectLayerByAttribute_management("networkPr_update", "NEW_SELECTION", expression)
    if int(arcpy.GetCount_management("networkPr_update").getOutput(0)) < 0:
        arcpy.DeleteRows_management("networkPr_update")
    updatedNetwork = arcpy.FeatureClassToShapefile_conversion("networkPr_update", "C:/Users/Simon/Documents/GitHub/Enrichment/")
    return updatedNetwork
Exemple #20
0
def doTruncate(target):
    # perform the append from a source table to a target table
    success = False
    if arcpy.Exists(target):
        gzSupport.addMessage("Deleting rows in " + target)
        arcpy.DeleteRows_management(target)
        success = True
        if debug:
            gzSupport.addMessage("Deleted")
    else:
        gzSupport.addMessage("Target: " + target + " does not exist")
    return success
Exemple #21
0
def ProcessReplica(conn):
    #Get the Extracted Geodatabase Name
    for file in os.listdir(wksp + "\\Temp\\"):
        if file.endswith(".gdb"):
            extracted_gdb = wksp + "\\Temp\\" + file

    arcpy.env.workspace = extracted_gdb
    surveytable = arcpy.ListTables()
    surveyfc = arcpy.ListFeatureClasses()

    #Trim All Field & Tables Here
    for fc in surveyfc:
        TrimFields(fc)

    for table in surveytable:
        TrimFields(table)

    arcpy.env.workspace = conn
    sde_tables = arcpy.ListTables()
    sde_fcs = arcpy.ListFeatureClasses()

    for fc in surveyfc:
        if not arcpy.Exists(conn + "\\" + fc):
            print "Feature class does not exists"
            arcpy.env.workspace = extracted_gdb
            arcpy.DeleteRows_management(extracted_gdb + "\\" + fc)
            for table in surveytable:
                if not arcpy.Exists(conn + "\\" + table):
                    arcpy.DeleteRows_management(fc)
                else:
                    print "Table already exists in database"
                    arcpy.AddMessage("Table already exists in database")
                    #handle table here

            arcpy.Copy_management(fc, conn + "\\" + fc)
        else:
            print "Survey already exists in database"
            arcpy.AddMessage("Survey already exists in database")
    return
    def InsertarRegistros(self):
        arcpy.env.workspace = "Database Connections/PruebaSegmentacion.sde"
        arcpy.env.outputCoordinateSystem = arcpy.SpatialReference(4326)
        if arcpy.Exists("GEODATABASE.sde") == False:
            arcpy.CreateDatabaseConnection_management(
                "Database Connections", "GEODATABASE.sde", "SQL_SERVER",
                self.server, "DATABASE_AUTH", "sde", "$deDEs4Rr0lLo", "#",
                "GEODB_CPV_SEGM", "#", "#", "#", "#")
        arcpy.env.workspace = "Database Connections/GEODATABASE.sde"
        path_conexion2 = "Database Connections/GEODATABASE.sde"
        segm_ruta_prueba = path_conexion2 + "/GEODB_CPV_SEGM.SDE.SEGM_RUTA_PRUEBA"
        segm_aeu_prueba = path_conexion2 + "/GEODB_CPV_SEGM.SDE.SEGM_AEU_PRUEBA"

        list_capas = [[self.tb_rutas, segm_ruta_prueba],
                      [self.tb_aeus, segm_aeu_prueba]]
        i = 0

        data = []
        for x in arcpy.da.SearchCursor(self.tb_zonas,
                                       ["UBIGEO", "ZONA", "ID_ESTRATO"]):
            if int(x[2]) == 1:
                data.append([
                    x[0], x[1], self.cant_viv_techo_gra_ciud,
                    self.techo_segunda_pasada_gra_ciud, self.uso_falso_cod
                ])

            else:
                data.append([
                    x[0], x[1], self.cant_viv_techo_peq_ciud,
                    self.techo_segunda_pasada_peq_ciud, self.uso_falso_cod
                ])

        where_final = expresiones_consulta_arcpy.Expresion_2(
            data, [['UBIGEO', 'TEXT'], ['ZONA', 'TEXT'], ['TECHO', 'SHORT'],
                   ['TECHO_S_P', 'SHORT'], ['FALSO_COD', 'SHORT']])

        print where_final
        for el in list_capas:
            i = i + 1
            #a = arcpy.MakeTableView_management(el[1], "a{}".format(i),  "({}) and TECHO={}".format(self.where_expression,self.cant_viv_techo_gra_ciud))
            a = arcpy.MakeTableView_management(el[1], "a{}".format(i),
                                               where_final)

            #print int(arcpy.GetCount_management(a).getOutput(0))
            if (int(arcpy.GetCount_management(a).getOutput(0)) > 0):
                arcpy.DeleteRows_management(a)

            #b = arcpy.MakeTableView_management(el[0], "b{}".format(i),  "({}) and TECHO={}".format(self.where_expression,self.cant_viv_techo_gra_ciud) )
            b = arcpy.MakeTableView_management(el[0], "b{}".format(i),
                                               where_final)
            arcpy.Append_management(b, el[1], "NO_TEST")
Exemple #23
0
 def DeleteEmptyGrids(self, gridName):
     arcpy.MakeFeatureLayer_management(gridName, "grid_layer")
     expression = ""
     for field in arcpy.ListFields(gridName):
         if "_num" in field.name:
             expression += field.name + " < 1 AND "
     expression = expression[:-5]
     print expression
     arcpy.SelectLayerByAttribute_management("grid_layer", "NEW_SELECTION",
                                             expression)
     print("Deleting {0} rows in {1}".format(
         arcpy.GetCount_management("grid_layer").getOutput(0), gridName))
     if int(arcpy.GetCount_management("grid_layer").getOutput(0)) > 0:
         arcpy.DeleteRows_management("grid_layer")
def truncateTable(table_path):

    rowCount = int(arcpy.GetCount_management(table_path).getOutput(0))
    arcpy.AddMessage("Existing Rows..." + str(rowCount))
    print("Existing Rows..." + str(rowCount))

    if rowCount > 0:
        arcpy.AddMessage("Truncate Populated Table... ")
        print "Truncate Populated Table..."
        arcpy.DeleteRows_management(table_path)
    else:
        arcpy.AddMessage("Count Is Good, Proceed...")
        print "Count Is Good, Proceed..."
        pass
Exemple #25
0
def doInlineAppend(source, target):
    # perform the append from a source table to a target table
    success = False
    if arcpy.Exists(target):
        gzSupport.addMessage("Deleting rows from  " + target)
        arcpy.DeleteRows_management(target)
        gzSupport.addMessage("Appending " + source + " TO " + target)
        arcpy.Append_management(source, target, "NO_TEST")
        success = True
        if debug:
            gzSupport.addMessage("completed")
    else:
        gzSupport.addMessage("Target: " + target + " does not exist")
        success = False
    return success
    def onClick(self):
        layer, data_frame = utils.get_layer_by_name(settings.LAYER_NAME)
        if layer:
            arcpy.DeleteRows_management(settings.LAYER_NAME)

            intersected_layer, data_frame = utils.get_layer_by_name(
                settings.INTERSECTED_LAYER_NAME)
            if intersected_layer:
                arcpy.mapping.RemoveLayer(data_frame, intersected_layer)

            message = 'LA CAPA "%s" HA SIDO LIMPIADA' % settings.LAYER_NAME
            utils.hide_or_show_layers(
                [settings.LAYER_NAME, settings.BASE_LAYER], visible=True)

            return pythonaddins.MessageBox(message, 'RESULTADO', 0)
Exemple #27
0
    def delete_and_append(self):

        logging.info('Starting delete and append for {0}'.format(self.name))
        arcpy.DeleteRows_management(self.esri_service_output)
        arcpy.Append_management(self.source, self.esri_service_output)

        logging.info('restarting service for {0}'.format(self.name))
        service_dict = {'gran_chaco_deforestation': 'forest_change'}
        service_name = service_dict[self.name]

        service = service_name

        for i in range(0, 2):
            arcgis_server.set_service_status(service, 'stop')
            arcgis_server.set_service_status(service, 'start')
Exemple #28
0
def deleteLogRows(mode, tableName):
    table = os.path.join(workspace, tableName)
    if mode.upper() == "ARCHIVE":
        try:
            arcpy.CalculateField_management(table, "ACTIVEFLAG", "N")
            msg = "Existing rows flagged as inactive: "
        except:
            msg = "Error: Unable to flag rows as inactive: "

    else:
        try:
            arcpy.DeleteRows_management(table)
            msg = "Existing rows deleted: "
        except:
            msg = "Error: Unable to delete existing rows: "
    addMessage(msg + tableName)
Exemple #29
0
def execute_analyst(hybasid):
    response_tmp = dict()
    response_tmp[_HYBASID] = hybasid
    try:
        print('NA: {}'.format(hybasid))
        query = "{} = '{}'".format(_HYBASID, hybasid)
        name = 'analystnetworkmfl'
        flayer = arcpy.MakeFeatureLayer_management(_INCIDENTS, name, query)
        update_incidents(flayer)
        na.Solve(network)

        buff = arcpy.Buffer_analysis('Closest Facility\Routes',
                                     'in_memory\\a{}'.format(name),
                                     _BUUFER_DISTANCE)
        clip = arcpy.Clip_analysis(_TRACK_SHP, buff,
                                   'in_memory\\b{}'.format(name))

        with arcpy.da.UpdateCursor(clip, [_HYBASID]) as cursor:
            for row in cursor:
                row[0] = hybasid
                cursor.updateRow(row)
            del cursor

        with arcpy.da.UpdateCursor(_TARGET_SHP, [_HYBASID], query) as cursor:
            for row in cursor:
                cursor.deleteRow()
            del cursor

        case = ';'.join([_SUPVIA, _HIERARCHY, _HYBASID])
        diss = arcpy.Dissolve_management(clip, 'in_memory\d{}'.format(name),
                                         case, '#', 'MULTI_PART',
                                         'DISSOLVE_LINES')

        arcpy.Append_management(diss, _TARGET_SHP, 'NO_TEST')

        arcpy.DeleteRows_management('Closest Facility\Routes')

        response_tmp['state'] = 1
        response_tmp['msg'] = 'success'
    except Exception as e:
        print(e.message.__str__())
        response_tmp['state'] = 0
        msg = traceback.format_exc().__str__()
        msg = msg.replace(',', ' ')
        msg = msg.replace('\n', ' ')
        response_tmp['msg'] = msg
    return response_tmp
def compilarTablaSCR(gdb):
    listaTablas = arcpy.ListTables()
    list = []
    pattern = r"SCR_"
    for i in listaTablas:
        if re.match(pattern, i):
            list.append(i)
        else:
            pass
    for i in list:
        campos = arcpy.ListFields(i)
        if "IDSCR" in [x.name for x in campos]:
            pass
        else:
            arcpy.AddField_management(i, "IDSCR", "TEXT", '#', '#', "20", '#',
                                      'NULLABLE', 'NON_REQUIRED', '#')
        with arcpy.da.UpdateCursor(i, ["IDSCR"]) as cursor:
            for x in cursor:
                x[0] = str(i)[4:]
                cursor.updateRow(x)
        if "FEC_CARGA" not in [x.name for x in campos]:
            arcpy.AddField_management(i, "FEC_CARGA", "TEXT", '#', '#', "30",
                                      '#', 'NULLABLE', 'NON_REQUIRED', '#')
        with arcpy.da.UpdateCursor(i, ["FEC_CARGA"]) as cursor:
            for x in cursor:
                x[0] = startTime
                cursor.updateRow(x)

        if "FLAG_NUEVO" not in [x.name for x in campos]:
            arcpy.AddField_management(i, "FLAG_NUEVO", "SHORT", '1', '#', "#",
                                      '#', 'NULLABLE', 'NON_REQUIRED', '#')
        with arcpy.da.UpdateCursor(i, ["FLAG_NUEVO"]) as cursor:
            for x in cursor:
                x[0] = 1
                cursor.updateRow(x)

    TabSCR = arcpy.Copy_management(os.path.join(str(gdb), list[0]),
                                   "TabSCR_{}".format(nomubigeo))
    arcpy.DeleteRows_management(TabSCR)
    arcpy.Append_management(list, TabSCR, "NO_TEST")
    arcpy.AddField_management(TabSCR, "UBIGEO", "TEXT", '#', '#', "6", '#',
                              'NULLABLE', 'NON_REQUIRED', '#')
    arcpy.CalculateField_management(TabSCR, "UBIGEO", "'{}'".format(nomubigeo),
                                    "PYTHON_9.3")
    return TabSCR