Пример #1
0
def main():
    ch = Checker()

    while True:
        a = int(ch.readLine())
        if a == -1:
            break
        ch.checkRange(a, 0, 315, 'd')
        ch.check(a % 45 == 0, 'd is a multiple of 45')
Пример #2
0
def fst_check(name):
    with open(path + '/sets/' + name + '.json') as f_obj:
        set = json.load(f_obj)
        for dic in set:
            if dic['f'] == 0:
                comic = Checker(dic['url'], dic['txt'], dic['pos'])
                comic.check()
            else:
                failure_mode(name, dic['name'], dic['txt'])
Пример #3
0
def check_set(setname):
    file = setname
    try:
        with open(path + '/sets/' + file + '.json') as f_obj:
            set = json.load(f_obj)
    except FileNotFoundError:
        print('That set does not exist')
        return
    for dic in set:
        comic = Checker(dic['url'], dic['txt'], dic['pos'])
        if comic.check() == 'This comic has updated':
            print(dic['name'] + ': ' + comic.check() + ' ' + '\033[32m' +
                  dic['url'] + '\033[0m')
        elif comic.check() == 'This comic has not been updated':
            print(dic['name'] + ': ' + comic.check())
def main():
  ch = Checker()

  while True:
    n = int(ch.readLine())
    if n == 0:
      break
    ch.checkRange(n, 3, 50, 'n')
    ps = []
    for _ in range(n):
      x, y = [int(w) for w in ch.readLine().strip().split()]
      ch.check((x, y) not in ps, "no dup points: (%d, %d)" % (x, y))
      ch.checkRange(x, -500, 500, 'x')
      ch.checkRange(y, -500, 500, 'y')
      ps.append((x, y))
Пример #5
0
def main():
    ch = Checker()

    while True:
        n = int(ch.readLine())
        if n == 0:
            break
        ch.checkRange(n, 1, 5, 'n')
        ps = set()
        ps.add((0, 0))
        for _ in range(n):
            x, y = [int(w) for w in ch.readLine().strip().split()]
            ch.check((x, y) not in ps, "no dup points")
            ch.checkRange(x, -50, 50, 'x')
            ch.checkRange(y, -50, 50, 'y')
            ps.add((x, y))
def main():
    ch = Checker()

    while True:
        n = int(ch.readLine())
        if n == -1:
            break
        ch.checkRange(n, 0, 23, 'n')
        ps = set()
        ps.add((1, 1))
        ps.add((5, 5))
        for _ in range(n):
            x, y = [int(w) for w in ch.readLine().strip().split()]
            ch.check((x, y) not in ps, 'no dup points')
            ch.checkRange(x, 1, 5, 'x')
            ch.checkRange(y, 1, 5, 'y')
            ps.add((x, y))
def checkproxys():
    from checker import Checker

    proxylist = open(proxyfile)
    proxylist = list(proxylist)
    checker = Checker()
    for item in proxylist:
        if checker.check(item):
            continue
        else:
            output = open(workingfile, 'a')
            output.write(item)
Пример #8
0
class Client:
    def __init__(self, session_name):
        self.session_name = session_name

        # Create the command checker
        self.checker = Checker()

        # Create the socket server
        self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

        # Get the server address
        self.server_address = self._get_server_address()

        # Run the server
        self.run()

    def _get_server_address(self):
        file_paths = constants.generate_file_paths(self.session_name)
        nets_file_path = file_paths['NETS_FILE_PATH']
        with open(nets_file_path, 'r') as file:
            for (host, port) in csv.reader(file, delimiter=','):
                return host, int(port)

    def run(self):
        # Connect to server
        self.socket.connect(self.server_address)

        # Loop
        while True:
            # Get the command from user input
            command = input('linda> ')

            # Check the command first before sending it
            if self.checker.check(command):
                # Send the command to the server
                encoded_command = command.encode('utf-8')
                compressed_command = zlib.compress(encoded_command)
                self.socket.send(compressed_command)

                # Get response from server
                data = self.socket.recv(1024)

                if not data:
                    # Consider no response as end of socket connection
                    self.socket.close()
                else:
                    # Decode the result and print it
                    uncompressed_data = zlib.decompress(data)
                    result = uncompressed_data.decode('utf-8')
                    print(result)
Пример #9
0
def main():
    ch = Checker()

    while True:
        n, m = ch.matchRegex(r'(\d+) (\d+)')
        n = int(n)
        m = int(m)
        if n == 0:
            break

        ch.checkRange(n, N_MIN, N_MAX, 'N')
        ch.checkRange(m, M_MIN, min(n * n - n, M_MAX), 'M')

        edgeset = set()
        for _ in xrange(m):
            a, b = ch.matchRegex(r'(\d+) (\d+)')
            a = int(a)
            b = int(b)
            ch.checkRange(a, 1, n, 'A')
            ch.checkRange(b, 1, n, 'B')
            ch.check(a != b, "there should not be self-loop")
            edgeset.add((a * (n + 1) + b))

        ch.checkLength(edgeset, m)
Пример #10
0
PATH = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, PATH + '/module')

from getpass import getpass, getuser
from checker import Checker
from mail import Email

name = os.environ.get('PYMAIL_ADR')
if not name:
    name = raw_input('User : '******'Sorry .. retry')
        psw = getpass()
    e = Email(name, psw)
    try:
        e.send()
    except:
        print('\nSomething went wrong, retry')
    else:
        if e.failed:
            print('Failed sending to ' + str(e.failed))
        else:
            print('Sent')
except KeyboardInterrupt:
    print('\nTerminated')
    sys.exit(0)
Пример #11
0
class CheckUI(Ui_MainWindow,QMainWindow):
    def __init__(self,parent=None,*arg,**kwargs):
        super().__init__(parent,*arg,**kwargs)
        # self.setAttribute( Qt.WA_SetWindowIcon )
        self.setAttribute(Qt.WA_StyleSheet)
        self.setupUi(self)
        self.chk =Checker()
        self.setup()
        self.input_ln.setFocus()

    def setAccount(self,user:str=None):
        self.user = user 

    def setup(self):
        self.user = "******"
        #加载日志管理器
        self.log = Log()
        #加载设置器c
        self.cfg = config
        
        #设置菜单栏的Action,绑定方法
        self.exit_ac.triggered.connect(self.close)
        self.edit_plicy_ac.triggered.connect(self.showPolicyManager)
        self.edit_item_ac.triggered.connect(self.showItemManager)
        self.ab_qt_ac.triggered.connect(lambda _,s="关于qt":QMessageBox.aboutQt(self,s))
        self.ab_author_ac.triggered.connect(self.showAuthor)
        self.ab_version_ac.triggered.connect(self.showVersion)
        self.logout_ac.triggered.connect(self.logout)
        self.help_ac.triggered.connect(self.showHelp)

        #设置tabelwidgets表头的尺寸#
        self.tableWidget.setColumnWidth(0,140)
        self.tableWidget.setColumnWidth(1,120)
        self.tableWidget.setColumnWidth(2,200)   
        #设置表头的行高
        self.tableWidget.setRowHeight(0,20)
        
        #在客户栏中初始化列表
        self.combo_list=(self.custom_cb,self.module_cb,self.name_cb,self.pn_cb)
        self.custom_cb.addItems(self.cfg.policy_cfg.keys())
        
        #设置系统托盘
        self.tray = QSystemTrayIcon(self)
        self.tray.setIcon(QIcon(":/bo/resource/ico.png"))
        minimizeAction = QAction("最小化", self, triggered = self.hide)
        maximizeAction = QAction("最大化", self, triggered = self.showMaximized)
        restoreAction = QAction("恢复默认大小", self, triggered = self.showNormal)
        quitAction = QAction("退出", self, triggered = QApplication.instance().quit)  # 退出APP
        self.trayMenu = QMenu(self)
        self.trayMenu.addAction(minimizeAction)
        self.trayMenu.addAction(maximizeAction)
        self.trayMenu.addAction(restoreAction)
        self.trayMenu.addSeparator()
        self.trayMenu.addAction(quitAction)
        self.tray.setContextMenu(self.trayMenu)
        self.tray.setToolTip('条码检查标签在这!')
        self.tray.showMessage("条码", '托盘信息内容', icon=1) #icon的值  0没有图标  1是提示  2是警告  3是错误
        self.tray.show()

    def logout(self):
        print(f"用户{self.user}注销登陆:")
        #待实现
    
    def showAuthor(self):
        about_text= f'版权所有 @<b><strong>{__author__}</strong></b> 保留所有权利,本软件产品仅限个人基于个人目的使用,禁止将本软件用于生产、经营等商业用途或其他用途 <br>'+f'作者:{__author__} <br> 邮箱:{__email__}<br>'
        QMessageBox.about(self,"关于作者",about_text)

    def showVersion(self):
        QMessageBox.about(self,"验证系统版本",f"当前验证系统版本:{__vesion__}<br>胡亮的git库:gitee.com/hl_lance/label_check")       

    def showPolicyManager(self):
        e =PolicyManager()
        e.data_update_signal.connect(self.reset_checker)
        e.exec()

    def showHelp(self):
        """帮助信息显示"""
        from help_ui import My_label
        self.l = My_label("帮助信息")
        self.l.init()
        self.l.show()
    
    def showItemManager(self):
        e = EditItem()
        e.exec()

    def closeEvent(self,evt):
        # print("关闭窗口")
        self.log =None
        evt.accept()
        # evt.ignore()  # 忽略关闭事件
        # self.hide()     # 隐藏窗体

    def check_model_change(self,model:bool):
        # print('校验模式变更:%s'%model)
        status = not model
        for cb in self.combo_list:
            cb.setEnabled(status)

    def changeComboBox(self,combo,txt):
        """改变combobox的信号处理方式"""    
        if combo not in self.combo_list:
            return
        index = self.combo_list.index(combo)
        #把剩余的选择控件清空并暂时屏蔽信号
        for cb in self.combo_list[index+1:]: 
            cb.blockSignals(True)
            cb.clear()
            cb.blockSignals(False)
        tmp = self.cfg.code_data   
        if index > 0:
            for cb in self.combo_list[:index]:
                tmp = tmp[cb.currentText()]
        if not tmp.get(txt): #防止None引起的程序崩溃
            return                 
        if index + 2 < len(self.combo_list): 
            self.combo_list[index+1].addItems( tmp[txt].keys()) 
        else:  
            # print("cblist",index+1,len(self.combo_list),tmp[txt])
            self.combo_list[index+1].addItems(tmp[txt])   

    def custom_change(self,txt):
        # print('客户变更:%s'%txt)     
        self.changeComboBox(self.custom_cb,txt)
        #修复客户规格为空时残留上一次数据
      
    def module_change(self,txt):
        # print('机型变更:%s'%txt)
        self.changeComboBox(self.module_cb,txt)

    def name_change(self,txt):
        # print('品名变更:%s'%txt)  
        self.changeComboBox(self.name_cb,txt)   

    def reset_checker(self):
        #设置条码校验器,每次校验时使用最新的规则
        self.chk = Checker()
        
    def input_scan(self, codebar:str):
        # print("扫描的数据:%s"%codebar)
        now = QDateTime.currentDateTime().toString("yyyy-MM-dd HH-mm-ss")
        # print("radio 状态",self.auto_radio.isChecked)
        if not self.auto_radio.isChecked():
            customer ,module ,name ,pn = (i.currentText() for i in self.combo_list)
            #只有combobox有数据时才进行单独的验证
            if len(customer) > 0 and len(pn) >0:           
                self.chk.setMode({"customer":customer,"module":module,"name":name,"pn":pn})
        else:
           self.chk.setMode(None) 
           
        result_b ,result_t =self.chk.check(codebar)
        print("-------UI 校验结果-----",result_b,result_t)
        if result_b == checker.SUCESS:          
            # print("检查的model:",self.chk.model)
            if self.chk.model:
                self.set_combo_text(self.chk.model.values())#校验成功会设置model
            style= "color:blue;"
            result_t  ="PASS"
        elif result_b == checker.PARTIY_SUCESS:          
            if self.chk.model:
                self.set_combo_text(self.chk.model.values())#校验成功会设置model
            style= "background-color:#FF3034;"
        else:
            style= "background-color:#FF3034;"
        style += 'font: 11pt "楷体";padding-left:20px;border:none;border-radius:25px;'
        self.result_txt.setStyleSheet(style)
        self.result_txt.setText(result_t+":\n"+codebar)  
        self.write_log(now, result_t, codebar)

    def write_log(self,now,result,codebar):
        #在tabelwidget中加入记录    
        rows =self.tableWidget.rowCount()
        # print("表格的数据:" ,self.tableWidget.itemAt(rows,0).text())
        if len(self.tableWidget.itemAt(rows,0).text()) >0:
            newrow = rows 
            self.tableWidget.setRowCount(newrow + 1)
            # self.tableWidget.insertRow(0)
        else:
            newrow = rows -1        
        # print("当前有%s行"%newrow)  
        data = [now, result, codebar, self.user]
        self._addData(self.tableWidget, newrow, data)
        self.log.make(data)

    def _addData(self,w:QTableWidget, row:int ,Data :List[str]):
        font_color = QColor(0,0,0)
        if Data[1] != "PASS":
            font_color = QColor(255,0,0)
        for n,d in enumerate(Data) :
            item =QTableWidgetItem(d)
            # print('正在添加数据', item)
            item.setTextAlignment(Qt.AlignCenter )
            item.setForeground(font_color)
            w.setItem(row ,n ,item)

    def set_combo_text(self,args):
        '''设置QComboBox当前文本,args为所用对应的数值迭代器'''
        for combo ,txt in zip(self.combo_list,args):
            combo.setCurrentText(txt)
Пример #12
0
    s.dump_to(f)
    f.close()
''' ###
s = ProvisionalKeyScraper(scraper='mains_2021')
with open("files/Provisional Answer Key.txt") as f:
    s.parse(f)
with open("files/provisional_answer.json", 'w') as f:
    s.dump_to(f)
    f.close()

'''
s = FinalKeyScraper(scraper='mains_2021')
with open("files/Final Answer Key.txt") as f:
    s.parse(f)
with open("files/final_answer.json", 'w') as f:
    s.dump_to(f)
    f.close()
'''


with open("files/provisional_answer.json") as f:
    c = Checker(f)
'''
with open("files/final_answer.json") as f:
    c = Checker(f)
###

with open("files/response.json") as f:
    c.check(f)
    c.display_default()
Пример #13
0
 def test_check(self):
     chk = Checker()
     psw = 'correct_one'
     assert chk.check(psw) == True
     assert chk.check('random_psw') == False
Пример #14
0
from checker import Checker
from scanner import Scanner
from parser import Parser
from encoder import Encoder

fileDir = './example_files/prog1.txt'

if __name__ == "__main__":
    scanner = Scanner(fileDir)
    parser = Parser(scanner)
    checker = Checker()
    encoder = Encoder()

    program = parser.parse_program()
    checker.check(program)
    encoder.encode(program)
    encoder.save_target_program('examples_files/prog1.tam')

    # print(json.dumps(program, default=lambda x: x.__dict__, indent=2))
Пример #15
0
import os
import json
import re
from checker import Checker


if __name__ == '__main__':
    checker = Checker()
    scores = {}
    results = {}
    folder_path = 'hw_data/significance/'
    for filename in os.listdir(folder_path):
        if filename.endswith('.py'):
            name, score = checker.check(folder_path + filename)
            print(name, score)
            if name is not None and score is not None:
                print('score is', max(round(2 ** (6 * (score - 2.8)), 2), 0.05))
                results[name] = score
            else:
                scores[name] = 0.05

    best_accuracy = max(results.values())
    for name in results:
        scores[name] = max(round(2 ** (6 * (results[name] - 2.8)), 2), 0.05)

    with open('hw_data/significance.json', 'w') as f:
        json.dump(scores, f, indent=4)

    with open('hw_data/significance.csv', 'w') as f:
        f.write('email, score\n')
        for name in sorted(scores):
Пример #16
0
from time import sleep

from checker import Checker
from logger import Logger
from producer import Producer

if __name__ == '__main__':
    log_level = os.getenv("LOG_LEVEL", "INFO")
    logger = Logger(log_level)
    main_logger = logger.get_logger("main")

    interval_ms = int(os.getenv("INTERVAL_MS", 1000))

    main_logger.info(f"Checks will be performed each {interval_ms} ms."
                     f"provide INTERVAL_MS env variable to change that.")

    target_url = os.getenv("TARGET_URL")
    if not target_url:
        raise Exception("Please provide target url in TARGET_URL env var.")
    main_logger.info(f"Target: {target_url}")

    regex = os.getenv("REGEX")
    main_logger.info(f"Regex to search: {regex}")

    producer = Producer(logger)
    checker = Checker(target_url, regex, producer, logger)
    while True:
        checker.check()
        sleep(interval_ms / 1000)
class CompilerCustomizationTest(unittest.TestCase):
    _CR_DEFINE_DEFINITION = Processor(rel_to_abs(CR_FILE)).contents

    def setUp(self):
        self._checker = Checker()

    def _runChecker(self, source_code):
        file_path = "/script.js"
        FileCache._cache[file_path] = source_code
        return self._checker.check(file_path)

    def _runCheckerTestExpectError(self, source_code, expected_error):
        _, output = self._runChecker(source_code)

        self.assertTrue(expected_error in output,
                        msg="Expected chunk: \n%s\n\nOutput:\n%s\n" %
                        (expected_error, output))

    def _runCheckerTestExpectSuccess(self, source_code):
        return_code, output = self._runChecker(source_code)

        self.assertTrue(
            return_code == 0,
            msg="Expected success, got return code %d\n\nOutput:\n%s\n" %
            (return_code, output))

    def testGetInstance(self):
        self._runCheckerTestExpectError(
            """
var cr = {
  /** @param {!Function} ctor */
  addSingletonGetter: function(ctor) {
    ctor.getInstance = function() {
      return ctor.instance_ || (ctor.instance_ = new ctor());
    };
  }
};

/** @constructor */
function Class() {
  /** @param {number} num */
  this.needsNumber = function(num) {};
}

cr.addSingletonGetter(Class);
Class.getInstance().needsNumber("wrong type");
""", "ERROR - actual parameter 1 of Class.needsNumber does not match formal "
            "parameter")

    def testCrDefineFunctionDefinition(self):
        self._runCheckerTestExpectError(
            self._CR_DEFINE_DEFINITION + """
cr.define('a.b.c', function() {
  /** @param {number} num */
  function internalName(num) {}

  return {
    needsNumber: internalName
  };
});

a.b.c.needsNumber("wrong type");
""", "ERROR - actual parameter 1 of a.b.c.needsNumber does not match formal "
            "parameter")

    def testCrDefineFunctionAssignment(self):
        self._runCheckerTestExpectError(
            self._CR_DEFINE_DEFINITION + """
cr.define('a.b.c', function() {
  /** @param {number} num */
  var internalName = function(num) {};

  return {
    needsNumber: internalName
  };
});

a.b.c.needsNumber("wrong type");
""", "ERROR - actual parameter 1 of a.b.c.needsNumber does not match formal "
            "parameter")

    def testCrDefineConstructorDefinitionPrototypeMethod(self):
        self._runCheckerTestExpectError(
            self._CR_DEFINE_DEFINITION + """
cr.define('a.b.c', function() {
  /** @constructor */
  function ClassInternalName() {}

  ClassInternalName.prototype = {
    /** @param {number} num */
    method: function(num) {}
  };

  return {
    ClassExternalName: ClassInternalName
  };
});

new a.b.c.ClassExternalName().method("wrong type");
""", "ERROR - actual parameter 1 of a.b.c.ClassExternalName.prototype.method "
            "does not match formal parameter")

    def testCrDefineConstructorAssignmentPrototypeMethod(self):
        self._runCheckerTestExpectError(
            self._CR_DEFINE_DEFINITION + """
cr.define('a.b.c', function() {
  /** @constructor */
  var ClassInternalName = function() {};

  ClassInternalName.prototype = {
    /** @param {number} num */
    method: function(num) {}
  };

  return {
    ClassExternalName: ClassInternalName
  };
});

new a.b.c.ClassExternalName().method("wrong type");
""", "ERROR - actual parameter 1 of a.b.c.ClassExternalName.prototype.method "
            "does not match formal parameter")

    def testCrDefineEnum(self):
        self._runCheckerTestExpectError(
            self._CR_DEFINE_DEFINITION + """
cr.define('a.b.c', function() {
  /** @enum {string} */
  var internalNameForEnum = {key: 'wrong_type'};

  return {
    exportedEnum: internalNameForEnum
  };
});

/** @param {number} num */
function needsNumber(num) {}

needsNumber(a.b.c.exportedEnum.key);
""", "ERROR - actual parameter 1 of needsNumber does not match formal "
            "parameter")

    def testObjectDefineProperty(self):
        self._runCheckerTestExpectSuccess("""
/** @constructor */
function Class() {}

Object.defineProperty(Class.prototype, 'myProperty', {});

alert(new Class().myProperty);
""")

    def testCrDefineProperty(self):
        self._runCheckerTestExpectSuccess(self._CR_DEFINE_DEFINITION + """
/** @constructor */
function Class() {}

cr.defineProperty(Class.prototype, 'myProperty', cr.PropertyKind.JS);

alert(new Class().myProperty);
""")

    def testCrDefinePropertyTypeChecking(self):
        self._runCheckerTestExpectError(
            self._CR_DEFINE_DEFINITION + """
/** @constructor */
function Class() {}

cr.defineProperty(Class.prototype, 'booleanProp', cr.PropertyKind.BOOL_ATTR);

/** @param {number} num */
function needsNumber(num) {}

needsNumber(new Class().booleanProp);
""", "ERROR - actual parameter 1 of needsNumber does not match formal "
            "parameter")

    def testCrDefineOnCrWorks(self):
        self._runCheckerTestExpectSuccess(self._CR_DEFINE_DEFINITION + """
cr.define('cr', function() {
  return {};
});
""")
Пример #18
0
 def run(self):
     conn = sqlite3.connect("database.db")
     cur = conn.cursor()
     self.try_create_solutions_table(conn)
     self.try_create_report_file()
     while True:
         compiler_output = ''
         failed_test_num = -1
         stderr = ''
         next_solution = cur.execute(
             'SELECT * FROM solutions WHERE status = ? OR status = ? ORDER BY id LIMIT 1',
             (Status.WAITING,
              Status.INVALID_SOLUTION_FORMAT_WAITING)).fetchone()
         if next_solution != None:
             solution_id, datetime, email, task, language, status = next_solution
             logging.info('Got new solution: ' +
                          str((solution_id, datetime, email, task, language,
                               Status.get_string(status))))
             if status == Status.INVALID_SOLUTION_FORMAT_WAITING:
                 new_status = Status.INVALID_SOLUTION_FORMAT_ERROR
             else:
                 solution_path = self.solutions_dir + '/' + str(solution_id)
                 task_path = self.tasks_dir + '/' + str(task)
                 solution_files = []
                 if os.path.exists(solution_path):
                     for f in os.listdir(solution_path):
                         if f.endswith(checker.EXTENSIONS[language]):
                             solution_files.append(f)
                 if language not in checker.RUN_COMMANDS or   \
                    task not in self.get_available_tasks() or \
                    not os.path.exists(solution_path) or      \
                    not solution_files:
                     new_status = Status.INVALID_SOLUTION_FORMAT_ERROR
                 else:
                     try:
                         c = Checker(language, solution_path, task_path,
                                     self.temp_dir)
                         new_status = c.check()
                         compiler_output = c.get_compiler_output()
                         failed_test_num = c.get_failed_test_num()
                         stderr = c.get_stderr()
                     except Exception as e:
                         logging.warning('Internal error: ' +
                                         traceback.format_exc())
                         new_status = Status.INTERNAL_ERROR
             try:
                 cur.execute('UPDATE solutions SET status = ? WHERE id = ?',
                             (new_status, solution_id))
                 conn.commit()
                 try:
                     self.add_solution_to_report(email, datetime, task,
                                                 language, new_status)
                 except:
                     logging.warning('Unable to update report file: ' +
                                     traceback.format_exc())
                 self.send_response(email, task, language, solution_id,
                                    new_status, compiler_output,
                                    failed_test_num, stderr)
                 logging.info('Checked solution: ' +
                              str((solution_id, datetime, email,
                                   task, language,
                                   Status.get_string(new_status))))
             except:
                 logging.warning('Unable to send response: ' +
                                 traceback.format_exc())
         try:
             self.try_send_daily_report()
         except:
             logging.warning('Unable to send daily report: ' +
                             traceback.format_exc())
         time.sleep(config.VERIFIER_UPDATE_PERIOD)
Пример #19
0
def foo(new, old, send):
	if not Checker.check(new, old):
		result = Checker.diff(new, old)
		send.append(result)
		return True
	return False