def createLayerCB(self, layer): qDebug('Opening cartodb layer') lr = QgsMapLayerRegistry.instance() lr.layerWasAdded.connect(self._onAddProjectLayer) # lr.removeMapLayer(layer.id()) # lr.addMapLayer(layer.cartodbLayer) self.layers.append(layer)
def __search(self, layer, searchString, error): """ :type layer: QgsVectorLayer :type searchString: str :type error: str :return: """ # parse search string and build parsed tree search = QgsExpression(searchString) rect = QgsRectangle() fIds = [] if search.hasParserError(): error += "Parsing error:" + search.parserErrorString() return fIds if not search.prepare(layer.pendingFields()): error + "Evaluation error:" + search.evalErrorString() layer.select(rect, False) fit = QgsFeatureIterator(layer.getFeatures()) f = QgsFeature() while fit.nextFeature(f): if search.evaluate(f): fIds.append(f.id()) # check if there were errors during evaluating if search.hasEvalError(): qDebug('\n (VFK) Evaluate error: {}'.format(error)) break return fIds
def __init__(self): # load object types self.modules = [] self.objTypes = { QGis.Point: [], QGis.Line: [], QGis.Polygon: [] } # each list item is ObjectTypeItem object module_names = ["point_basic", "line_basic", "polygon_basic"] module_names += ["point_json"] module_fullnames = map(lambda x: "Qgis2threejs.objects." + x, module_names) for modname in module_fullnames: mod = ObjectTypeModule.load(modname) if mod is None: QMessageBox.warning( None, "Qgis2threejs", "Failed to load the module: {0}\nIf you have just upgraded this plugin, please restart QGIS." .format(modname)) return mod_index = len(self.modules) self.modules.append(mod) for type_index, name in enumerate(mod.objectTypeNames): self.objTypes[mod.geometryType].append( ObjectTypeItem(name, mod_index, type_index)) if debug_mode: qDebug("ObjectTypeManager: " + str(self.objTypes))
def layerRemoved(self, layerId): if layerId in self.layers: self.iface.legendInterface().removeLegendLayerAction( self.layers[layerId].saveTilesAction) del self.layers[layerId] if debug_mode: qDebug("Layer %s removed" % layerId.encode("UTF-8"))
def __init__(self, iface, toolbar, parent=None): CartoDBPluginUserDialog.__init__(self, toolbar, parent) self.iface = iface self.ui = Ui_Upload() self.ui.setupUi(self) self.ui.bar = QgsMessageBar() self.ui.bar.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed) self.ui.verticalLayout.insertWidget(0, self.ui.bar) self.ui.uploadBT.clicked.connect(self.upload) self.ui.cancelBT.clicked.connect(self.reject) self.ui.layersList.itemSelectionChanged.connect(self.validateButtons) layers = QgsMapLayerRegistry.instance().mapLayers() # TODO Implement add to project # self.ui.convertCH.hide() self.ui.overideCH.hide() self.ui.layersList.clear() self.ui.uploadBar.setValue(0) self.ui.uploadBar.hide() self.ui.uploadingLB.hide() for id_ly, ly in layers.iteritems(): qDebug('Layer id {}'.format(stripAccents(id_ly))) if ly.type() == QgsMapLayer.VectorLayer and not isinstance(ly, CartoDBLayer): item = QListWidgetItem(self.ui.layersList) widget = CartoDBLayerListItem(ly.name(), ly, getSize(ly), ly.dataProvider().featureCount()) item.setSizeHint(widget.sizeHint()) self.ui.layersList.setItemWidget(item, widget)
def _loadLibrary(self): if self.hasError: return False if self.state != PluginSpec.Resolved: if self.state == PluginSpec.Loaded: return True self.errorString = QCoreApplication.translate("PluginSpec", "Loading the library failed because state != Resolved") self.hasError = True return False moduleName = self.name.lower() try: plugin = import_module("medux.plugins." + moduleName) qDebug(QCoreApplication.translate("PluginSpec", "Successfully imported '{}' plugin").format(moduleName)) except ImportError as e: self.hasError = True self.errorString = QCoreApplication.translate("PluginSpec", "Warning: cannot import '{}' plugin: {}").format(self.name, e.msg) return False # everything ok, assign then plugin to member variable to keep track of it # and for easy access if hasattr(plugin, self.name + "Plugin"): self.plugin = getattr(plugin, self.name + "Plugin")
def getElevation(crs,point): epsg4326 = QgsCoordinateReferenceSystem(4326, QgsCoordinateReferenceSystem.EpsgCrsId) mycrs = QgsCoordinateReferenceSystem(int(crs), 0) reprojectgeographic = QgsCoordinateTransform(mycrs, epsg4326) pt = reprojectgeographic.transform(point) conn = httplib.HTTPConnection("maps.googleapis.com") QgsMessageLog.instance().logMessage( "http://maps.googleapis.com/maps/api/elevation/json?locations=" + str(pt[1]) + "," + str( pt[0]) + "&sensor=false", "Elevation") try: conn.request("GET", "/maps/api/elevation/json?locations=" + str(pt[1]) + "," + str(pt[0]) + "&sensor=false") response = conn.getresponse() jsonresult = response.read() elevation = 0.0 results = json.loads(jsonresult).get('results') print results if 0 < len(results): elevation = float(round(results[0].get('elevation'),4)) except Exception as e: print (e.message) qDebug(e.message) elevation=0.0 return elevation
def _removeTree(self, path): try: shutil.rmtree(path) return True except OSError as e: qDebug("FileSystem.removeTree - %s: '%s'" % (e, path)) return False
def updateQuotes(self): for exchange in self.tickersByExchange.keys(): qDebug("Getting quotes for exchange: %s" %(exchange)) symbols = self.tickersByExchange[exchange] self.throttledQuoter.updateCache(exchange, symbols) qDebug("[Updater] interval: %d" % (self.currentUpdateInterval))
def cbGetLayers(self, data): item = self.ui.mapList.item(0) widget = self.ui.mapList.itemWidget(item) layer = widget.layer cartoCSS = self.convert2CartoCSS(layer) cartoDBApi = CartoDBApi(self.currentUser, self.currentApiKey, self.currentMultiuser) layer1 = data['layers'][1] layer1['options']['tile_style'] = cartoCSS layer1["options"]["legend"] = None cartoDBApi.fetchContent.connect(self.showMessage) cartoDBApi.updateLayerInMap(self.currentViz['map_id'], layer1) for i in range(1, self.ui.mapList.count()): item = self.ui.mapList.item(i) widget = self.ui.mapList.itemWidget(item) layer = widget.layer qDebug('Agregando: {} en pos: {}'.format(layer.tableName(), i)) cartoCSS = self.convert2CartoCSS(layer) # cartoDBApi.fetchContent.connect(self.cbCreateViz) newLayer = copy.deepcopy(layer1) newLayer["options"]["table_name"] = layer.tableName() newLayer["options"]["tile_style"] = cartoCSS newLayer["options"]["order"] = i + 1 newLayer["order"] = i + 1 newLayer["id"] = None cartoDBApi.addLayerToMap(self.currentViz['map_id'], newLayer)
def log(level, text, *args, **kwargs): if level in ('1', '2') and config.DEBUG in '2': qDebug("[D2]: " + text) elif level in '1' and config.DEBUG in '1': qDebug("[D1]: " + text) else: pass
def search(self): """ """ QApplication.setOverrideCursor(Qt.WaitCursor) QApplication.processEvents() if int( self.__controls.formCombobox.itemData( self.__controls.formCombobox.currentIndex()) ) == self.Form.Parcely: self.__searchParcely() elif int( self.__controls.formCombobox.itemData( self.__controls.formCombobox.currentIndex()) ) == self.Form.Budovy: self.__searchBudovy() elif int( self.__controls.formCombobox.itemData( self.__controls.formCombobox.currentIndex()) ) == self.Form.Jednotky: self.__searchJednotky() elif int( self.__controls.formCombobox.itemData( self.__controls.formCombobox.currentIndex()) ) == self.Form.Vlastnici: self.__searchVlastnici() else: qDebug("Neplatna hodnota v SearchComboBoxu!!!") QApplication.restoreOverrideCursor()
def symbolicLink(self, source, target): try: os.symlink(source, target) return True except OSError as (t, e): qDebug('FileSystem.symbolicLink - %s: \'%s\' -> \'%s\'' % (e, source, target)) return False
def setupWidgets(self, dialog, mapTo3d, layer, geom_type, item_index): try: typeitem = self.objTypes[geom_type][item_index] return self.modules[typeitem.mod_index].setupWidgets(dialog, mapTo3d, layer, typeitem.type_index) except: qDebug("Qgis2threejs: Failed to setup form") return False
def writeLine(self, data): try: self.m_file.write(data + '\n') return True except IOError as e: qDebug('File.writeLine - %s: \'%s\'' % (e, self.m_file.name)) return False
def _copy(self, source, target): try: shutil.copy2(source, target) return True except IOError as (_, e): qDebug("FileSystem.copy - %s: '%s' -> '%s'" % (e, source, target)) return False
def removeTree(self, path): try: os.removedirs(path) return True except OSError as e: qDebug('FileSystem.removeTree - %s: \'%s\'' % (e, path)) return False
def symbolicLink(self, source, target): try: os.symlink(source, target) return True except OSError as (_, e): qDebug("FileSystem.symbolicLink - %s: '%s' -> '%s'" % (e, source, target)) return False
def write(self, data): try: self.m_file.write(data) return True except IOError as e: qDebug("File.write - %s: '%s'" % (e, self.m_file.name)) return False
def makeDirectory(self, path): try: os.mkdir(path) return True except OSError as e: qDebug('FileSystem.makeDirectory - %s: \'%s\'' % (e, path)) return False
def injectJsInFrame(filePath, scriptEncoding, libraryPath, targetFrame, startingScript=False): try: # if file doesn't exist in the CWD, use the lookup if not os.path.exists(filePath): filePath = os.path.join(libraryPath, filePath) try: with codecs.open(filePath, encoding=scriptEncoding) as f: script = f.read() except UnicodeDecodeError as e: sys.exit("%s in '%s'" % (e, filePath)) if script.startswith("#!") and not filePath.lower().endswith(".coffee"): script = "//" + script if filePath.lower().endswith(".coffee"): result = coffee2js(script) if not result[0]: if startingScript: sys.exit("%s: '%s'" % (result[1], filePath)) else: qDebug("%s: '%s'" % (result[1], filePath)) script = "" else: script = result[1] targetFrame.evaluateJavaScript(script) return True except IOError as (t, e): qDebug("%s: '%s'" % (e, filePath)) return False
def changeWorkingDirectory(self, path): try: os.chdir(path) return True except OSError as e: qDebug("FileSystem.changeWorkingDirectory - %s: '%s'" % (e, path)) return False
def _copy(self, source, target): try: shutil.copy2(source, target) return True except IOError as (t, e): qDebug("FileSystem.copy - %s: '%s' -> '%s'" % (e, source, target)) return False
def __init__(self, gui, text, orientation, buttons, parent): OrientedWidget.__init__(self, orientation, parent) self.buttons = {} self.groups = {} i = 0 n = len(buttons) while i < n: if buttons[i] == gui.StateButtonsBegin: state_buttons = [] for j in range(i + 1, n): if buttons[j] == gui.StateButtonsEnd: qDebug("Adding state buttons " + repr(state_buttons) + " to layout " + repr(self.layout())) s = gui.state_buttons(orientation, state_buttons, self) self.buttons.update(s.buttons) self.groups[buttons[i + 1]] = s i = j break else: state_buttons.append(buttons[j]) elif buttons[i] == gui.Spacing: self.layout().addSpacing(10) elif type(buttons[i] == int): self.buttons[buttons[i]] = gui.tool_button(buttons[i], self) elif len(buttons[i] == 4): gui.tool_button(buttons[i], self) else: self.buttons[buttons[i][0]] = gui.tool_button(buttons[i], self) i = i + 1 self.layout().addStretch()
def setBusyStatus(self, busy): try: self.setAttribute(Qt.WA_Maemo5ShowProgressIndicator, busy) from PyQt4.QtGui import QApplication QApplication.processEvents() except AttributeError: qDebug("Can't use WA_Maemo5ShowProgressIndicator")
def injectJsInFrame(filePath, libraryPath, targetFrame, startingScript=False): try: # if file doesn't exist in the CWD, use the lookup if not os.path.exists(filePath): filePath = os.path.join(libraryPath, filePath) with codecs.open(filePath, encoding='utf-8') as f: script = f.read() if script.startswith('#!') and not filePath.lower().endswith('.coffee'): script = '//' + script if filePath.lower().endswith('.coffee'): result = coffee2js(script) if result[0] is False: if startingScript: sys.exit('%s: \'%s\'' % (result[1], filePath)) else: qDebug('%s: \'%s\'' % (result[1], filePath)) script = '' else: script = result[1] targetFrame.evaluateJavaScript(script) return True except IOError as (t, e): qDebug('%s: \'%s\'' % (e, filePath)) return False
def makeTree(self, path): try: os.makedirs(path) return True except OSError as e: qDebug("FileSystem.makeTree - %s: '%s'" % (e, path)) return False
def _open(self, path, mode): try: f = codecs.open(path, mode, encoding='utf-8') return File(self, f) except (IOError, ValueError) as (t, e): qDebug("FileSystem.open - %s: '%s'" % (e, path)) return
def makeDirectory(self, path): try: os.mkdir(path) return True except OSError as e: qDebug("FileSystem.makeDirectory - %s: '%s'" % (e, path)) return False
def makeTree(self, path): try: os.makedirs(path) return True except OSError as e: qDebug('FileSystem.makeTree - %s: \'%s\'' % (e, path)) return False
def _remove(self, path): try: os.remove(path) return True except OSError as e: qDebug("FileSystem.remove - %s: '%s'" % (e, path)) return False
def checkTest(self, **kwargs): self.lyr.writeToLayer(self.layer) ms = self._MapSettings # class settings settings_type = 'Class' if self._TestMapSettings is not None: ms = self._TestMapSettings # per test settings settings_type = 'Test' if 'PAL_VERBOSE' in os.environ: qDebug('MapSettings type: {0}'.format(settings_type)) qDebug(mapSettingsString(ms)) img = renderMapToImage(ms, parallel=False) self._TestImage = getTempfilePath('png') if not img.save(self._TestImage, 'png'): os.unlink(self._TestImage) raise OSError('Failed to save output from map render job') self.saveControlImage(self._TestImage) mismatch = 0 if 'PAL_NO_MISMATCH' not in os.environ: # some mismatch expected mismatch = self._Mismatch if self._Mismatch else 0 if self._TestGroup in self._Mismatches: mismatch = self._Mismatches[self._TestGroup] colortol = 0 if 'PAL_NO_COLORTOL' not in os.environ: colortol = self._ColorTol if self._ColorTol else 0 if self._TestGroup in self._ColorTols: colortol = self._ColorTols[self._TestGroup] self.assertTrue(*self.renderCheck(mismatch=mismatch, colortol=colortol, imgpath=self._TestImage))
def _open(self, path, mode): try: f = codecs.open(path, mode, encoding='utf-8') return File(f, self) except (IOError, ValueError) as (t, e): qDebug("FileSystem.open - %s: '%s'" % (e, path)) return
def _removeDirectory(self, path): try: os.rmdir(path) return True except OSError as e: qDebug("FileSystem.removeDirectory - %s: '%s'" % (e, path)) return False
def checkTest(self, **kwargs): self.lyr.writeToLayer(self.layer) ms = self._MapSettings # class settings settings_type = 'Class' if self._TestMapSettings is not None: ms = self._TestMapSettings # per test settings settings_type = 'Test' if 'PAL_VERBOSE' in os.environ: qDebug('MapSettings type: {0}'.format(settings_type)) qDebug(mapSettingsString(ms)) res_m, self._TestImage = self.get_composer_output(self._TestKind) self.assertTrue(res_m, 'Failed to retrieve/save output from composer') self.saveControlImage(self._TestImage) mismatch = 0 if 'PAL_NO_MISMATCH' not in os.environ: # some mismatch expected mismatch = self._Mismatch if self._Mismatch else 20 if self._TestGroup in self._Mismatches: mismatch = self._Mismatches[self._TestGroup] colortol = 0 if 'PAL_NO_COLORTOL' not in os.environ: colortol = self._ColorTol if self._ColorTol else 0 if self._TestGroup in self._ColorTols: colortol = self._ColorTols[self._TestGroup] self.assertTrue(*self.renderCheck(mismatch=mismatch, colortol=colortol, imgpath=self._TestImage))
def hardLink(self, source, target): try: os.link(source, target) return True except OSError as (t, e): qDebug("FileSystem.hardLink - %s: '%s' -> '%s'" % (e, source, target)) return False
def changePermissions(self, path, permissions): # permissions uses an object in 4 types: owner, group, others, special # owner,group,others each has 3 types, read,write,executable, contained in an array # special uses setuid,setgid,sticky # # In order to turn values on or off, just use true or false values. # # Permissions can alternatively be a numeric mode to chmod too. keys = { 'owner': {'read': 'S_IRUSR', 'write': 'S_IWUSR', 'executable': 'S_IXUSR'}, 'group': {'read': 'S_IRGRP', 'write': 'S_IWGRP', 'executable': 'S_IXGRP'}, 'others': {'read': 'S_IROTH', 'write': 'S_IWOTH', 'executable': 'S_IXOTH'}, 'special': {'setuid': 'S_ISUID', 'setgid': 'S_ISGID', 'sticky': 'S_ISVTX'} } try: if isinstance(permissions, int): os.chmod(path, permissions) else: bitnum = os.stat(path).st_mode for section in permissions: for key in permissions[section]: try: if permissions[section][key] is True: bitnum = bitnum | stat.__dict__[keys[section][key]] elif permissions[section][key] is False: bitnum = bitnum & ~stat.__dict__[keys[section][key]] except KeyError: pass os.chmod(path, bitnum) return True except OSError as (t, e): qDebug("FileSystem.changePermissions - %s: '%s'" % (e, path)) return False
def checkTest(self, **kwargs): self.lyr.writeToLayer(self.layer) ms = self._MapSettings # class settings settings_type = 'Class' if self._TestMapSettings is not None: ms = self._TestMapSettings # per test settings settings_type = 'Test' if 'PAL_VERBOSE' in os.environ: qDebug('MapSettings type: {0}'.format(settings_type)) qDebug(mapSettingsString(ms)) res_m, self._TestImage = self.get_composer_output(self._TestKind) self.assertTrue(res_m, 'Failed to retrieve/save output from composer') self.saveControlImage(self._TestImage) mismatch = 0 if 'PAL_NO_MISMATCH' not in os.environ: # some mismatch expected mismatch = self._Mismatch if self._Mismatch else 20 if self._TestGroup in self._Mismatches: mismatch = self._Mismatches[self._TestGroup] colortol = 0 if 'PAL_NO_COLORTOL' not in os.environ: colortol = self._ColorTol if self._ColorTol else 0 if self._TestGroup in self._ColorTols: colortol = self._ColorTols[self._TestGroup] self.assertTrue(*self.renderCheck( mismatch=mismatch, colortol=colortol, imgpath=self._TestImage))
def removeTree(self, path): try: os.removedirs(path) return True except OSError as e: qDebug("FileSystem.removeTree - %s: '%s'" % (e, path)) return False
def copyLinkTree(self, source, target): try: shutil.copytree(source, target, True) return True except IOError as (t, e): qDebug("FileSystem.copyLinkTree - %s: '%s' -> '%s'" % (e, source, target)) return False
def removeDirectory(self, path): try: os.rmdir(path) return True except OSError as e: qDebug("FileSystem.removeDirectory - %s: '%s'" % (e, path)) return False
def move(self, source, target): try: shutil.move(source, target) return True except IOError as (t, e): qDebug("FileSystem.move - %s: '%s' -> '%s'" % (e, source, target)) return False
def rename(self, source, target): try: os.rename(source, target) return True except OSError as (t, e): qDebug("FileSystem.rename - %s: '%s' -> '%s'" % (e, source, target)) return False
def checkTest(self, **kwargs): self.lyr.writeToLayer(self.layer) ms = self._MapSettings # class settings settings_type = 'Class' if self._TestMapSettings is not None: ms = self._TestMapSettings # per test settings settings_type = 'Test' if 'PAL_VERBOSE' in os.environ: qDebug('MapSettings type: {0}'.format(settings_type)) qDebug(mapSettingsString(ms)) img = renderMapToImage(ms, parallel=False) self._TestImage = getTempfilePath('png') if not img.save(self._TestImage, 'png'): os.unlink(self._TestImage) raise OSError('Failed to save output from map render job') self.saveControlImage(self._TestImage) mismatch = 0 if 'PAL_NO_MISMATCH' not in os.environ: # some mismatch expected mismatch = self._Mismatch if self._Mismatch else 0 if self._TestGroup in self._Mismatches: mismatch = self._Mismatches[self._TestGroup] colortol = 0 if 'PAL_NO_COLORTOL' not in os.environ: colortol = self._ColorTol if self._ColorTol else 0 if self._TestGroup in self._ColorTols: colortol = self._ColorTols[self._TestGroup] self.assertTrue(*self.renderCheck( mismatch=mismatch, colortol=colortol, imgpath=self._TestImage))
def injectJsInFrame(filePath, libraryPath, targetFrame, startingScript=False): try: # if file doesn't exist in the CWD, use the lookup if not os.path.exists(filePath): filePath = os.path.join(libraryPath, filePath) with codecs.open(filePath, encoding='utf-8') as f: script = f.read() if script.startswith('#!') and not filePath.lower().endswith('.coffee'): script = '//' + script if filePath.lower().endswith('.coffee'): result = coffee2js(script) if result[0] is False: if startingScript: sys.exit("%s: '%s'" % (result[1], filePath)) else: qDebug("%s: '%s'" % (result[1], filePath)) script = '' else: script = result[1] targetFrame.evaluateJavaScript(script) return True except IOError as (t, e): qDebug("%s: '%s'" % (e, filePath)) return False
def list_(self, path): try: p = os.listdir(path) p[0:2] = ('.', '..') return p except OSError as e: qDebug("FileSystem.list - %s: '%s'" % (e, path)) return
def createCartoCss(self): item = self.ui.availableList.currentItem() if item is not None: widget = self.ui.availableList.itemWidget(item) layer = widget.layer cartoCSS = self.convert2CartoCSS(layer) qDebug('CartoCSS: {}'.format(cartoCSS))
def _remove_ogrconfig_tmp(self): if self._ogrconfig_tmp is not None: try: os.remove(self._ogrconfig_tmp) except WindowsError: qDebug("WindowsError: Couldn't delete %s" % self._ogrconfig_tmp) self._ogrconfig_tmp = None
def upload(self): """Init upload proccess""" for layer_item in self.ui.layersList.selectedItems(): widget = self.ui.layersList.itemWidget(layer_item) qDebug('Layer: ' + str(widget.layer.storageType())) layer = checkCartoDBId(widget.layer, self.ui.convertCH.isChecked()) zip_path = zipLayer(layer) self.uploadZip(zip_path, widget, layer, self.ui.convertCH.isChecked())