{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**Demo 5b - Select Layer by Attribute and Select Layer by Location"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Add the comments, title, import line, variables.\n",
    "Change the workspace folder path to your data location"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Demo 5b  Select Layer by Attribute and Select Layer by Location\n",
    "# Created by:  Nathan Jennings\n",
    "#              www.urbandalespatial.com\n",
    "# Created on:  01.16.2011\n",
    "# Updated on:  12.13.2014\n",
    "# Copyright:   2011\n",
    "\n",
    "'''\n",
    "Example of using the Make Feature Layer tool that is used to implement the\n",
    "Select Layer by Attribute and Select Layer by Location ArcGIS tools.  The\n",
    "Copy Features and Copy Row tools are used to store the selected records.\n",
    "Copy Features will store the selected geographic features and attributes from\n",
    "the parcel file, whereas, the Copy Rows will be used to store the selected\n",
    "attributes from the streets file.\n",
    "\n",
    "'''\n",
    "print ('Demo 5b - Select Layer by Attribte and Location\\n')\n",
    "\n",
    "import arcpy, sys, traceback\n",
    "\n",
    "#arcpy.env.workspace = \"C:\\\\PythonPrimer\\\\Chapter05\\\\Data\\\\\"\n",
    "arcpy.env.workspace = \"C:\\\\temp\\\\Chapter05\\\\Data\\\\\"\n",
    "\n",
    "streets = \"Sacramento_Streets.shp\"\n",
    "street_layer = \"street_layer\"\n",
    "\n",
    "parcels = \"City_Parcels.shp\"\n",
    "parcel_layer = \"parcel_layer\"\n",
    "search_distance = '200 FEET'\n",
    "\n",
    "out_parcel_fc = \"out_parcels.shp\"\n",
    "out_street_attributes = \"out_street_attributes.dbf\""
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Write the try: block\n",
    "Note the arcpy.GetCount_management routine to determine how many features are in a feature class, feature layer, table, or table view.\n",
    "Use MakeFeatureLayer to create an in-memory representation of the feature class (that is on disk)\n",
    "NOTE: the \"try:\" line is commented out so the script will run within Jupyter. The actual demo5b.py script has the try: line added."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "#try:\n",
    "\n",
    "    # 1. Make a feature layer for streets\n",
    "\n",
    "    if arcpy.Exists(street_layer):\n",
    "        arcpy.Delete_management(street_layer)\n",
    "    \n",
    "    arcpy.MakeFeatureLayer_management(streets, street_layer)\n",
    "\n",
    "    # 2. Create a query statement to select highways\n",
    "\n",
    "    # Create query statement\n",
    "    query = \"\"\"\"CLASS\" = 'H'\"\"\"\n",
    "\n",
    "    # 3. Select by attributes using the query\n",
    "\n",
    "    # Select features by attribute using query\n",
    "    arcpy.SelectLayerByAttribute_management(street_layer, \"NEW_SELECTION\", query)\n",
    "\n",
    "    # 4. Select parcels that are 200 ft from highways\n",
    "\n",
    "    # 4a. Make feature layer\n",
    "\n",
    "    if arcpy.Exists(parcel_layer):\n",
    "        arcpy.Delete_management(parcel_layer)\n",
    "        \n",
    "    arcpy.MakeFeatureLayer_management(parcels, parcel_layer)\n",
    "\n",
    "    \n",
    "    # 4b. Select Parcels\n",
    "    arcpy.SelectLayerByLocation_management(parcel_layer, \"INTERSECT\", \\\n",
    "                                           street_layer, search_distance, \"NEW_SELECTION\") \n",
    "\n",
    "\n",
    "    # 4c. Get the number of selected records and create a print statement for each\n",
    "    \n",
    "    # print the number of selected records in the respective layers with a query\n",
    "    result = arcpy.GetCount_management(street_layer) \n",
    "    print (\"Number of selected streets in the street layer \" + street_layer + \" with a query: \"+ str(result))\n",
    "\n",
    "    result = arcpy.GetCount_management(parcel_layer) \n",
    "    print (\"Number of selected parcels in the parcel layer \" + parcel_layer + \\\n",
    "          \"\\n within a distance of \" + search_distance + \": \"+ str(result))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Copy selected features to an output feature class think of this as a \"save selected features.\"\n",
    "Copy selected attributes to an output table."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 5. Write out selected parcel features to file (SHP)\n",
    "\n",
    "    # Copy the selected polygon features to a new shapefile\n",
    "\n",
    "    if arcpy.Exists(out_parcel_fc):\n",
    "        arcpy.Delete_management(out_parcel_fc)\n",
    "        \n",
    "    arcpy.CopyFeatures_management(parcel_layer, out_parcel_fc)\n",
    "    print (\"Copied selected features from \" + parcels  + \" to \" + out_parcel_fc)\n",
    "\n",
    "    # 6. Write out selected street attributes to a table file (DBF)\n",
    "\n",
    "\n",
    "    # Copy the selected street segment attributes to a dBase table\n",
    "\n",
    "    if arcpy.Exists(out_street_attributes):\n",
    "        arcpy.Delete_management(out_street_attributes)\n",
    "        \n",
    "    arcpy.CopyRows_management(street_layer, out_street_attributes)\n",
    "    print (\"Copied selected attributes from \" + streets + \" to \" + out_street_attributes)\n",
    "\n",
    "    print (\"Completed Script\")\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Add the exception block\n",
    "within the Jupyter notebook, this block will not run.  It is presented to show proper form."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "except:\n",
    "    # http://help.arcgis.com/en/arcgisdesktop/10.0/help/index.html#//002z0000000q000000\n",
    "    \n",
    "    tb = sys.exc_info()[2]\n",
    "    tbinfo = traceback.format_tb(tb)[0]\n",
    "    pymsg = \"PYTHON ERRORS:\\nTraceback Info:\\n\" + tbinfo + \"\\nError Info:\\n     \" +        str(sys.exc_type) + \": \" + str(sys.exc_value) + \"\\n\"\n",
    "    msgs = \"ARCPY ERRORS:\\n\" + arcpy.GetMessages(2) + \"\\n\"\n",
    "\n",
    "    arcpy.AddError(msgs)\n",
    "    arcpy.AddError(pymsg)\n",
    "\n",
    "    print (msgs)\n",
    "    print (pymsg)\n",
    "    \n",
    "    arcpy.AddMessage(arcpy.GetMessages(1))\n",
    "    print (arcpy.GetMessages(1))"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.8"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
