def testTaskFromFunctionWithFlags(self): """ test creating task from function with flags""" task = QgsTask.fromFunction('test task', run, 20, flags=QgsTask.Flags()) self.assertFalse(task.canCancel()) task2 = QgsTask.fromFunction('test task', run, 20, flags=QgsTask.CanCancel) self.assertTrue(task2.canCancel())
def testTaskFromFunctionWithSubTaskCompletedIsCalledOnce(self): # spellok """ test that when a parent task has subtasks it does emit taskCompleted only once""" self.finished = 0 self.completed = 0 def _on_finished(e): self.finished += 1 def _on_completed(): self.completed += 1 task = QgsTask.fromFunction('test task', run_no_result, on_finished=_on_finished) task.taskCompleted.connect(_on_completed) spy = QSignalSpy(task.taskCompleted) sub_task_1 = QgsTask.fromFunction('test subtask 1', run_no_result, on_finished=_on_finished) sub_task_2 = QgsTask.fromFunction('test subtask 2', run_no_result, on_finished=_on_finished) task.addSubTask(sub_task_1, [], QgsTask.ParentDependsOnSubTask) task.addSubTask(sub_task_2, [], QgsTask.ParentDependsOnSubTask) QgsApplication.taskManager().addTask(task) while task.status() not in [QgsTask.Complete, QgsTask.Terminated]: QCoreApplication.processEvents() while QgsApplication.taskManager().countActiveTasks() > 0: QCoreApplication.processEvents() self.assertEqual(self.completed, 1) self.assertEqual(self.finished, 3) self.assertEqual(len(spy), 1)
def testTaskFromFunctionWithKwargs(self): """ test creating task from function using kwargs """ task = QgsTask.fromFunction('test task3', run_with_kwargs, result=5, password=1) QgsApplication.taskManager().addTask(task) while task.status() not in [QgsTask.Complete, QgsTask.Terminated]: pass self.assertEqual(task.returned_values, 5) self.assertFalse(task.exception) self.assertEqual(task.status(), QgsTask.Complete)
def testTaskFromFunction(self): """ test creating task from function """ task = QgsTask.fromFunction('test task', run, 20) QgsApplication.taskManager().addTask(task) while task.status() not in [QgsTask.Complete, QgsTask.Terminated]: pass self.assertEqual(task.returned_values, 20) self.assertFalse(task.exception) self.assertEqual(task.status(), QgsTask.Complete) # try a task which cancels itself bad_task = QgsTask.fromFunction('test task2', run, None) QgsApplication.taskManager().addTask(bad_task) while bad_task.status() not in [QgsTask.Complete, QgsTask.Terminated]: pass self.assertFalse(bad_task.returned_values) self.assertTrue(bad_task.exception) self.assertEqual(bad_task.status(), QgsTask.Terminated)
def testTaskFromFunctionFinished(self): """ test that task from function can have callback finished function""" task = QgsTask.fromFunction('test task', run_no_result, on_finished=finished_no_val) QgsApplication.taskManager().addTask(task) while task.status() not in [QgsTask.Complete, QgsTask.Terminated]: pass while QgsApplication.taskManager().countActiveTasks() > 0: QCoreApplication.processEvents() # check that the finished function was called self.assertFalse(task.returned_values) self.assertFalse(task.exception) self.assertTrue(finished_no_val.called)
def testTaskFromFunctionFinishedFail(self): """ test that task from function which fails calls finished with exception""" task = QgsTask.fromFunction('test task', run_fail, on_finished=finished_fail) QgsApplication.taskManager().addTask(task) while task.status() not in [QgsTask.Complete, QgsTask.Terminated]: pass while QgsApplication.taskManager().countActiveTasks() > 0: QCoreApplication.processEvents() # check that the finished function was called self.assertTrue(task.exception) self.assertTrue(finished_fail.finished_exception) self.assertEqual(task.exception, finished_fail.finished_exception)
def testTaskFromFunctionFinishedWithVal(self): """ test that task from function can have callback finished function and is passed result values""" task = QgsTask.fromFunction('test task', run_single_val_result, on_finished=finished_single_value_result) QgsApplication.taskManager().addTask(task) while task.status() not in [QgsTask.Complete, QgsTask.Terminated]: pass while QgsApplication.taskManager().countActiveTasks() > 0: QCoreApplication.processEvents() # check that the finished function was called self.assertEqual(task.returned_values, (5)) self.assertFalse(task.exception) self.assertEqual(finished_single_value_result.value, 5)
def testTaskFromFunctionIsCancellable(self): """ test that task from function can check canceled status """ bad_task = QgsTask.fromFunction('test task4', cancellable) QgsApplication.taskManager().addTask(bad_task) while bad_task.status() != QgsTask.Running: pass bad_task.cancel() while bad_task.status() == QgsTask.Running: pass while QgsApplication.taskManager().countActiveTasks() > 0: QCoreApplication.processEvents() self.assertEqual(bad_task.status(), QgsTask.Terminated) self.assertTrue(bad_task.exception)
def testTaskFromFunctionCanceledWhileQueued(self): """ test that task from finished is called with exception when task is terminated while queued""" task = QgsTask.fromFunction('test task', run_no_result, on_finished=finished_fail) task.hold() QgsApplication.taskManager().addTask(task) task.cancel() while task.status() not in [QgsTask.Complete, QgsTask.Terminated]: pass while QgsApplication.taskManager().countActiveTasks() > 0: QCoreApplication.processEvents() # check that the finished function was called self.assertTrue(task.exception) self.assertTrue(finished_fail.finished_exception) self.assertEqual(task.exception, finished_fail.finished_exception)
def testTaskFromFunctionCanSetProgress(self): """ test that task from function can set progress """ task = QgsTask.fromFunction('test task5', progress_function) QgsApplication.taskManager().addTask(task) while task.status() != QgsTask.Running: pass # wait a fraction so that setProgress gets a chance to be called sleep(0.001) self.assertEqual(task.progress(), 50) self.assertFalse(task.exception) task.cancel() while task.status() == QgsTask.Running: pass while QgsApplication.taskManager().countActiveTasks() > 0: QCoreApplication.processEvents()
def testTaskFromFunctionFinishedFail(self): """ test that task from function which fails calls finished with exception""" finished_exception = None def finished_fail(e): nonlocal finished_exception assert e finished_exception = e task = QgsTask.fromFunction('test task', run_fail, on_finished=finished_fail) QgsApplication.taskManager().addTask(task) while task.status() not in [QgsTask.Complete, QgsTask.Terminated]: pass while QgsApplication.taskManager().countActiveTasks() > 0: QCoreApplication.processEvents() # check that the finished function was called self.assertTrue(task.exception) self.assertTrue(finished_exception) self.assertEqual(task.exception, finished_exception)
def testTaskFromFunctionCanceledWhileQueued(self): """ test that task from finished is called with exception when task is terminated while queued""" finished_exception = None def finished_fail(e): nonlocal finished_exception assert e finished_exception = e task = QgsTask.fromFunction('test task', run_no_result, on_finished=finished_fail) task.hold() QgsApplication.taskManager().addTask(task) task.cancel() while task.status() not in [QgsTask.Complete, QgsTask.Terminated]: pass while QgsApplication.taskManager().countActiveTasks() > 0: QCoreApplication.processEvents() # check that the finished function was called self.assertTrue(task.exception) self.assertTrue(finished_exception) self.assertEqual(task.exception, finished_exception)
def getInterval(self): """ Zebranie geometrii punktów na linii zgodnie z zadanym interwałem """ interval, ok = QInputDialog.getDouble(self.parent, 'Podaj interwał', 'Interwał [m]:') if not ok: self.reset() return geom = self.parent.transformGeometry( self.tempGeom.asGeometry(), current_crs=QgsProject.instance().crs().authid(), ) meters_len = geom.length() if meters_len <= interval: self.parent.on_message.emit( 'Długość linii krótsza lub równa podanemu interwałowi', Qgis.Critical, 5) self.reset() return try: num_points = meters_len / interval except ZeroDivisionError: self.parent.on_message.emit('Interwał musi być większy od 0', Qgis.Critical, 4) self.reset() return points_on_line = [] max_interval = 0 intervals = [] for i in range(int(num_points) + 1): pt = geom.interpolate(float(max_interval)).asPoint() points_on_line.append(f'{pt.y()}%20{pt.x()}') intervals.append(max_interval) max_interval += interval data = {'points': points_on_line, 'intervals': intervals} self.task = QgsTask.fromFunction( 'Pobieranie wysokości dla przekroju...', self.generateProfileFromPoints, data=data) QgsApplication.taskManager().addTask(self.task)
def runTask(self, dataRun): def finished(exception, dataResult): def endEditable(): self.layerPolygon.commitChanges() self.layerPolygon.updateExtents() if self.isIniEditable: self.layerPolygon.startEditing() def setRenderLayer(): fileStyle = os.path.join( os.path.dirname( __file__ ), "gimpselectionfeature_with_expression.qml" ) self.layerPolygon.loadNamedStyle( fileStyle ) self.mapCanvasEffects.zoom( self.layerPolygon, dataResult['geomBBox'] ) self.msgBar.clearWidgets() if exception: self.msgBar.pushMessage( self.nameModulus, str( exception ), Qgis.Critical ) return self.msgBar.pushMessage( self.nameModulus, dataResult['message'], dataResult['level'] ) if 'getFeatures' == dataResult['process']: endEditable() imgs = filter( lambda f: os.path.exists( f ), ( self.pathfileImage, self.pathfileImageSelect ) ) [ os.remove( item ) for item in imgs ] if dataResult['isOk']: setRenderLayer() self.setEnabledWidgetTransfer( True, True ) else: self.setEnabledWidgetTransfer( True ) else: self.setEnabledWidgetTransfer( True ) def run(task, data): self.worker.setData( task, data ) return self.worker.run() self.setEnabledWidgetTransfer( False ) task = QgsTask.fromFunction('GimpSelectionFeature Task', run, dataRun, on_finished=finished ) if not self.layerPolygon is None: task.setDependentLayers( [ self.layerPolygon ] ) self.taskManager.addTask( task )
def extendLayerByHeight(self): """ Rozszerzenie warstwy o pole z wysokością """ layer = self.cbLayers.currentLayer() if not layer: return exp = QgsExpression('num_geometries($geometry) > 1') multipart_features = [f for f in layer.getFeatures(QgsFeatureRequest(exp))] if multipart_features: self.on_message.emit("Rozszerzenie nie jest możliwe, ponieważ warstwa zawiera obiekty o wieloczęściowych geometriach", Qgis.Warning, 5) if self.cbxUpdateField.isChecked(): field_id = layer.dataProvider().fields().indexFromName(self.cbFields.currentText()) elif 'nmt_wys' not in layer.fields().names(): field_id = self.createNewField(layer) else: field_id = layer.dataProvider().fields().indexFromName('nmt_wys') if self.cbxSelectedOnly.isChecked(): feats = layer.selectedFeatures() else: feats = list(layer.getFeatures()) data = {'feats':feats, 'field_id':field_id} self.task2 = QgsTask.fromFunction('Dodawanie pola z wysokościa...', self.addHeightToFields, data=data) QgsApplication.taskManager().addTask(self.task2)
def start_download(self): """ Start/cancel task to download item asset(s) """ if self.downloading: globals()['cbers4a_tasks'].cancel() else: item_id = self.dockwidget.item_id.text() sel_assets = self.dockwidget.assetsList.checkedItems() if sel_assets: assets = [asset for asset in sel_assets] else: assets = self.result[item_id].assets # # create the task variable with global scope # workaround for QGIS Issue #28531 # https://gis.stackexchange.com/questions/296175/issues-with-qgstask-and-task-manager/304801#304801 # globals()['cbers4a_tasks'] = QgsTask.fromFunction( 'Download {0}'.format(item_id), self.download_asset, on_finished=self.download_finished, item_id=item_id, assets=assets) # self.info('Starting task to download {} asset(s)'.format(item_id), duration=1) QgsApplication.taskManager().addTask(globals()['cbers4a_tasks']) # lock downloading self.downloading = True self.dockwidget.options.setDisabled(True) self.dockwidget.results.setDisabled(True) self.dockwidget.downloadButton.setText('Cancel Download') self.dockwidget.downloadButton.setStyleSheet( 'background-color: #ff3336') self.dockwidget.assetsList.setDisabled(True)
def testTaskFromFunctionFinishedWithVal(self): """ test that task from function can have callback finished function and is passed result values""" result_value = None def finished_single_value_result(e, value): nonlocal result_value assert e is None result_value = value return task = QgsTask.fromFunction('test task', run_single_val_result, on_finished=finished_single_value_result) QgsApplication.taskManager().addTask(task) while task.status() not in [QgsTask.Complete, QgsTask.Terminated]: pass while QgsApplication.taskManager().countActiveTasks() > 0: QCoreApplication.processEvents() # check that the finished function was called self.assertEqual(task.returned_values, (5)) self.assertFalse(task.exception) self.assertEqual(result_value, 5)
def on_run(self): verhang_first_distance = self.dlg.verhang_table[0][1] verhang_largest_distance = self.dlg.verhang_table[-1][1] #verhang_gradient_check = all([row[2]>0 for row in self.dlg.verhang_table]) if self.dlg.trace_max_distance > verhang_largest_distance: self.iface.messageBar().pushMessage("Maximum distance in gradient table not sufficient, not all pipes have a gradient", level=Qgis.Warning, duration=5) elif self.dlg.dekking == 0: self.iface.messageBar().pushMessage("Minimum cover should be larger than 0", level=Qgis.Warning, duration=5) else: task = QgsTask.fromFunction('Calculate Pipe Levels', bereken_bobs, on_finished=self.completed, trace_fn = self.dlg.trace_layer, dem_fn = self.dlg.raster_layer, minimale_dekking = self.dlg.dekking, maximale_valhoogte = self.dlg.valhoogte, verhang_tabel = self.dlg.verhang_table, egalisatie = self.dlg.egalisatie, egalisatiehoek = self.dlg.egalisatie_hoek) self.tm.addTask(task)
def testExecuteSqlCancel(self): """Test that feedback can cancel an executeSql query""" if hasattr(self, 'slowQuery'): md = QgsProviderRegistry.instance().providerMetadata(self.providerKey) conn = md.createConnection(self.uri, {}) feedback = QgsFeedback() def _run(task): conn.executeSql(self.slowQuery, feedback=feedback) def _cancel(): feedback.cancel() start = time.time() QtCore.QTimer.singleShot(500, _cancel) task = QgsTask.fromFunction('test long running query', _run) QgsApplication.taskManager().addTask(task) while task.status() not in [QgsTask.Complete, QgsTask.Terminated]: QgsApplication.processEvents() end = time.time() self.assertTrue(end - start < 1)
def testTaskFromFunctionFinished(self): """ test that task from function can have callback finished function""" called = False def finished_no_val(e): nonlocal called assert e is None called = True return task = QgsTask.fromFunction('test task', run_no_result, on_finished=finished_no_val) QgsApplication.taskManager().addTask(task) while task.status() not in [QgsTask.Complete, QgsTask.Terminated]: pass while QgsApplication.taskManager().countActiveTasks() > 0: QCoreApplication.processEvents() # check that the finished function was called self.assertFalse(task.returned_values) self.assertFalse(task.exception) self.assertTrue(called)
def georeferencingVideo(parent): """ Extract Current Frame Thread :param packet: Parent class """ image = parent.videoWidget.currentFrame() folder = getVideoFolder(parent.fileName) qgsu.createFolderByName(folder, "mosaic") out = os.path.join(folder, "mosaic") position = str(parent.player.position()) taskGeoreferencingVideo = QgsTask.fromFunction( 'Georeferencing Current Frame Task', GeoreferenceFrame, image=image, output=out, p=position, on_finished=parent.finishedTask, flags=QgsTask.CanCancel) QgsApplication.taskManager().addTask(taskGeoreferencingVideo) return
def SaveACSV(self): """ Save Table as CSV """ data = self.player.GetPacketData() out, _ = askForFiles(self, QCoreApplication.translate( "QgsFmvMetadata", "Save CSV"), isSave=True, exts='csv') if out == "": return def finished(e): QApplication.restoreOverrideCursor() if e is None: qgsu.showUserAndLogMessage(QCoreApplication.translate( "QgsFmvMetadata", "Succesfully creating CSV")) else: qgsu.showUserAndLogMessage(QCoreApplication.translate( "QgsFmvMetadata", "Failed creating CSV : "), str(e), level=QGis.Warning) return task = QgsTask.fromFunction('Save CSV Report Task', QgsFmvMetadata.CreateCSV, out=out, data=data, VManager=self.VManager, on_finished=finished, flags=QgsTask.CanCancel) QCoreApplication.processEvents() tm.addTask(task) QCoreApplication.processEvents() while task.status() not in [QgsTask.Complete, QgsTask.Terminated]: QCoreApplication.processEvents() pass while QgsApplication.taskManager().countActiveTasks() > 0: QCoreApplication.processEvents() return
def testTaskFromFunctionFinishedWithMultipleValues(self): """ test that task from function can have callback finished function and is passed multiple result values""" result_value = None result_statement = None def finished_multiple_value_result(e, results): nonlocal result_value nonlocal result_statement assert e is None result_value = results[0] result_statement = results[1] task = QgsTask.fromFunction('test task', run_multiple_val_result, on_finished=finished_multiple_value_result) QgsApplication.taskManager().addTask(task) while task.status() not in [QgsTask.Complete, QgsTask.Terminated]: pass while QgsApplication.taskManager().countActiveTasks() > 0: QCoreApplication.processEvents() # check that the finished function was called self.assertEqual(task.returned_values, (5, 'whoo')) self.assertFalse(task.exception) self.assertEqual(result_value, 5) self.assertEqual(result_statement, 'whoo')
def SaveAsPDF(self): """ Save Table as pdf The drawings are saved by default """ timestamp = _seconds_to_time(self.player.currentInfo) # Frame save drawings frame = BurnDrawingsImage(self.player.videoWidget.currentFrame() , self.player.videoWidget.grab(self.player.videoWidget.surface.videoRect()).toImage()) data = self.player.GetPacketData() rows = self.VManager.rowCount() columns = self.VManager.columnCount() fileName = self.player.fileName out, _ = askForFiles(self, QCoreApplication.translate( "QgsFmvMetadata", "Save PDF"), isSave=True, exts='pdf') if not out: return task = QgsTask.fromFunction('Save PDF Report Task', self.CreatePDF, out=out, timestamp=timestamp, data=data, frame=frame, rows=rows, columns=columns, fileName=fileName, VManager=self.VManager, on_finished=self.finishedTask, flags=QgsTask.CanCancel) QgsApplication.taskManager().addTask(task) return
def report_per_field(self): """Creates a QgsTask in order to collect data then on finish it runs simple_field.""" if self.path is None: QMessageBox.information( None, self.tr('Error'), self.tr('A directory to save the report must be selected.')) return year = self.dw.DEReportYear.text() if self.dw.RBReportWithoutDetails.isChecked(): self.report_name = '{p}\\{t}_{y}.pdf'.format( p=self.path, t=self.tr('GeoDataFarm_Limited_report'), y=year) if self.dw.RBAllYear.isChecked(): year = None else: year = self.dw.DEReportYear.text() task = QgsTask.fromFunction('Run import text data', self.collect_data, year, on_finished=self.simple_field) self.tsk_mngr.addTask(task) else: report_name = '{p}\\{t}_{y}.pdf'.format( p=self.path, t=self.tr('GeoDataFarm_Limited_report'), y=year)
def SaveACSV(self): """ Save Table as CSV """ data = self.player.GetPacketData() out, _ = askForFiles( self, QCoreApplication.translate("QgsFmvMetadata", "Save CSV"), isSave=True, exts="csv", ) if not out: return task = QgsTask.fromFunction( "Save CSV Report Task", self.CreateCSV, out=out, data=data, VManager=self.VManager, on_finished=self.finishedTask, flags=QgsTask.CanCancel, ) QgsApplication.taskManager().addTask(task) return
def CreateBitratePlot(self): ''' Create video Plot Bitrate Thread ''' sender = self.sender().objectName() if sender == "actionAudio": taskactionAudio = QgsTask.fromFunction( 'Show Audio Bitrate', self.BitratePlot.CreatePlot, fileName=self.fileName, output=None, t='audio', on_finished=self.finishedTask, flags=QgsTask.CanCancel) QgsApplication.taskManager().addTask(taskactionAudio) elif sender == "actionVideo": taskactionVideo = QgsTask.fromFunction( 'Show Video Bitrate', self.BitratePlot.CreatePlot, fileName=self.fileName, output=None, t='video', on_finished=self.finishedTask, flags=QgsTask.CanCancel) QgsApplication.taskManager().addTask(taskactionVideo) elif sender == "actionSave_Audio": fileaudio, _ = askForFiles(self, QCoreApplication.translate( "QgsFmvPlayer", "Save Audio Bitrate Plot"), isSave=True, exts=[ "png", "pdf", "pgf", "eps", "ps", "raw", "rgba", "svg", "svgz" ]) if not fileaudio: return taskactionSave_Audio = QgsTask.fromFunction( 'Save Action Audio Bitrate', self.BitratePlot.CreatePlot, fileName=self.fileName, output=fileaudio, t='audio', on_finished=self.finishedTask, flags=QgsTask.CanCancel) QgsApplication.taskManager().addTask(taskactionSave_Audio) elif sender == "actionSave_Video": filevideo, _ = askForFiles(self, QCoreApplication.translate( "QgsFmvPlayer", "Save Video Bitrate Plot"), isSave=True, exts=[ "png", "pdf", "pgf", "eps", "ps", "raw", "rgba", "svg", "svgz" ]) if not filevideo: return taskactionSave_Video = QgsTask.fromFunction( 'Save Action Video Bitrate', self.BitratePlot.CreatePlot, fileName=self.fileName, output=filevideo, t='video', on_finished=self.finishedTask, flags=QgsTask.CanCancel) QgsApplication.taskManager().addTask(taskactionSave_Video)
def createTaskCalcIntersects(self): taskManager = QgsApplication.taskManager() self.task1 = QgsTask.fromFunction(self.MESSAGE_CATEGORY, self.calcIntersects, on_finished=self.completed) taskManager.addTask(self.task1)
def call_import_temps_task(self): self.taskWeather = QgsTask.fromFunction(u'QWeather', self.import_temps_task, on_finished=self.completed, wait_time=4) QgsApplication.taskManager().addTask(self.taskWeather)
def update_pic(self): """Collects the data that the user gave as input and starts the QgsTask that runs the SQL query. On finish plot_data is called""" if self.canvas is not None: self.dlg.mplvl.removeWidget(self.canvas) if self.dlg.CBLimitArea.isChecked() and self.search_area == '': try: self.iface.actionSaveActiveLayerEdits().trigger() self.iface.actionToggleEditing().trigger() feature = self.add_field.field.getFeature(1) QgsProject.instance().removeMapLayer(self.add_field.field.id()) self.add_field.field = None except: QMessageBox.information( None, self.tr("Error:"), self. tr('No coordinates where found, did you mark the field on the canvas?' )) return limiting_polygon = feature.geometry().asWkt() self.search_area = limiting_polygon elif self.dlg.CBLimitArea.isChecked( ) and self.add_field.field is not None: self.iface.actionSaveActiveLayerEdits().trigger() self.iface.actionToggleEditing().trigger() feature = self.add_field.field.getFeature(1) QgsProject.instance().removeMapLayer(self.add_field.field.id()) self.add_field.field = None limiting_polygon = feature.geometry().asWkt() self.search_area = limiting_polygon elif self.dlg.CBLimitArea.isChecked(): limiting_polygon = self.search_area else: limiting_polygon = None self.search_area = '' other_parameters = {} investigating_param = {} investigating_param['values'] = [] prefixes = {} prefix_count = 0 for nbr, col in enumerate(self.layout_dict.keys()): self.update_top_panel(nbr, col) for tbl_nr in range(len(self.layout_dict[col]['tbl'])): table = self.layout_dict[col]['tbl'][tbl_nr] schema = self.layout_dict[col]['schema'][tbl_nr] data_type = self.layout_dict[col]['type'] ha = self.layout_dict[col]['harvest'][tbl_nr]['tbl_name'] s_t = '{schema}.{table}'.format(schema=schema, table=table) if s_t not in prefixes.keys(): prefix_count += 1 prefixes[s_t] = 'a{prefix_count}'.format( prefix_count=prefix_count) if self.cb[nbr].isChecked(): column_investigated = col if ha not in investigating_param.keys(): investigating_param[ha] = {} investigating_param[ha]['ha_col'] = \ self.layout_dict[col]['harvest'][tbl_nr]['index_col'] if s_t not in investigating_param[ha].keys(): investigating_param[ha][s_t] = {} investigating_param[ha][s_t] = {} investigating_param[ha][s_t]['prefix'] = prefixes[s_t] investigating_param[ha][s_t]['col'] = col i_col = col analyse_params = self.get_initial_distinct_values( col, table, schema) investigating_param['values'].extend( analyse_params['distinct_values']) # Can happens multiple times, hence shouldn't be a problem. if data_type == 'checked': investigating_param['checked'] = True else: investigating_param['checked'] = False else: if ha not in other_parameters.keys(): other_parameters[ha] = {} if s_t not in other_parameters[ha].keys(): other_parameters[ha][s_t] = {} other_parameters[ha][s_t]['prefix'] = prefixes[s_t] other_parameters[ha][s_t][col] = {} if self.layout_dict[col]['type'] == 'max_min': other_parameters[ha][s_t][col]['type'] = 'max_min' other_parameters[ha][s_t][col][ 'min'] = self.layout_dict[col]['min'] other_parameters[ha][s_t][col][ 'max'] = self.layout_dict[col]['max'] else: other_parameters[ha][s_t][col]['type'] = 'checked' other_parameters[ha][s_t][col]['check_text'] = "'" if not investigating_param['checked']: minvalue = float(self.layout_dict[i_col]['min']) maxvalue = float(self.layout_dict[i_col]['max']) values = copy.deepcopy(investigating_param['values']) for value in investigating_param['values']: if value is None: values.remove(value) elif round(value, 3) < minvalue: values.remove(value) elif round(value, 3) > maxvalue: values.remove(value) investigating_param['values'] = values if not investigating_param['checked'] and len( investigating_param['values']) > 20: investigating_param['hist'] = True investigating_param['values'].sort() temp = [] for val in range( 0, len(investigating_param['values']), int(round(len(investigating_param['values']) / 20))): temp.append(investigating_param['values'][val]) temp.append(investigating_param['values'][-1]) investigating_param['values'] = temp elif not investigating_param['checked']: investigating_param['hist'] = False investigating_param['values'].sort() else: investigating_param['hist'] = False investigating_param['values'] = "'" other_parameters, investigating_param = self.update_checked_field( other_parameters, investigating_param) min_counts = self.dlg.minNumber.text() self.column_investigated = column_investigated self.investigating_param = investigating_param task1 = QgsTask.fromFunction('running script', sql_query, investigating_param, other_parameters, self.db, min_counts, limiting_polygon, on_finished=self.plot_data) self.tsk_mngr.addTask(task1)
def call_import_photos(self): self.taskPhotos = QgsTask.fromFunction(u'ImportPhotos', self.import_photos_task, on_finished=self.completed, wait_time=4) QgsApplication.taskManager().addTask(self.taskPhotos)
def prepareXsdForMetadata(self): task = QgsTask.fromFunction('Wczytywanie schematu XSD dla metadanych', self.createMetadataValidator) if task.description() not in [task.description() for task in QgsApplication.taskManager().activeTasks()]: QgsApplication.taskManager().addTask(task) QgsMessageLog.logMessage('starting XSD reading task')
def convertVideo(self): '''Convert Video To Other Format ''' out, _ = askForFiles(self, QCoreApplication.translate( "QgsFmvPlayer", "Save Video as..."), isSave=True, exts=[ "mp4", "ogg", "avi", "mkv", "webm", "flv", "mov", "mpg", "mp3" ]) if not out: return # TODO : Make Correct format Conversion and embebed metadata info = self.converter.probeInfo(self.fileName) if info is not None: if self.HasFileAudio: audio_codec = info.audio.codec audio_samplerate = info.audio.audio_samplerate audio_channels = info.audio.audio_channels video_codec = info.video.codec video_width = info.video.video_width video_height = info.video.video_height video_fps = info.video.video_fps _, out_ext = os.path.splitext(out) if self.HasFileAudio: options = { 'format': out_ext[1:], 'audio': { 'codec': audio_codec, 'samplerate': audio_samplerate, 'channels': audio_channels }, 'video': { 'codec': video_codec, 'width': video_width, 'height': video_height, 'fps': video_fps } } else: options = { 'format': out_ext[1:], 'video': { 'codec': video_codec, 'width': video_width, 'height': video_height, 'fps': video_fps } } taskConvertVideo = QgsTask.fromFunction('Converting Video Task', self.converter.convert, infile=self.fileName, outfile=out, options=options, twopass=False, on_finished=self.finishedTask, flags=QgsTask.CanCancel) QgsApplication.taskManager().addTask(taskConvertVideo)
def run_waiting(self): waiting_msg = WaitingMsg() task = QgsTask.fromFunction('waiting', waiting_msg.run) self.tsk_mngr.addTask(task)
def updateFeatures(self): def addExpField(expField): field = QgsField(expField, QVariant.String) sq, iniBraces, endBraces = "'{}" value = self._frm_url for c in 'xyzq': src = f"{iniBraces}{c}{endBraces}" dest = f"{sq} || {c} || {sq}" value = value.replace(src, dest) end_sq = f" || {sq}" if value.endswith(end_sq): total = -1 * (len(end_sq)) value = f"{sq}" + value[:total] else: value = f"{sq}{value}{sq}" self._layer.addExpressionField(value, field) def run(task, prov): totalTiles = self.getTotalTiles() c_tiles = 0 for tile in self._tilesCanvas(self._zoom): if task.isCanceled(): return {'canceled': True, 'total': c_tiles} feat = QgsFeature() geom = QgsGeometry.fromRect(tile.rect) feat.setGeometry(geom) feat.setAttributes([tile.x, tile.y, tile.z, tile.q]) prov.addFeature(feat) progress = c_tiles / totalTiles * 100 task.setProgress(progress) c_tiles += 1 return {'canceled': False, 'total': c_tiles} def finished(exception, result=None): self.selectedFeatures.emit(0) self._layer.updateExtents() self._layer.triggerRepaint() self._currentTask = None r = {'name': 'update'} if exception: r['error'] = f"Exception, {exception}" r.update(result) self.finishProcess.emit(r) if self._currentTask: self._currentTask.cancel() return prov = self._layer.dataProvider() prov.truncate() # Delete all expField = 'url' idExpField = self._layer.fields().indexOf(expField) if idExpField > -1: self._layer.removeExpressionField(idExpField) if self._frm_url: addExpField(expField) # Task self.finishedTask = False args = { 'description': f"{self.__class__.__name__}.populate", 'function': run, 'prov': prov, 'on_finished': finished } self._currentTask = QgsTask.fromFunction(**args) self._currentTask.setDependentLayers([self._layer]) self.taskManager.addTask(self._currentTask)
def trigger_insection(self): """Preparing the data, by setting the correct type (including the date and time format), creating a shp file and finally ensure that the coordinates is in EPSG:4326 """ params = {} params['schema'] = self.data_type params['column_types'] = self.col_types params['heading_row'] = [] for col in self.heading_row: params['heading_row'].append(check_text(col)) params['encoding'] = self.encoding params['file_name_with_path'] = self.file_name_with_path params['field'] = self.ITD.CBField.currentText() params['longitude_col'] = self.longitude_col params['latitude_col'] = self.latitude_col params['focus_col'] = [] if self.ITD.RBDateOnly.isChecked(): is_ok, first_date = check_date_format( self.sample_data, check_text(self.ITD.ComBDate.currentText()), self.ITD.ComBDate_2.currentText()) if not is_ok: QMessageBox.information( None, self.tr('Error'), self. tr("The date format didn't match the selected format, please change" )) return params['date_row'] = check_text(self.ITD.ComBDate.currentText()) params['date_format'] = self.ITD.ComBDate_2.currentText() params['all_same_date'] = '' manual_date = 'date_' table_date = first_date else: params['all_same_date'] = self.ITD.DE.text() manual_date = 'c_' + self.ITD.DE.text() table_date = self.ITD.DE.text() params['date_row'] = '' self.tbl_name = check_text(self.ITD.CBField.currentText() + '_' + self.data_type + '_' + table_date) params['tbl_name'] = self.tbl_name if self.db.check_table_exists(self.tbl_name, self.data_type): return for i in range(self.add_to_param_row_count): params['focus_col'].append( check_text(self.ITD.TWtoParam.item(i, 0).text())) self.focus_cols = params['focus_col'] if params['schema'] == 'harvest': params['yield_row'] = params['focus_col'][0] params['max_yield'] = float(self.ITD.LEMaximumYield.text()) params['min_yield'] = float(self.ITD.LEMinimumYield.text()) self.mff.insert_manual_data(manual_date, self.ITD.CBField.currentText(), self.tbl_name, self.data_type) params['sep'] = self.sep params['tr'] = self.tr params['epsg'] = self.ITD.LEEPSG.text() if float(self.ITD.LEMoveX.text()) != 0.0 or float( self.ITD.LEMoveY.text()) != 0.0: params['move'] = True params['move_x'] = float(self.ITD.LEMoveX.text()) params['move_y'] = float(self.ITD.LEMoveY.text()) else: params['move'] = False #a = insert_data_to_database('debug', self.db, params) #print(a) task = QgsTask.fromFunction('Run import text data', insert_data_to_database, self.db, params, on_finished=self.finish) self.tsk_mngr.addTask(task)
def openAllResults(self): resultPath = os.path.join( os.path.join(self.ProjectDirectory, "Results"), self.NetworkName + "_" + self.Scenario) if not os.path.exists(resultPath): self.iface.messageBar().pushMessage( "Warning", "No scenario results are available", level=1, duration=5) return if not self.setVariables(): return # Process self.setLayersNames(True) # Task is necessary because after remove layers, DBF files are in use. With the task, # the remove process finishs and filer are not in use task1 = QgsTask.fromFunction("", self.removeResults, on_finished=self.openAllResultsProcess) task1.run() QgsApplication.taskManager().addTask(task1)