本文整理汇总了Python中midvatten_utils.ru函数的典型用法代码示例。如果您正苦于以下问题:Python ru函数的具体用法?Python ru怎么用?Python ru使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了ru函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: __init__
def __init__(self, tables_columns):
super(DistinctValuesBrowser, self).__init__()
self.browser_label = qgis.PyQt.QtWidgets.QLabel(ru(QCoreApplication.translate('DistinctValuesBrowser', 'DB browser:')))
self.table_label = qgis.PyQt.QtWidgets.QLabel(ru(QCoreApplication.translate('DistinctValuesBrowser', 'Table')))
self._table_list = qgis.PyQt.QtWidgets.QComboBox()
self.column_label = qgis.PyQt.QtWidgets.QLabel(ru(QCoreApplication.translate('DistinctValuesBrowser', 'Column')))
self._column_list = qgis.PyQt.QtWidgets.QComboBox()
self.distinct_value_label = qgis.PyQt.QtWidgets.QLabel(ru(QCoreApplication.translate('DistinctValuesBrowser', 'Distinct values')))
self._distinct_value = qgis.PyQt.QtWidgets.QComboBox()
self._distinct_value.setEditable(True)
self._table_list.addItem('')
self._table_list.addItems(sorted(tables_columns.keys()))
self._table_list.currentIndexChanged.connect(
lambda: self.replace_items(self._column_list, tables_columns.get(self.table_list, [])))
self._column_list.currentIndexChanged.connect(
lambda: self.replace_items(self._distinct_value, self.get_distinct_values(self.table_list, self.column_list)))
for widget in [self.browser_label, self.table_label, self._table_list,
self.column_label, self._column_list, self.distinct_value_label,
self._distinct_value]:
self.layout.addWidget(widget)
示例2: update_settings
def update_settings(self, _db_settings):
db_settings = None
if not _db_settings or _db_settings is None:
return
try:
db_settings = ast.literal_eval(_db_settings)
except:
utils.MessagebarAndLog.warning(log_msg=ru(QCoreApplication.translate('DatabaseSettings', 'Reading db_settings failed using string %s'))%_db_settings)
else:
pass
for setting in [db_settings, _db_settings]:
if isinstance(setting, str):
# Assume that the db_settings is an old spatialite database
if os.path.isfile(setting) and setting.endswith('.sqlite'):
db_settings = {'spatialite': {'dbpath': setting}}
break
if isinstance(db_settings, dict):
for dbtype, settings in db_settings.items():
self.dbtype_combobox = dbtype
self.choose_dbtype()
for setting_name, value in settings.items():
try:
if hasattr(self.db_settings_obj, str(setting_name)):
setattr(self.db_settings_obj, str(setting_name), value)
else:
utils.MessagebarAndLog.warning(log_msg=ru(QCoreApplication.translate('DatabaseSettings', "Databasetype %s didn' t have setting %s"))%(dbtype, setting_name))
except:
print(str(setting_name))
raise
else:
utils.MessagebarAndLog.warning(bar_msg=ru(QCoreApplication.translate('DatabaseSettings', "Could not load database settings. Select database again!")), log_msg=ru(QCoreApplication.translate('DatabaseSettings', 'Tried to load db_settings string %s'))%_db_settings)
示例3: print_selected_features
def print_selected_features(self):
""" Returns a list of obsid as unicode
thelayer is an optional argument, if not given then activelayer is used
"""
activelayer = utils.get_active_layer()
if activelayer is not self.activelayer:
self.reload_combobox()
utils.MessagebarAndLog.warning(
bar_msg=ru(QCoreApplication.translate('ValuesFromSelectedFeaturesGui', 'Column list reloaded. Select column and press Ok.')))
return None
self.selected_column = self.columns.currentText()
selected_values = utils.getselectedobjectnames(thelayer=self.activelayer, column_name=self.selected_column)
if not selected_values:
utils.MessagebarAndLog.info(bar_msg=ru(QCoreApplication.translate('ValuesFromSelectedFeaturesGui',
'No features selected!')))
else:
if self.unique_sorted_list_checkbox.isChecked():
selected_values = sorted(set(selected_values))
nr = len(selected_values)
utils.MessagebarAndLog.info(bar_msg=ru(
QCoreApplication.translate('ValuesFromSelectedFeaturesGui',
'List of %s selected %s written to log'))%(str(nr), self.selected_column),
log_msg='{} IN ({})'.format(self.selected_column,
', '.join(["'{}'".format(value) if value is not None else 'NULL'
for value in selected_values])))
self.close()
示例4: load_files
def load_files(self):
charset = utils.ask_for_charset()
if not charset:
raise utils.UserInterruptError()
filename = utils.select_files(only_one_file=True, extension=ru(QCoreApplication.translate('GeneralCsvImportGui', "Comma or semicolon separated csv file %s;;Comma or semicolon separated csv text file %s;;Comma or semicolon separated file %s"))%('(*.csv)', '(*.txt)', '(*.*)'))
if isinstance(filename, (list, tuple)):
filename = filename[0]
filename = ru(filename)
delimiter = utils.get_delimiter(filename=filename, charset=charset, delimiters=[',', ';'])
self.file_data = self.file_to_list(filename, charset, delimiter)
header_question = utils.Askuser(question="YesNo", msg=ru(QCoreApplication.translate('GeneralCsvImportGui', """Does the file contain a header?""")))
utils.start_waiting_cursor()
if header_question.result:
# Remove duplicate header entries
header = self.file_data[0]
seen = set()
seen_add = seen.add
remove_cols = [idx for idx, x in enumerate(header) if x and (x in seen or seen_add(x))]
self.file_data = [[col for idx, col in enumerate(row) if idx not in remove_cols] for row in self.file_data]
self.table_chooser.file_header = self.file_data[0]
else:
header = ['Column ' + str(colnr) for colnr in range(len(self.file_data[0]))]
self.table_chooser.file_header = header
self.file_data.reverse()
self.file_data.append(header)
self.file_data.reverse()
utils.stop_waiting_cursor()
示例5: showSurvey
def showSurvey(self):
#lyr = self.iface.activeLayer() # THIS IS TSPLOT-method, GETS THE SELECTED LAYER
lyr = self.layer
ids = lyr.selectedFeatureIds()
if len(ids) == 0:
utils.pop_up_info(ru(QCoreApplication.translate(' Stratigraphy', "No selection")), ru(QCoreApplication.translate(' Stratigraphy', "No features are selected")))
return
# initiate the datastore if not yet done
self.initStore()
utils.start_waiting_cursor() # Sets the mouse cursor to wait symbol
try: # return from store.getData is stored in data only if no object belonging to DataSanityError class is created
self.data = self.store.getData(ids, lyr) # added lyr as an argument!!!
except DataSanityError as e: # if an object 'e' belonging to DataSanityError is created, then do following
print("DataSanityError %s"%str(e))
utils.stop_waiting_cursor()
utils.pop_up_info(ru(QCoreApplication.translate(' Stratigraphy', "Data sanity problem, obsid: %s\n%s")) % (e.sond_id, e.message))
return
except Exception as e: # if an object 'e' belonging to DataSanityError is created, then do following
print("exception : %s"%str(e))
utils.stop_waiting_cursor()
utils.MessagebarAndLog.critical(bar_msg=ru(QCoreApplication.translate(' Stratigraphy', "The stratigraphy plot failed, check Midvatten plugin settings and your data!")))
return
utils.stop_waiting_cursor() # Restores the mouse cursor to normal symbol
# show widget
w = SurveyDialog()
#w.widget.setData2_nosorting(data) #THIS IS IF DATA IS NOT TO BE SORTED!!
w.widget.setData(self.data) #THIS IS ONLY TO SORT DATA!!
w.show()
self.w = w # save reference so it doesn't get deleted immediately This has to be done both here and also in midvatten instance
示例6: load_from_active_layer
def load_from_active_layer(self, only_selected=False):
self.file_data = None
self.table_chooser.file_header = None
active_layer = utils.get_active_layer()
if not active_layer:
utils.MessagebarAndLog.critical(bar_msg=ru(QCoreApplication.translate('GeneralCsvImportGui', 'Import error, no layer selected.')))
return None
if not only_selected:
active_layer.selectAll()
features = list(active_layer.getSelectedFeatures())
file_data = [[ru(field.name()) for field in active_layer.fields()]]
[file_data.append([ru(attr) if all([ru(attr).strip() != 'NULL' if attr is not None else '', attr is not None]) else '' for attr in feature]) for feature in features]
geometries = [feature.geometry().asWkt() if feature.geometry().asWkt() else None for feature in features]
if any(geometries):
geom_name = 'geometry'
while geom_name in file_data[0]:
geom_name += '_'
file_data[0].append(geom_name)
[file_data[idx+1].append(wkt) for idx, wkt in enumerate(geometries)]
self.file_data = file_data
self.table_chooser.file_header = file_data[0]
示例7: sanityCheck
def sanityCheck(self, _surveys):
""" does a sanity check on retreived data """
surveys = {}
for (obsid, survey) in _surveys.items():
# check whether there's at least one strata information
if len(survey.strata) == 0:
#raise DataSanityError(str(obsid), "No strata information")
try:
print(str(obsid) + " has no strata information")
except:
pass
continue
#del surveys[obsid]#simply remove the item without strata info
else:
# check whether the depths are valid
top1 = survey.strata[0].depthTop
bed1 = survey.strata[0].depthBot
for strato in survey.strata[1:]:
# top (n) < top (n+1)
if top1 > strato.depthTop:
raise DataSanityError(str(obsid), ru(QCoreApplication.translate('SurveyStore', "Top depth is incorrect (%.2f > %.2f)")) % (top1, strato.depthTop))
# bed (n) < bed (n+1)
if bed1 > strato.depthBot:
raise DataSanityError(str(obsid), ru(QCoreApplication.translate('SurveyStore', "Bed depth is incorrect (%.2f > %.2f)")) % (bed1, strato.depthBot))
# bed (n) = top (n+1)
if bed1 != strato.depthTop:
raise DataSanityError(str(obsid), ru(QCoreApplication.translate('SurveyStore', "Top and bed depth don't match (%.2f != %.2f)")) % (bed1, strato.depthTop))
top1 = strato.depthTop
bed1 = strato.depthBot
surveys[obsid] = survey
return surveys
示例8: execute
def execute(self, sql, all_args=None):
"""
:param sql:
:param all_args: A list of lists of equal lenght to sql (if sql is a list) containing arguments for ? in the
corresponding sql.
:return:
"""
if isinstance(sql, str):
sql = [sql]
elif not isinstance(sql, (list, tuple)):
raise TypeError(ru(QCoreApplication.translate('DbConnectionManager', 'DbConnectionManager.execute: sql must be type string or a list/tuple of strings. Was %s'))%ru(type(sql)))
for idx, line in enumerate(sql):
if all_args is None:
try:
self.cursor.execute(line)
except Exception as e:
textstring = ru(QCoreApplication.translate('sql_load_fr_db', """DB error!\n SQL causing this error:%s\nMsg:\n%s""")) % (ru(line), ru(str(e)))
utils.MessagebarAndLog.warning(
bar_msg=utils.sql_failed_msg(),
log_msg=textstring)
raise
elif isinstance(all_args, (list, tuple)):
args = all_args[idx]
try:
self.cursor.execute(line, args)
except Exception as e:
textstring = ru(QCoreApplication.translate('sql_load_fr_db', """DB error!\n SQL causing this error:%s\nusing args %s\nMsg:\n%s""")) % (ru(line), ru(args), ru(str(e)))
utils.MessagebarAndLog.warning(
bar_msg=utils.sql_failed_msg(),
log_msg=textstring)
raise
else:
raise TypeError(ru(QCoreApplication.translate('DbConnectionManager', 'DbConnectionManager.execute: all_args must be a list/tuple. Was %s')) % ru(type(all_args)))
示例9: import_foreign_keys
def import_foreign_keys(self, dbconnection, goal_table, temptablename, foreign_keys, existing_columns_in_temptable):
#TODO: Empty foreign keys are probably imported now. Must add "case when...NULL" to a couple of sql questions here
#What I want to do:
# import all foreign keys from temptable that doesn't already exist in foreign key table
# insert into fk_table (to1, to2) select distinct from1(cast as), from2(cast as) from temptable where concatted_from_and_case_when_null not in concatted_to_and_case_when_null
for fk_table, from_to_fields in foreign_keys.items():
from_list = [x[0] for x in from_to_fields]
to_list = [x[1] for x in from_to_fields]
if not all([_from in existing_columns_in_temptable for _from in from_list]):
utils.MessagebarAndLog.warning(bar_msg=ru(QCoreApplication.translate('midv_data_importer', 'Import of foreign keys failed, see log message panel')), log_msg=ru(QCoreApplication.translate('midv_data_importer', 'There were keys missing for importing to fk_table %s, so no import was done.'))%fk_table)
continue
nr_fk_before = dbconnection.execute_and_fetchall('''select count(*) from %s''' % fk_table)[0][0]
table_info = db_utils.db_tables_columns_info(table=fk_table, dbconnection=dbconnection)[fk_table]
column_headers_types = dict([(row[1], row[2]) for row in table_info])
null_replacement_string = 'NULL_NULL_NULL_NULL_NULL_NULL_NULL_NULL_NULL_NULL'
concatted_from_string = '||'.join(["CASE WHEN %s is NULL THEN '%s' ELSE %s END"%(x, null_replacement_string, x) for x in from_list])
concatted_to_string = '||'.join(["CASE WHEN %s is NULL THEN '%s' ELSE %s END"%(x, null_replacement_string, x) for x in to_list])
sql = u'INSERT INTO %s (%s) SELECT DISTINCT %s FROM %s AS b WHERE %s NOT IN (SELECT %s FROM %s) AND %s'%(fk_table,
u', '.join([u'"{}"'.format(k) for k in to_list]),
u', '.join([u'''CAST("b"."%s" as "%s")'''%(k, column_headers_types[to_list[idx]]) for idx, k in enumerate(from_list)]),
temptablename,
concatted_from_string,
concatted_to_string,
fk_table,
' AND '.join([''' b.{} IS NOT NULL and b.{} != '' '''.format(k, k, k) for k in from_list]))
dbconnection.execute(sql)
nr_fk_after = dbconnection.execute_and_fetchall('''select count(*) from %s''' % fk_table)[0][0]
if nr_fk_after > nr_fk_before:
utils.MessagebarAndLog.info(log_msg=ru(QCoreApplication.translate('midv_data_importer', 'In total %s rows were imported to foreign key table %s while importing to %s.'))%(str(nr_fk_after - nr_fk_before), fk_table, goal_table))
示例10: delete_selected_range
def delete_selected_range(self, table_name):
""" Deletes the current selected range from the database from w_levels_logger
:return: De
"""
current_loaded_obsid = self.obsid
selected_obsid = self.load_obsid_and_init()
if current_loaded_obsid != selected_obsid:
utils.pop_up_info(ru(QCoreApplication.translate('Calibrlogger', "Error!\n The obsid selection has been changed but the plot has not been updated. No deletion done.\nUpdating plot.")))
self.update_plot()
return
elif selected_obsid is None:
utils.pop_up_info(ru(QCoreApplication.translate('Calibrlogger', "Error!\n No obsid was selected. No deletion done.\nUpdating plot.")))
self.update_plot()
return
fr_d_t = str((self.FromDateTime.dateTime().toPyDateTime() - datetime.datetime(1970,1,1)).total_seconds())
to_d_t = str((self.ToDateTime.dateTime().toPyDateTime() - datetime.datetime(1970,1,1)).total_seconds())
sql_list = []
sql_list.append(r"""DELETE FROM "%s" """%table_name)
sql_list.append(r"""WHERE obsid = '%s' """%selected_obsid)
# This %s is db formatting for seconds. It is not used as python formatting!
sql_list.append(r"""AND CAST(strftime('%s', date_time) AS NUMERIC) """)
sql_list.append(r""" > '%s' """%fr_d_t)
# This %s is db formatting for seconds. It is not used as python formatting!
sql_list.append(r"""AND CAST(strftime('%s', date_time) AS NUMERIC) """)
sql_list.append(r""" < '%s' """%to_d_t)
sql = ''.join(sql_list)
really_delete = utils.Askuser("YesNo", ru(QCoreApplication.translate('Calibrlogger', "Do you want to delete the period %s to %s for obsid %s from table %s?"))%(str(self.FromDateTime.dateTime().toPyDateTime()), str(self.ToDateTime.dateTime().toPyDateTime()), selected_obsid, table_name)).result
if really_delete:
utils.start_waiting_cursor()
db_utils.sql_alter_db(sql)
utils.stop_waiting_cursor()
self.update_plot()
示例11: secplot_default_template
def secplot_default_template():
loaded_template = {}
loaded_template['ticklabels_Text_set_fontsize'] = {'fontsize': 10}
loaded_template['Axes_set_xlabel'] = {
'xlabel': ru(QCoreApplication.translate('SectionPlot', "Distance along section")),
'fontsize': 10}
loaded_template['Axes_set_xlim'] = None # Tuple like (min, max)
loaded_template['Axes_set_ylim'] = None # Tuple like (min, max)
loaded_template['Axes_set_ylabel'] = {
'ylabel': ru(QCoreApplication.translate('SectionPlot', "Level, masl")),
'fontsize': 10}
loaded_template['dems_Axes_plot'] = {'DEFAULT': {'marker': 'None',
'linestyle': '-',
'linewidth': 1}}
loaded_template['drillstop_Axes_plot'] = {'marker': '^',
'markersize': 8,
'linestyle': '',
'color': 'black'}
loaded_template['geology_Axes_bar'] = {'edgecolor': 'black'}
loaded_template['grid_Axes_grid'] = {'b': True,
'which': 'both',
'color': '0.65',
'linestyle': '-'}
loaded_template['layer_Axes_annotate'] = {'xytext': (5, 0),
'textcoords': 'offset points',
'ha': 'left',
'va': 'center',
'fontsize': 9,
'bbox': {'boxstyle': 'square,pad=0.05',
'fc': 'white',
'edgecolor': 'white',
'alpha': 0.6}}
loaded_template['legend_Axes_legend'] = {'loc': 0,
'framealpha': 1,
'fontsize': 10}
loaded_template['legend_Text_set_fontsize'] = 10
loaded_template['legend_Frame_set_facecolor'] = '1'
loaded_template['legend_Frame_set_fill'] = False
loaded_template['obsid_Axes_annotate'] = {'xytext': (0, 10),
'textcoords': 'offset points',
'ha': 'center',
'va': 'top',
'fontsize': 9,
'rotation': 0,
'bbox': {'boxstyle': 'square,pad=0.05', 'fc': 'white',
'edgecolor': 'white', 'alpha': 0.4}}
loaded_template['obsid_Axes_bar'] = {'edgecolor': 'black',
'fill': False,
'linewidth': 0.5}
loaded_template['plot_height'] = None
loaded_template['plot_width'] = None
loaded_template[
'Figure_subplots_adjust'] = {} # {"top": 0.95, "bottom": 0.15, "left": 0.09, "right": 0.97}
loaded_template['wlevels_Axes_plot'] = {'DEFAULT': {'markersize': 6,
'marker': 'v',
'linestyle': '-',
'linewidth': 1}}
return loaded_template
示例12: write_strat_data
def write_strat_data(self, strat_data, _strat_columns, table_header, strat_sql_columns_list, decimal_separator):
if table_header:
rpt = r"""<P><U><B><font size=3>%s</font></B></U></P>""" % table_header
else:
rpt = r''
strat_columns = [x.split(';')[0] for x in _strat_columns]
col_widths = [x.split(';')[1] if len(x.split(';')) == 2 else '1*' for x in _strat_columns]
rpt += r"""<TABLE style="font-family:'Ubuntu'; font-size:8pt; font-weight:400; font-style:normal;" WIDTH=100% BORDER=0 CELLPADDING=0 class="no-spacing" CELLSPACING=0>"""
for col_width in col_widths:
rpt += r"""<COL WIDTH={}>""".format(col_width)
rpt += r"""<p style="font-family:'Ubuntu'; font-size:8pt; font-weight:400; font-style:normal;">"""
headers_txt = OrderedDict([('stratid', ru(QCoreApplication.translate('Drillreport2_strat', 'Layer number'))),
('depth', ru(QCoreApplication.translate('Drillreport2_strat', 'level (m b gs)'))),
('depthtop', ru(QCoreApplication.translate('Drillreport2_strat', 'top of layer (m b gs)'))),
('depthbot', ru(QCoreApplication.translate('Drillreport2_strat', 'bottom of layer (m b gs)'))),
('geology', ru(QCoreApplication.translate('Drillreport2_strat', 'geology, full text'))),
('geoshort', ru(QCoreApplication.translate('Drillreport2_strat', 'geology, short'))),
('capacity', ru(QCoreApplication.translate('Drillreport2_strat', 'capacity'))),
('development', ru(QCoreApplication.translate('Drillreport2_strat', 'development'))),
('comment', ru(QCoreApplication.translate('Drillreport2_strat', 'comment')))])
if len(strat_data) > 0:
rpt += r"""<TR VALIGN=TOP>"""
for header in strat_columns:
rpt += r"""<TD><P><font size=2><u>{}</font></P></u></TD>""".format(headers_txt[header])
rpt += r"""</TR>"""
for rownr, row in enumerate(strat_data):
rpt += r"""<TR VALIGN=TOP>"""
for col in strat_columns:
if col == 'depth':
try:
depthtop_idx = strat_sql_columns_list.index('depthtop')
depthbot_idx = strat_sql_columns_list.index('depthbot')
except ValueError:
utils.MessagebarAndLog.critical(bar_msg=ru(QCoreApplication.translate('Drillreport2',
'Programming error, depthtop and depthbot columns was supposed to exist')))
rpt += r"""<TD><P><font size=1> </font></P></TD>""".format(value)
else:
depthtop = '' if row[depthtop_idx] == 'NULL' else row[depthtop_idx].replace('.', decimal_separator)
depthbot = '' if row[depthbot_idx] == 'NULL' else row[depthbot_idx].replace('.', decimal_separator)
rpt += r"""<TD><P><font size=1>{}</font></P></TD>""".format(' - '.join([depthtop, depthbot]))
else:
value_idx = strat_sql_columns_list.index(col)
value = '' if row[value_idx] == 'NULL' else row[value_idx]
if col in ('depthtop', 'depthbot') and decimal_separator != '.':
value = value.replace('.', decimal_separator)
rpt += r"""<TD><P><font size=1>{}</font></P></TD>""".format(value)
rpt += r"""</TR>"""
rpt += r"""</p>"""
rpt += r"""</TABLE>"""
return rpt
示例13: calcselected
def calcselected(self):
obsids = ru(utils.getselectedobjectnames(self.layer), keep_containers=True)
if not obsids:
utils.pop_up_info(ru(QCoreApplication.translate('Calclvl',
'Adjustment aborted! No obsids selected.')),
ru(QCoreApplication.translate('Calclvl', 'Error')))
else:
self.calc(obsids)
示例14: replace_items
def replace_items(combobox, items):
combobox.clear()
combobox.addItem('')
try:
combobox.addItems(ru(items, keep_containers=True))
except TypeError:
for item in items:
combobox.addItem(ru(item))
示例15: setlastcalibration
def setlastcalibration(self, obsid):
if not obsid=='':
self.lastcalibr = self.getlastcalibration(obsid)
text = ru(QCoreApplication.translate('Calibrlogger', """There is no earlier known position for the logger in %s"""))%self.selected_obsid
if self.lastcalibr:
if all([self.lastcalibr[0][0], self.lastcalibr[0][1] is not None, self.lastcalibr[0][1] != '']):
text = ru(QCoreApplication.translate('Calibrlogger', "Last pos. for logger in %s was %s masl at %s"))%(obsid, str(self.lastcalibr[0][1]), str(self.lastcalibr[0][0]))
self.INFO.setText(text)