texts: Spatial join in Python invalid parameters

texts:
I'm getting an error when excecuting a script thats suppose to spatial join two point layers. Code says:

  Error 000561 Invalid parameters

But, I'm pretty certain that they are correct.

Can anyone tell me what might be wrong with the code?

I've read that it might be because multiple points might be withing distance of parameters of one point so that it requires fieldmapping. But I have not figured out how I'm suppose to do this.

import arcpy, sys, string, os, datetime, copy

# Local Path
sti_endring =
r"Y:\N50_Kartdata\Arbeidsfiler\Kontroll\Script\N250_Kontroll\Dataopp
datering\Endringsdata\finn_endring.gdb\\"

# Local variables:
N250_HoydetallObjkoord = sti_endring + "N250_HoydetallObjkoord"
N50_HoydetallObjkoord = sti_endring + "N50_HoydetallObjkoord"
HoydetallObjkoord_joined = sti_endring + "HoydetallObjkoord_joined"

# Process: Spatial Join
target_features = N250_HoydetallObjkoord
join_features = N50_HoydetallObjkoord
out_feature_class = HoydetallObjkoord_joined
arcpy.SpatialJoin_analysis(target_features, join_features,
out_feature_class, "JOIN_ONE_TO_MANY", "KEEP_ALL", "INTERSECT", "350
Meters", "")


texts: Converting KML to shapefile without losing attributes using QGIS?

texts:
I have a KML file with hundreds of points. To each point there is information, such as Name, Power, Age (it's a map of hydroenergy powerplants).  If I import that KML file to QGIS, this information is lost.

Is there a way I can keep this information?

The Information looks like this:

<ExtendedData>
 <SchemaData schemaUrl="#vorlage">
  <SimpleData name="Name">Test</SimpleData>
  <SimpleData name="Power">10895</SimpleData>
  <SimpleData name="Location">L</SimpleData>
 </SchemaData>
</ExtendedData>

Is there anything wrong with my code?


texts: Merging overlapping coordinates to polygons

texts:
Currently I have circa 6,700 geocoded sports club data which indicates the location of the club, the grant they received in a particular year, along with the intended sport.

My shapefile consists of 3,409 regions. What I would like to do is merge the attribute table of my shapefile which contains regional information with my geocoded sports data.

However, while I could normally use "Join Attributes by Location" the issue here is that certain clubs receive more than one grant during the time period (thus an overlapping polygon) and there is also more than one club in a region. Thus, when I use the "Join Attributes by Location" function only one piece of information is taken for each region. So rather than having 6,700 lines of data, I only have 3,409.

In essence I want all my geocoded sports information to be treated as unique.

Is there anyway to merge these two datasets so I'll have regional information for every sports club, rather than having just one piece of sports information for every region?


texts: Cluster analysis using buffers and polygon features (NOT layer)

texts:
I have a point-based vector layer, where each point represents a road accident. I am trying to write a function that:

Loops through my accident layer
creates a buffer, of a given radius, around each point/accident
counts the number of accidents, from the accident layer, within each buffer
if the number of accidents within (i.e. that intersect) the buffer is above a given threshold, then add this buffer as a polygon to a separate, pre-defined layer

What I have so far:

def get_clusters(layer, out_layer, buff_size, acc_threshold):

    segs = 100   #buffer segments

    source_layer = core.QgsMapLayerRegistry.instance().mapLayersByName(layer)[0]
    # get CRS
    CRS = source_layer.crs().authid()
    # make the output layer
    cluster_layer = QgsVectorLayer("Polygon?crs={0}".format(CRS),out_layer,"memory")

    # set up loop and empty list for areas of interest
    my_clusters = []
    for accident_feature in source_layer.getFeatures():
        acc_buffer = accident_feature.geometry().buffer(buff_size,segs)

        # At this point I'm not sure how to proceed. I think I need to use something like

        request = QgsFeatureRequest().setFilterRect(acc_buffer.geometry().boundingBox())
        areas_of_interest = source_layer.getFeatures(request)

        for area in areas_of_interest:
        ## pseudo-code - haven't got far enough to test this
           if area.featureCount() >= acc_threshold:
              my_clusters.append(area.id())

but that's about as far as I can get. I need the intersection-object to be a circle (i.e. just the buffer polygon), but I can't find something like setFilterArea that I could pass the acc_buffer.geometry() in to.

I hope the above is clear, if someone could point me in the right direction I'm quite content working out the rest for myself but currently I'm a bit stuck!


texts: GPS data based track/trip calculation algorithm available?

texts:
Currently I'm receiving position data of moving assets every 90 or 120 seconds (depending on the asset). What I'd like to achieve now is to detect standstill and movement phases (tracks/trips) on the receiving side for these assets.

What are the generic principles of detecting tracks/trips only by GPS data?

For the most assets I'll have additional data like ignition state or other engine parameters that will help to distinguish movement and standstill. But that's not the case for all assets.

As I have no university degree and clearly lacking the mathematical basics that should help in solving such problems I'm generally interested in pointers on how to solve such a problem and sharpen my math/arithmetical skills for the future.


texts: Exporting PDF from QGIS Print Layout including clickable hyperlinks

texts:
I am having difficulties to export a PDF from QGIS 3.4 (having the same issue in 3.12 though) print layout with a clickable hyperlink. Looking at https://docs.qgis.org/2.8/en/docs/user_manual/print_composer/print_composer.html (The label item -> main properties) this should be possible since QGIS 2.8.

  Labels can be interpreted as HTML code: check checkbox Render as HTML.
  You can now insert a URL, a clickable image that links to a web page
  or something more complex.

I simply want to add a text box below my map including a clickable hyperlink controlled by atlas. I added Click me and set the label box as "Render as HTML". I also tried to achieve this by adding a HTML Frame instead of a text box, but still no luck.

The text/link is not clickable when opening the PDF in Adobe Acrobat or other software. During the export I tried both options: Text export as path and as object. Also I tried to force the export as vector. What am I missing?

This related question was asked before the release of QGIS 2.8 and the accepted answer is outdated as well.

This is how the attributes look like:


texts: I am trying to find data at the block level or even block group level for the SF1 files and ACS 2010 or 2009.  Just recently, two months ago, I was able to get this data but for some reason I am now only able to get it at the census tract level??? I have followed all the ways in which I am suppose to extract this data.  Did this change?


texts: classify colourramp with new min and max value with python

texts:
For my script i want to update the existing colourramp of a raster with new min and max value. In my current code is can fill the min and max but can't classify and update the raster.

How does the classify button works to classifies colours with the new min and max values.

My current code is:

rLayer = iface.activeLayer()
provider = rLayer.dataProvider()
stats = provider.bandStatistics(1, QgsRasterBandStats.All, rLayer.extent())

min = 2
max = 5

rLayer.renderer().setClassificationMin(min)
rLayer.renderer().setClassificationMax(max)

This result in the following image:

as you can see the new min and max is filled but the colour ramp isn't classified. I hope there is generic code to fill the colours with their new min and max because the chosen colourramp is variabel.


texts:
Trying to clip a line layer with another renders an empty shapefile. I've looked through older threads and have made sure that the CRS is the same (they do align) and that I've converted multipart files to singlepart ones and use these for clipping.  Have tried with numerous line layers from different datasets. Still getting nothing but an empty shapefile.

Using QGIS 2.10 (tried with the new 2.12 as well) in Windows 7.


texts: processing.run() returns string instead of QgsVectorLayer with QgsProcessingFeatureSourceDefinition as parameter

texts:
I try to run qgis:difference on selected features of 2 layers. But the result of my code :

parameters = {'INPUT': QgsProcessingFeatureSourceDefinition(layer1.id(), True),
              'OVERLAY': QgsProcessingFeatureSourceDefinition(layer2.id(), True),
              'OUTPUT': 'memory:'}
differenced = processing.run('qgis:difference', parameters)

is a string output_... instead of a QgsVectorLayer as usual.
I have added :

QgsProject.instance().addMapLayer(layer1, False)
QgsProject.instance().addMapLayer(layer2, False)

before but the algorithm doesn't work as I want.


texts: ST_Intersection + ST_Difference + not overlapping Polygons

texts:
I have a PostGIS table with some overlapping polygon and need a PostGIS view where no polygon is overlapping and the data is aggregated (like in the picture).

With a Union of ST_Intersection() and ST_Difference() I get the upper 3 polygons, but then I'm missing the Polygons with no overlap?

SELECT ST_Intersection(a.geometry, b.geometry), a.color||','||b.color as color
FROM mytable a, mytable b
WHERE a.fid < b.fid AND ST_INTERSECTS(a.geometry, b.geometry)
UNION
SELECT ST_Difference(a.geometry, b.geometry), a.color as color
FROM mytable a, mytable b
WHERE a.fid < b.fid AND ST_INTERSECTS(a.geometry, b.geometry)

How do I include the polygons with no overlap?
Is there maybe an easier solution for my problem, like a split/aggregate function?


texts:
Please sorry for my bad english :(

Here is the situation:

I have a .Net DLL written on C#, witch contains windows form.

MapInfo calls function from this DLL witch opens form.

Is there any way to get instance of MapInfo, that called this function? (Not just first opened instance, because i can have multiple opened)


texts: iOS Sharing of Base Map file between several apps

texts:
I am new to iOS development and looking for general advice on how to achieve the following situation:

We have developed our first iOS mapping application using the Agentry platform. The application uses the ArcGIS iOS SDK for mapping functionality and we included a base map file for offline use that is over 1GB in size.

Now the second app request has come in for similar functionality and we are wondering whether it is possible to somehow share the base map file so that we do not have to have another 1+ GB app.

I know the security limitations of iOS make sharing of files a little more difficult, but is this type of approach possible? I have looked a little into iOS extensibility SDK to see if that is an option but I am not really sure where to begin.


texts: Copying feature classes in feature dataset returns ERROR 000732: Input Features does not exist or is not supported

texts:
I'm pretty new to python and I have some trouble getting this snippet of code to work. I have some lines that work to copy shapefiles and feature classes, but I haven't managed to be able to copy feature classes from a feature dataset.

A "lookup table" exists with info on the source path, source name, target path, target name, etc.
There's a field called 'BatchID' that is used as a reference for what the user wants to be copied. That said, there's a raw input that is in the code and once the user enters the number, the data in that row(s) is copied. I keep getting the error:

  ERROR 000732: Input Features: Dataset C:...file path
  here...\test1.gdb\SanTest does not exist or is not supported Failed to
  execute (CopyFeatures).

Copy Feature dataset- features

            if batch_id == int(btch_num):
                ds = arcpy.ListFeatureClasses('','', source_name)
                for fc in ds:
                    print ('These features') + (fc) + (' are in the feature dataset!')
                    arcpy.CopyFeatures_management(fc, os.path.join(target_path, os.path.splitext(fc)[0]))


texts:
I am new in R and I am facing a problem. I have a list with many SpatialPolygonsDataFrames. Some of them are like this example

This is a SpatialPolygonsDataFrame. My "problem" is that the data.frame has two rows for this SpatialPolygonsDataFrame. How can I keep the two polygons with only one row in data.frame? I think is something like merge but how can I do this in R?

I use the sp package for geometry representation.


texts: I have been using ArcGIS ArcMap's Identity Tool to find out what's found in a selected polygon (AOI) from multiple visible layers.  The results gets displayed in the Identify Window.  How can I get the result directly to text format without going through copy selected fields? Does anyone know the code behind the Identify Window?


texts: Is there any QGIS 3.x alternative tool for osmpoly_export plugin?

texts:
I used this plugin in QGIS2 for easy defining the area of interest using some vector polygon and then cropping the OSM data with osmctools and the poly file.
However the plugin is QGIS2 only:

This is QGIS 2.x plugin.
It exports all or selected vector polygons to poly-files used by Osmosis, Osmconvert (and probably other OSM-related tools) for cliping OpenStreetMap data.

plugin source:
https://github.com/nextgis/osmpoly_export
Is there any alternative for QGIS3?
thanks


texts: Delete ALL ArcCatalog Database Connections using ArcPy?

texts: What arcpy function deletes ALL database connections in ArcCatalog?


texts: How can I import layer symbology from another layer programmaticaly with ArcObjects & VBA?

texts:
I would like to be able to develop a procedure that runs through all layers in the TOC and if the layer (name) exists in a specific folder where I am storing layer files with complex symbology I would like to import the procedure to import the symbology from the layer files. I have a similar procedure for importing stored Label schema so combining the two into a more dynamic solution would save me a lot of time.
Thanks


texts:
I've got this process I'm trying to automate that essentially iterates across a set of rasters, runs a con statement on them to put values from a separate raster wherever the first raster has certain values, save the max value of that new raster in a dictionary and finally save the new raster to disk.

Here's a reprex, then I'll explain some issues:

import arcpy, os
from arcpy import env
from arcpy.sa import *

path = r"C:\GIS\CMP\test"
outName = 'test.gdb'
riskMax = {}

arcpy.env.workspace = path
arcpy.env.addOutputsToMap = 0
print("Creating test.tif")
test = arcpy.CreateRandomRaster_management(path, 'test.tif', 'NORMAL 3.0', '0 0 500 500', 50)

print("Creating file geodatabase")
arcpy.CreateFileGDB_management(path, outName)

gdb = os.path.join(path, outName)
arcpy.env.workspace = gdb

for i in range(10):
    name = 'rand' + str(i)
    print("Creating " + name)
    arcpy.CreateRandomRaster_management(gdb, name, 'NORMAL 3.0', '0 0 500 500', 50)

try:
    for ras in arcpy.ListRasters():
        print('Running Con')
        riskProd = Con(Raster(ras) > 0, test)
        print('Storing max value')
        riskMax[ras] = riskProd.maximum
        outName = os.path.join(gdb, "{0}_{1}".format('out', ras))
        print("Saving " + outName)
        riskProd.save(outName)
except Exception:
    e = sys.exc_info()[1]
    print(e.args[0])
    arcpy.AddError(e.args[0])

So if you run this in the python window, you should get the ERROR 000732 mentioned in the title specifically for the SECOND rand raster.  So it makes it through the first iteration of the for loop in the try block, but it fails on the Con() statement the second time through.  I've identified two workarounds for this problem, but I want to understand why it is happening.

First, if you set

arcpy.env.addOutputsToMap = 1

this prevents the error.  It completes the loop just fine and creates all the out_rand rasters successfully.

The other option, which is weirder to me, is that AFTER the Con() call, if you just save riskProd to the dictionary instead of riskProd.maximum, that works as well. Then you can just call

Raster(riskMax[ras]).maximum

later to retrieve the max value.

Can someone explain what is causing this error?

Why can I not Con() a raster if it hasn't been displayed?

I want to be able to prevent adding outputs to the map, and it's cleaner (and uses less memory) to save the max value in a dictionary, rather than saving the entire rasters and extracting attributes later.

Note: in other tests, rasters that have been displayed, but are not currently in the table of contents still pass Con() just fine and it will fail on the first raster it encounters that has not been displayed yet.  I had mixed results with calculating pyramids for a raster that hasn't been displayed.  Sometimes it helped, sometimes it didn't.


texts: Using qgis:lineintersection in QGIS console?

texts:
console usage for qgis:lineintersection processing tool has been given as below

processing.runalg('qgis:lineintersections', input_a, input_b, field_a, field_b, output)

and i loaded a polyline layer onto qgis and executed following commands in console

layer = qgis.utils.iface.activeLayer()

provider = layer.dataProvider()

columns = provider.fields()

id=columns[0]

processing.runalg('qgis:lineintersections', layer, layer, id, id,'output' )

lineintersection tool is working properly when i use it directly in qgis, but i want to execute it in console for which i m getting error as below .......

  Traceback (most recent call last):   File "", line 1, in
     File
  "C:/PROGRA~1/QGISWI~1/apps/qgis-ltr/./python/plugins\processing\tools\general.py",
  line 71, in runalg
      alg = Processing.runAlgorithm(algOrName, None, *args)   File "C:/PROGRA~1/QGISWI~1/apps/qgis-ltr/./python/plugins\processing\core\Processing.py",
  line 317, in runAlgorithm
      if not param.setValue(args[i]):   File "C:/PROGRA~1/QGISWI~1/apps/qgis-ltr/./python/plugins\processing\core\parameters.py",
  line 676, in setValue
      elif len(value) > 0: TypeError: object of type 'QgsField' has no len()

i think problem is with passing values in function

Can anyone give the solution?


texts: QGIS Identify feature Cartesian area in degrees

texts:
In QGIS 3, the identify feature tool automatically calculates area.  However, there are two areas: Cartesian and ellipsoid.  The first is being calculated in degrees (not wanted) and the second in hectares (as set in settings).

How can I set the units for the first one (Cartesian) in hectares?  I have already set hectares in project settings.


texts: How to maintain integrity between changing street network and geocoded points?

texts:
We maintain hundreds of thousands of points geocoded against a dual-centerline Navteq street network. We are faced with the challenge of maintaining referential integrity between our points and the street network, which changes with each Navteq update. A high percentage of our points are geocoded manually, so we can't just run them again through an automated geocode process.

Some points are geocoded by street address, others by distance and direction from an intersection, still others by GPS coordinates. In each case we need to retain the closest possible match on the updated street network.

I solved this problem once before on a single-centerline network, using linear referencing, geocoding, and snapping techniques, but the process was very rigid and brittle. (See http://thewyvern.co/Thesis.final.pdf for details.)

Has anyone else confronted this problem? Do you have any suggestions? Can you point to any research out there that could help us develop a robust solution?

For context: we are using a custom geocoding algorithm coded in ArcObjects, which relies only partly on ESRI's Locator class. Our system is based on ArcGIS Server 9.3.1, with data stored in ArcSDE 9.3.1 on Oracle. Navteq data is delivered in shapefile format.


texts: Selecting by location using cursor layer

texts:
I am trying to run a script which for each row in an attribute able of catchment-shapefile select points from postal shapefile that fall inside the area of the selected catchment row feature.

Here is my script. I am having an issue where it does not select features correctly I end up with an exact copy of the original postal shapefile. I cannot see why this is happening.

import os, arcpy
arcpy.env.overwriteOutput = True
postal = r"U:\fwd_sept16\postal2_fz2.shp"
catchment = r"H:\Documents\robgis\fwd Data\properties_catchment.shp"
infield = "catch"
outname = r"U:\fwd_sept16"

arcpy.MakeFeatureLayer_management(postal,"temp")
with arcpy.da.SearchCursor(catchment, "catch") as cursor:
    for row in cursor:
        #SELECT PROPERTIES BY CATCHMENT
        arcpy.SelectLayerByLocation_management("temp","INTERSECT",catchment,"","NEW_SELECTION")
        #OUTFIELD NAMEING
        outFeature = outname + "\\" + row[0]
        #COPY SELECTED FEATURES
        arcpy.CopyFeatures_management("temp", outFeature)
        print row[0]


texts: Error when creating new view using ST_Union (PostGIS)

texts:
I have a table in PostGIS (2.1.7) containing adjacent multipolygons, and I'd like to create a view containing polygons which are merged versions of the multipolygons based on some field value.

I tried the following query:

CREATE VIEW results AS
SELECT somefield, ST_Union(geom)::geometry(Polygon, 2056) AS geom FROM somelayer GROUP BY somefield;

and I got the following error:

  Geometry type (MultiPolygon) does not match column type (Polygon)

I thus tried to change the result type to multipolygon:

CREATE VIEW results AS
SELECT somefield, ST_Union(geom)::geometry(MultiPolygon, 2056) AS geom FROM somelayer GROUP BY somefield;

But it didn't help since I got the following error:

  Geometry type (Polygon) does not match column type (MultiPolygon)

The following query finally worked but it is not optimal since I'd like to have polygons instead of multipolygons (it should be possible since the resulting polygons are all singlepart):

CREATE VIEW results AS
SELECT somefield, ST_Multi(ST_Union(geom))::geometry(MultiPolygon, 2056) AS geom FROM somelayer GROUP BY somefield;

How can I get the desired results?


texts: Multiplying respective cell values from two different raster layers

texts:
I am very new to GIS, I have two raster layers and a shapefile. I need to:

Multiply the respective cell values of both raster layers and then store final value into a new raster. So, I found a function called overlay and used this code:

from osgeo import gdal
ds = gdal.Open("CEC_sd3_M_02_apr_2014_bbclip.tif")
ds1 = gdal.Open("BLD_sd3_M_02_apr_2014_bbclip.tif")
zeroRaster <- overlay(ds,ds1 fun=function(x,y){return (x*y*300000)})

But I end up getting syntax error, I know there is something wrong with this, but was not able to figure it out
Error Message:

Traceback (most recent call last):
  File "<input>", line 1, in <module>
  File "c:/users/lenovo/appdata/local/temp/tmp9tzawc.py", line 7
    zeroRaster <- overlay(ds,ds1 fun=function(x,y),{return(x*y*300000)})
                                   ^
SyntaxError: invalid syntax
execfile(u'c:/users/lenovo/appdata/local/temp/tmpng20xy.py'.encode('mbcs'))
Traceback (most recent call last):
  File "<input>", line 1, in <module>
  File "c:/users/lenovo/appdata/local/temp/tmpng20xy.py", line 7
    zeroRaster <- overlay(ds,ds1 fun=function(x,y){return (x*y*300000)})
                                   ^
SyntaxError: invalid syntax


texts: Error importing shapefile to database even if the connection is successful

texts: Recently I have installed shapefile import export plugin in pgadmin3. I need to import shapefile in my database but I can't. Connection to database was also successful but unfortunately the error message is as follows:


texts: Qgis Plugin development with postgres data

texts:
can someone help me with initial developing on qgis plugin that displays postgres data table on a QTTableView or QTTableWidget?

So far:

I can connect to database using psycopg2 or using QtSql(tested inside QGIS console)
Using idle i can't because it does not load the QPSQL drivers...although i have them on my qt binary install.
I'm using pluginbuilder for initial setup, but i don't know how to get a reference to my tablewidget, to pass data from sql query.
Using IDLE i can draw a form with a tablewidget that is filled with data from sel query.

I already read this question :(but still have doubts...)

I need help putting things together.

Thanks for reading.

UPDATE:
 In here if i run from terminal i can fill a qtablewidget with sql data:
http://pastebin.com/Lm6GsUMk

I want to draw a widget like this inside a qgisplugin.
My Plugin(TestPlugin) was buit with plugin builder, asnd inside my ui_testplugin.ui, i have a QtTableWidget draw with QtDesigner and compiled using a generated makefile.
I know that i have to insert logic inside testplugin.py, inside run block, but i don't know to get a reference to QtTableWidget.

Hope this makes it clear.
Thanks.


texts: ArcGIS REST API requesting features over the dateline

texts:
I'm trying to get ArcGIS REST API Feature Server layers working on a map application. I'm trying to query a feature server using a bbox extent or the esriGeometryEnvelope going with their documentation here https://developers.arcgis.com/rest/services-reference/query-feature-service-.htm
The [xmin, ymin, xmax, ymax] format.
With the requests themselves looking a little like this in the network console: https://sampleserver6.arcgisonline.com/arcgis/rest/services/EmergencyFacilities/FeatureServer/0/query?f=geojson&inSR=4326&outSR=4326&geometryType=esriGeometryEnvelope&geometry=%7B%22xmin%22:-135.5059441708454,%22ymin%22:26.15237520400559,%22xmax%22:-100.1189675144052,%22ymax%22:39.37701094586817,%22spatialReference%22:%7B%22wkid%22:4326,%22latestWkid%22:4326%7D%7D
Having an extent over the dateline is causing errors because the xmin/xmax value are off. Since say xmin is close 180 while the xmax is -180 since it's crossing the dateline. For example this request.
https://sampleserver6.arcgisonline.com/arcgis/rest/services/EmergencyFacilities/FeatureServer/0/query?f=geojson&inSR=4326&outSR=4326&geometryType=esriGeometryEnvelope&geometry=%7B%22xmin%22:169.36619488161068,%22ymin%22:9.5965433698799,%22xmax%22:-40.819711707314596,%22ymax%22:63.589712748663146,%22spatialReference%22:%7B%22wkid%22:4326,%22latestWkid%22:4326%7D%7D
One solution may be to split the bbox extent into two as detailed here: https://community.esri.com/thread/222404-retrieving-map-extent-across-180
That would though require extra logic to check for that and sending two backend requests to the ArcGIS REST API.
However is there a way with ArcGIS REST API to change the query params so that it can handle when the extent is over the dateline? Can I get around the problem without sending two requests to ArcGIS?


texts: How to cut a raster with a polygon, but I'm interested in what remains after cutting?

texts:
I am using QGIS 2.14.

What I have: A raster file and a polygon.
What I need to do: Cut the raster using the polygon.

Important: But I want to keep the remaining part of the raster from which the polygon has been cut. Basically, I want to make a hole on a raster, shaped like the polygon.


texts: Drawing a shape on an image with matplotlib

texts:
From a polygon shape I create a square buffer to create a sattelite image of my location.
The shape is defined as a .shp file that I read with geopandas.
I'd like to display the image AND the shape on the same graph using matplotlib, the finale result should look like that :

I manage to display and stretch the image on a matplotlib figure
with rio.open(file) as f:
    data = f.read([1, 2, 3], masked=True)

    bands = []
    for i in range(3):
        band = data[i]
        h_, bin_ = np.histogram(band[np.isfinite(band)].flatten(), 3000, density=True) #remove the NaN from the analysis

        cdf = h_.cumsum() # cumulative distribution function
                    cdf = 3000 * cdf / cdf[-1] # normalize

        # use linear interpolation of cdf to find new pixel values
        band_equalized = np.interp(band.flatten(), bin_[:-1], cdf)
        band_equalized = band_equalized.reshape(band.shape)

        bands.append(band_equalized)

    data = np.stack( bands, axis=0 )

    data = data/3000
    data = data.clip(0, 1)
    data = np.transpose(data,[1,2,0])

    i = year - start_year
    ax = axes[getPositionPdf(i)[0], getPositionPdf(i)[1]]
    ax.imshow(data, interpolation='nearest')
    #[...] unrelevant display customization

But I don't know how to display the shape on top of it. Does anyone know how to perform this trick?


texts: Is there a way to hide passwords from the ToC from WFS layers in QGIS?

texts:
So I have layers in WFS format being served from Geoserver for different users to be used in QGIS.

Problem is that every single layer shows the login and password for geoserver in 2 places:

the table of contents when moused over
in properties > general > layer source as shown below

Is there a way to block it from showing?


texts: Creating IDs for multiple features in Python Parser of ArcGIS Field Calculator?

texts:
Does anyone know how to create ID numbers for multiple features using python?

For example; (IDs being the object ID, Name and object ID being two different fields)

Names //// IDs

Street 01

River 02

Mountain 03

Hill 04

Names //// Desired IDs;

Street 01

River 01

Mountain 02

River 02

I was hoping to write a code in the Python Parser of the field calculator, as I have over 3 thousand points, every three needing the same ID. I need to have each three consecutive entries given the same numeric ID, in a new field.


texts: R.Watershed unable to process a large geotiff (dem) file

texts: I have a large geotiff file (dem) that I am planning to use with r.watershed to delineate a very large drainage basin.  The file is 142 GB. When I try to run r.watershed after a few second it gives me error messages (ex: unable to write ...).  I tried a different approach by clipping a small portion of the geotiff and run r.watershed again.  This time r.watershed runs properly, and all the support output files are created.  My question, is there a way to process a large geotiff in r.watershed?


texts:
Total QGIS newbie here.

I installed 2.16.2 on a Dell Optiplex GX260 with Pentium 4 @ 2.4 or so Ghz, 2GB RAM.  30-something GB free on the hard disk after installation.

I started up the QGIS "desktop" (without GRASS) and tried to navigate to a folder containing ESRI shapefiles I wanted to edit.  QGIS hangs up, apparently trying to open the directory, with a rotating "wait" icon on the directory.  According to Task Manger, CPU use is pegged at 100%.  Memory useage is at 859MB so I assume disk-swapping due to insufficient RAM isn't the problem.

I tried exiting the application normally, but qgis-bin.exe remained running, still pegging the CPU.  Closing this module from task manager finally lets CPU usage return to the minimum.

Then if I re-start QGIS desktop, it makes an uncommanded return to the rotating wait icon on the same directory I previously tried to open.  CPU usage goes back to 100% and stays there.

What should I try now?  Is CPU speed the issue?  Should I re-install on a faster one?


texts:
I have the windows installation of python 2.7 that came with arcgis 10.2.  In my linux installation of python, I've become fond of other packages, and I'd like to incorporate them into the windows python.  I went through the steps to install pip, and I've got pip working in c:\python2.7\scripts.  But, each time I try to pip install anything (run from that Scripts directory), it fails (with various errors, mostly not finding certain files).

On the other hand, I've used package managers like Canopy or Anaconda, but I don't know how to get arcpy into one of those.

I surely don't quite have the hang of site-packages, dist-packages, paths and environments, particularly in Windows.

Has anyone done this successfully, and can you summarize your steps?


texts: When buton clicked, open new window - pyqgis

texts:
I'm making a plugin which has two windows. What I want to know is how to refer pushButton in one window to method which opens new window.

I have dialog *.ui files for both windows and their *.py. Should I have a method in my main_plugin.py file which opens new window? Should I have two classes in my main_plugin.py file or should I make a new file for new window 'body'? Is there anything else I should take into consideration?

Maybe someone have a code with similar button-window connection?

EDIT:
I tried to do it like dmh126 said, but something is still wrong. Here is my code I what had I changed:

plugin_dialog.py:

import os
from PyQt4 import QtGui, uic

FORM_CLASS, _ = uic.loadUiType(os.path.join(
    os.path.dirname(__file__), 'Symbolizacja_dialog_base.ui'))

class SymbolizacjaDialog(QtGui.QDialog, FORM_CLASS):
    def __init__(self, parent=None):
        """Constructor."""
        super(SymbolizacjaDialog, self).__init__(parent)
        # Set up the user interface from Designer.
        # After setupUI you can access any designer object by doing
        # self.<objectname>, and you can use autoconnect slots - see
        # http://qt-project.org/doc/qt-4.8/designer-using-a-ui-file.html
        # #widgets-and-dialogs-with-auto-connect
        self.setupUi(self)

plugin_config_dialog.py:

import os
from PyQt4 import QtGui, uic

FORM_CLASS, _ = uic.loadUiType(os.path.join(
    os.path.dirname(__file__), 'Symbolizacja_dialog_ustawienia.ui'))

class SymbolizacjaConfigDialog(QtGui.QDialog, FORM_CLASS):
    def __init__(self, parent=None):
        """Constructor."""
        super(SymbolizacjaConfigDialog, self).__init__(parent)
        # Set up the user interface from Designer.
        # After setupUI you can access any designer object by doing
        # self.<objectname>, and you can use autoconnect slots - see
        # http://qt-project.org/doc/qt-4.8/designer-using-a-ui-file.html
        # #widgets-and-dialogs-with-auto-connect
        self.setupUi(self)

plugin.py:

in main class (Symbolizacja):

from Symbolizacja_dialog import SymbolizacjaDialog
from Symbolizacja_config_dialog import SymbolizacjaConfigDialog

in def init(self, iface):

self.dlg.pushButton.clicked.connect(self.handleButton)

added new method:

def handleButton(self):
        self.sc = SymbolizacjaConfig(self)
        self.sc.show()

added new class (at the end):

class SymbolizacjaConfig(QtGui.QWidget):
    def __init__(self, parent):
        super(SymbolizacjaConfig, self).__init__(parent)


texts: is it possible to obtain layerInfo from the Layer's URL

texts:
I am trying to fetch the names of the layers in the MapService, so that I can populate them in the dijit.form.select. I am able to get the layerInfo when the ArcGISDynamicMapServiceLayer is added to the map by using,

map.getLayer(map.layerIds[0]).layerInfos[0].name

But this is only after the layer has been added to the map. Is there some way by which I can get the layerInfo names directly from the URL?


texts:
I am trying to merge two rasters using the "merge" tool on Qgis 2.6.
Qgis does complete the process, but the resulting image only shows one of the two rasters with the rest of the extent with really negative values (black)...
Is there another way to merge?
I added a screenshot of the dialogbox/configuration and one of the resulting raster.


texts: PgRouting Driving Distance crashing postgis server

texts:
I haven't used PgRouting much so I'm a little in the dark here.  However, I am attempting a driving distance calculation like the one described by Underdark here.

My SQL is identical, I have a routable network etc etc.  I have also successfully run this in the past on another database.  However, when I run the simple piece of sql below, it completely crashes the Postgresql server with no error other than connection to server has been lost:

SELECT * FROM driving_distance('
      SELECT gid AS id,
          start_id::int4 AS source,
          end_id::int4 AS target,
          shape_leng::float8 AS cost
      FROM network',
      494902005,
      50000,
      false,
      false)

I first spotted the crash when trying to run this from Python.  I restarted the computer and tried to run the stripped down version above from PGAdmin.  It still crashes.  BTW the '494902005' value is my node id and I want to limit the search to 50km.  Because I am not getting any feed back, I don't know where to start diagnosing the issue.  I am using PostGIS 2/PostGreSQL 9.1 on 32bit Windows 7.

Any ideas gratefully received!


texts: Programatically write values to ArcPad Form control box

texts:
Using this blog post I've managed to store user names as global variables in ArcPad.  The next step is to use those variables in form 'controls' aka form fields.

Per the author's comments under his original quote I've attempted to go this route:

  If you are writing the value to a field that is linked to a control on the form, set the control value:
  pForm.Pages("PAGE1").Controls("EMPLOYEE").Value =
  Application.UserProperties("LoggedInEmployee")

Unfortunately I'm not getting anything written into the field when I open the form (this is an onLoad event handling script).  I'm not getting an error message at this point, and the value in the control box is changing from  to being totally empty.

I have managed to 'echo' or 'alert' back the user-name with Application.MessageBox Application.UserProperties("LoggedInEmployee") associated with an onUnload event, so I know that it's stored properly.

Any Ideas?


texts: TinyOWS on IIS 7.5 as FastCGI does not see GET query string?

texts:
I'm trying to set up TinyOWS on IIS 7.5 as a FastCGI application.

I've got the binary allowed in 'ISAPI and CGI restrictions', configured the handler for my virtual directory, set the TINYOWS_CONFIG_FILE environment variable for the TinyOWS FastCGI application.

The problem is, if I send some basic HTTP GET request like

http://localhost/[path to my virtual dir]/tinyows.exe?SERVICE=wfs&REQUEST=GetCapabilities&version=1.0.0

The response is always an ows:ExceptionReport with:

<ows:ExceptionText>Service Unknown</ows:ExceptionText>

If I configure tinyows to log everything the logfile looks like this:

[Fri May 09 16:10:42 2014] [EVENT] == FCGI START ==
[Fri May 09 16:10:42 2014] [QUERY] (null)
[Fri May 09 16:10:42 2014] [ERROR] Service Unknown
[Fri May 09 16:10:44 2014] [QUERY] (null)
[Fri May 09 16:10:44 2014] [ERROR] Service Unknown

So it seems like the QUERY_STRING environment variable is not set properly for the FastCGI.

Quick search in TinyOWS source on Github seems to confirm this: https://github.com/mapserver/tinyows/blob/38510100f539a80b26f707dcc0c458982050f9a6/src/ows/ows.c#L382

Most probably i just misconfigured IIS in some way... Does anybody have some idea?


texts: Can ArcGIS Server 10.4 be configured to include the bbox property in the GeoJson response?

texts:
I am querying a map service for a GeoJson format and the GeoJson FeatureCollection geometries from ArcGIS Server 10.4.1 do not include the bbox property.

Is it possible to configure this, either as an ArcGIS server configuration or in the query request i

I am getting this:

{
    "type": "Polygon",
    "coordinates": [[[...]]
}

But want this:

{
    "type": "Polygon",
    "bbox": [...],
    "coordinates": [[[...]]]
}

Further clarification:

  The  query request itself has no spatial conditions.  Basically, I'm
  looking to return the same format as the PostGIS ST_AsGeoJSON
  http://postgis.net/docs/manual-2.2/ST_AsGeoJSON.html with option 1.


texts: While performing run / previewing classified image in SCP, the statement Information [18]: Select at least one signature appears. What is the solution to this?


texts: How to pass an extent parameter to a Processing algorithm in PyQGIS?

texts:
I want to convert a point shapefile to a raster with the same extent and resolution as an input raster using the algorithm saga:shapestogrid.
When I run this code:

##Sampled_trees=vector
##Input_field= field Sampled_trees
##Elevation_model=raster

from qgis.core import *
from PyQt4.QtCore import *

inputTrees= processing.getObject(Sampled_trees)
inputField = inputTrees.fieldNameIndex(Input_field)
dem = processing.getObject(Elevation_model)

result = processing.runalg('saga:shapestogrid', inputTrees, Input_field, 0, 0, 4, dem.extent(),  dem.rasterUnitsPerPixelX(), path)

I get the error: Error: Wrong parameter value: qgis._core.QgsRectangle object at 0x0000000019F287B8

If I add or remove any parameter, the error will be Error: Wrong number of parameters.

The documentation gives the following syntax:
processing.runalg('saga:shapestogrid', input, field, multiple, line_type, grid_type, output_extent, user_size, user_grid)

How should I define the output_extent parameter to make the algorithm to run?


texts: Static images not appearing in OpenLayers 3?

texts:
I am developing an application using OpenLayers 3 with a choice of base layer, overlay layer, and feature (vector) layer, and it seems to be going well. You can see the prototype system at http://mapping4ops.org/ShowMaps/M4OPS-index.html. Switching base layers, overlay layers, and vector layers work OK.

I now want to add two images (dated 1764 and 1847) as overlay layer options.

I have georeferenced these images in QGIS using the georeferencer plugin, and they both look good in QGIS. However when I try to load them in OpenLayers 3 they are not appearing. One of the images I reduced in size with GDAL JPEG compression, and the other I chose the LZW compression option. I used Filezilla to copy the files to my web server.

I have checked the extents,and everything else I can think of, as well as put in console.log statements to try and examine the layer in detail, but I cannot get either image to appear at all. All the previous layers I have added (tiled and vector) have worked fine.

There are no errors flagged in the console.

To make diagnosis easier I have created a very simple one layer map for the 1747 image, and this shows the same lack of image. You can see it at http://mapping4ops.org/ShowMaps/testing/Static%20Image.html.

I am fairly new to the geo world.


texts: Overlay AutoCAD drawing on QGIS desktop shapefiles

texts: I have sewerage network data in shapefiles. I want to overlay with drawing.dwg file so i can update shape files in QGIS. How to directly open drawing.dwg file in QGIS desktop?


texts: Inconsistencies in R rasterize polygons, packages raster and sf

texts:
I was trying to calculate species richness from IUCN distribution data in R, and I decided to check my results with two different methods, both of which rely on rasterize function from the raster package.

The simplest method consists in counting the number of species in each grid cell by using the length function in rasterize (it is actually described in rasterize help as an example to be used to calculate richness).
A slightly more complex method consist in rasterizing each species polygon into presence-absence rasters, and then summing all rasters to obtain a species richness raster.

However, I ran into minor inconsistencies in the results, and I am not able to figure out why.

I paste below the code I used for these two methods. The dataset I used can be downloaded from the IUCN website here, download the Tailed amphibians dataset (25MB). The IUCN requires an account to download the data, I am sorry about that but I cannot find another way to make a reproducible example of this dataset (and I am not allowed to redistribute it).

Note that in this dataset, there can be multiple polygons for each species. Species names are in the column binomial of the IUCN dataset.

Data preparation

# Packages
library(raster)
library(sf)

# Reading the polygons
iucn_sf <- st_read("./data/IUCN data/CAUDATA.shp")
# Some data filtering
iucn_sf <- iucn_sf[which(iucn_sf$presence == 1), ]
iucn_sf <- iucn_sf[which(iucn_sf$origin == 1), ]
iucn_sf$binomial <- droplevels(iucn_sf$binomial)

# Creating a raster at the desired resolution
r <- raster(nrows=180, ncols=360, xmn=-180, xmx=180, ymn=-90, ymx=90,
            crs = "+proj=longlat +datum=WGS84 +no_defs +ellps=WGS84 +towgs84=0,0,0",
            resolution = 1, vals=NULL)

Method 1: rasterize species polygons into richness raster with length

This method is described in the rasterize documentation.

a <- rasterize(iucn_sf,
               r,
               field = "binomial",
               fun = function (x, ...) length(unique(na.omit(x))))
plot(a)

The maximum richness with method 1 is 26.

Method 2: rasterize each species into a presence-absence raster and then calculate the sum

pa.stack <- stack()
for(sp in levels(iucn_sf$binomial))
{
 # We rasterize the polygons of the current species into values of 1
 pa.stack <- addLayer(pa.stack,
                      rasterize(iucn_sf[iucn_sf$binomial == sp, ],
                                r,
                                field = "binomial",
                                fun = function(x, ...) 1))
}
# After the loop, we sum all presences to obtain the species richness
b <- sum(pa.stack, na.rm = T)
plot(b)

The maximum richness with method 2 is 25.

Differences between methods 1 and 2:

plot(a - b)

You can see that most of the results are the same, except for a few pixels where there can be a difference of 1 or 2 species. I do not understand where this difference comes from (is this a mistake in my code or a difference in the procedure?), which is why I turn to the wider community to seek advice.

I used R version 3.5.2, packages sf version 0.7-2 and raster version 2.8-4.


texts: Plotting a hyperbola, or, solving spherical triangles

texts:
I am trying to create a GeoJSON path containing lines of hyperbola, in order to recreate Decca Navigator charts in QGIS, something like this:

The chart has nine lines of hyperbola plotted between each master-slave pair of radio beacons labelled B to J, where the beacons are the focus points.

I've written a C++ program which parses the location of the radio beacons, and attempts to construct the lines of hyperbola as a series of GeoJSON lines, but my maths is wrong and the lines are drawn in the wrong place:

(The red line labelled J should be between the Master and Red beacons, not beyond Red.)

My approach to construct the lines is to plot a series of triangles, where two corners are the radio beacons, and the sides are a ratio of the baseline distance plus an offset. For instance the line labelled G crosses the baseline at 60% of the distance from the master to the slave.

for (auto line = 0; line < 10; line++) {
  std::vector<coord> pts;
  for (auto pt = -150; pt < 150; pt++) {
    if (pt != 0)
      pts.emplace_back(
          findHyperbolaPoint(masterCoords, slaveCoords, line * 0.1, abs(pt) * pt * -0.00005));
  }
  deccaLines.emplace_back(linestring(pts));
}

The findHyperbolaPoint performs these steps using handrolled spherical geometry functions:

Find arclength between Master and Slave
Calculate bearing from Master to Slave
Define the arclength of Projected from Master and from Slave
Calculate angle between Slave-Master-Projected and hence, the bearing from Master to Projected
Find the coordinates of Projected by travelling the Master-Projected arclength along that bearing

Evidently something is going wrong at step 5 as the projected point is drawn too far from Master:

coord ptFromBearingArc(coord origin, double bearing_rad, double dist_rad) {
  double lat, lon;
  lat = asin(sin(origin.lat) * cos(dist_rad) +
             cos(origin.lat) * sin(dist_rad) * cos(bearing_rad));
  lon = origin.lon + atan2(sin(bearing_rad) * sin(dist_rad) * cos(origin.lat),
                           cos(dist_rad) - sin(origin.lat) * sin(lat));
  return {lat, lon};
}

The formulas appear to be correct but evidently I've gone wrong somewhere. Update: this was due to a simple typo in a function. Which wouldn't have occurred if I'd used a library.

Does my approach look sensible? Are better approaches available for plotting hyperbolae in QGIS?

Are there straightforward lightweight C++ library for spherical geometry calculations and/or WGS84 calculations?


texts: Problems with interpolating in ArcMap 10

texts:
I would be extremely grateful if I can get help with this question. I can't find anyone who had a similar problem. I am trying to make a raster from point data. My data is in .txt form and contains of x,y,z; that is, coordinates and elevation. I have about 156000 points. So, these points are imported into ArcMap, showing up at the correct positions.

Now, for some reason I can't make these into a raster... WHATEVER tool I try (spatial analyst, 3D analyst...) nothing works! I just get an error 99999 code. I am really stuck on this one and no one seems to be able to help me!

Do you have any idea why?


texts: qgis2web - show specific layers in layer list

texts:
Is there a way to display specific layers in layer list when exporting map with qgis2web plugin? I have created a map with bunch of layers like roads, names of places, rivers etc. but i don't want this layers to appear on layer list. On the other hand I have layers like coffee shops, fast food restaurants, nightclubs and I want these layers on my layer list so I can toggle them on/off.
I'm using OpenLayers for export.


texts: Transfer spatial data between databases using pgAdmin4

texts:
I'm new to pgAdmin4 and performing tests before jumping in the deep end.

I've uploaded a large dataset into a the public schema within a database named 'spatial_db'. Rather than re-uploading the data to a new database through the DB Manager in QGIS, is there a way to transfer the spatial data in the public schema of the new database as shown below?

I'm conscious that moving the table alone, will only bring the attribute table across but perhaps I have this wrong, will it will bring the geometry across too?


texts: Find area with highest relative density of one type of object

texts:
I'm using PostgreSQL/PostGIS and I have an advanced type of query.

My database contains two types of object - let's say pubs and churches :)

Is there a way that I can find the area with the densest concentration of pubs compared to churches, and vice versa?

I can obviously display this visually with a heatmap, but I just wondered if there was a programmatic way to do this with PostgreSQL? Perhaps the point that is closest to the most churches relative to pubs?

Thanks.


texts: I have a 10-m resolution DEM, in the form of a .gdb. The "Value" field is in feet and cannot be edited. I am working with SWAT -- which uses the Band 1/Value field-- and assumes units are in meters. I have tried copying the raster and creating a new attribute table. Creating an additional field and converting from ft to meters will not work in this case as I have no way of selecting it as the elevation band. Any suggestions for creating a new DEM in which the units are in meters?


texts: basically i am trying to get out the direction and magnitude information of the current (flow/movement of water) information layer of a grib weather data file - which is a mesh in qgis terminology. I was following the instrucionts in Tutorial on using QGIS for marine data. the tools used there need a raster dataset for u and v components of the current. so far i have found information of how to transfer grib2 to geotiff. but the GDAL / raster analysis / translate function from Processing Toolbox doesn't seem to support mesh-data as input type. is there a straigth forward way within qgis to convert mesh into raster? or is there a way to display a u / v information from mesh as a vector field ?


texts: I am new to FME and need to perform an intersect with a specific cluster tolerance. In ArcGIS Pro you can set the cluster tolerance during an intersect (http://pro.arcgis.com/en/pro-app/tool-reference/analysis/intersect.htm) but I don't know how I can reproduce this in FME? The intersector does not have this option and there is no "cluster tolerance" transformer. Any suggestions?


texts: Calculate raster statistics for polygons in a polygon feature class

texts:
I have a DEM across my study area where symbology has been changed to show elevation changes in 100m intervals.

I have a polygon feature class where each polygon delineates a landslide.

My landslide polygons sit atop the DEM. Some of the polygons cross different elevations, e.g. part of the polygon is at 500-600m and the rest at 400-500m. I would like to calculate the proportion of the landslide polygon that lies in each bracket of the DEM. In the example: I would like to know what percentage of the polygon has elevation of 500-600m and what percentage has an elevation of 400-500m?
I read a previous question with a similar issue that mentioned using zonal statistics but I haven’t been able to work it out.

I am using ArcMap 10.3.1. I have the 3D Analyst and Spatial Analyst extensions.


texts: Displaying row and column indexes for image in ArcGIS DEsktop?

texts:
I have been struggling with how to  find the row number and column number for
particular points in any raster map.

My raster details:

columns and rows:  720 360
cell size (0.5, 0.5)

How can I know the row number and column number by pointing the cursor at any location in the map?


texts: In QGIS, how to group the days of a year every 15 days? I have a column with date values throughout 2018, I would like to create a new column identifying which group that date is in


texts:
I would like to display a circle object under the OSMbuildings layer with OSMBuildings
. I was trying to change zIndex, bringToBack(), bringToFront() but it doesn't work. I don't use my own GeoJSON data to create 3d buildings. Any help?


texts: Specifying input layer in custom QGIS function to rank features

texts:
How do I specify the input layer so it refers to the layer from which the function was called (without having to explicitly identify it by name)?

I have written a custom function to use in the expression editor. It returns the rank of each feature based on the specified attribute. For example, if I want to highlight the smallest 10 cities I can use an expression along the lines of: top_rank('citypopulation')<=10
to filter the top 10 ranked features.

The function sort of works, however, if I use it on different layers at the same time the outputs for each layer change. After some consideration, I think it might be due to using  aLayer = qgis.utils.iface.activeLayer() to specify the layer and that each time I select a new layer it changes aLayer throughout the project.

from qgis.core import *
from qgis.gui import *
from qgis.utils import qgsfunction
from qgis.core import QGis

# this line puts  function into 'Custom' group in the expression builder
@qgsfunction(args="auto", group='Custom')

# custom functions must take (fields,feature,parent as arguments)
# usage is : top_rank('attribute_name')
def top_rank(field, feature, parent):
    aLayer = qgis.utils.iface.activeLayer()
    target_field=feature.fieldNameIndex(field) # gets index of target field - checked
    f_id=feature.id() #gets target feature id - checked
    aList= [(feat[target_field], feat.id()) for feat in aLayer.getFeatures()]
    aList.sort()  # sort list of tuples
    i = 1
    row_index=0
    for feat in aList:
        if feat[1]==f_id:
            row_index=i
        i  += 1
    return(row_index)

(I initially asked this on Stack Overflow but I think it is more relevant here)

(Previously, I have written a function that adds a new column to the attribute table with rank based on an attribute but I don't want to have to add a new column containing the rank for each attribute individually.)


texts: Convert the polygon format with lat lon?


texts:
I'm hoping to run some Python mathematics on a raster, outside of ArcGIS. It's important to have a cell by cell table for the analysis I want to run. I plan to store it in a python dictionary similar to this:

Dict = {
    row1:[0,1,0,2,1,0,1,1,1,3],
    row2:[3,1,0,3,1,0,0,1,0,3],
    row3:[0,1,1,2,3,0,1,2,1,3]}

Obviously this is just and example, but this is what I want to turn my raster into. I always see these diagrams within the ArcGIS help:

And this is exactly what I would like out of a raster. I can easily go from a CSV to the dictionary I want, but I'm having trouble getting a raster to a cell by cell table.


texts: FME - Copying a full list of 'user attributes'

texts:
I'm new to FME, so just getting used to the interface.

I've loaded a template .fmw which has given me a full process, including an example 'Writer'. This writer is no use to me, and as I can't change it to PostGIS, I've created a new writer for the output. However, there is a really long list of attributes that need to be duplicated into the new writer.

Does anyone have any idea if there is a quick way to copy across multiple attributes from one writer to another?


texts: QGIS Python way to see if line is on top of another line

texts:
I want to be able to tell if a line from one layer is on top of a line of another line of a different layer. For example I want to see black lines are on top of the other lines in the image. My code is as follows:

from qgis.core import QgsVectorLayer, QgsMapLayerRegistry
from qgis.utils import iface
from PyQt4.QtCore import *

layers = iface.legendInterface().layers()

for layer in layers:
   name = layer.name()
   if "Black" in name:
      blacklayer=layer
   if "Color" in name:
      colorlayer=layer
blackFeatures=[feat for feat in blacklayer.getFeatures()]
colorFeatures=[feat for feat in colorlayer.getFeatures()]
for colorFeat in colorFeatures:
   for blackFeat in blackFeatures:
      if colorFeat.geometry().within(blackFeat.geometry()):
        print 'in'
    if blackFeat.geometry().within(colorFeat.geometry()):
        print 'in'

I am not sure if order of lines matters but I haven't gotten anything to work. I have tried within, intersects, overlap, contains, crosses, and touches but nothing seems to work. I have snapping on, so the black line is completely on the color line. Any idea on how to get this to work?


texts: QGIS: Show line ELEV on hover or select?

texts: I've installed the value tool plugin, but cannot figure out where it outputs. I tried map tips in qgis. How can I see the elevation of a line or selected point on hover or select?


texts: Creating perpendicular snapped polylines between an existing point and polyline using arcpy

texts:
Here's my situation - I'm working on a project that requires 20,000+ short connector lines be created, each drawn from a point to a snapped location on a nearby polyline such that the resulting connector line is perpendicular to the polyline.

If done with arcpy, this requires a script that can a.) find the nearest polyline, b.) calculate the place on that polyline that will enable a perpendicular line to be created, c.) create temporary coordinates at that location, and d.) create the connector line.

Has anybody tried something like this?  What specific commands might be necessary?  Thanks in advance for your help.

-Michael


texts: the renderering of mapcanvas is still active

texts:
i am working with qgis c++ api 2.8.2 and qt4.8.5
i want to disable the rendering during zoom in or zoom out fonction in order to have a fast zoom
i try to use :

MyMapCanvas->stopRendering();

and

MyMapCanvas->setRenderFlag(false);

before the call of zoomIn ou zoomOut method but the renderer seems to be already active

how can i disable it before a zoomIn or zoomOut operation ?


texts:
What database engine can be used for GE Smallworld?

I have poor information but I read about Smallword proprietary VMDS.

Is it possible to use Oracle or SQL Server?


texts: Creating a multiband raster from netcdf in R

texts:
I have a netcdf file of downward longwave radiation for the whole of China dated 1979 - December. It has got three dimensions namely: longitude , latitude and time. The file contains the data for every 3 hours, which means that for the month of December (31 days), there are 248 values of downward longwave radiation. I have listed the characteristics of the source netcdf file below:

 1 variables (excluding dimension variables):
    short lrad[lon,lat,time]
        scale_factor: 0.25
        add_offset: 685
        _FillValue: -32767
        missing_value: -32767
        units: W m-2
        long_name: Surface downward longwave radiation

 3 dimensions:
    lon  Size:700
        units: degrees_east
        long_name: Longitude
    lat  Size:400
        units: degrees_north
        long_name: Latitude
    time  Size:248   *** is unlimited ***
        units: hours since 1900-01-01 00:00:0.0
        long_name: Time

I have converted the nc file to raster using the following code:

lradin <- raster("lrad_ITPCAS-CMFD_V0106_B-01_197912.nc")

The internal raster attributes of the created raster object "lradin" shows the following information:

class       : RasterLayer
band        : 1  (of  248  bands)
dimensions  : 400, 700, 280000  (nrow, ncol, ncell)
resolution  : 0.1, 0.1  (x, y)
extent      : 70, 140, 15, 55  (xmin, xmax, ymin, ymax)
coord. ref. : +proj=longlat +datum=WGS84 +ellps=WGS84 +towgs84=0,0,0
data source : C:\Program Files\RStudio\bin\lrad_ITPCAS-CMFD_V0106_B-
01_197912.nc
names       : Surface.downward.longwave.radiation
z-value     : 1979-12-01 00:00:00
zvar        : lrad

The problem is that the attribute of the raster object "lradin" shows only one band of time, i.e. out of time size of 248, "lradin" is showing only 1 time size. This means that I will have to create 248 rasters (for every 3 hours) for the month of December.

Does anybody have idea about how to create the multiband raster that has all the time size of 248 in it ? So that I could have a single raster for the month of December ?


texts: Under what circumstances would the _DELETE trigger get called? (_EVW)

texts:
Oracle 18c/10.7.1 geodatabase:
When an FC is registered as versioned (with option to move edits to base), several triggers get automatically created:

V000001_DELETE
V000001_INSERT
V000001_UPDATE

When I look at the _DELETE trigger, I see that it belongs to the versioned view:
INSTEAD OF DELETE
ON MAXIMO.TEST_FC_EVW  --<<--- versioned view

If I delete a feature from the feature class while using the default version, the trigger does not get called.
Question:
Under what circumstances would the _DELETE trigger get called?


texts: Duplicated vertices in contour features of GRASS?

texts:
I use GRASS to produce contours from DEM (r.contours for SRTM rasters). They looks fine, but  most of the line features occures to be duplicated; i.e. verticies duplicated.
Here are pictures of output line (first) and line with some moved vertices (second) to make my problem more clear

This happens to contours, which are not closed.
So, they looks fine, but after generalization occure lots of artifacts, and this is unsuitable for relief visualisation.

Could somebody point out the reason of this duplication or offer a way to correct them?


texts: How to keep the georeferencing data from ArcGIS when importing rasters into Erdas imagine?

texts:
I have a bunch of WWII Aerial images that I georeferenced in ArcMap and when I load them in Imagine they are being displayed as plain rasters. I tried the Import Data tool, converted the georeferenced JPG files to IMG files, but still, when I load the IMG files, they do not keep their location.
Does anyone have a solution for this?


texts: Why does QGIS treat NULL values in VARCHAR columns as real data?

texts:
We've noticed in QGIS (v. 3.8.1) that VARCHAR columns from PostgreSQL(v9.5) containing empty values are being read as the text value of the word "NULL".

Here's the data in QGIS (highlighted records are VARCHAR, the other one is integer):

And here's the same data for the same record in DBeaver:

You can see that DBeaver treats the NULL values as empty, while QGIS treats the same empty data as the word NULL.

This is an issue for a number of reasons, but came to our attention when trying to filter a set of data in QGIS using a WHERE COLUMN_NAME LIKE 'N%' - we were looking for values referring to NO/NON/N but ended up picking up all the NULL values as well!


texts: Can I filter a subset of the polygons without affecting the rest of the polygons in QGIS?

texts:
When using QGIS 3.10, I often filter out unneeded features to create my maps. Is there a way for me to filter a subset of the polygons without affecting the rest?
For example: The shapefile I have contains states and counties as of 1860. All of the polygons have a STATE attribute and a COUNTY_TYPE attribute. For South Carolina, I need to show polygons with "COUNTY_TYPE" = 'District,' but all other states need to show polygons with "COUNTY_TYPE" = 'County' (based on my data). I tried using an if/then operation in Query Builder, but this showed me only SC and eliminated the other states.
Can I filter the map to affect only SC while keeping the other states the same?


texts:
I have two tables both of them has linestring geometry. I try to make a new one which contain the first one and from the second take only the decimal v when the linestring of the first table touch a linestring of the second.

CREATE TABLE Three AS(
SELECT st_astext(r.geom),e."v" FROM r , e WHERE ST_Touches(e.geom, ST_Transform(r.geom,4326)));

But i am not take an error or a result , the geom of r is in another srid than the 4326 which is the e and i transform it.


texts: How to snap line string start & end vertex to the nearest point?

texts:
I have a point layer and a line layer. The points are road junctions, collected using DGPS, while the lines are the connecting roads, collected through Handheld GPS in tracking mode. As a result, the lines are not actually connected to the points.

Now I want to:

Remove all intermediate nodes from each line string, to make it a straight line.
Snap the start & end vertex of lines to the nearest points.

I am using PostGIS 2.0.This by far what I have done:

UPDATE line
SET geom = ST_Simplify(geom, 1000);

Q. Is there any other better way to accomplish it?(Since I am using an absurd tolerance)

UPDATE line
SET geom = ST_AddPoint(
(SELECT geom FROM line WHERE id = 1),
(SELECT p.geom FROM point AS p, line AS l
    ORDER BY ST_Distance(p.geom,(SELECT ST_StartPoint(l.geom) FROM lt WHERE l.id=1)) LIMIT 1),
0)
WHERE id=1;

This will extend the line(with id=1) to the nearest point(point added at the beginning of the line).

Q. The above looks a bit complicated, is there any other efficient method/function available?


texts: Sample random points on the borders of the US states with sf package

texts:
I want to sample points (latitude-longitude pairs) on borders of the US states, or points close to borders. With the following code, I am able to sample points in an example multipolygon. How can I do this on the borders instead?

library(sf)
nc = st_read(system.file("shape/nc.shp", package="sf"))
plot(nc$geometry[1])
plot(st_sample(nc$geometry[1], 1000))


texts: Fill fields in PDF with python from final product of Model Builder

texts:
I am trying to fill a PDF file from a Excel file data produced by a Model Builder after GIS processing with ArcMap. I am using the Python language.

I consider that using a PDF form is the most appropiate way to carry out this task (use the Excel values to fill the fields of the PDF form)

I show an image of what I am trying to do. The reason to use python (I saw a code in VB) is that I want to connect the script of Model Builder with the script of this task (reading excel file and export values to the PDF form)

Which Python packages are the most suitable for this task?


texts: Count number of vertices in a shapefile using OGR

texts:
I'd like to extract the total number of vertices in a shapefile using command-line OGR.

This answer suggests a method for intersections, but it isn't clear how to cross-apply it.

Many other methods suggest writing little Python scripts, but this seems like a needlessly complex solution.


texts:
I am trying to set up a daily water and cloud detection system and need to use a high temporal resolution. Therefore I intend on using daily MODIS imagery (MOD09GQ). In the water detection, cloud shadows interfere with the image. Question:

Is there alternative (daily) method (e.g. MODIS band combination) or image collection, which could work in combination with the 250m daily MODIS imagery to distinguish cloud shadows and surface water?

Code:

var modis = ee.ImageCollection("MODIS/006/MOD09GQ"),
aoi = /* color: #d63000 */ee.Geometry.Polygon(
    [[[1.95556640625, 6.782807298156471],
      [1.966552734375, 6.127810565018445],
      [2.757568359375, 6.127810565018445],
      [2.74658203125, 6.804625672985183]]]);

// center image on aoi
Map.setCenter(2.44720458984375,6.443588525393941, 10); // Lake Nokoue

// Select the image
var image = ee.Image(modis.filterDate('2017-12-03','2017-12-05').filterBounds(aoi).first());
print('A MODIS Scene', image);

// Retrieve the timestamp and convert it to a date
var date = ee.Date(image.get('system:time_start'));
print('TIMESTAMP MODIS: ', date);

var bands_normal_2 = {
  bands: ['sur_refl_b02'],
  min: 0,
  max: 10000
};

var bands_normal_1 = {
  bands: ['sur_refl_b01'],
  min: 0,
  max: 4000
};

var bands_clouds = {
  bands: ['sur_refl_b01'],
  min: 1000,
  max: 4000
};

var bands_water = {
  bands: ['sur_refl_b02'],
  min: 0,
  max: 1500
};

Map.addLayer(image, bands_normal_2, 'MODIS image b02');
Map.addLayer(image, bands_normal_1, 'MODIS image b01');
Map.addLayer(image, bands_clouds, 'Clouds MODIS');
Map.addLayer(image, bands_water, 'Water MODIS');

Surface water and cloud shadow

Normal surface reflectance image


texts: How to do a Lee’s Tetrahedral Conformal Projection of Antarctic/South pole on QGIS?

texts: I want to do map of Antarctic using the Lee's Tetrahedral conformal map projection as the image below using QGIS version 3.4. Is it possible to make a custom CRS to do it? If yes, what's the parameters?


texts: TinyOWS failing to connect to postgresql - Ident authentication failed for user "postgres"

texts:
I'm getting the above error on a new and local TinyOWS installation on Centos 6. Postgresql 9.2, PostGIS 2.0.
I can connect to PostGreSQL locally and from my LAN using several other methods (psql, QGIS, PgAdmin). I've fiddled around with pg_hba.conf so it currently looks like this:

# TYPE  DATABASE        USER            ADDRESS                 METHOD

# "local" is for Unix domain socket connections only
local   all             all                                     md5
# IPv4 local connections:
host    all             all             127.0.0.1/32            md5
host    all             all             192.168.0.10/20         md5
# IPv6 local connections:
host    all             all             ::1/128                 ident
# Allow replication connections from localhost, by a user with the

and /etc/tinyows.xml is like this:

<tinyows online_resource="http://127.0.0.1/cgi-bin/tinyows"
 schema_dir="/usr/local/share/tinyows/schema/"
     log="/var/log/tinyows.log"
     log_level="15">

<pg host="localhost" user="postgres" password="*****" dbname="tinyows_demo" port="5432"/>

<metadata name="TinyOWS Server"
    title="TinyOWS Server - Demo Service" />

<layer retrievable="1"
 writable="1"
 ns_prefix="tows"
 ns_uri="http://www.tinyows.org/"
     name="world"
     title="World Administrative Boundaries" />

<layer retrievable="1"
 writable="1"
 ns_prefix="tows"
 ns_uri="http://www.tinyows.org/"
     name="france"
     title="French Administrative Sub Boundaries (IGN - GeoFLA Departements)" />

</tinyows>

bit puzzled as to why it's using ident

Can anyone help?


texts: Creating parallel lines at particular distance from lines which are part of a shapefile

texts: I am using QGIS 2.18 . I have shapefile which contains multiple lines. After processing certain data processing , I need to draw parallel lines at different distances from existing lines. For example I have 32 lines in existing shapefile. I want to draw parallel lines at distance of 50, 100, 170, 500,400 from line ID no. 3 ,6,20,25,31 in one go. Is there any method or plugin in QGIS for doing same?


texts: Feeding GTFS files to OTP server without restarting it?

texts:
I am new to OTP. AS far as I know, you would have to restart OTP server each time to feed new GTFS files. Meaning, each time when you get a new set of GTFS files, you would have to re-run the OTP server.

Is my understanding correct and, if not, how would you feed new files to the server without restarting it?

The reason I am asking this is, I am planning to use OTP server in a kubernetes cluster.


texts:
I have a GeoDataFrame : df

   gid  complement  geom
0   0   None    POINT (601719.697 6316169.550)
1   1   None    POINT (889885.470 6766441.264)
2   2   None    POINT (841297.833 6819921.974)
3   3   None    POINT (868509.310 6741434.511)
4   4   None    POINT (868800.981 6741780.168)
...     ...     ...     ...
2230    735794  None    POINT (928202.527 6895078.782)
2231    735795  None    POINT (958274.959 6891683.317)

I tried to convert the geometry to WKT but some None geometries failed it.
I tried to look at the rows with missing geometries with :

df.loc[df.loc[:, 'geom'].isna(), :]
>>>IndexError: too many indices for array

I found it the gid corresponding to the empty geometries and tried :

df.loc[df.loc[:, 'gid'].isin([90138, 424617, 559838, 565628]), :]
>>>IndexError: too many indices for array

I really do not understand why this behaviour is raised. Is it proper to GeoPandas ? How should I solve it ?


texts: Exploratory search for clusters in point data

texts:
This is a more conceptual than practical question and is about exploratory cluster identification. While there are very specific meanings in the geography canon as to what they are, in economics they seem to be somewhat loosely defined, often following Porter's lead:

  Clusters are geographic concentrations of interconnected companies and
  institutions in a particular field. Clusters encompass an array of
  linked industries and other entities important to competition. Porter, M. E. (1998). Clusters and the New Economics of Competition. Harvard Business Review, (November-December 1998), 77–90.

However, I am interested in specifics and formal definitions. I work in city plannning, and there is plenty of talk about cluster x or cluster y being in existence at place z, but I would like to pin it down more and have a data-driven, rather than policy-driven inventory of any and all clusters.

Specifically, assuming a point data set representing business establishments, weighted by their employment, and I am interested in exploring, rather than confirming pre-conceived ideas of which clusters may or may not exist, which GIS approach is best suited for identifying which industries might exhibit clustering at a given scale? Is this a Ripley's K case where each industry grouping would be passed separately, or is there a more appropriate approach in the exploration stage when it is not 'known' which industry levels might cluster (depending on how one aggregates the classes, there could be several hundred distinct industries).


texts: Script to unzip a file geodatabase fails with Memory Leak

texts:
Hijacked the ESRI script to unzip. After research I found there is a memory leak. There are three zip files I download on a regular basis. Each .zip contains one (1) .gdb.
The largest is 2 GB zipped, and 6 GB .gdb. I'm running Windows 7 64 bit, with 32 GB RAM. ArcGIS 10.2.2 and python 2.7 (32 bit on win 32)
What is interesting is the leak will reset itself with each zip.namelist(). Meaning I will end up with all three .gdb's I need, but their contents will not be complete.

#**********************************************************************
# Description:
#    Unzips the contents of a zip file into an existing folder.
# Arguments:
#  0 - Input zip file
#  1 - Input folder - path to existing folder that will contain
#      the contents of the zip file.
#**********************************************************************

# Import modules and create the geoprocessor
#
import sys, zipfile, arcpy, os, traceback
from os.path import isdir, join, normpath, split

# Function to unzipping the contents of the zip file
#
pathz = "C:/HEP/Data"
os.chdir(pathz)

mylist = os.listdir(pathz)
for z in mylist:
    if z.endswith('.zip'):
        print z
        def unzip(path, zip):
            # If the output location does not yet exist, create it
            #
            if not isdir(path):
                os.makedirs(path)

            for each in zip.namelist():
                print "Attempting unzip"
                arcpy.AddMessage("Extracting " + os.path.basename(each) + " ...")

                # Check to see if the item was written to the zip file with an
                # archive name that includes a parent directory. If it does, create
                # the parent folder in the output workspace and then write the file,
                # otherwise, just write the file to the workspace.
                #
                if not each.endswith('/'):
                    print "Splitting files"
                    root, name = split(each)
                    directory = normpath(join(path, root))
                    if not isdir(directory):
                        os.makedirs(directory)
                    print "Writing files"
                    file(join(directory, name), 'wb').write(zip.read(each))
                    print "Successful Unzip"

        if __name__ == '__main__':
            try:
                # Get the tool parameter values
                #
                infile = z
                outfol = pathz

                # Create the zipfile handle for reading and unzip it
                #
                print "Trying to Unizp"
                zip = zipfile.ZipFile(infile, 'r')
                print "Zip understood"
                unzip(outfol, zip)
                zip.close()

            except:
                # Return any Python specific errors and any error returned by the geoprocessor
                #
                print "Error"
                tb = sys.exc_info()[2]
                tbinfo = traceback.format_tb(tb)[0]
                pymsg = "PYTHON ERRORS:\nTraceback Info:\n" + tbinfo + "\nError Info:\n    " + \
                        str(sys.exc_type)+ ": " + str(sys.exc_value) + "\n"
                arcpy.AddError(pymsg)

                msgs = "GP ERRORS:\n" + arcpy.GetMessages(2) + "\n"
                arcpy.AddError(msgs)


texts:
Using the following example I'm able to resize by scale and origin.

    polygonFeature.geometry.resize(scale, origin);
    vectorLayer.redraw();

But does anyone have any suggestions or sample code on how I would go about resizing a polygon on one of its axes?

For example: I would like to resize the orange polygon to something like the red polygon. So only the north and south edges move while the east west edges stay constant.

EDIT #1
Here's a use case and example data:
A user only wants a portion of the orange rectangle because he's only interested in the coastline and satellite vendors will charge him more for the entire image. User needs to specify what portion of the image they want to order.

Although, i don't need the entire solution with sizing handles all i need is the ability to resize the Height of the polygon.

EDIT #2: Maybe i'm going about this wrong. I need an openlayers javascript (browser) solution and cannot go back to the server for resizing. Maybe what i should be doing is interpolating points along east and west edges of the polygon geometry (black dots). Then create two lines (green lines) in which the user can drag but restricting movement(draging) to those interpolated points. When the user is "done" i get the remaining yellow polygon?


texts: Cannot upgrade User Schema Geodatabase when Master Schema Geodatabase is at previous release?

texts:
I am getting this error when trying to upgrade ArcSDE from 10.0 to 10.1:

  Cannot upgrade a user schema geodatabase when the master schema
  geodatabase is at a previous release.

  The master schema geodatabase must be upgraded first.

  ERROR: Geodatabase schema object install not completed (-522).

However, I am updating the ArcSDE master geodatabase only, so why am I getting this error?


texts: Joining Information from Point and Polygon

texts: I tried to find the answer to this question by searching, but I was not too successful. My issue is that I have a point file of around 400 Organizations that do not have a column of county names tied to them. I also have a polygon shapefile of all counties in the United States. I selected the counties that all had an organization located within them, and now I want to give each organization the name of the County that they are located in. How would I go about doing this? I attempted a Join but was unsuccessful; both attribute columns have the same name and data type.


texts: A geodatabase doesn't provide much flexibility in organizing your data hierarchically. All feature sets live either at the top level of the database, or one level down in feature datasets. A feature dataset can't, in turn, contain another dataset. I'm interested in hearing how others organize their data, especially in environments where they must use a geodatabase and are stuck with these limitations.


texts: Joining features across boundary lines of target feature in spatial join?

texts:
I have a file geodatabase named ElectionData2012.gdb containing two feature classes:

Counties: The feature data for California counties
PrecinctVotingData: Feature data for California precincts for the 2012 election. Has two relevant attributes:

a. total_votes: a field containing the total number of individuals who voted in the precinct

b. proposition_37_yes_votes: a field containing the number of individuals that voted for the measure in the precinct

I want to conduct my analysis and aggregate the precinct total votes and yes vote data up to the county level. To complete this I used spatial join tool:

target feature: county
join feature: PrecinctVotingData

And for the merge rule I used sum for the total and the yes votes but the total votes in the original shapefile and the spatial join layer are not the same
cause some of the precinct lines cross the county lines.

How can I clean this up if I want to get the total value from all of the precincts attached to the counties correct.

I use ArcGIS 10.3


texts:
I found this error at a graphical modeler of QGIS 2.14.4.

When I try to move(drag) some algorithm to a new model,
I saw this message as below:

Can you explain why this error occurred?

I expect a reinstall will solve this problems, but I want to know why exactly.

An error has occurred while executing Python code:

NameError: global name 'QTextBrowser' is not defined
Traceback (most recent call last):
  File "C:/PROGRA~1/QGIS21~1.4/apps/qgis-ltr/./python/plugins\processing\modeler\ModelerDialog.py", line 94, in _dropEvent
    self._addAlgorithm(alg.getCopy(), event.pos())
  File "C:/PROGRA~1/QGIS21~1.4/apps/qgis-ltr/./python/plugins\processing\modeler\ModelerDialog.py", line 429, in _addAlgorithm
    dlg = ModelerParametersDialog(alg, self.alg)
  File "C:/PROGRA~1/QGIS21~1.4/apps/qgis-ltr/./python/plugins\processing\modeler\ModelerParametersDialog.py", line 64, in __init__
    self.setupUi()
  File "C:/PROGRA~1/QGIS21~1.4/apps/qgis-ltr/./python/plugins\processing\modeler\ModelerParametersDialog.py", line 172, in setupUi
    self.txtHelp = QTextBrowser()
NameError: global name 'QTextBrowser' is not defined

파이썬 버전: 2.7.5 (default, May 15 2013, 22:44:16) [MSC v.1500 64 bit (AMD64)]
QGIS 버전: 2.14.4-Essen Essen, 634f24b

Python Path:
C:/PROGRA~1/QGIS21~1.4/apps/qgis-ltr/./python/plugins\processing
C:/PROGRA~1/QGIS21~1.4/apps/qgis-ltr/./python
C:/Users/bhyu/.qgis2/python
C:/Users/bhyu/.qgis2/python/plugins
C:/PROGRA~1/QGIS21~1.4/apps/qgis-ltr/./python/plugins
C:\PROGRA~1\QGIS21~1.4\apps\Python27\lib\site-packages\matplotlib-1.3.1-py2.7-win-amd64.egg
C:\PROGRA~1\QGIS21~1.4\apps\Python27\lib\site-packages\nose-1.3.3-py2.7.egg
C:\PROGRA~1\QGIS21~1.4\apps\Python27\lib\site-packages\tornado-4.0.1-py2.7-win-amd64.egg
C:\PROGRA~1\QGIS21~1.4\apps\Python27\lib\site-packages\backports.ssl_match_hostname-3.4.0.2-py2.7.egg
C:\PROGRA~1\QGIS21~1.4\apps\Python27\lib\site-packages\certifi-14.05.14-py2.7.egg
C:\PROGRA~1\QGIS21~1.4\bin\python27.zip
C:\PROGRA~1\QGIS21~1.4\apps\Python27\DLLs
C:\PROGRA~1\QGIS21~1.4\apps\Python27\lib
C:\PROGRA~1\QGIS21~1.4\apps\Python27\lib\plat-win
C:\PROGRA~1\QGIS21~1.4\apps\Python27\lib\lib-tk
C:\PROGRA~1\QGIS21~1.4\bin
C:\PROGRA~1\QGIS21~1.4\apps\Python27
C:\PROGRA~1\QGIS21~1.4\apps\Python27\lib\site-packages
C:\PROGRA~1\QGIS21~1.4\apps\Python27\lib\site-packages\PIL
C:\PROGRA~1\QGIS21~1.4\apps\Python27\lib\site-packages\jinja2-2.7.2-py2.7.egg
C:\PROGRA~1\QGIS21~1.4\apps\Python27\lib\site-packages\markupsafe-0.23-py2.7-win-amd64.egg
C:\PROGRA~1\QGIS21~1.4\apps\Python27\lib\site-packages\pytz-2012j-py2.7.egg
C:\PROGRA~1\QGIS21~1.4\apps\Python27\lib\site-packages\win32
C:\PROGRA~1\QGIS21~1.4\apps\Python27\lib\site-packages\win32\lib
C:\PROGRA~1\QGIS21~1.4\apps\Python27\lib\site-packages\Pythonwin
C:\PROGRA~1\QGIS21~1.4\apps\Python27\lib\site-packages\Shapely-1.2.18-py2.7-win-amd64.egg
C:\PROGRA~1\QGIS21~1.4\apps\Python27\lib\site-packages\wx-2.8-msw-unicode
C:\PROGRA~1\QGIS21~1.4\apps\Python27\lib\site-packages\xlrd-0.9.2-py2.7.egg
C:\PROGRA~1\QGIS21~1.4\apps\Python27\lib\site-packages\xlwt-0.7.5-py2.7.egg
C:/Users/bhyu/.qgis2//python
C:\Users\bhyu\.qgis2\python\plugins\gearthview\ext-libs
C:\Users\bhyu\.qgis2\python\plugins
C:\PROGRA~1\QGIS21~1.4\apps\qgis-ltr\python\plugins\fTools\tools


texts: Which software to use for designing city plans?

texts:
Which software would you suggest I use for designing city plans? The result needs to be an image (jpeg) so georeferencing is not necessary. I have options like ArcGIS, AdobeInDesign, Adobe Illustrator. I don't know which software is the best for maps like these in example:

Also, I would need to add some 2d effects on the buildings.


texts: What is the correct (QGIS) syntax for a masked PostQIS spatial query?

texts:
What is the correct syntax if I want to query a masked region from PostGIS from inside QGIS ?

The data is from "planet_osm_poly" (imported via osm2pgsql) and I'd like to use a polygon from a different table (table=e2e_buffers with name=corridor01) of the same database as mask of the spatial query.


texts: Algorithm to cluster coordinates within a maximum radius

texts:
I am looking for an algorithm that will allow me to find the centers of clusters of an arbitrary radius, such that all coordinates are covered.

Currently, I am doing a very basic routine where I randomize my array, loop through it, and find the distance from one point to all points - if any point falls within my radius, it gets removed from the array and the loop starts over. I then do this x amount of times and keep the best (smallest) attempt of coordinates. Naturally this is very inefficient and also doesnt produce the best results, as sometimes there will be two or more points slightly farther apart than the given radius but a midpoint between them will cover them all.

I have looked around at other clustering algorithms such as kmeans and they don't seem to really handle my case (covering points with a maximum radius), but this is also my first time working on a project anything like this so I am pretty new to dealing with maps and coordinates.

Currently I am usually working with about 500-2000 points spread out across maybe 50 square miles, and keeping with a 500m radius

I am using a leaflet frontend and pulling coordinates from a database using ajax and PHP, so something that could be done either in javascript or PHP would be ideal. My current solution runs on the server using PHP since front end processing capabilties vary, but performance is not my biggest concern right now.


texts: Ogr2ogr importing shapefiles into postgresql

texts:
I have enabled postgis extension already and have imported 3 shapefiles through the qgis db manager. Problem is that now I still have 2 large files to import and leaving qgis importing the entire night was not able to do finish the import. This is why I would need ogr2ogr to work
When I try to use the following command
ogr2ogr -f PostgreSQL PG:"dbname='postgres' host='hostnamehere' port='5432' user='user' password=passwordhere" folders/file.shp -nlt MULTIPOLYGON

I simply get the following error:
Unable to open datasource `folders/file.shp' with the following drivers.

The file opens just fine on QGIS. Is my ogr2ogr command wrong?
Alternatively I also tried psql as I've seen here on this website using:
psql -h host=hosthere gis postgres -p 5432

But got met with this error
psql: could not translate host name "host=host.rds.amazonaws.com" to address: nodename nor servname provided, or not known

I then tried using dbeaver to import a file from a csv but I keep getting
java.lang.NullPointerException and it just doesnt appear to match the fields, yet the file still opens fine on Excel
Is my Ogr2ogr wrong or is there a different thing I can try?


texts: Is there any way to aggregate points within a certain distance of eachother into groups of X?

texts:
I know it's possible to aggregate points within a certain distance of each other, but is it also possible to aggregate them into groups of e.g. 20?

I'm fine with using most open source GIS software or ArcGIS.


texts: Is it possible to automate georeferencing in graphical modeler, I want to extract images from a site and georeference them with QGIS. Graphical modeler algorithms won't show Georeferencer.


texts:
I am interpolating a large gridded DSM in QGIS. I end up with 5 or 6  lines across the final raster, which drop (or raise) the elevation by c.5m if you plot a profile across them. Ther are relatively narrow in breadth.

I only see these if I set the grid size to 0.5m. If I set the grid size to c.1m, they disappear. I would like to interpolate to a smaller grid size if possible.

I've scoured through the data points, and it doesn't seem to be a data artefact from the sampling of the dsm, nor any downsampling I do afterwards in CloudCompare.

Has anyone else seen this, or know a work around?


texts: How to count the proportion of points in protected areas shape file using R packages?

texts:
I have some GPS relocation data and I want to calculate the proportion of those points that fall within protected areas. I'm downloading the protected areas using the wdpar package which uses sf to deal with spatial data.

This question on counting points in polygons was helpful but I haven't been able to integrate the two packages. Hope you can help.

# load packages
library(wdpar)
library(dplyr)
library(ggmap)
library(sf)

# download protected area data
# (excluding areas represented as point localities)
sa_raw_pa_data <- wdpa_fetch(c("South Africa"))
sa_raw_pa_data

# reproject data
sa_pa_data <- st_transform(sa_raw_pa_data, 4326)

# plot it
plot(sa_pa_data)

# create some random data
set.seed(123); d = data.frame(long=runif(100,-180,180), lat=runif(100,-90,90))

# here's where I fall down

# calculate the overlap with something like
    over(d,sa_pa_data$WDPAID)

# or
lengths(st_intersects(sa_pa_data$WDPAID, d))


texts: How to create a weighted square lattice as well as a weighted network graph

texts:
I am planning to create a weighted square lattice for different sizes, and then label each edge with its associated weight. It's similar to this thread "How to load a weighed shapefile in networkX" that looks like intersection of different lines with different weights.

How can plot such a network and their weights? The weight can be for example just a random generator at this moment.

I have the following piece code from above page which does not work:

import networkx as nx
import matplotlib.pyplot as plt
import numpy as np

N = 10
G=nx.grid_2d_graph(N,N)
weighted_G = str (np.random.rand())
pos = {v:v for v in weighted_G.nodes()}
labels = nx.get_edge_attributes(weighted_G,'weight')
nx.draw_networkx_nodes(weighted_G,pos, node_size=10,node_color='r')
nx.draw_networkx_edges(weighted_G, pos)
nx.draw_networkx_edge_labels(G,pos,edge_labels=labels)

# plt.xlim(577000, 579500) #This changes and is problem specific
# plt.ylim(9718500, 9721000) #This changes and is problem specific

plt.xlabel('X [m]')
plt.ylabel('Y [m]')
plt.show()


texts: Generating defined rectangles (size, position) as a new shapefile layer in distance to specific points from another shapefile layer in QGIS

texts:
I'm familiar with the basics of QGIS, but now I'm confronted with a difficult task.

I want to create a new shapefile (as a layer) which contains defined rectangles (size, position) from another layer with specific points.

These points are single points (coordinates of places for instance). The rectangles should be something like a labelling field.

If possible, I want to connect the generated labelling field layer to aggregated information from a third layer. But this is only optional. At last, I want to export the labelling field as KML-file (with MMQGIS for instance).

Background

I tried buffering methods with the point-layer as well as the symbology implemented geometry generator. I also tried specific labelling from the symbology. I was satisfied with the first results of the last mentioned methods.

Unfortunately, it wasn't possible to export the "virtual" rectangles as KML. I couldn't find a suitable plugin for this task. Maybe I have to think about PyQGIS.

Fortunately, I got some (rough) ideas to deal with this task:

Read coordinates from the points (point-layer)
Generate "virtual" rectangle coordinates in relation to the point-coordinates (size + position)
Create a new shapefile layer with rectangles from the generated "virtual" rectangle coordinates and save it
Export the layer as KML

Optional

Connect the shapes with aggregated field values of a third layer, save it and export it as KML (I know the single steps, but maybe there is something like a compound function?)

See the wished result (1-3) made by "hand":

Maybe someone could help me with that. Would be great!


texts: I'm looking for a road dataset for the entire US that includes road and/or lane widths. For my purposes, the difference between an 8 foot wide lane and a 10 food wide lane matters a lot, so the OSM road type doesn't quite cut it. I already have access to the HERE dataset, and that doesn't include widths. My company is happy to throw money at the problem, but I can't even find this data to purchase.


texts: Can QGIS save a Multi-band Raster image as KML/KMZ?

texts:
System — MacOS 10.14.6, QGIS 3.4.14

Issue — When I select a multi-band raster image layer, then select Layer>Save as… KML is not one the many formats in the popup list.

Workaround — Save the Multi-band layer as GeoTIFF. Drag and drop the GeoTIFF onto the Google Earth. Then in GE, Save Place as… to generate a KML or KMZ file.

Is this the best/easiest way to save a multi-band raster image in QGIS to a KML/KMZ format?

I posted this question so that people who search for “QGIS save raster as KML” would get at least one hit that…

a - confirms — that saving a raster layer to KML is not as simple as selecting the layer, selecting Save as and then selecting KML as the format.

b - provides a work around — save the raster layer as a GeoTiff (rendered image), then drag & drop the GeoTiff onto Google earth pro, then Save Place as… KML/KMZ. BTW this drag & drop even works for large GeoTiffs because Google earth pro gives you the option to tile the image or reduce the resolution on import. This work around also allows using an image editor (e.g. Photoshop) to adjust the colors, exposure, contrast, etc. of the GeoTiff prior to importing it into Google earth.

I had hoped that I was wrong and that QGIS had an easy way to save a raster layer in KML/KMZ format that didn’t involve tiling.


texts: how can i store my coordinates in wkb.. i want to know its implementation of wkb and wkt in db .. any one can please guide me.


texts: Startup python script to re-join layers in QGIS?

texts:
In QGIS 2.2, there is a bug which involves using the JOINS properties on a vector layer (that is already being joined with several other vector layers) whereby the attributes are not fully loaded.

Example:

Result_Layer > Middle_Layer > Layer_1
                            > Layer_2
                            > Layer_3

In the above case, the Result_Layer will only show the values of its own columns and their respective fields and about a dozen columns coming from the Middle_Layer and their respective values before showing NULL for the rest of the attribute table.

The number of column and field attributes I am using in total is extensive ( ~200 columns; ~20,000 fields) so I haven't tested this on a much smaller scale.

The workaround at the moment is to re-join the Result_Layer to the Middle_Layer.

UPDATE:

I've been looking at refreshing the mapCanvas() to see if that would somehow 'rejoin' the layers and bring back the values. I've tried the following in the Python console:

from qgis.utils import iface
iface.mapCanvas().refresh()

It probably refreshes but doesn't automatically rejoin. I tried also using self.iface.mapCanvas().refresh() but I get an error.

This is for a client who wants to stick with QGIS 2.2 and does not want to use PostGIS/SpatiaLite as suggested by @mapBaker. Therefore, the only alternative I can think of is to write a script that automatically rejoins all layers when loading up the project.

Also, as a matter of curiosity, is this problem fixed in QGIS 2.4?


texts: PostGIS : Does the  operator work for Geography?

texts:
With the recent PostgreSQL/PostGIS version, you can now use the <-> operator to find the nearest rows to a point:
 Indexed Nearest Neighbour Search in PostGIS

According to my tests, this query:

SELECT name, gid
FROM geonames
ORDER BY geom <-> st_setsrid(st_makepoint(-90,40),4326)
LIMIT 10;

is the same precision and a bit slower than if I use the PostgreSQL Point type.

I would like to use this new operator with the Geography type to do better calculus on a spheroid. Is this possible?


texts: converting random point order into polygons

texts:
We received a kml file with polygons but the points are not in a logical sequence and we end up with strange overlapping shapes that are supposed to be an open polygon.  We did identify a point near the center and found the azimuth and then sorted in that order and it helped but still did not solve. The bounds of the polygon do contain convex sides.  Is anyone aware of an approach to process the random points and get the best open polygon?  We have considered calculating bearing and distance from each point and looking for non intersecting line segments but wanted to see if there is a better approach.

We are using php to calculate and then pass into mapping api.. our database is mysql.

Trying to do as minimal programming as possible.