-
Notifications
You must be signed in to change notification settings - Fork 13
/
ArcPlus.leo
2222 lines (1812 loc) · 74.6 KB
/
ArcPlus.leo
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?xml version="1.0" encoding="utf-8"?>
<!-- Created by Leo: http://leoeditor.com/leo_toc.html -->
<leo_file xmlns:leo="http://leoeditor.com/namespaces/leo-python-editor/1.1" >
<leo_header file_format="2"/>
<globals/>
<preferences/>
<find_panel_settings/>
<vnodes>
<v t="mhw.20190606134904.1"><vh>@path arcplus</vh>
<v t="mhw.20190606134949.1"><vh>@clean arcplus.py</vh>
<v t="mhw.20190925103251.3"><vh>Declarations (arcplus.py)</vh></v>
<v t="mhw.20190925103251.4"><vh>listAllFeatureClasses (arcplus.py)</vh></v>
<v t="mhw.20190925103251.5"><vh>layer_from_selected (arcplus.py)</vh></v>
</v>
<v t="mhw.20190708130736.1"><vh>@clean gpcodes.py</vh>
<v t="mhw.20190925103251.6"><vh>Declarations (gpcodes.py)</vh></v>
</v>
<v t="mhw.20190606135052.12"><vh>@clean profile-arcpy-listFC.py</vh>
<v t="mhw.20190925103251.7"><vh>Declarations (profile-arcpy-listFC.py)</vh></v>
<v t="mhw.20190925103251.8"><vh>arcpy_listFC (profile-arcpy-listFC.py)</vh></v>
</v>
<v t="mhw.20190606135052.9"><vh>@clean profile-arcplus-listAllFC.py</vh>
<v t="mhw.20190925103251.9"><vh>Declarations (profile-arcplus-listAllFC.py)</vh></v>
<v t="mhw.20190925103251.10"><vh>listAllFeatureClasses (profile-arcplus-listAllFC.py)</vh></v>
</v>
<v t="mhw.20190606135052.7"><vh>@clean interpolate_z_between.py</vh>
<v t="mhw.20190925103251.11"><vh>Declarations (interpolate_z_between.py)</vh></v>
</v>
<v t="mhw.20190606135052.2"><vh>@clean count-vertices.py</vh>
<v t="mhw.20190925103251.12"><vh>Declarations (count-vertices.py)</vh></v>
<v t="mhw.20190925103251.13"><vh>count_vertices (count-vertices.py)</vh></v>
<v t="mhw.20190925103251.14"><vh>print_report (count-vertices.py)</vh></v>
<v t="mhw.20190925103251.15"><vh>get_feature_classes (count-vertices.py)</vh></v>
</v>
<v t="maphew.20120201135209.1853"><vh>@file AttributedMultiRingBuffer.py</vh></v>
</v>
<v t="maphew.20140522093157.1505"><vh>@path ArcToolbox/Scripts</vh>
<v t="mhw.20190925103922.1"><vh>@clean save-layers-my-credentials.py</vh>
<v t="mhw.20190925103950.1"><vh>Declarations (save-layers-my-credentials.py)</vh></v>
<v t="mhw.20190925103950.2"><vh>get_filenames (save-layers-my-credentials.py)</vh></v>
</v>
<v t="mhw.20190606135214.14"><vh>@clean ungenerate.py</vh>
<v t="mhw.20190925103252.1"><vh>Declarations (ungenerate.py)</vh></v>
<v t="mhw.20190925103252.2"><vh>get_sepchar (ungenerate.py)</vh></v>
<v t="mhw.20190925103252.3"><vh>validate_id (ungenerate.py)</vh></v>
</v>
<v t="mhw.20190606135214.11"><vh>@clean TableToCSV.py</vh>
<v t="mhw.20190925103252.4"><vh>Declarations (TableToCSV.py)</vh></v>
<v t="mhw.20190925103252.5"><vh>table2csv (TableToCSV.py)</vh></v>
</v>
<v t="mhw.20190606135214.9"><vh>@clean symbol_from_table.py</vh>
<v t="mhw.20190925103252.6"><vh>Declarations (symbol_from_table.py)</vh></v>
</v>
<v t="mhw.20190606135214.7"><vh>@clean shp2gen.py</vh>
<v t="mhw.20190925103252.7"><vh>Declarations (shp2gen.py)</vh></v>
</v>
<v t="mhw.20190606135214.5"><vh>@clean set_legend_descriptions.py</vh>
<v t="mhw.20190925103252.8"><vh>Declarations (set_legend_descriptions.py)</vh></v>
</v>
<v t="mhw.20190606135214.1"><vh>@clean sdeconn.py</vh>
<v t="mhw.20190925103252.9"><vh>Declarations (sdeconn.py)</vh></v>
<v t="mhw.20190925103252.10"><vh>connect (sdeconn.py)</vh></v>
<v t="mhw.20190925103252.11"><vh>get_profile_info (sdeconn.py)</vh></v>
<v t="mhw.20190925103252.12"><vh>connect_filename (sdeconn.py)</vh></v>
<v t="mhw.20190925103252.13"><vh>listFcsInGDB (sdeconn.py)</vh></v>
</v>
<v t="mhw.20190606135213.47"><vh>@clean metadata_batch_upgrade.py</vh>
<v t="mhw.20190925103252.14"><vh>Declarations (metadata_batch_upgrade.py)</vh></v>
<v t="mhw.20190925103252.15"><vh>main (metadata_batch_upgrade.py)</vh></v>
</v>
<v t="mhw.20190606135213.44"><vh>@clean layer_from_selected.py</vh>
<v t="mhw.20190925103252.16"><vh>Declarations (layer_from_selected.py)</vh></v>
<v t="mhw.20190925103252.17"><vh>main (layer_from_selected.py)</vh></v>
</v>
<v t="mhw.20190606135213.40"><vh>@clean interp_missing_z.py</vh>
<v t="mhw.20190925103252.18"><vh>Declarations (interp_missing_z.py)</vh></v>
<v t="mhw.20190925103252.19"><vh>showPyMessage (interp_missing_z.py)</vh></v>
<v t="mhw.20190925103252.20"><vh>main (interp_missing_z.py)</vh></v>
</v>
<v t="mhw.20190606135213.33"><vh>@clean GPXtoFeaturesXY.py</vh>
<v t="mhw.20190925103252.21"><vh>Declarations (GPXtoFeaturesXY.py)</vh></v>
<v t="mhw.20190925103252.22"><vh>gpxToPoints (GPXtoFeaturesXY.py)</vh></v>
<v t="mhw.20190925103252.23"><vh>class classGPXPoint(object)</vh>
<v t="mhw.20190925103252.24"><vh>classGPXPoint(object).__init__</vh></v>
<v t="mhw.20190925103252.25"><vh>classGPXPoint(object).asPoint</vh></v>
</v>
<v t="mhw.20190925103252.26"><vh>GeneratePointFromXML (GPXtoFeaturesXY.py)</vh></v>
</v>
<v t="mhw.20190606135213.31"><vh>@clean filter-dissolve.py</vh>
<v t="mhw.20190925103252.27"><vh>Declarations (filter-dissolve.py)</vh></v>
</v>
<v t="mhw.20190606135213.26"><vh>@clean FeaturesToGPX.py</vh>
<v t="mhw.20190925103252.28"><vh>Declarations (FeaturesToGPX.py)</vh></v>
<v t="mhw.20190925103252.29"><vh>prettify (FeaturesToGPX.py)</vh></v>
<v t="mhw.20190925103252.30"><vh>featuresToGPX (FeaturesToGPX.py)</vh></v>
<v t="mhw.20190925103252.31"><vh>generatePointsFromFeatures (FeaturesToGPX.py)</vh></v>
</v>
<v t="mhw.20190606135213.19"><vh>@clean ExportLayerSymbolDefinitions.py</vh>
<v t="mhw.20190925103252.32"><vh>Declarations (ExportLayerSymbolDefinitions.py)</vh></v>
<v t="mhw.20190925103252.33"><vh>class LayerExtras(object)</vh></v>
<v t="mhw.20190925103252.34"><vh>class MxdExtras(dict)</vh>
<v t="mhw.20190925103252.35"><vh>MxdExtras(dict).__init__</vh></v>
<v t="mhw.20190925103252.36"><vh>MxdExtras(dict).loadMxdPath</vh></v>
<v t="mhw.20190925103252.37"><vh>MxdExtras(dict).loadMsdLayerDom</vh></v>
</v>
</v>
<v t="mhw.20190606135213.16"><vh>@clean ExportFolder2PDF.py</vh>
<v t="mhw.20190925103252.38"><vh>Declarations (ExportFolder2PDF.py)</vh></v>
<v t="mhw.20190925103252.39"><vh>exportmap (ExportFolder2PDF.py)</vh></v>
</v>
<v t="mhw.20190606135213.13"><vh>@clean export_gdb_domains.py</vh>
<v t="mhw.20190925103252.40"><vh>Declarations (export_gdb_domains.py)</vh></v>
<v t="mhw.20190925103252.41"><vh>export_domains (export_gdb_domains.py)</vh></v>
</v>
<v t="mhw.20190606135213.10"><vh>@clean ExcelSheetsToTables.py</vh>
<v t="mhw.20190925103252.42"><vh>Declarations (ExcelSheetsToTables.py)</vh></v>
<v t="mhw.20190925103252.43"><vh>importallsheets (ExcelSheetsToTables.py)</vh></v>
</v>
<v t="mhw.20190606135213.8"><vh>@clean clip_all_layers.py</vh>
<v t="mhw.20190925103252.44"><vh>Declarations (clip_all_layers.py)</vh></v>
</v>
<v t="mhw.20190606135213.6"><vh>@clean change_datasource_paths.py</vh>
<v t="mhw.20190925103252.45"><vh>Declarations (change_datasource_paths.py)</vh></v>
</v>
<v t="mhw.20190606135213.1"><vh>@clean xx-z-from-intersect-line.py</vh>
<v t="mhw.20190925103252.46"><vh>Declarations (xx-z-from-intersect-line.py)</vh></v>
<v t="mhw.20190925103252.47"><vh>read_stream (xx-z-from-intersect-line.py)</vh></v>
<v t="mhw.20190925103252.48"><vh>thing (xx-z-from-intersect-line.py)</vh></v>
<v t="mhw.20190925103252.49"><vh>main (xx-z-from-intersect-line.py)</vh></v>
</v>
</v>
</vnodes>
<tnodes>
<t tx="maphew.20140522093157.1505"></t>
<t tx="mhw.20190606134904.1"></t>
<t tx="mhw.20190606134949.1">@others
@language python
@tabwidth -4
</t>
<t tx="mhw.20190606135052.12">@others
@language python
@tabwidth -4
</t>
<t tx="mhw.20190606135052.2">@others
@language python
@tabwidth -4
</t>
<t tx="mhw.20190606135052.7">@others
@language python
@tabwidth -4
</t>
<t tx="mhw.20190606135052.9">@others
@language python
@tabwidth -4
</t>
<t tx="mhw.20190606135213.1">@others
if __name__ == '__main__':
#read_stream(fc_stream, fc_contour)
thing(fc_stream, fc_contour)
@language python
@tabwidth -4
</t>
<t tx="mhw.20190606135213.10"># -*- coding: utf-8 -*-
@others
if __name__ == "__main__":
in_excel = arcpy.GetParameterAsText(0)
table_prefix = arcpy.GetParameterAsText(1)
out_gdb = arcpy.GetParameterAsText(2)
importallsheets(in_excel, table_prefix, out_gdb)
@language python
@tabwidth -4
</t>
<t tx="mhw.20190606135213.13"># -*- coding: utf-8 -*-
@others
if __name__ == "__main__":
domains = arcpy.da.ListDomains(gdb)
export_domains(domains)
@language python
@tabwidth -4
</t>
<t tx="mhw.20190606135213.16">@others
@language python
@tabwidth -4
</t>
<t tx="mhw.20190606135213.19"># courtesy of Micheal Jackson
# https://gis.stackexchange.com/questions/1466/using-arcpy-to-get-layer-symbology
@others
@language python
@tabwidth -4
</t>
<t tx="mhw.20190606135213.26">@others
if __name__ == "__main__":
''' Gather tool inputs and pass them to featuresToGPX(features, output files) '''
inputFC = arcpy.GetParameterAsText(0)
outGPX = arcpy.GetParameterAsText(1)
pretty = arcpy.GetParameterAsText(2)
featuresToGPX(inputFC, outGPX, pretty=pretty)
@language python
@tabwidth -4
</t>
<t tx="mhw.20190606135213.31"># -*- coding: utf-8 -*-
# ---------------------------------------------------------------------------
# filter-dissolve.py
# Created on: 2016-01-13 10:34:31.00000
# (generated by ArcGIS/ModelBuilder)
# Usage: filter-dissolve <Input_Features> <Filter_Expression> <Output_Features>
# Description:
# ---------------------------------------------------------------------------
# Import arcpy module
@others
if Input_Features == '#' or not Input_Features:
Input_Features = "D:\\p\\NHN\\yt_nhn.gdb\\Dataset\\NHN_HD_WATERBODY_2" # provide a default value if unspecified
Filter_Expression = arcpy.GetParameterAsText(1)
if Filter_Expression == '#' or not Filter_Expression:
Filter_Expression = "lakeId1 NOT LIKE ''" # provide a default value if unspecified
Output_Features = arcpy.GetParameterAsText(2)
if Output_Features == '#' or not Output_Features:
Output_Features = "D:\\p\\NHN\\yt_nhn.gdb\\Regions\\Named_Lakes" # provide a default value if unspecified
# Local variables:
nameId_not_empty = "arc_Named_Lakes"
Dissolve_Field_s_ = "permanency;lakeId1;lakeName1;waterDefinitionText"
# Process: Make Feature Layer
arcpy.MakeFeatureLayer_management(Input_Features, nameId_not_empty, Filter_Expression, "", "OBJECTID OBJECTID VISIBLE NONE;SHAPE SHAPE VISIBLE NONE;nid nid VISIBLE NONE;validityDate validityDate VISIBLE NONE;acquisitionTechnique acquisitionTechnique VISIBLE NONE;datasetName datasetName VISIBLE NONE;planimetricAccuracy planimetricAccuracy VISIBLE NONE;provider provider VISIBLE NONE;completelyCover completelyCover VISIBLE NONE;waterDefinition waterDefinition VISIBLE NONE;isolated isolated VISIBLE NONE;permanency permanency VISIBLE NONE;geographicalNameDB geographicalNameDB VISIBLE NONE;lakeId1 lakeId1 VISIBLE NONE;lakeId2 lakeId2 VISIBLE NONE;riverId1 riverId1 VISIBLE NONE;riverId2 riverId2 VISIBLE NONE;lakeName1 lakeName1 VISIBLE NONE;lakeName2 lakeName2 VISIBLE NONE;riverName1 riverName1 VISIBLE NONE;riverName2 riverName2 VISIBLE NONE;idDate idDate VISIBLE NONE;nameDate nameDate VISIBLE NONE;waterDefinitionText waterDefinitionText VISIBLE NONE;SHAPE_Length SHAPE_Length VISIBLE NONE;SHAPE_Area SHAPE_Area VISIBLE NONE")
# Process: Dissolve
arcpy.Dissolve_management(nameId_not_empty, Output_Features, Dissolve_Field_s_, "", "MULTI_PART", "DISSOLVE_LINES")
@language python
@tabwidth -4
</t>
<t tx="mhw.20190606135213.33">@others
if __name__ == "__main__":
''' Gather tool inputs and pass them to gpxToPoints(file, outputFC) '''
gpx = arcpy.GetParameterAsText(0)
outFC = arcpy.GetParameterAsText(1)
gpxToPoints(gpx, outFC)
@language python
@tabwidth -4
</t>
<t tx="mhw.20190606135213.40">@others
if __name__ == '__main__':
main()
@language python
@tabwidth -4
</t>
<t tx="mhw.20190606135213.44">@others
if __name__ == "__main__":
''' Gather tool inputs and pass them to gpxToPoints(file, outputFC) '''
layer = arcpy.GetParameterAsText(0)
main(layer)
@language python
@tabwidth -4
</t>
<t tx="mhw.20190606135213.47">@others
if __name__ == "__main__":
''' Gather tool inputs and pass them to gpxToPoints(file, outputFC) '''
gdb = arcpy.GetParameterAsText(0)
main(gdb)
@language python
@tabwidth -4
</t>
<t tx="mhw.20190606135213.6">@others
@language python
@tabwidth -4
</t>
<t tx="mhw.20190606135213.8">@others
if not mxd:
mxd = arcpy.mapping.MapDocument("CURRENT")
else:
mxd = arcpy.mapping.MapDocument(mxd)
for lyr in arcpy.mapping.ListLayers(mxd):
if lyr.isBroken:
arcpy.AddMessage('"%s"\t skipping broken layer' % lyr)
continue
elif not lyr.isGroupLayer:
arcpy.AddMessage('"%s"\t Clipping...' % lyr)
out_layer = os.path.join(out_gdb, lyr.name)
if lyr.isFeatureLayer:
arcpy.Clip_analysis(lyr, clip_layer, out_layer)
elif lyr.isRasterLayer:
arcpy.Clip_management(lyr, '#', out_layer, clip_layer, '#', 'ClippingGeometry')
else:
arcpy.AddMessage('"%s" skipping, not a Feature or Raster layer')
else:
if not lyr.isGroupLayer:
arcpy.AddMessage('"%s"\t unknown layer type, dont know what to do with it.' % lyr)
print arcpy.GetMessages()
@language python
@tabwidth -4
</t>
<t tx="mhw.20190606135214.1">@others
if __name__ == '__main__':
print "started main"
platform = arcpy.GetParameterAsText(0)
database = arcpy.GetParameterAsText(1)
server = arcpy.GetParameterAsText(2)
username = arcpy.GetParameterAsText(3)
password = arcpy.GetParameterAsText(4)
version = arcpy.GetParameterAsText(5)
if not platform:
platform = 'Oracle'
if not version:
version = "SDE.DEFAULT"
profile = get_profile_info()
print "make connection file"
sde = connect(platform, database, server, username, password, version)
print sde
arcpy.env.workspace = sde
print arcpy.env.workspace
for fc in listFcsInGDB():
print fc
print arcpy.GetMessages()
@language python
@tabwidth -4
</t>
<t tx="mhw.20190606135214.11">@others
if __name__ == "__main__":
''' Gather tool inputs and pass them to main function '''
table = arcpy.GetParameterAsText(0)
outfile = arcpy.GetParameterAsText(1)
table2csv(table, outfile)
@language python
@tabwidth -4
</t>
<t tx="mhw.20190606135214.14">@others
if len(sys.argv) < 4: raise Exception, msgNotEnoughParams
inputFC = sys.argv[1]
outFile = open(sys.argv[2], "w")
#optional parameters
sepchar = get_sepchar(decimalchar)
arcpy.AddMessage('\n--- {0}'.format(inputFC))
inDesc = arcpy.Describe(inputFC)
id_field = validate_id(id_fieldname, inDesc)
inRows = arcpy.SearchCursor(inputFC, where_clause)
inRow = inRows.next()
## This confuses ANUDEM, leave out for now.
##outFile.write("//{0}\n".format(inDesc.ShapeType))
while inRow:
feat = inRow.getValue(inDesc.ShapeFieldName)
if inDesc.ShapeType.lower() == "point":
pnt = feat.getPart()
## outLine = "{0},{1},{2},{3},{4}\n".format(inRow.getValue(id_field), pnt.X, pnt.Y, pnt.Z, pnt.M)
outLine = "{0},{1},{2}\n".format(inRow.getValue(id_field), pnt.X, pnt.Y)
if sepchar == "": outFile.write(outLine)
else: outFile.write(outLine.replace(".", sepchar))
elif inDesc.ShapeType.lower() == "multipoint":
partnum = 0
partcount = feat.partCount
outFile.write("{0},{1}\n".format(inRow.getValue(id_field), str(partnum))) # begin new feature
while partnum < partcount:
pnt = feat.getPart(partnum)
## outLine = "{0},{1},{2},{3},{4}\n".format(partnum, pnt.X, pnt.Y, pnt.Z, pnt.M)
outLine = "{0},{1},{2}\n".format(partnum, pnt.X, pnt.Y)
if sepchar == "": outFile.write(outLine)
else: outFile.write(outLine.replace(".", sepchar))
partnum += 1
else:
partnum = 0
partcount = feat.partCount
while partnum < partcount:
## outFile.write("{0},{1}\n".format(inRow.getValue(id_field), str(partnum))) # begin new feature
outFile.write("{0}\n".format(inRow.getValue(id_field))) # begin new feature
part = feat.getPart(partnum)
part.reset()
pnt = part.next()
pnt_count = 0
while pnt:
## outLine = "{0},{1},{2},{3}\n".format(pnt.X, pnt.Y, pnt.Z, pnt.M)
outLine = "{0},{1}\n".format(pnt.X, pnt.Y)
if sepchar == "": outFile.write(outLine)
else: outFile.write(outLine.replace(".", sepchar))
pnt = part.next()
pnt_count += 1
if not pnt:
pnt = part.next()
if pnt:
## outFile.write("InteriorRing\n%s\n" % partnum)
outFile.write("END\n") # end feature part
outFile.write("{0},{1}\n".format(inRow.getValue(id_field), str(pnt_count))) # begin new feature part
outFile.write("END\n") # end feature
partnum += 1
inRow = inRows.next()
outFile.write("END\n")
outFile.flush()
outFile.close()
arcpy.AddMessage('Wrote {0}'.format(outFile.name))
print arcpy.GetMessages()
@language python
@tabwidth -4
</t>
<t tx="mhw.20190606135214.5">@others
if lyr.symbologyType == "UNIQUE_VALUES":
#extract matches
for symbol in lyr.symbology.classValues:
desclist.append(descriptions[symbol])
# assign the descriptions
lyr.symbology.classDescriptions = desclist
mxd.saveACopy(output_map)
del mxd
@language python
@tabwidth -4
</t>
<t tx="mhw.20190606135214.7">#!/usr/bin/env python
#
# shp2gen.py
# Convert shapefile to arcinfo generate format
#
# Author: Matthew Perry
#
@others
if __name__ == "__main__":
try:
inputFile = sys.argv[1];
except:
print " usage: shp2gen.py input.shp > output.gen"
sys.exit(1)
# Open dataset and get layer
ds = ogr.Open(inputFile)
layer = ds.GetLayer()
coords = ''
feature = layer.GetNextFeature()
fn = 0
while feature is not None:
coords = '';
geom = feature.GetGeometryRef()
geomtype = geom.GetGeometryType()
if geomtype == ogr.wkbPoint:
coords = coords + str(fn) + "," + str(geom.GetX(0)) + "," + \
str(geom.GetY(0)) + "\n";
elif geomtype == ogr.wkbLineString or geomtype == ogr.wkbPolygon:
geom = geom.GetGeometryRef(0)
numpoints = geom.GetPointCount()
coords = coords + str(fn) + "\n"
for i in range(numpoints):
coords = coords + str(geom.GetX(i)) + " " + \
str(geom.GetY(i)) + "\n";
coords = coords + "END"
feature.Destroy()
feature = layer.GetNextFeature()
fn = fn+1
if coords != '':
print coords
print 'END'
ds.Destroy()
@language python
@tabwidth -4
</t>
<t tx="mhw.20190606135214.9">@others
if lyr.symbologyType == "UNIQUE_VALUES":
lyr.symbology.classValues = stateList
lyr.symbology.showOtherValues = False
arcpy.RefreshActiveView()
arcpy.RefreshTOC()
del mxd
@language python
@tabwidth -4
</t>
<t tx="mhw.20190708130736.1">@others
@language python
@tabwidth -4
</t>
<t tx="mhw.20190925103251.10">def listAllFeatureClasses (gdb,**kwargs):
import arcpy
'''
list all Feature Classes in a geodatabase or coverage recursively
(normal listFeatureClasses does not recurse)
import arcplus
fcs = arcplus.listAllFeatureClasses('d:\default.gdb')
for fc in fcs:
print "magic happens with: ", fc
Arcplus also adds wildcard filtering; to process only feature classes
that start with "HD_" within feature datasets containing "Hydro"
fcs = arcplus.listAllFeatureClasses(gdb, fd_filter='*Hydro*', fc_filter='HD_*')
'''
arcpy.env.workspace = gdb
if not kwargs.has_key('fc_filter'): fc_filter = '*'
else: fc_filter = kwargs ['fc_filter']
if not kwargs.has_key('fd_filter'): fd_filter = '*'
else: fd_filter = kwargs ['fd_filter']
print 'Looking in %s for "%s" ' % (arcpy.env.workspace,fc_filter)
fcs = []
for fds in arcpy.ListDatasets(fd_filter,'feature') + ['']:
for fc in arcpy.ListFeatureClasses(fc_filter,'',fds):
#print '%s\\%s' % (fds,fc)
fcs.append(os.path.join(fds,fc))
return fcs
listAllFeatureClasses(r'X:\Env-dat.081\source\yt_courbe_niveau_imperial.gdb')
</t>
<t tx="mhw.20190925103251.11">'''
Interpolate missing Z values along a 3D line.
*** BROKEN ***
Adapted from @Tomek's work at
http://gis.stackexchange.com/a/18655/108
'''
from arcplus import ao
sPath = r'd:\s\test.gdb'
fcName = 'centerline'
# import arcobjects libraries
ao.GetStandaloneModules()
ao.InitStandalone()
import comtypes.gen.esriSystem as esriSystem
import comtypes.gen.esriGeoDatabase as esriGeoDatabase
import comtypes.gen.esriDataSourcesGDB as esriDataSourcesGDB
### Open the FGDB
##pWS = ao.Standalone_OpenFileGDB(gdb)
# open geodatabase and featureclass
pWSF = ao.NewObj(esriDataSourcesGDB.FileGDBWorkspaceFactory, esriGeoDatabase.IWorkspaceFactory)
pWS = pWSF.OpenFromFile(sPath, 0)
pFWS = pWS.QueryInterface(esriGeoDatabase.IFeatureWorkspace)
pFClass = pFWS.OpenFeatureClass(str(fcName))
# set update cursor on the featureclass
pFCursor = pFClass.Update(None, True)
pFeat = pFCursor.NextFeature()
# loop trough features in featureclass
while pFeat:
print "--- Feature:", pFeat.OID
pShape = pFeat.ShapeCopy # clone shape of current feature
pIZ = pShape.QueryInterface(esriGeometry.IZ2) #set IZ interface on the data - allow for interpolation of the Z value
IPointCollection = pShape.QueryInterface(esriGeometry.IPointCollection) # set IPointCollection interface on the data - allow for points manipulation within the point collection
IPoint = ao.NewObj(esriGeometry.Point, esriGeometry.IPoint) # create Point object with IPoint interface
pStart = 0 # set pStart parameter to index[0]
# loop trough IPointCollection within the polyline, find pStart and pEnd point within the polyline for IZ.InterpolateZsBetween
for i in range(IPointCollection.PointCount):
Point = IPointCollection.QueryPoint(i, IPoint) # query for point within the IPointCollection at index i and insert it in to IPoint
# selection of the pStart and pEnd properties based on points Z value and interpolation of the vertexes within the polyline
if i==0: # skip value at index[0]
## pass
print '\tSkipping point:', i
continue
elif IPoint.Z != 0: # assign pEnd and pStart if Z value of the point (vertex) is larger than 0.01 (0.01 not 0 as 0 in arcgis is returned in python as 4.54747350886e-013)
pEnd = i
pIZ.InterpolateZsBetween(0,pStart,0,pEnd) # program assumes that is dealing with single part polylines
pFeat.Shape = pIZ
pFCursor.UpdateFeature(pFeat)
pStart = pEnd
pFeat = pFCursor.NextFeature()
</t>
<t tx="mhw.20190925103251.12">import os
import arcpy
workspace = arcpy.GetParameterAsText(0)
if not workspace:
workspace = r'Z:\V5\ENV_250k.gdb\admin_env'
</t>
<t tx="mhw.20190925103251.13">def count_vertices(fc, table):
'''Count vertices in Feature Class, insert to dictionary named "table"'''
# Adapted from Alex Tereshenkov (@alex-tereshenkov)
# https://gis.stackexchange.com/questions/84796/extracting-number-of-vertices-in-each-polygon
features = [feature[0] for feature in arcpy.da.SearchCursor(fc,"SHAPE@")]
count_vertices = sum([f.pointCount-f.partCount for f in features])
table[fc] = count_vertices
</t>
<t tx="mhw.20190925103251.14">def print_report(table):
'''Print dictionary as table
(Naive, paths longer than X characters mess up the table)'''
print "{:60}\t:\t{:>12}".format('-' * 60, '-' * 12)
print "{:60}\t:\t{:>12}".format('Feature Class', 'Vertices')
print "{:60}\t:\t{:>12}".format('-' * 60, '-' * 12)
for k,v in table.items():
print "{:60}\t:\t{:>12,}".format(k,v)
</t>
<t tx="mhw.20190925103251.15">def get_feature_classes(workspace):
'''Return list of all feature classes under Workspace (recursive)'''
# https://gis.stackexchange.com/questions/5893/listing-all-feature-classes-in-file-geodatabase-including-within-feature-datase
feature_classes = []
walk = arcpy.da.Walk(workspace, datatype="FeatureClass")
print 'Finding feature classes in', workspace
for dirpath, dirnames, filenames in walk:
for filename in filenames:
feature_classes.append(os.path.join(dirpath, filename))
return feature_classes
table = {}
for fc in get_feature_classes(workspace):
print 'Counting', fc
count_vertices(fc,table)
print_report(table)
</t>
<t tx="mhw.20190925103251.3">'''
Module: arcplus
Source: arcplus.py
Author: [email protected]
License: X/MIT, (c) 2014 Environment Yukon
Functions missing from regular ol' arcpy module
Place with your other code or PYTHONPATH and then:
import arcplus
fcs = arcplus.cool_extra_function(...)
for fc in fcs:
print "magic happens with: ", fc
(there is only one extra function at the moment... ;-)
'''
import os
</t>
<t tx="mhw.20190925103251.4">def listAllFeatureClasses (gdb,**kwargs):
import arcpy
'''
list all Feature Classes in a geodatabase or coverage recursively
(normal listFeatureClasses does not recurse)
import arcplus
fcs = arcplus.listAllFeatureClasses('d:\default.gdb')
for fc in fcs:
print "magic happens with: ", fc
Arcplus also adds wildcard filtering; to process only feature classes
that start with "HD_" within feature datasets containing "Hydro"
fcs = arcplus.listAllFeatureClasses(gdb, fd_filter='*Hydro*', fc_filter='HD_*')
'''
arcpy.env.workspace = gdb
if not kwargs.has_key('fc_filter'): fc_filter = '*'
else: fc_filter = kwargs ['fc_filter']
if not kwargs.has_key('fd_filter'): fd_filter = '*'
else: fd_filter = kwargs ['fd_filter']
print 'Looking in %s for "%s" ' % (arcpy.env.workspace,fc_filter)
fcs = []
for fds in arcpy.ListDatasets(fd_filter,'feature') + ['']:
for fc in arcpy.ListFeatureClasses(fc_filter,'',fds):
#print '%s\\%s' % (fds,fc)
fcs.append(os.path.join(fds,fc))
return fcs
</t>
<t tx="mhw.20190925103251.5">def layer_from_selected(layer):
''' Create in-memory layer using only selected features of the input layer.
Basically this is to replicate the functionality of "{Layer} >> r-click >> Selection >> Create Layer from Selected Features" in a manner that can used in a python script.
Arguments: Layer with selected features
Adapted from @Pete
http://gis.stackexchange.com/questions/63717/use-a-selection-of-features-in-arcmap-in-python-script/63743#63743
'''
import arcpy
arcpy.env.workspace = "in_memory"
results_layer = layer + "_selection"
#this will create a new feature class from the selected features but will do it In Memory
arcpy.CopyFeatures_management(layer, results_layer)
#Now do all the other stuff you want like convert it to a layer and work with it
arcpy.MakeFeatureLayer_management(results_layer)
return
</t>
<t tx="mhw.20190925103251.6">''' Generate list of possible geoprocessing error codes. These error codes are
not documented in the help anymore so Curtis wrote a script to make a list.
Initial version: 2019-Jul-05, Curtis Price <[email protected]>
'''
import sys
import arcpy
# start code to fetch
try:
n = int(sys.argv[1])
except IndexError:
print('''Usage: gpcodes [start number] {optional end number}\n''')
sys.exit()
# optional end code to fetch
try:
nn = int(sys.argv[2])
except IndexError:
nn = n # default to start number
nn += 1 # increment by 1 so we return the final code as well
for k in range(n,nn):
try:
dsc = arcpy.GetIDMessage(k)
if dsc:
print("{:6d}\t{}".format(k, dsc))
except:
pass
</t>
<t tx="mhw.20190925103251.7">import arcpy
#gdb = r'X:\Env-dat.081\source\yt_courbe_niveau_imperial.gdb'
gdb = r'D:\s\yt_courbe_niveau_imperial.gdb'
</t>
<t tx="mhw.20190925103251.8">def arcpy_listFC(gdb):
arcpy.env.workspace = gdb
print 'Looking in "%s" ' % arcpy.env.workspace
fcs = arcpy.ListFeatureClasses()
return fcs
fcs = arcpy_listFC(gdb)
print 'Feature classes found: %s' % len(fcs)
</t>
<t tx="mhw.20190925103251.9">import os
</t>
<t tx="mhw.20190925103252.1">''' ungenerate.py - write features to ArcInfo GENERATE text file format.
Arguments:
- input feature class
- output file name
- decimal separator character (comma, period, system locale)
- field to use for ID of each feature (optional)
[email protected], 2015-Feb-13
Tested with ArcGIS 10.3.
Adapted from "WriteFeaturesFromTextFile.py" in the Samples Toolbox distributed
by Environmental Systems Research Institute Inc. (Esri) in ArcGIS 9.x.
http://webhelp.esri.com/arcgisdesktop/9.3/index.cfm?TopicName=An_overview_of_the_Samples_toolbox
'''
import string, os, sys, locale
Usage = '''
Usage: ungenerate (in feature class) (out filename, #) (decimal separator, #) (ID field, #) {SQL where clause}
'#' = use default
{ } = optional
ungenerate D:\data\park_bound.shp x:\scratch\parks.gen # #
ungenerate D:\data\park_bound.shp x:\scratch\parks.gen comma ParkName
ungenerate D:\data\park_bound.shp x:\scratch\parks.gen comma ParkName """Type""" LIKE '%Territorial%'"
'''
if len(sys.argv) < 5:
print Usage
sys.exit(1)
import arcpy
inputFC = arcpy.GetParameterAsText(0)
outFile = arcpy.GetParameterAsText(1)
decimalchar = arcpy.GetParameterAsText(2)
id_fieldname = arcpy.GetParameterAsText(3)
argcount = arcpy.GetArgumentCount()
if argcount > 4:
where_clause = ' '.join([arcpy.GetParameterAsText(x) for x in range(4, argcount)])
print '\nSELECT * WHERE:\t', where_clause
else:
where_clause = None
if outFile[-1] == '#':
outFile = os.path.join(os.path.basename(inputFC), '.gen')
msgNotEnoughParams = "Incorrect number of input parameters."
msgUseValidDecimalPointSep = "Please use one of the valid decimal point separators."
msgFieldNotFound = 'ID field not found. Specify "#" for default or one of:'
</t>
<t tx="mhw.20190925103252.10">def connect(platform, database, server="<default server>", username="<default user>", password="<default password>", version="SDE.DEFAULT", Connection_File_Name):
# Check if value entered for option
try:
#Usage parameters for spatial database connectdaion to upgrade
service = "sde:{}:{}".format(platform, server)
account_authentication = 'DATABASE_AUTH'
version = version.upper()
database = database.lower()
# Check if direct connection
if service.find(":") <> -1: #This is direct connect
ServiceConnFileName = service.replace(":", "")
ServiceConnFileName = ServiceConnFileName.replace(";", "")
ServiceConnFileName = ServiceConnFileName.replace("=", "")
ServiceConnFileName = ServiceConnFileName.replace("/", "")
ServiceConnFileName = ServiceConnFileName.replace("\\", "")
else:
arcpy.AddMessage("\n+++++++++")
arcpy.AddMessage("Exiting!!")
arcpy.AddMessage("+++++++++")
sys.exit("\nSyntax for a direct connection in the Service parameter is required for geodatabase upgrade.")
# Local variables
Conn_File_NameT = server + "_" + ServiceConnFileName + "_" + database + "_" + username
if os.environ.get("TEMP") == None:
temp = "c:\\temp"
else:
temp = os.environ.get("TEMP")
if os.environ.get("TMP") == None:
temp = "/usr/tmp"
else:
temp = os.environ.get("TMP")
#Connection_File_Name = temp + os.sep + Conn_File_NameT + ".sde"
#if os.path.isfile(Connection_File_Name):
# return Connection_File_Name
# Check for the .sde file and delete it if present
arcpy.env.overwriteOutput=True
# Variables defined within the script; other variable options commented out at the end of the line
saveUserInfo = "SAVE_USERNAME" #DO_NOT_SAVE_USERNAME
saveVersionInfo = "SAVE_VERSION" #DO_NOT_SAVE_VERSION
print "\nCreating ArcSDE Connection File...\n"
# Process: Create ArcSDE Connection File...
# Usage: out_folder_path, out_name, server, service, database, account_authentication, username, password, save_username_password, version, save_version_info
print temp
print Conn_File_NameT
print server
print service
print database
print account_authentication
print username
print password
print saveUserInfo
print version
print saveVersionInfo
arcpy.CreateArcSDEConnectionFile_management(temp,
Conn_File_NameT,
server,
service,
database,
account_authentication,
username,
password,
saveUserInfo,
version,
saveVersionInfo)
for i in range(arcpy.GetMessageCount()):
if "000565" in arcpy.GetMessage(i): #Check if database connection was successful
arcpy.AddReturnMessage(i)
arcpy.AddMessage("\n+++++++++")
arcpy.AddMessage("Exiting!!")
arcpy.AddMessage("+++++++++\n")
sys.exit(3)
else:
arcpy.AddReturnMessage(i)
arcpy.AddMessage("+++++++++\n")
return Connection_File_Name
#Check if no value entered for option
except SystemExit as e:
print e.code
return
</t>
<t tx="mhw.20190925103252.11">def get_profile_info():
'''
Kudos @Michael-Stimson https://gis.stackexchange.com/a/154572/108
'''
d = {}
d['appdata'] = os.environ.get("APPDATA") # not case sensitive
d['II'] = arcpy.GetInstallInfo()
d['version'] = II["Version"] # Case sensitive
d['desktop_fld'] = "{0}\\ESRI\\Desktop{1}".format(AppData,Version)
d['connections'] = "{}\\ArcCatalog".format(d['desktop_fld'])
return d
</t>
<t tx="mhw.20190925103252.12">def connect_filename(profile, database, username):
'''Return full path for connection file
Example:
"C:\Users\mhwilkie\AppData\Roaming\ESRI\Desktop10.6\ArcCatalog\Connection to CSWPROD (mhwilkie).sde"
'''
fname = '{0}\\Connection to {1} ({2}).sde'.format(
profile['connections'],
database,
username)
return fname
</t>
<t tx="mhw.20190925103252.13">def listFcsInGDB():
''' set your arcpy.env.workspace to a gdb before calling '''
for fds in arcpy.ListDatasets('','feature') + ['']:
for fc in arcpy.ListFeatureClasses('','',fds):
yield os.path.join(arcpy.env.workspace, fds, fc)
</t>
<t tx="mhw.20190925103252.14">'''
Tool Name: Metadata Batch Upgrade
Source Name: metadata_batch_upgrade.py
Version: ArcGIS 10.2.2
Author: [email protected]
Started: 2013-May-16
License: X/MIT, (c) 2014 Environment Yukon
Required Arguments:
Input Geodatabase or Workspace: path to gdb or workspace
Description:
Recursively walk through a GDB or workspace and upgrades the metadata record of any feature class found.
'''
import arcpy
import arcplus
</t>
<t tx="mhw.20190925103252.15">def main(gdb):
fcs = arcplus.listAllFeatureClasses(gdb)
for fc in fcs:
print "magic happens with: ", fc
arcpy.UpgradeMetadata_conversion(
Source_Metadata=fc,
Upgrade_Type="FGDC_TO_ARCGIS")
print arcpy.GetMessages()
</t>
<t tx="mhw.20190925103252.16">'''
Tool Name: Create layer from selected features
Version: ArcGIS 10.3
Author: [email protected]
Started: 2015-Apr-07
License: X/MIT, (c) 2015 Environment Yukon
Required Arguments:
Layer with selected features
Description:
Create in-memory layer using only selected features of the input layer. Basically this is to replicate the functionality of "{Layer} >> r-click >> Selection >> Create Layer from Selected Features" in a manner that can used in a python script.
Adapted from @Pete
http://gis.stackexchange.com/questions/63717/use-a-selection-of-features-in-arcmap-in-python-script/63743#63743
'''
import arcpy
from arcpy import env
</t>
<t tx="mhw.20190925103252.17">def main(layer):
arcpy.env.workspace = "in_memory"