Exemplo n.º 1
0
 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
Exemplo n.º 3
0
    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))
Exemplo n.º 4
0
 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"))
Exemplo n.º 5
0
    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)
Exemplo n.º 6
0
    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")
Exemplo n.º 7
0
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
Exemplo n.º 8
0
 def _removeTree(self, path):
     try:
         shutil.rmtree(path)
         return True
     except OSError as e:
         qDebug("FileSystem.removeTree - %s: '%s'" % (e, path))
         return False
Exemplo n.º 9
0
    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))
Exemplo n.º 10
0
    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)
Exemplo n.º 11
0
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()
Exemplo n.º 13
0
 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
Exemplo n.º 14
0
 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
Exemplo n.º 15
0
 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
Exemplo n.º 16
0
 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
Exemplo n.º 17
0
 def removeTree(self, path):
     try:
         os.removedirs(path)
         return True
     except OSError as e:
         qDebug('FileSystem.removeTree - %s: \'%s\'' % (e, path))
         return False
Exemplo n.º 18
0
 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
Exemplo n.º 19
0
 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
Exemplo n.º 20
0
 def makeDirectory(self, path):
     try:
         os.mkdir(path)
         return True
     except OSError as e:
         qDebug('FileSystem.makeDirectory - %s: \'%s\'' % (e, path))
         return False
Exemplo n.º 21
0
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
Exemplo n.º 22
0
 def changeWorkingDirectory(self, path):
     try:
         os.chdir(path)
         return True
     except OSError as e:
         qDebug("FileSystem.changeWorkingDirectory - %s: '%s'" % (e, path))
         return False
Exemplo n.º 23
0
 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
Exemplo n.º 24
0
 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()
Exemplo n.º 25
0
 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")
Exemplo n.º 26
0
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
Exemplo n.º 27
0
 def makeTree(self, path):
     try:
         os.makedirs(path)
         return True
     except OSError as e:
         qDebug("FileSystem.makeTree - %s: '%s'" % (e, path))
         return False
Exemplo n.º 28
0
 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
Exemplo n.º 29
0
 def makeDirectory(self, path):
     try:
         os.mkdir(path)
         return True
     except OSError as e:
         qDebug("FileSystem.makeDirectory - %s: '%s'" % (e, path))
         return False
Exemplo n.º 30
0
 def makeTree(self, path):
     try:
         os.makedirs(path)
         return True
     except OSError as e:
         qDebug('FileSystem.makeTree - %s: \'%s\'' % (e, path))
         return False
Exemplo n.º 31
0
 def _removeTree(self, path):
     try:
         shutil.rmtree(path)
         return True
     except OSError as e:
         qDebug("FileSystem.removeTree - %s: '%s'" % (e, path))
         return False
Exemplo n.º 32
0
 def _remove(self, path):
     try:
         os.remove(path)
         return True
     except OSError as e:
         qDebug("FileSystem.remove - %s: '%s'" % (e, path))
         return False
Exemplo n.º 33
0
    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))
Exemplo n.º 34
0
 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
Exemplo n.º 35
0
 def _removeDirectory(self, path):
     try:
         os.rmdir(path)
         return True
     except OSError as e:
         qDebug("FileSystem.removeDirectory - %s: '%s'" % (e, path))
         return False
Exemplo n.º 36
0
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
Exemplo n.º 37
0
    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))
Exemplo n.º 38
0
 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
Exemplo n.º 39
0
    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
Exemplo n.º 40
0
 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
Exemplo n.º 41
0
 def changeWorkingDirectory(self, path):
     try:
         os.chdir(path)
         return True
     except OSError as e:
         qDebug("FileSystem.changeWorkingDirectory - %s: '%s'" % (e, path))
         return False
Exemplo n.º 42
0
    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))
Exemplo n.º 43
0
    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
Exemplo n.º 44
0
 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)
Exemplo n.º 45
0
 def removeTree(self, path):
     try:
         os.removedirs(path)
         return True
     except OSError as e:
         qDebug("FileSystem.removeTree - %s: '%s'" % (e, path))
         return False
Exemplo n.º 46
0
 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
Exemplo n.º 47
0
 def removeDirectory(self, path):
     try:
         os.rmdir(path)
         return True
     except OSError as e:
         qDebug("FileSystem.removeDirectory - %s: '%s'" % (e, path))
         return False
Exemplo n.º 48
0
 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
Exemplo n.º 49
0
 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
Exemplo n.º 50
0
    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)
Exemplo n.º 51
0
    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))
Exemplo n.º 52
0
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
Exemplo n.º 53
0
 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
Exemplo n.º 54
0
    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))
Exemplo n.º 55
0
 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
Exemplo n.º 56
0
 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
Exemplo n.º 57
0
 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
Exemplo n.º 58
0
 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
Exemplo n.º 59
0
 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())