def assert_installed(win=None, modules=[], binaries=[]):
missing = defaultdict(list)
for items, what, func in ((modules, 'modules', find_spec),
(binaries, 'binaries', which)):
for item in items:
if not func(item):
missing[what].append(item)
if missing:
msg = []
for subject, names in missing.items():
if len(names) == 1:
subject = {'modules': 'module', 'binaries': 'binary'}[subject]
msg.append('%s "%s"' % (subject, '", "'.join(names)))
msg = 'You are missing the %s for this.' % ' and '.join(msg)
if win:
from PyQt5.QtWidgets import QMessageBox
QMessageBox.warning(win, ' ', msg)
else:
raise ImportError(msg)
return not missing
python类warning()的实例源码
def extraction_done(self, outputs):
nb_written_all, wrote_endpoints = 0, False
for folder, output in outputs.items():
nb_written, wrote_endpoints = extractor_save(BASE_PATH, folder, output)
nb_written_all += nb_written
if wrote_endpoints:
self.set_view(self.welcome)
QMessageBox.information(self.view, ' ', '%d endpoints and their <i>.proto</i> structures have been extracted! You can now reuse the <i>.proto</i>s or fuzz the endpoints.' % nb_written_all)
elif nb_written_all:
self.set_view(self.welcome)
QMessageBox.information(self.view, ' ', '%d <i>.proto</i> structures have been extracted! You can now reuse the <i>.protos</i> or define endpoints for them to fuzz.' % nb_written_all)
else:
self.set_view(self.choose_extractor)
QMessageBox.warning(self.view, ' ', 'This extractor did not find Protobuf structures in the corresponding format for specified files.')
def save(self):
"""
Orders the AppController to save the current trained models.
Parameters
----------
None
Return
----------
None
"""
if self.controller.isTrained():
self.controller.save()
QMessageBox.information(self.train, "Message", "Save succesful.")
else:
QMessageBox.warning(self.train, "Message", "Must have at least 1 trained classifier.")
def trainSystem(self):
"""
Orders the AppController to train a model based on the selected database.
Parameters
----------
None
Return
----------
None
"""
if self.path_train:
trained = self.controller.train(self.path_train, self.comboBoxDatabaseTrain.currentText())
self.path_train = None
if not trained:
QMessageBox.critical(self.train, "Message", "File columns or labels mismatch.")
else:
QMessageBox.information(self.train, "Message", "Training succesful.")
else:
QMessageBox.warning(self.train, "Message", "Must pick a database file.")
def add_bars(win):
if len(win.edges) == 0:
QMessageBox.warning(win, "????????!", "?? ?????? ??????????!")
return
win.pen.setColor(red)
w.lines.append([[win.edges[0].x() - 15, win.edges[0].y() - 15],
[win.edges[1].x() - 15, win.edges[1].y() - 15]])
add_row(w.table_bars)
i = w.table_bars.rowCount() - 1
item_b = QTableWidgetItem("[{0}, {1}]".format(win.edges[0].x() - 15 , win.edges[0].y() - 15))
item_e = QTableWidgetItem("[{0}, {1}]".format(win.edges[1].x() - 15, win.edges[1].y() - 15))
w.table_bars.setItem(i, 0, item_b)
w.table_bars.setItem(i, 1, item_e)
w.scene.addLine(win.edges[0].x() - 15, win.edges[0].y() - 15, win.edges[1].x() - 15, win.edges[1].y() - 15, w.pen)
win.pen.setColor(red)
w.lines.append([[win.edges[0].x() + 15, win.edges[0].y() + 15],
[win.edges[1].x() + 15, win.edges[1].y() + 15]])
add_row(w.table_bars)
i = w.table_bars.rowCount() - 1
item_b = QTableWidgetItem("[{0}, {1}]".format(win.edges[0].x() + 15, win.edges[0].y() + 15))
item_e = QTableWidgetItem("[{0}, {1}]".format(win.edges[1].x() + 15, win.edges[1].y() + 15))
w.table_bars.setItem(i, 0, item_b)
w.table_bars.setItem(i, 1, item_e)
w.scene.addLine(win.edges[0].x() + 15, win.edges[0].y() + 15, win.edges[1].x() + 15, win.edges[1].y() + 15, w.pen)
def clipping(win):
if len(win.clip) <= 1:
QMessageBox.warning(win, "??????!", "?????????? ?? ?????!")
if len(win.pol) <= 1:
QMessageBox.warning(win, "??????!", "????????????? ?? ?????!")
if len(win.pol) > 1 and len(win.clip) > 1:
norm = isConvex(win.clip)
if not norm:
QMessageBox.warning(win, "??????!", "?????????? ?? ????????!???????? ?? ????? ???? ?????????!")
else:
p = sutherland_hodgman(win.clip, win.pol, norm)
if p:
win.pen.setWidth(2)
win.pen.setColor(red)
win.scene.addPolygon(p, win.pen)
win.pen.setWidth(1)
def bolumFormatla(self, hedef):
komut = "umount -l " + hedef
self.f.bilgi_label.setText(komut)
if os.path.exists(hedef):
os.system(komut)
self.f.surec_cubugu.setValue(50)
komut2 = "mkfs.ext4 -F " + hedef
try:
os.system(komut2)
self.f.surec_cubugu.setValue(100)
except OSError as e:
QMessageBox.warning(self, self.e.d[self.e.s_d]["Hata"], str(e))
qApp.closeAllWindows()
self.f.bilgi_label.setText(hedef + self.e.d[self.e.s_d][" disk bölümü formatland?."])
else:
QMessageBox.warning(self, self.e.d[self.e.s_d]["Hata"], self.e.d[self.e.s_d]["Disk bulunamad?. Program kapat?lacak."])
qApp.closeAllWindows()
def App_Cont_or_Calc_IntPts(self, geo=None, cont=None):
"""
App_Cont_or_Calc_IntPts()
Calculate and assign the start and end points
"""
tol = g.config.point_tolerance
points = []
warning = 0
for i in range(len(geo)):
# logger.debug("geo: %s" %geo[i])
warning = geo[i].App_Cont_or_Calc_IntPts(cont, points, i, tol, warning)
if warning:
QMessageBox.warning(g.window, self.tr("Short Elements"),
self.tr("Length of some Elements too short!"
"\nLength must be greater than tolerance."
"\nSkipped Geometries"))
return points
def create_file(self, update_data=True):
# TODO: save changes in current file
file_name = get_save_file_name(_('Create SportOrg file'), _("SportOrg file (*.sportorg)"),
str(time.strftime("%Y%m%d")))
if file_name is not '':
try:
GlobalAccess().clear_filters(remove_condition=False)
File(file_name, logging.root).create()
self.file = file_name
self.add_recent_file(self.file)
self.set_title(file_name)
except Exception as e:
logging.exception(str(e))
QMessageBox.warning(self, _('Error'), _('Cannot create file') + ': ' + file_name)
# remove data
if update_data:
races[0] = Race()
self.refresh()
def tag_save(self):
tag_id = self.tag_id_line_edit.text()
tag_name = self.tag_name_line_edit.text()
tag_description = self.tag_description_text_edit.toPlainText()
if tag_name == '' or tag_description == '':
QMessageBox.warning(self, 'tag editor', 'tag name and description can\'t be empty')
else:
if len(tag_name) > 8:
QMessageBox.warning(self, 'tag editor', 'tag name is not greater than 8 characters')
else:
if tag_id:
self.tag.name = tag_name
self.tag.description = tag_description
self.db_helper.update_tag()
QMessageBox.information(self, 'tag editor', 'tag update success')#todo ??????
else:
tag = self.db_helper.query_tag_by_name(tag_name)
if tag is None:
tag = self.db_helper.insert_tag(tag_name, tag_description)
self.tag_id_line_edit.setText(str(tag.id))
self.tag = tag
QMessageBox.information(self, 'tag editor', 'tag insert success')#todo ??????
else:
QMessageBox.warning(self, 'tag editor', 'tag has existed')
def acquire_vm_from_vmpool(self, rowid):
"""
Description: A machine will be acquired by a user if they click on the icon of a VmPool
Arguments: The row id that has been clicked. This relationship is stored using the VmData class.
Returns: Nothing
"""
self.lastclick = int(time()) # Last click timestamp update
vmtype = self.vmdata[rowid].vmtype
if vmtype == 'vmpool':
try:
QMessageBox.information(None, _('apptitle') + ': ' + _('info'), _('acquiring_vm_from_pool'))
vmp = conf.OVIRTCONN.vmpools.get(id=self.vmdata[rowid].vmid)
vmp.allocatevm()
self.refresh_grid()
except ConnectionError:
QMessageBox.critical(None, _('apptitle') + ': ' + _('error'), _('unexpected_connection_drop'))
quit()
except RequestError:
QMessageBox.critical(None, _('apptitle') + ': ' + _('error'), _('cannot_attach_vm_to_user'))
else:
QMessageBox.warning(None, _('apptitle') + ': ' + _('warning'), _('object_is_not_a_vmpool'))
def calculateDalpha(self):
try:
a_par = self.ui.alpha_par.text();
a_perp = self.ui.alpha_perp.text();
if (a_par == ""):
a_par = "0";
if (a_perp == ""):
a_perp = "0";
self.ui.deltaAlpha.setText(str(round(float(a_par)-float(a_perp),5)));
except ValueError:
self.ui.deltaAlpha.setText("");
# try:
# result = QMessageBox.information(QWidget(),'Information','Some informative text');
# print(result);
# result = QMessageBox.warning(QWidget(),'Warn','WARNONNN!');
# result = QMessageBox.warning(QWidget(),'Warn','WARNONNN!');
# print(result);
# self.enable_save_option();
# finally:
# self.enable_Go_button();
#
def check_user_and_secret():
github_secret = github.GithubSecret()
if not github_secret.secret_available:
QMessageBox.warning(None, 'No authentification possible',
'Authentificated requests are not possible - this will limit you to only a few GitHub requests per hour. '
'Please ensure that the user file ({}) and the secret file ({}) exist in your setup. '
'The file names must match exactly, including the file extension, which is not visible on all systems.'.format(
configserver.get('user_file'), configserver.get('secret_file')))
##
# \brief Class for communication between UI and algorithm.
#
# This class is responsible for the communication between the algorithm and the UI (written in QML).
# All classes decleared as Qt slots are callable from QML. Only one instance of the class should be used.
def get_file_content(self):
filename = QFileDialog.getOpenFileName(None, 'Open file')[0]
if filename is '':
return ''
try:
with open(filename, 'r') as file:
try:
return str(file.read())
except Exception as e:
QMessageBox.warning(None, 'Can not open file', 'Can not open file {}:\n{}'.format(filename, e))
return ''
except IOError:
return ''
##
# \brief Returns the remaining rate limit
#
# Returns -1 if an error occurred. This request do not xount against the rate limit.
#
# \return Rate limit or -1 if error occurred
def login_click(self):
string = ''
ID = self.inputID.text()
passwd = self.inputPW.text()
result = mysign.login(ID, passwd, s, key)
if result == 1:
QMessageBox.warning(self, '???', '??? ?? ????? ?? ????.')
elif result == 3:
QMessageBox.warning(self, '???', '??? ?? ????? ???? ????')
else:
QMessageBox.information(self, '???', result + '?, ?????.')
user_info['username'] = result
user_info['account'] = ID
self.tmp = MainForm()
self.hide()
self.tmp.draw()
self.inputID.setText("")
self.inputPW.setText("")
def check_btn_click(self):
ID = self.inputID.text()
if len(ID) < 5 or len(ID) > 20:
QMessageBox.warning(self, '?? ??', '???? 5???? 20?? ??? ?????.')
self.inputID.setText("")
return
elif len(ID) > 5 or len(ID) < 20:
string = mysign.overlap(ID, s, key)
if string == 'success':
QMessageBox.information(self, '?? ??', '?? ??? ??? ???')
self.i = 1
else:
QMessageBox.warning(self, '?? ??', '?? ???? ??? ???.')
self.inputID.setText("")
def search_click(self):
ID = self.input_search_ID.text()
mysocket.sendMsg(s, '3', key)
mysocket.sendMsg(s, ID, key)
string = mysocket.getMsg(s, key)
self.add_btn.setVisible(False)
self.nickname.setText(string)
if string == 'not Find!' or string == 'not Find! ':
QMessageBox.warning(self, '', '???? ?? ID ???.')
self.nickname.setText('???? ?? ID ???.')
elif friend.__contains__(ID) == False:
self.add_btn.setVisible(True)
#string2 = mysocket.getMsg(s, key)
#print(string2)
else:
QMessageBox.warning(self, '', '?? ???? ?? ??? ???.')
self.nickname.setText(self.input_search_ID.text()+' ?? ?? ??? ??? ???.')
def with_btn_click(self):
if self.input_PW.text() == '':
QMessageBox.warning(self, '?? ??', '????? ??? ???')
return
answer = QMessageBox.warning(self, '?? ??', '??? ?? ???????\n??? ??? ??? ??????.', QMessageBox.Ok|QMessageBox.No)
if (answer == QMessageBox.No):
return
else:
QMessageBox.information(self, '??? ??', '?? ????')
"""
mysocket.sendMsg(s, '2', key)
mysocket.sendMsg(s, self.input_PW.text(), key)
result = mysocket.getMsg(s, key)
if result == 'PW different' or result == 'PW different ':
QMessageBox.warning(self, '?? ??', '?? ?? ??')
return
else:
QMessageBox.information(self, '?? ??', '???? ??????. ??~')
??? ???.
"""
def onDelete(self):
student = self.selection
if not student:
return
confirm = QMessageBox.warning(QtWidgets.QWidget(),
"????", "????????",
QMessageBox.Yes | QMessageBox.No)
if confirm == QMessageBox.Yes:
item = self.tableIndex[student]
n = self.studentTable.topLevelItemCount()
for i in range(0, n):
if self.studentTable.topLevelItem(i) == item:
self.studentTable.takeTopLevelItem(i)
self.tableList.remove(student)
self.tableIndex.pop(student)
break
public.studentManager.delete(student)
def prompt_rename(self):
text, good = QInputDialog.getText(self.app.view, ' ', 'Rename this field:', text=self.text(0).strip('+ '))
if text:
if not match('^[a-zA-Z0-9_]+$', text):
QMessageBox.warning(self.app.view, ' ', 'This is not a valid alphanumeric name.')
self.prompt_rename()
else:
try:
if self.do_rename(text):
return
except Exception:
pass
QMessageBox.warning(self.app.view, ' ', 'Field was not found in .proto, did you edit it elsewhere?')
def new_endpoint(self, path):
if not self.proto_fs.isDir(path):
path = self.proto_fs.filePath(path)
if not getattr(self, 'only_resp_combo', False):
self.create_endpoint.pbRequestCombo.clear()
self.create_endpoint.pbRespCombo.clear()
has_msgs = False
for name, cls in load_proto_msgs(path):
has_msgs = True
if not getattr(self, 'only_resp_combo', False):
self.create_endpoint.pbRequestCombo.addItem(name, (path, name))
self.create_endpoint.pbRespCombo.addItem(name, (path, name))
if not has_msgs:
QMessageBox.warning(self.view, ' ', 'There is no message defined in this .proto.')
return
self.create_endpoint.reqDataSubform.hide()
if not getattr(self, 'only_resp_combo', False):
self.create_endpoint.endpointUrl.clear()
self.create_endpoint.transports.clear()
self.create_endpoint.sampleData.clear()
self.create_endpoint.pbParamKey.clear()
self.create_endpoint.parsePbCheckbox.setChecked(False)
for name, meta in transports.items():
item = QListWidgetItem(meta['desc'], self.create_endpoint.transports)
item.setData(Qt.UserRole, (name, meta.get('ui_data_form')))
elif getattr(self, 'saved_transport_choice'):
self.create_endpoint.transports.setCurrentItem(self.saved_transport_choice)
self.pick_transport(self.saved_transport_choice)
self.saved_transport_choice = None
self.only_resp_combo = False
self.set_view(self.create_endpoint)
def validateSystem(self):
"""
Orders the AppController to validate a model based on the selected database.
Parameters
----------
None
Return
----------
None
"""
if self.path_validate:
checked, validated, accuracy, precision, sensitivity, specificity, kappa = self.controller.validate(self.path_validate, self.spinBoxFolds.value(), self.comboBoxDatabaseValidate.currentText())
self.path_validate = None
if not validated:
QMessageBox.warning(self.validate, "Message", "Classifier for "+ self.comboBoxDatabaseValidate.currentText() + " database is not trained.")
self.clearValidateLineEdits()
else:
self.lineEditAccuracy.setText(str(accuracy))
self.lineEditPrecision.setText(str(precision))
self.lineEditSensitivity.setText(str(sensitivity))
self.lineEditSpecificity.setText(str(specificity))
self.lineEditKappa.setText(str(kappa))
QMessageBox.information(self.train, "Message", "Validation finished.")
if not checked:
QMessageBox.critical(self.validate, "Message", "File columns or labels mismatch.")
self.clearValidateLineEdits()
else:
QMessageBox.warning(self.validate, "Message", "Must pick a database file.")
self.clearValidateLineEdits()
def predictDiagnosis(self):
"""
Orders the AppController to predict the class and probabilities of the selected features.
Parameters
----------
None
Return
----------
None
"""
predicted, diagnosis, prediction, classes = self.controller.predict(self.comboBoxCDR.currentText(),
self.spinBoxMMSE.value(),
self.spinBoxMoCA.value(),
self.spinBoxGDS.value(),
self.spinBoxAge.value(),
self.spinBoxEducation.value(),
self.comboBoxDatabase.currentText())
if not predicted:
QMessageBox.warning(self.train, "Message", "Classifier for "+ self.comboBoxDatabase.currentText() + " database is not trained.")
self.clearResultLineEdits()
else:
self.lineEditResult.setText(str(diagnosis[0]))
self.lineEditSane.setText(str(prediction[0][list(classes).index('Sane')]) + '%')
self.lineEditMild.setText(str(prediction[0][list(classes).index('Mild')]) + '%')
self.lineEditSerious.setText(str(prediction[0][list(classes).index('Serious')]) + '%')
def _save_local(self):
path = self.localPathEdit.text()
if not path:
QMessageBox.warning(self, "Invalid path", "Enter correct path for local file.")
return
try:
with open(path, "w") as file:
file.write(self.codeEdit.toPlainText())
except IOError:
QMessageBox.critical(self, "Save operation failed", "Couldn't save the file. Check path and permissions.")
def _save_to_mcu(self):
name = self.remotePathEdit.text()
if not name:
QMessageBox.warning(self, "Invalid name", "Enter correct name for remote file.")
return
content = self.codeEdit.toPlainText()
if not content:
QMessageBox.warning(self, "Empty file", "Can't write empty file.")
return
progress_dlg = FileTransferDialog(FileTransferDialog.UPLOAD)
progress_dlg.finished.connect(self.mcu_file_saved.emit)
progress_dlg.show()
self._connection.write_file(name, content, progress_dlg.transfer)
def clipping(win):
norm = isConvex(win.edges)
if not norm:
QMessageBox.warning(win, "??????!", "?????????? ?? ????????!???????? ?? ????? ???? ?????????!")
for b in win.lines:
win.pen.setColor(blue)
cyrus_beck(b, win.edges, norm, win.scene, win.pen)
win.pen.setColor(red)
def bolumBagla(self, hedef, baglam):
komut = "mount " + hedef + " " + baglam
try:
os.system(komut)
self.f.surec_cubugu.setValue(100)
except OSError as e:
QMessageBox.warning(self, self.e.d[self.e.s_d]["Hata"], str(e))
qApp.closeAllWindows()
self.f.bilgi_label.setText(hedef + " " + baglam + self.e.d[self.e.s_d][" alt?na ba?land?."])
def bolumCoz(self, hedef):
komut = "umount -l " + hedef
try:
os.system(komut)
except OSError as e:
QMessageBox.warning(self, self.e.d[self.e.s_d]["Hata"], str(e))
qApp.closeAllWindows()
self.f.surec_cubugu.setValue(100)
self.f.bilgi_label.setText(hedef + self.e.d[self.e.s_d][" çözüldü."])
def checkDiskSpace(self, path: str):
# noinspection PyCallByClass
if self.spaceWarningDelivered or not QFileInfo.exists(path):
return
info = QStorageInfo(path)
available = info.bytesAvailable() / 1000 / 1000
if available < VideoService.spaceWarningThreshold:
warnmsg = 'There is less than {0}MB of disk space available at the target folder selected to save ' \
'your media. VidCutter WILL FAIL to produce your media if you run out of space during ' \
'operations.'
QMessageBox.warning(self.parentWidget(), 'Disk space warning',
warnmsg.format(VideoService.spaceWarningThreshold))
self.spaceWarningDelivered = True
def Get_Line_Pairs(self, string):
line = 0
line_pairs = dxflinepairsClass([])
# Start at the first SECTION
while not string[line].startswith("SECTION"):
line += 1
line -= 1
# Continue to the end if no error occurs. Otherwise abort with error
try:
while line + 1 < len(string):
line_pairs.line_pair.append(dxflinepairClass(int(string[line].strip()), string[line + 1].strip()))
line += 2
except ValueError:
message = self.tr('Reading stopped at line %i.\n "%s" is not a valid code (number) - please, check/correct dxf file')\
% (line + 1, string[line].strip())
logger.warning(message)
QMessageBox.warning(g.window, self.tr("Warning reading linepairs"), message)
line_pairs.nrs = len(line_pairs.line_pair)
logger.debug(self.tr('Did read %i of linepairs from DXF') % line_pairs.nrs)
return line_pairs
# Search the sections in the DXF file to recognize Blocke.