Who doesn't love C++/C, I sure do....
Here is a great guide to developing all your c/c++ extension here (https://docs.python.org/3.4/extending/).
Happy Coding!
Showing posts with label Programming. Show all posts
Showing posts with label Programming. Show all posts
Friday, November 6, 2015
Great Blog to Follow (Dan Patterson's GeoNet Blog)
If you have used any ArcGIS software over the years, and asked a question on the Esri or GeoStackExchange Forums you have probably encountered Dan Patterson. He has a great blog, which is full of knowledge any programmer, cartographer or GIS analyst should know.
I don't know the man, but I love reading his posts. I am sure you will too.
The web address is: https://geonet.esri.com/blogs/dan_patterson
Enjoy.
Labels:
ArcGIS,
Programming,
Python
Wednesday, April 24, 2013
Using pyODBC to Connect To Access with ArcPy
pyODBC allows users to access any data source with the proper ODBC driver installed on the system. This is very convenient, and helpful because at 10.1 using ArcPy only you cannot create ODBC connection.
Here we connected to the MS Access database using the drivers installed on my local system. Next I performed a simple query to return all records from the table. With the new da.NumPyArrayToTable() at 10.1, I want to convert the pyodbc rows to a table that can be used in ArcMap. I convert the list of tuples (rows object) to a numpy.array object. After the conversion, I fire off the arcpy function and now I have a table on disk.
For a complete listing of 10.1 numpy functions, check out: http://resources.arcgis.com/en/help/main/10.1/index.html#/What_is_the_data_access_module/018w00000008000000/
There you can learn about extending tables, convert feature classes to numpy arrays, and rasters as well.
Enjoy
You can download pyODBC here. Grab the correct python version and install it.
Once installed, let's try to access a 2010-2012 MS Access Database.
I create a dummy database called 'db_text.accdb' and create a table called 'Addresses' with 5 text fields:
- name
- street
- town
- country
- zipcode
After that I populated two rows with dummy data. Once you have some dummy data, let's move forward.
import pyodbc
import arcpy
import numpy
arcpy.env.overwriteOutput = True
accb = r"C:\temp\db_test.accdb"
access_con_string = r"Driver={Microsoft Access Driver (*.mdb, *.accdb)};Dbq=%s" % accb
cnxn = pyodbc.connect(access_con_string)
cursor = cnxn.cursor()
cursor.execute("select * from Addresses")
rows = cursor.fetchall()
dts = {'names': ('ID','name','street', 'town', 'country', 'zipcode'),
'formats':(numpy.uint8, 'S255','S255','S255','S10','S10')}
array = numpy.rec.fromrecords(rows, dtype=dts)
arcpy.da.NumPyArrayToTable(array, r"c:\temp\scratch.gdb\outTable")
Here we connected to the MS Access database using the drivers installed on my local system. Next I performed a simple query to return all records from the table. With the new da.NumPyArrayToTable() at 10.1, I want to convert the pyodbc rows to a table that can be used in ArcMap. I convert the list of tuples (rows object) to a numpy.array object. After the conversion, I fire off the arcpy function and now I have a table on disk.
For a complete listing of 10.1 numpy functions, check out: http://resources.arcgis.com/en/help/main/10.1/index.html#/What_is_the_data_access_module/018w00000008000000/
There you can learn about extending tables, convert feature classes to numpy arrays, and rasters as well.
Enjoy
Labels:
ArcGIS 10.1,
Programming,
Python
Monday, April 8, 2013
Great Learning Python Resource
Hey Everyone,
The Internet is filled with great resources for learning programming, almost too much, but here is a great resource: http://learnpythonthehardway.org/book/
This site hosts a e-book called 'Learn Python The Hard Way' and I highly recommend if you are starting out programming, or want to just a refresher course on python that you take a look.
There are also courses on C, CLI, SQL, Ruby, and Regex.
You might learn something new, so give it a try.
As always, I encourage my reader to please support my idea on the ArcGIS Ideas Site to allow GUI integration with ArcPy. Please vote it up here: http://ideas.arcgis.com/ideaView?id=087E00000004SmHIAU
Enjoy
The Internet is filled with great resources for learning programming, almost too much, but here is a great resource: http://learnpythonthehardway.org/book/
This site hosts a e-book called 'Learn Python The Hard Way' and I highly recommend if you are starting out programming, or want to just a refresher course on python that you take a look.
There are also courses on C, CLI, SQL, Ruby, and Regex.
You might learn something new, so give it a try.
As always, I encourage my reader to please support my idea on the ArcGIS Ideas Site to allow GUI integration with ArcPy. Please vote it up here: http://ideas.arcgis.com/ideaView?id=087E00000004SmHIAU
Enjoy
Labels:
Programming,
Python,
Scripting
Thursday, March 28, 2013
Support GUI Design in ArcGIS for Desktop
Please support this idea of having GUI designer in python built in with python add-ins.
It can be found here: http://ideas.arcgis.com/ideaView?id=087E00000004SmHIAU
Thanks everyone.
Labels:
ArcGIS 10,
ArcGIS 10.1,
ArcPy,
GP Task,
Programming,
Python,
Python Add-ins
Friday, March 22, 2013
ArcGIS for Developers
Today I noticed a new site from Esri, and it's called 'ArcGIS for Developers'. This website consolidates the web, mobile, and introduces some new desktop APIs.
The one that really excites me is the Qt API because I'm a fan of C++. I also introduces the new approach to open for Esri by using GitHub for code sharing. I've only started playing, but I'm excited to see what comes.
Check it out here: http://developers.arcgis.com/en/
Happy coding.
The one that really excites me is the Qt API because I'm a fan of C++. I also introduces the new approach to open for Esri by using GitHub for code sharing. I've only started playing, but I'm excited to see what comes.
Check it out here: http://developers.arcgis.com/en/
Happy coding.
Labels:
C++,
Programming
Wednesday, March 13, 2013
The random Module (python)
The random module is pseudo-random number generator. This means that's truly not random, but close enough.
You should seed, initialize the generator with either a value, or with the system time (default value).
Example:
Random also has the ability to pick from ranges and collection of elements, like letter:
Happy Randomness.
You should seed, initialize the generator with either a value, or with the system time (default value).
Example:
>>> import random >>> random.seed() >>> print random.random() 0.884447776659 >>> print random.random() 0.379767969805 >>> print random.random() 0.580327390006
Random also has the ability to pick from ranges and collection of elements, like letter:
>>> random.randrange(start=0, stop=101, step=1) 52
>>> random.choice('abcdefghij')
'b'
Happy Randomness.
Labels:
Programming,
Python
Friday, February 22, 2013
Creating a List with n number of entries (Python)
Normally when you create a list object in python, you cannot specify the number of items in the object by default unlike say an array object in C# or C++. I recently ran into a situation where I was using the arcpy.da cursor objects for table that could have n number of fields. I wanted the row to be initialized with a default value, so I used the * operator on the list to multiply a single value into a multi-value list.
Example:
This will create a list object called row, where each value by default is an empty string ("").
Enjoy
Example:
# Get a list of fields that are not BLOB, OBJECTID, RASTER, GEOMETRY or GUID
fields = [field.name for field in arcpy.ListFields(service_table) \
if not(field.type.upper() in ['BLOB', 'OID', 'RASTER','GEOMETRY','GUID'])
# create a row list with default values
row = [""]* len(fields)
This will create a list object called row, where each value by default is an empty string ("").
Enjoy
Labels:
ArcGIS 10,
ArcGIS 10.1,
ArcPy,
Programming,
Python
Thursday, February 21, 2013
Query Feature Service By Object IDs (Python)
To query a feature service using object ids, you need to perform a POST. For those who don't know the difference between a "GET" and "POST" here is a quick blurb based on the HTML specifications:
Even simpler, "GET" is basically for just getting data where a "POST" may involve anything, like updating data, sending, or creating data.
Using python, you can perform both "GET" and "POST" methods, but since we need a "POST" to query by IDs, here is a simple example. Please note that most feature services limit 1000 features being returned, so if you want to grab all of the features from a feature service, you'll have to perform multiple queries to get all the features back in JSON format.
Example:
So we have a simple "POST" example. This sample should work with both ArcGIS Server 10.1 and ArcGIS Online feature services.
Please support my idea of having a python GUI by voting it up here.
Enjoy
"POST" means that former means that form data is to be encoded (by a browser) into a URL while the "GET" means that the form data is to appear within a message body.
Even simpler, "GET" is basically for just getting data where a "POST" may involve anything, like updating data, sending, or creating data.
Using python, you can perform both "GET" and "POST" methods, but since we need a "POST" to query by IDs, here is a simple example. Please note that most feature services limit 1000 features being returned, so if you want to grab all of the features from a feature service, you'll have to perform multiple queries to get all the features back in JSON format.
Example:
import urllib2
import urllib
import urlparse
import httplib
def query_by_objectid(url, objectIDStart=0, objectIDEnd=1001):
""" performs a POST operation where the query is called using
the object id method. If a feature service has more than
1000 records, use this method to get a range of features
from the feature service.
Inputs:
:url: - string of feature service URL
:objectIDStart: - integer of the start whole number
:objectIDEnd: - end range whole number
Returns:
returns string JSON of query
"""
url = url + '/query'
start = int(objectIDStart)
end = int(objectIDEnd)
objectIDs = ",".join([str(x) for x in range(start, end)])
headers = {"Content-type": "application/x-www-form-urlencoded",
"Accept": "text/plain"}
parameters = {'objectIds' : objectIDs,
'f' : 'json'}
urlparams = urllib.urlencode(parameters)
parts = urlparse.urlparse(url)
h = httplib.HTTPConnection(parts.netloc)
headers = {"Content-type": "application/x-www-form-urlencoded", "Accept": "text/plain"}
h.request('POST', parts.path, urlparams, headers)
r = h.getresponse()
return r.read()
if __name__ == "__main__":
url = 'http://sampleserver1.arcgisonline.com/ArcGIS/rest/services/TaxParcel/AssessorsLiveLayers/MapServer/1'
print query_by_objectid(url=url,
objectIDStart=0,
objectIDEnd=5)
So we have a simple "POST" example. This sample should work with both ArcGIS Server 10.1 and ArcGIS Online feature services.
Please support my idea of having a python GUI by voting it up here.
Enjoy
Thursday, February 14, 2013
Creating an Map Document From Python (10.1)
Previous posts, I have discussed ways to create map service layers from scratch, and now I'm going to show you how to create a blank map document using the 'ConvertWebMapToMapDocument' tool in ArcToolbox. The beauty of this tool is that it doesn't have to be run on server, but can be run from desktop. It uses JSON based on the ExportWebMap specification.
A JSON map consists of the following:
Now you can do whatever you need to do with your map document.
A JSON map consists of the following:
{
"mapOptions": {},
"operationalLayers": [],
"baseMap": [],
"exportOptions": {},
"layoutOptions": {}
}
import json
from arcpy import mapping
mapService = {}
jsonDump = json.dumps(mapService)
result = mapping.ConvertWebMapToMapDocument(jsonDump)
mxd = result.mapDocument
mxd.saveACopy(r"c:\temp\blank.mxd")
Now you can do whatever you need to do with your map document.
Labels:
ArcGIS 10.1,
ArcPy,
Programming,
Python
Wednesday, February 13, 2013
wx GUI Article for ArcGIS
Here is an interesting article on how to create an interactive GUI for ArcGIS 10.1.
Basically what it does is it creates the form before ArcMap/Catalog finishes loading therefore the core software doesn't prevent the mainloop() to fail. At least that's my take on it.
If you think custom GUIs should be part of the next major release, I suggest you go to the Esri Idea site and vote up this idea. It will need YOUR support to get into the next release.
Happy GUI designing!
Labels:
ArcPy,
Programming,
Python,
Scripting
Monday, February 4, 2013
Convert Table or Feature class to CSV (10.1)
Sometimes you need to export data from a feature class or table to a CSV file. CSV stands for comma separated values. Wikipedia defines a CSV file as such:
Next you need to write the field names and rows to a file. This is extremely easy with the CSV library in python. Documentation about this standard library can be found here.
Here we have a function called get_rows() which takes two parameters. The first is the data_set, which can be a table or feature class. The next is the fields. At 10.1, you must define your fields unlike the 10.0 cursor objects. The function uses the yield, which is a generator. Basically the code only runs if the function is called in a loop (I know that's not 100% correct), but here is a better explanation. Using the CSV module in python, we can then easily write out each row within the rows generator object.
FYI, this is written so you can put this code into a script and toolbox for ArcGIS 10.1. Just add the imports.
Enjoy
A comma-separated values (CSV) file stores tabular data (numbers and text) in plain-text form. Plain text means that the file is a sequence of characters, with no data that has to be interpreted instead, as binary numbers. A CSV file consists of any number of records, separated by line breaks of some kind; each record consists of fields, separated by some other character or string, most commonly a literal comma or tab. Usually, all records have an identical sequence of fields.
To create a CSV file at 10.1, you need to strip out certain field types: Geometry, Blob and Raster because the file format only supports plain text. This can be done by doing the following:
fieldnames = [f.name for f in desc.fields if f.type not in ["Geometry", "Raster", "Blob"]]Next you need to write the field names and rows to a file. This is extremely easy with the CSV library in python. Documentation about this standard library can be found here.
def get_rows(data_set, fields):
with da.SearchCursor(data_set, fields) as cursor:
for row in cursor:
yield row
if __name__ == "__main__":
data_set = arcpy.GetParameterAsText(0) # feature class/Table
output = arcpy.GetParameterAsText(1) # csv file
desc = arcpy.Describe(data_set)
fieldnames = [f.name for f in desc.fields if f.type not in ["Geometry", "Raster", "Blob"]]
rows = get_rows(data_set, fieldnames)
with open(output,'wb') as out_file:
out_writer = csv.writer(out_file)
out_writer.writerow(fieldnames)
for row in rows:
out_writer.writerow(row)
Here we have a function called get_rows() which takes two parameters. The first is the data_set, which can be a table or feature class. The next is the fields. At 10.1, you must define your fields unlike the 10.0 cursor objects. The function uses the yield, which is a generator. Basically the code only runs if the function is called in a loop (I know that's not 100% correct), but here is a better explanation. Using the CSV module in python, we can then easily write out each row within the rows generator object.
FYI, this is written so you can put this code into a script and toolbox for ArcGIS 10.1. Just add the imports.
Enjoy
Labels:
ArcGIS 10.1,
ArcPy,
GP Task,
Programming,
Python
Friday, January 18, 2013
10.1 SP 1 32 bit vs 64 bit
I ran across an interesting forum posting about the differences of 32 vs 64 bit python.
Check it out here: http://forums.arcgis.com/threads/70241-10.1-sp-1-and-32-64-bit-Python-versions
It's worth a good read to understand if you install the 64-bit background processor provided at SP 1 how it operates and works on your machine.
Remember if you do install the 64-bit version of python, you will have to install the 64-bit of all your extensions as well.
Enjoy
Labels:
ArcGIS 10.1,
ArcPy,
Programming,
Python Add-ins
Thursday, January 3, 2013
ArcPy 10.1 - Multiple Data Frames and Data Driven Pages
Data driven pages is a great way to automate map production over a given area, and it works right out of the box with a single data frame. If you have 2 or more data frames though, you will need to control the movement of each data frame object by performing some sort of coding (ArcObjects or ArcPy).
A simple way to move multiple data frames is to:
A simple way to move multiple data frames is to:
- Get a list of all data frames
- Identify the parent data frame
- Move the extents of the other data frame
Sounds simple? Well it is.
To get started, get a reference to the map document
mxd = arcpy.mapping.MapDocument("CURRENT")
Change "CURRENT" to a path if not run in ArcMap. Then list all the data frames
dfs = arcpy.mapping.ListDataFrames(mxd)
Now how do you know what data frame is the parent data frame or what data frame is a child data frame? Luckily at 10.1, the data driven page object provides a property called dataFrame, which returns the DataFrame object. At 10.0, you would either use names or indexing values to determine which is the parent or not, but this example is for 10.1.
ddp = mxd.dataDrivePages
parentDF = ddp.dataFrame
Next step is to pan the other data frames to the extent of the parent data frame's extent.
for pageNum in range(1, ddp.pageCount + 1):
for df in dfs:
ddp.currentPageID = pageNum
row = ddp.pageRow
extent = row.Shape.extent
if (df.name == parentDF.name) and (df.scale == parentDF.scale):
print 'I found the parent frame'
else:
df.panToExtent(extent)
arcpy.mapping.ExportToPNG(mxd, r"C:\Project\OutPut\ParcelAtlas_" + str(pageNum) + ".png")
Here we have a bunch of code that loops through each data driven page area and then modifies each underlying data frame that isn't the parent. After the data frames are changes, the code then exports the maps to PNG to the '...\output' folder with reference to the page number.
Enjoy
Labels:
ArcGIS 10.1,
ArcPy,
Programming,
Python,
Scripting
Tuesday, December 18, 2012
Using env.addOutputsToMap
The environmental variable addOutputsToMap prevents geoprocessing task results from being displayed in the TOC. This environmental property by default is set to true, so every tool's result will display in the table of contents in ArcMap.
When developing python add-ins, you should utilize this tool to prevent sub-processes results from being added to the map. A good example of this, is if your python add-in creates a table if it doesn't exist for logging purposes. Your end user does not want to see this table, or know it exists, but if addOutputsToMap is set to true, the value will display in the table of contents. Changing it to false would prevent the data from showing.
Example:
Enjoy
When developing python add-ins, you should utilize this tool to prevent sub-processes results from being added to the map. A good example of this, is if your python add-in creates a table if it doesn't exist for logging purposes. Your end user does not want to see this table, or know it exists, but if addOutputsToMap is set to true, the value will display in the table of contents. Changing it to false would prevent the data from showing.
Example:
from arcpy import env
env.addOutputsToMap = false
#... perform GP task...
env.addOutputsToMap = true
Enjoy
Labels:
ArcPy,
Programming,
Python,
Python Add-ins
Thursday, December 6, 2012
Monday, December 3, 2012
Truncate Table, A New Way To Erase Rows
Truncate table is the 10.1 way to erase ALL the rows in a table or feature class. It will ignore any sql query, so use this tool carefully.
Some Notes:
This is a good tool for workflows where you need to clear out rows on some regular basis.
Usage Example:
Enjoy
Some Notes:
- Supported data types are simple, meaning no terrains, topologies, etc..
- Data must be unversioned to execute
- After rows are removed, the data is unrecoverable, so make sure you know what you are doing before you go and use this.
This is a good tool for workflows where you need to clear out rows on some regular basis.
Usage Example:
import arcpy
from arcpy import env
wrksp = r"c:\temp\data.gdb"
env.workspace = wrksp
fcs = arcpy.ListFeatureClasses()
for fc in fcs:
arcpy.TruncateTable_management(fc)
del fcs
Enjoy
Labels:
ArcGIS 10.1,
ArcPy,
Programming,
Scripting
Thursday, November 29, 2012
Walk, new arcpy.da function as 10.1 SP1
Walk is a useful function that walks directories. Though this is an easy function to create using recursion, it is now including as a core function at 10.1 SP1 for arcpy.
The help describes the function as such:
Enjoy
The help describes the function as such:
Generate data names in a catalog tree by walking the tree top-down or bottom-up. Each directory/workspace in the tree yields a tuple of three: dirpath, dirnames, and filenames. Python's os module includes an os.walk function that can be used to walk through a directory tree and find data. os.walk is file based and does not recognize database contents such as geodatabase feature classes, tables, or rasters. arcpy.da.Walk can be used to catalog data.Example:
import arcpy
import os
workspace = "c:/data"
feature_classes = []
for dirpath, dirnames, filenames in arcpy.da.Walk(workspace,
datatype="FeatureClass",
type="Polygon"):
for filename in filenames:
feature_classes.append(os.path.join(dirpath, filename))
Enjoy
Labels:
ArcGIS 10.1,
ArcPy,
Programming,
Python,
Scripting
Wednesday, November 21, 2012
Shift Those Polygons at 10.1
The arcpy team at Esri has a great blog post that shows how to shift polygons using the SHAPE@XY tag.
Here is the sample:
Here is the sample:
with arcpy.da.UpdateCursor(in_features, ['SHAPE@XY']) as cursor:
for row in cursor:
cursor.updateRow([[row[0][0] + (x_shift or 0),
row[0][1] + (y_shift or 0)]])
Here we have the shape column (column 0) and to access the X and Y property, you just edit the first and second objects in the X,Y pair. The x_shift and y_shift are float values that will move the code in one direction or another.
It's very simple sample, but it shows how you can easily move polygons. In the past you had to adjust each vertex, but now this is done internally thanks to the new arcpy.da module at 10.1.
Labels:
ArcGIS 10.1,
ArcPy,
Programming,
Python,
Scripting
Thursday, October 25, 2012
Using pythonaddins Messagebox
New 10.1, there is a module created for python add-ins. It's called the pythonaddins module, and you can create a messagebox. The messagebox object allows you to display messages to an end user.
The arcpy help can be found here.
So the messagebox can be defined as such:
MessageBox(message, title, {mb_type})
To use you just pass in a message and title as text. The mb_type is the type of messagebox type value. It supports the following types:
Complete Example:
Simple Right!
The arcpy help can be found here.
So the messagebox can be defined as such:
MessageBox(message, title, {mb_type})
To use you just pass in a message and title as text. The mb_type is the type of messagebox type value. It supports the following types:
| mb_type | value |
|---|---|
0
|
OK Only
|
1
|
OK/Cancel
|
2
|
Abort/Retry/Cancel
|
3
|
Yes/No/Cancel
|
4
|
Yes/No
|
5
|
Retry/Cancel
|
6
|
Cancel/Try Again/Continue
|
Complete Example:
>>> import pythonaddins
>>> result = pythonaddins.MessageBox("Press Cancel", "TITLE", 1)
>>> print result
CancelSimple Right!
Labels:
ArcGIS 10.1,
ArcPy,
Programming,
Python,
Python Add-ins,
Scripting
Subscribe to:
Posts (Atom)