예제 #1
0
    def __init__(self, user, page_controller, article_path, **kw):
        super().__init__(**kw)
        self.user = user

        # Initialize page controller module
        self.controller = page_controller

        # Initialize article path
        self.article_path = article_path

        # Set background image of page
        Utils.set_background(self, 'data/home_background.png')

        # Initialize the main root widget
        self.root_widget = BoxLayout(orientation='horizontal',
                                     padding=40,
                                     spacing=20)
        self.add_widget(self.root_widget)

        #Initialize typing score metrics
        self.adjusted_speed = 0
        self.speed = 0
        self.accuracy = 0
        self.time_passed = 0
        self.started_timer = False
        self.times_per_block = []
        self.words_typed = []
        self.document_words = []

        # Generate all elements of the page by calling the generate methods
        self.generate_metrics_and_cancel_box()
        # Utils.add_empty_space(self.root_widget, (0, 1), orientation='horizontal')
        self.generate_story_and_typing_box()
예제 #2
0
    def direct_problem(a, b, eps, M, N, u_left, u_right, t, x, q, h, tau,
                       u_init):
        def func(y, t, x, q):
            f = np.zeros(N - 1)
            f[0] = (eps * (y[1] - 2 * y[0] + u_left) /
                    h**2) + (y[0] * (y[1] - u_left) / (2 * h)) - y[0] * q[1]
            for n in range(1, N - 2):
                f[n] = (eps * (y[n + 1] - 2 * y[n] + y[n - 1]) /
                        h**2) + (y[n] * (y[n + 1] - y[n - 1]) /
                                 (2 * h)) - y[n] * q[n + 1]
            f[N - 2] = (eps * (u_right - 2 * y[N - 2] + y[N - 3]) /
                        h**2) + (y[N - 2] * (u_right - y[N - 3]) /
                                 (2 * h)) - y[N - 2] * q[N - 1]
            return f

        u = np.zeros((M + 1, N + 1))
        y = np.zeros((M + 1, N - 1))
        for n in range(N + 1):
            u[0, n] = u_init[n]
        y[0, :] = u[0, 1:N]

        for m in range(M):
            a_diag, b_diag, c_diag = Utils.DiagonalPreparationDirect(
                N, eps, tau, q, h, y[m, :], u_left, u_right)
            w_1 = Utils.TridiagonalMatrixAlgorithm(
                a_diag, b_diag, c_diag,
                func(y[m, :], (t[m] + t[m + 1]) / 2, x, q))
            tmp2 = tau * w_1.real
            y[m + 1] = y[m] + np.transpose(tmp2)
            u[m + 1, 1:N] = y[m + 1]
            u[m + 1, 0] = u_left
            u[m + 1, N] = u_right

        return u
예제 #3
0
def pic2pdf(pdf_file, pic_path):
    """
    把图片插入 pdf
    :param pdf_file:要保存的pdf文件
    :param pic_path:图片目录
    :return:
    """

    t0 = time.perf_counter()  # 生成图片初始时间

    ll = sorted(glob.glob(f"{pic_path}/*"))
    Utils.sort_nicely(ll)
    # ll = ll[0:4]

    doc = fitz.open()
    for img in ll:  # 读取图片,确保按文件名排序
        print(img)
        imgdoc = fitz.open(img)  # 打开图片
        pdfbytes = imgdoc.convertToPDF()  # 使用图片创建单页的 PDF
        imgpdf = fitz.open("pdf", pdfbytes)
        doc.insertPDF(imgpdf)  # 将当前页插入文档

    if os.path.exists(pdf_file):
        os.remove(pdf_file)
    doc.save(pdf_file)  # 保存pdf文件
    doc.close()

    t1 = time.perf_counter()  # 图片完成时间
    print("总共合并了{}张图片".format(len(ll)))
    print("运行时间:{}s".format(t1 - t0))
예제 #4
0
    def add_account(self, page_controller, button:Button):
        
        # get user input
        username_entered = str(self.username_input.text)

        # validate input
        is_valid, error_title, error_message = Utils.validate_username(username_to_check=username_entered)
        if not is_valid:
            Utils.generate_error_popup(title=error_title, message=error_message)
            return
        
        # Save new user to users folder and update layout
        Utils.create_directory(username_entered.lower(), 'users')
        # with open(f'users/{username_entered.lower()}/{username_entered.lower()}.csv', 'w') as csv_file:
        #         field_names = ['date', 'story', 'speed', 'accuracy', 'adjusted_speed']
        #         writer = csv.DictWriter(csv_file, fieldnames=field_names)

        #         writer.writeheader()

        self.root_box.remove_widget(self.accounts_box)
        self.generate_accounts_box(page_controller=page_controller)



        # call next page and parse user
        self.add_account_popup.dismiss()
        self.user = str(username_entered).lower()
        self.go_to_home_page(page_controller=page_controller)
예제 #5
0
파일: temp.py 프로젝트: MikaYusub/Diploma
def conjucate_problem(eps, M, N, t, x, q, h, u, f_obs):
    def func_psi(y, u, t, q):
        f = np.zeros(N - 1)
        f[0] = (-eps * (y[1] - 2 * y[0]) / h ** 2) \
               + (u[1] * y[1] / (2 * h)) \
               + y[0] * q[1]
        for n in range(1, N - 2):
            f[n] = (-eps * (y[n + 1] - 2 * y[n] + y[n - 1]) / h ** 2) \
                   + (u[n + 1] * (y[n + 1] - y[n - 1]) / (2 * h)) \
                   + y[n] * q[n + 1]
        f[N - 2] = (-eps * (-2 * y[N - 2] + y[N - 3]) / h ** 2) \
                   - (u[N - 1] * y[N - 3] / (2 * h)) \
                   + y[N - 2] * q[N - 1]
        return f

    psi = np.zeros((M + 1, N + 1))
    y = np.zeros((M + 1, N - 1))

    psi[M, :] = -2 * (u[M, :] - f_obs)
    y[M, :] = psi[M, 1:N]
    for m in range(M, 0, -1):
        a_diag_conj, b_diag_conj, c_diag_conj = Utils.DiagonalPreparationConjugate(
            eps, tau, q, h, u[m, :])
        w_1 = Utils.TridiagonalMatrixAlgorithm(
            a_diag_conj, b_diag_conj, c_diag_conj,
            func_psi(y[m, :], u[m, :], (t[m] + t[m - 1]) / 2, q))
        tmp2 = (t[m - 1] - t[m]) * w_1.real
        y[m - 1, :] = y[m, :] + np.transpose(tmp2)
        psi[m - 1, 1:N] = y[m - 1, :]
    psi[:, 0] = 0
    psi[:, N] = 0
    return psi
예제 #6
0
    def __init__(self, page_controller, user, **kw):
        super().__init__(**kw)

        # instantiate the user
        self.user = user

        # instantiate the controller
        self.controller = page_controller

        # Add app background
        Utils.set_background(self, 'data/home_background.png')

        # Initialize articles directory
        self.articles_dir = 'data/articles'
        self.full_articles_dir = f'{os.getcwd()}/{self.articles_dir}'
        self.article_images_dir = f'{os.getcwd()}/data/article_images'

        # Initialize root widget
        self.root_widget = BoxLayout(orientation="horizontal")
        self.root_widget.spacing = 15
        self.root_widget.padding = 15
        self.add_widget(self.root_widget)

        # Generate articles layout
        self.generate_articles_layout()

        # Generate the preview layout
        self.generate_preview_layout()

        # Generate history, accounts and start box
        self.generate_history_account_start_layout()
예제 #7
0
    def generate_history_account_start_layout(self):
        history_account_start_layout_box = BoxLayout(orientation='vertical',
                                                     spacing=12,
                                                     size_hint=(.7, 1))

        history_account_box = BoxLayout(orientation='horizontal', spacing=10)

        history_button = Button(text='History',
                                font_size=20,
                                on_release=self.go_to_history_page)
        accounts_button = Button(text=str(self.user[0]).upper(),
                                 font_size=20,
                                 background_color=Utils.get_color_from_letter(
                                     self.user[0]),
                                 on_release=self.go_to_login_page)
        history_account_box.add_widget(history_button)
        history_account_box.add_widget(accounts_button)
        history_account_start_layout_box.add_widget(history_account_box)

        Utils.add_empty_space(history_account_start_layout_box, (1, 2.4))

        start_button_box = BoxLayout(orientation='vertical')
        start_button = Button(text='start',
                              font_size=25,
                              on_release=self.go_to_typing_page)
        start_button_box.add_widget(start_button)
        history_account_start_layout_box.add_widget(start_button_box)

        Utils.add_empty_space(history_account_start_layout_box, (1, 2.4))

        self.root_widget.add_widget(history_account_start_layout_box)
예제 #8
0
    def slot_animation(self, control):
        # print('56')
        if control.objectName() == 'toolButton_add':
            # self.model = DlgModel(self)
            # rect = self.rect()
            # self.model.setGeometry(rect.x() + rect.width(), rect.y(), self.model.width(), rect.height())
            # Utils.doAnim(self.model)

            model = DlgModel(self)
            model.init_ui()
            rect = self.rect()
            model.setGeometry(rect.x() + rect.width(), rect.y(), model.width(),
                              rect.height())
            Utils.doAnim(model)
        elif control.objectName() == 'toolButton_edit':
            # if self.card:
            #     return
            print('toolButton_edit')

            self.card = DlgCard(self)
            rect = self.rect()
            self.card.setGeometry(rect.x() + rect.width(), rect.y(),
                                  self.card.width(), rect.height())
            Utils.doAnim(self.card)
            self.card.update_card(0, False)
예제 #9
0
 def show_card(self, index):
     print('show_card')
     rect = self.rect()
     dlg = DlgCard(index, self)
     dlg.setGeometry(rect.x() + rect.width(), rect.y(), dlg.width(),
                     rect.height())
     Utils.doAnim(dlg, self)
예제 #10
0
 def __init__(self, id_plaza, fecha_deposito, fecha_salida, facturado):
     self.__id_plaza = id_plaza
     self.__matricula = Utils.generar_matricula()
     self.__pin = Utils.generar_pin()
     self.__fecha_deposito = fecha_deposito
     self.__fecha_salida = fecha_salida
     self.__facturado = facturado
예제 #11
0
    def _init_main(self):
        self.resize(1200, 800)
        self.setWindowFlags(QtCore.Qt.FramelessWindowHint
                            | QtCore.Qt.WindowSystemMenuHint)  # 设置无边框窗口
        self.setAttribute(QtCore.Qt.WA_TranslucentBackground)  # 设置窗口背景透明
        # self.setAttribute(Qt.WA_StyledBackground, True)  # 子QWdiget背景透明
        self.setMouseTracking(True)  # 跟踪鼠标移动事件的必备

        layout = QtWidgets.QVBoxLayout(self)
        layout.setContentsMargins(0, 0, Const.MARGIN,
                                  Const.MARGIN)  # 给阴影留下位置,不过左边和上边就没有拉伸的功能,被遮蔽了
        # layout.setContentsMargins(0, 0, 0, 0)  # 给阴影留下位置
        layout.setSpacing(0)
        layout.addWidget(self.titleBar)
        # self.titleBar.setVisible(False)
        layout.addWidget(self.toolbar)
        # layout.addStretch()
        layout.addWidget(self.canvas)
        # pb = QtWidgets.QPushButton('dgskgls')
        # pb.setToolTip('测试一下')
        # layout.addWidget(pb)

        Utils.center_win(self)
        self.titleBar.setTitle('文件管家')
        self._init_toolbar()
        self._init_canvas()

        # 信号槽
        # self.titleBar.sign_pb_prev.connect(partial(self.sign_title_clicked, '打开文件夹'))
        # self.titleBar.sign_pb_next.connect(partial(self.sign_title_clicked, '打开文件'))
        self.titleBar.sign_win_minimize.connect(self.sign_showMinimized)
        self.titleBar.sign_win_maximize.connect(self.sign_showMaximized)
        self.titleBar.sign_win_resume.connect(self.sign_showNormal)
        self.titleBar.sign_win_close.connect(self.close)
        self.titleBar.sign_win_move.connect(partial(self.sign_move, 0))
예제 #12
0
    def __init__(self, *args, **kwargs):
        super(MainWin, self).__init__(*args, **kwargs)
        self.go = GoBoard(self)

        self.platform = QtWidgets.QFrame()
        self.cb_coord = QtWidgets.QCheckBox('显示坐标')
        self.cb_lot = QtWidgets.QCheckBox('显示手数')
        self.cb_coord.stateChanged.connect(
            partial(self.go.slot_checked, self.cb_coord))
        self.cb_lot.stateChanged.connect(
            partial(self.go.slot_checked, self.cb_lot))

        self.lb_lot = QtWidgets.QLabel('当前手数:0')
        self.lb_lib = QtWidgets.QLabel('所选棋子的气数:0')
        self.pb_withdraw = QtWidgets.QPushButton('悔棋')
        self.pb_withdraw.clicked.connect(self.go.slot_withdraw)
        lv = QtWidgets.QVBoxLayout(self.platform)
        lv.addWidget(self.cb_coord)
        lv.addWidget(self.cb_lot)
        lv.addWidget(self.lb_lot)
        lv.addWidget(self.lb_lib)
        lv.addWidget(self.pb_withdraw)
        lv.addStretch()

        self.resize(1200, 800)
        lh = QtWidgets.QHBoxLayout(self)
        # lh.setContentsMargins(0, 0, 0, 0)
        lh.setSpacing(10)
        lh.addWidget(self.go)
        lh.addWidget(self.platform)

        Utils.center_win(self)
예제 #13
0
    def slot_pb_clicked(self, controls):
        name = controls.objectName()
        # print(name)
        if name == 'pb_add_files':
            file_list, _ = QtWidgets.QFileDialog.getOpenFileNames(
                self, '多文件选取', '', self.ext_filter, None,
                QtWidgets.QFileDialog.DontUseNativeDialog)
            # print(file_list)
            data = self.createDate(file_list)
            self.tableWidget.update_data(data)
            self.tableWidget.update_table()
        elif name == 'pb_open_dir':
            path = QtWidgets.QFileDialog.getExistingDirectory(
                self, "选取源文件夹", '', QtWidgets.QFileDialog.ShowDirsOnly)  # 起始路径
            if path:
                self.src_path = path
                self.lineEdit_src_dir.setText(path)
                self.src_files = Utils.files_in_dir(path, ['.doc', '.docx'],
                                                    True)

                data = self._createDate(self.src_files)
                self.tableWidget.update_data(data)
                self.tableWidget.update_table()
        elif name == 'pb_clear':
            self.tableWidget.update_data(None)
            self.tableWidget.update_table()
        elif name == 'pb_save_path':
            path = QtWidgets.QFileDialog.getSaveFileName(
                self, "选取保存文件夹", '.', self.ext_filter)  # 起始路径
            if path:
                # self.save_path, self.save_file = os.path.splitdrive(path[0])
                # self.save_path, self.save_file = os.path.splitext(path[0])
                self.save_path, self.save_file = os.path.split(path[0])
                self.save_path = path[0]
                # print(path)
                self.lineEdit_save_path.setText(self.save_path)
        elif name == 'pb_merge':
            rows = self.tableWidget.selectedItems()
            self.merge_files.clear()
            # self.files_weight.clear()
            for each in rows:
                file_name = each.text()
                file_path = os.path.join(self.src_path, file_name)  # 构造完整路径
                if os.path.isfile(file_path):
                    self.merge_files.append(file_path)
                    # self.files_weight.append(Utils.get_FileSize(file_path))

            # print(self.files_weight)
            # print(self.save_path)

            if self.save_path:
                # path = os.path.join(self.save_path, self.save_file)  # 构造完整路径
                if self.merge_files:
                    Utils.mergewords(self.merge_files, self.save_path,
                                     self.progressBar)
                else:
                    AnimWin('请指定保存路径')
        else:
            pass
예제 #14
0
    def slot_btn_clicked(self, flag):
        if flag == '生成密码':
            if self.cipher_type == 'PIN':  # PIN码
                print(self.code_type)
                bits = self.code_type & 0x0F
                mold = (self.code_type & 0xF0) >> 4

                self.ciphers.clear()
                for i in range(self.ciphers_count):
                    code = [
                        self.numerals_arabic[Utils.rand_int(0, 9)]
                        for _ in range(bits)
                    ]
                    pin = Utils.get_pin(code, mold)
                    print('sgsd', bits, mold, code, pin)

                    self.ciphers.append(pin)

                self.shell.textEdit.clear()
                for each in self.ciphers:
                    self.shell.textEdit.append(str(each))
                self.shell.label_tip.setText("PIN 码是字符串,拷贝时根据类型自动转为数字或字符。")

            else:  # 随机码、易记密码
                if not self.char_set:
                    return
                # print('生成密码')

                num = len(self.char_set) - 1
                char_list = list(self.char_set)
                # print(char_list)
                self.ciphers.clear()
                for i in range(self.ciphers_count):
                    pwd = [
                        char_list[Utils.rand_int(0, num)]
                        for _ in range(self.cipher_length)
                    ]
                    s = "".join(pwd)  # list 转成字符串
                    level = self.checker.check_password(s) - 1
                    # print('level', level)
                    self.ciphers.append(s)
                    tip = '  '.join(self.msg[level])
                    self.shell.label_tip.setText(f"密码:{tip}")

                # print(self.ciphers)
                # pe = QtWidgets.QTextEdit()
                pe = self.shell.textEdit
                pe.clear()
                for each in self.ciphers:
                    pe.append(each)

        elif flag == '复制密码':
            # pe = QtWidgets.QTextEdit()
            pe = self.shell.textEdit

            text_cursor = pe.textCursor()
            text_cursor.select(QtGui.QTextCursor.LineUnderCursor)
            curText = text_cursor.selectedText()
            pyperclip.copy(curText)
예제 #15
0
파일: user.py 프로젝트: mohllal/daily-blog
 def register(cls, name, pw, phone=None, address=None, email=None):
     pw_hash = Utils.make_pw_hash(name, pw)
     return cls(parent=Utils.users_key(),
                name=name,
                pw_hash=pw_hash,
                phone=phone,
                address=address,
                email=email)
예제 #16
0
 def __init__(self, id_plaza, tipo_vehiculo):
     self.__id_plaza = id_plaza
     self.__tipo_vehiculo = tipo_vehiculo
     self.__matricula = Utils.generar_matricula()
     self.__pin = Utils.generar_pin()
     self.__fecha_deposito = datetime.now()
     self.__fecha_salida = None
     self.__facturado = None
예제 #17
0
    def deal(self):
        """
        抓牌顺时针抓,打牌逆时针打
        :return:
        """
        if self.tiles_count < 54:  # 不够起牌的
            return

        self.dealer %= 4  # 轮流坐庄 4人麻将

        # 庄家掷骰子找到二次掷骰人,并确定开门方向
        # die1 = random.randint(1, 12)
        die_1 = Utils.rand_int(1, 12)
        door = (self.dealer + die_1 - 1) % 4  # 开门方向
        # 二次掷骰子
        # die2 = random.randint(1, 12)
        die_2 = Utils.rand_int(1, 12)
        dice = (door + 1) * 34 - die_2 * 2
        # zero = dice % self.tiles_count      # 开始摸牌的位置
        new_round = self.round[dice:]
        new_round.extend(self.round[:dice])
        self.round = new_round  # 重新起算
        # print(dice, len(self.round))
        # print(self.data.cards2names(sorted(self.round)))  # 返回新的排序队列,原队列不排序

        self.lots = 0
        # 给玩家发牌,顺时针抓牌
        for k in range(3):  # 发三次牌,每人每次拿连续的4张
            for i in range(4):
                player_id = (i + self.dealer) % 4  # 循环坐庄
                for j in range(4):
                    # # 牌号、牌卡控件、翻牌等标志
                    # ID = self.round[self.lots]  # 牌号,兼做排序用
                    index = j + 4 * k  # 槽位
                    # player_id 也代表卡牌类型
                    # self.card_players[player_id][index] = Tile(self, ID, player_id, index)
                    # self.card_players[player_id][index][0] = self.round.pop(0)  # 牌号,兼做排序用
                    self.card_players[player_id][index] = [self.round.pop(0), 0]  # 牌号,兼做排序用
                    # print(player_id, index, self.card_players[player_id][index])
                    self.lots += 1

        # 每人再模一张,叫牌空置
        for i in range(4):
            player_id = (i + self.dealer) % 4  # 从庄家开始
            self.card_players[player_id][12] = [self.round.pop(0), 0]  # 返回弹出值
            # self.card_players[player_id][12] = Tile(self, self.round[self.lots], player_id, 12)
            # self.card_players[player_id][13] = Tile(self, 999, 4 + player_id, 13)  # 叫牌,确保排在最后,每台不用清零
            # self.tile_shadow = Tile(self, 999, 1, 13)  # 把影子牌实例化
            self.lots += 1

            # for j in range(13, 18):
            #     self.card_players[player_id][j] |= 0xff  # 叫牌,确保排在最后,每台不用清零

            self.card_players[player_id].sort()  # 排序
            # self.data.sortArray(self.card_players[player_id])

        # 庄家不多摸,现在从庄家开始摸牌再发牌
        self.speaker = self.dealer  # 目前的摸/出牌者
예제 #18
0
    def max_lib(self):
        row = Utils.rand_int(0, self.board_lines - 1)
        col = Utils.rand_int(0, self.board_lines - 1)

        # self.lot_cur += 1
        state = 1  # 2 - self.lot_cur % 2
        self.board_map[row][col] = [state, self.lot_cur]
        self._find(row, col, state)
        print(self.get_liberty(row, col))
예제 #19
0
    def init_ui(self):
        self.setMinimumSize(800, 800)
        self.setMouseTracking(True)  # 跟踪鼠标移动
        # self.setAttribute(QtCore.Qt.WA_StyledBackground, True)
        # self.setStyleSheet('background-color:BurlyWood')  # Tan
        self.setStyleSheet('background-image:url(./res/images/wenli4.jpg)')
        Utils.set_effect(self, 1, 25, MARGIN, MARGIN, QtCore.Qt.darkGray)

        self.update_board()
예제 #20
0
 def generate_article_images(self):
     article_names = Utils.iter_files('data/articles', '.txt')[0]
     for article in article_names:
         article_image_path_to_save = f'{os.getcwd()}/data/article_images/{article}.png'
         if not os.path.exists(article_image_path_to_save):
             article_image = Utils.text_to_image(
                 f'/data/articles/{article}')
             article = str(article).replace('.txt', '')
             article_image.save(
                 fp=f'{os.getcwd()}/data/article_images/{article}.png')
예제 #21
0
    def _createDate(self, files):
        if not files:
            return

        data = []
        for i in range(len(files)):
            file = files[i]
            size = Utils.getFileInfo(file)['文件大小']
            ct = Utils.getFileInfo(file)['最后一次的修改时间']
            data.append([files[i], '', '', size, ct])
        return data
예제 #22
0
    def render(self, current_user_id):
        key = db.Key.from_path('User',
                               int(self.user.key().id()),
                               parent=Utils.users_key())
        user = db.get(key)

        self._render_text = self.content.replace('\n', '<br>')
        return Utils.render_str("single-post.html",
                                post=self,
                                current_user_id=current_user_id,
                                author=user.name)
예제 #23
0
파일: parsers.py 프로젝트: bretlowery/snakr
 def _get_pdf_title(self, documenturl):
     title = None
     try:
         pdf = PDFDocument(PDFParser(StringIO(urllib2.urlopen(documenturl).read())))
         title = Utils.remove_nonascii(pdf.info[0]["Title"]).strip()
         if not title:
             title = Utils.remove_nonascii(pdf.info[0]["Subject"]).strip()
         if len(title) < 1:
             title = None
     except:
         pass
     return title
예제 #24
0
    def customUI(self):
        # self.verticalLayout.setMargin(self.margin)
        self.setupUi(self)
        self.tableWidget.initUI()

        pss = Utils.readQss('res/style/QProgressBarQss.txt')
        self.progressBar.setStyleSheet(pss)

        self.statusbar.showMessage(
            '我昔钓白龙,放龙溪水傍。',
            0)  # 状态栏本身显示的信息 第二个参数是信息停留的时间,单位是毫秒,默认是0(0表示在下一个操作来临前一直显示)
        self.allNum = QtWidgets.QLabel('总数:')
        self.selectNum = QtWidgets.QLabel('选中:')

        self.statusbar.addPermanentWidget(self.allNum, stretch=0)
        self.statusbar.addPermanentWidget(self.selectNum, stretch=0)

        font = QtGui.QFont('楷体', 14)
        # font.setBold(True)  # 设置字体加粗
        self.setFont(font)  # 设置字体
        qss = Utils.readQss('./res/style/radio_checkQss.txt')
        self.setStyleSheet(qss)

        self.cb_exit.setChecked(True)
        self.rb_digit_little.setChecked(True)
        # self.cb_select_all.setStyleSheet(qss)

        wg = self.tableWidget.createWidget(1)
        self.horizontalLayout_3.addWidget(wg)

        self.pb_save_path.clicked.connect(
            partial(self.slot_pb_clicked, self.pb_save_path))
        self.pb_merge.clicked.connect(
            lambda: self.slot_pb_clicked(self.pb_merge))
        self.pb_add_files.pressed.connect(
            lambda: self.slot_pb_clicked(self.pb_add_files))
        self.pb_open_dir.pressed.connect(
            lambda: self.slot_pb_clicked(self.pb_open_dir))
        self.pb_clear.pressed.connect(
            lambda: self.slot_pb_clicked(self.pb_clear))
        self.cb_select_all.pressed.connect(
            lambda: self.slot_cb_clicked(self.cb_select_all))
        self.comboBox.currentIndexChanged['int'].connect(
            self.slot_comboBox_clicked)
        self.cb_eyebrow.clicked.connect(
            partial(self.slot_cb_clicked, self.cb_eyebrow))
        self.cb_watermark.clicked.connect(
            partial(self.slot_cb_clicked, self.cb_watermark))
        self.lineEdit_src_dir.editingFinished.connect(
            partial(self.slot_le_edited, self.lineEdit_src_dir))
        self.lineEdit_save_path.editingFinished.connect(
            partial(self.slot_le_edited, self.lineEdit_save_path))
예제 #25
0
    def slot_toolbar_clicked(self, name):
        if name == 'doc转换':
            wg = self.canvas.currentWidget()

            # path = QtWidgets.QFileDialog.getExistingDirectory(
            #     self, "选取源文件夹", r'F:\重要\法律与工程经济讲义',
            #     QtWidgets.QFileDialog.ShowDirsOnly)  # 起始路径
            path = r'F:\重要\法律与工程经济讲义'
            print(path)
            # return
            if path:
                self.src_path = path
                self.src_files = Utils.files_in_dir(path, ['.doc', '.docx'])

                Utils.sort_nicely(self.src_files)
                print(self.src_files)
                if not self.src_files:
                    return
                for each in self.src_files:
                    item = QtWidgets.QListWidgetItem(QtGui.QIcon(), each, wg)
                    #     item.setToolTip(self.data[i])
                    item.setSizeHint(QtCore.QSize(
                        16777215, 50))  # 设置item的默认宽高(这里只有高度比较有用)
                    item.setTextAlignment(QtCore.Qt.AlignCenter)  # 文字居中

                    name, _ = os.path.splitext(each)
                    doc = f'{path}\\{each}'
                    pdf = f'{path}\\{name}.pdf'
                    print(doc, pdf)

                    self.butler.word2pdf(doc, pdf)
                #
                # # print(path)
                self.butler.merge_pdf(path, '合并.pdf')

        elif name == '缩图':
            file_list, _ = QtWidgets.QFileDialog.getOpenFileNames(
                self, '多文件选取', '',
                'img Files(*.png *.jpg *.jpeg *.gif *.bmp *.tiff);;All Files(*.*)',
                None, QtWidgets.QFileDialog.DontUseNativeDialog)
            print(file_list)

            scale = 1.0
            for each in file_list:
                file_in, ext = os.path.splitext(each)
                file_jpg = f'{file_in}.jpg'
                print(file_in, file_jpg, ext)
                ImageConvert.png_jpg(each, file_jpg, scale)

        elif name == '水印':
            # self.child_win.show()  # -----  modeless dialog
            self.child_win.exec()  # ------ modal  dialog
예제 #26
0
    def generate_metrics_and_cancel_box(self):
        # Initialize box to contain all metric buttons
        metrics_and_cancel_box = BoxLayout(orientation='vertical',
                                           spacing=15,
                                           size_hint=(.5, 1))

        # Add average speed button
        self.speed_button = Button(
            text=f'Speed: {self.speed} WPM',
            font_size=20,
            color='white',
            background_normal='data/home_background.png')
        metrics_and_cancel_box.add_widget(self.speed_button)

        # Add accuracy button
        self.accuracy_button = Button(
            text=f'Accuracy: {self.accuracy}%',
            font_size=20,
            color='white',
            background_normal='data/home_background.png')
        metrics_and_cancel_box.add_widget(self.accuracy_button)

        # Add adjusted speed button
        self.adjusted_speed_button = Button(
            text=f'Adjusted Speed: {self.adjusted_speed} WPM',
            font_size=20,
            color='white',
            background_normal='data/home_background.png')
        metrics_and_cancel_box.add_widget(self.adjusted_speed_button)

        # Add timer
        self.timer_button = Button(
            text=f'time elapsed: 00:00',
            font_size=20,
            color='white',
            background_normal='data/home_background.png')
        metrics_and_cancel_box.add_widget(self.timer_button)

        # Add Show/Hide keyboard button
        self.show_hide_keyboard = Button(text=f'Show Keyboard', font_size=20)
        # metrics_and_cancel_box.add_widget(self.show_hide_keyboard)

        # Add Empty space
        Utils.add_empty_space(metrics_and_cancel_box, (1, 1.5))

        # Add Cancel button
        self.cancel_button = Button(text='Back to Home', font_size=20)
        metrics_and_cancel_box.add_widget(self.cancel_button)

        # Add metrics and cancel box to the root widget
        self.root_widget.add_widget(metrics_and_cancel_box)
예제 #27
0
    def __init__(self, *args, **kwargs):
        super(ArrowWidget, self).__init__(*args, **kwargs)

        self.start_pos = 0
        self.triangle_width = 0
        self.triangle_height = 0

        # self.setWindowFlags(Qt.FramelessWindowHint | Qt.WindowSystemMenuHint)  # 设置无边框窗口
        # self.setAttribute(Qt.WA_TranslucentBackground)  # 设置窗口背景透明

        # 设置阴影边框
        Utils.set_effect(self, 1, self.SHADOW_WIDTH, 0, 0, QtCore.Qt.gray)

        self.setFixedSize(150, 200)
예제 #28
0
    def deal(self):
        """
        抓牌顺时针抓,打牌逆时针打
        :return:
        """
        if self.tiles_count < 54:  # 不够起牌的
            return

        self.dealer %= 4  # 轮流坐庄 4人麻将

        # 庄家掷骰子找到二次掷骰人,并确定开门方向
        # die1 = random.randint(1, 12)
        die_1 = Utils.rand_int(1, 12)
        door = (self.dealer + die_1 - 1) % 4  # 开门方向
        # 二次掷骰子
        # die2 = random.randint(1, 12)
        die_2 = Utils.rand_int(1, 12)
        dice = (door + 1) * 34 - die_2 * 2
        # zero = dice % self.tiles_count      # 开始摸牌的位置
        new_round = self.round[dice:]
        new_round.extend(self.round[:dice])
        self.round = new_round  # 重新起算
        # print(len(self.round))

        self.lots = 0
        # 给玩家发牌,顺时针抓牌
        for k in range(3):  # 发三次牌,每人每次拿连续的4张
            for i in range(4):
                player_id = (i + self.dealer) % 4  # 循环坐庄
                for j in range(4):
                    index = j + 4 * k  # 槽位
                    # player_id 也代表卡牌类型
                    self.card_players[player_id][index] = self.round.pop(
                        0)  # 牌号,兼做排序用
                    self.lots += 1

        # 每人再模一张,叫牌空置
        for i in range(4):
            player_id = (i + self.dealer) % 4  # 从庄家开始
            self.card_players[player_id][12] = self.round.pop(0)  # 返回弹出值
            self.lots += 1

            # for j in range(13, 18):
            #     self.card_players[player_id][j] |= 0xff  # 叫牌,确保排在最后,每台不用清零

            self.card_players[player_id].sort()  # 排序

        # 庄家不多摸,现在从庄家开始摸牌再发牌
        self.speaker = self.dealer  # 目前的摸/出牌者
예제 #29
0
def pic_pdf(pdf_name, pic_path):
    file_list = os.listdir(pic_path)
    pic_name = []
    im_list = []
    for x in file_list:
        if "jpg" in x or 'png' in x or 'jpeg' in x:
            pic_name.append(x)

    pic_name.sort()
    new_pic = []

    for x in pic_name:
        if "jpg" in x:
            new_pic.append(x)

    for x in pic_name:
        if "png" in x:
            new_pic.append(x)

    Utils.sort_nicely(new_pic)
    # new_pic = new_pic[0:4]
    print("hec", len(new_pic), new_pic)

    im1 = Image.open(os.path.join(pic_path, new_pic[0]))  # 第一幅图像文件
    w, h = im1.size
    scale = 4
    im1 = im1.resize((w // scale, h // scale), Image.ANTIALIAS)
    print(w, h, im1.size)
    new_pic.pop(0)
    for i in new_pic:
        img = Image.open(os.path.join(pic_path, i))
        w, h = img.size
        img = img.resize((w // scale, h // scale), Image.ANTIALIAS)
        # print(type(img))

        # im_list.append(Image.open(i))
        if img.mode == "RGBA":
            img = img.convert('RGB')
            im_list.append(img)
        else:
            im_list.append(img)
    # out = im1.resize((w_new, h_new), Image.ANTIALIAS)
    im1.save(pdf_name,
             "PDF",
             resolution=100.0,
             save_all=True,
             append_images=im_list)

    print("输出文件名称:", pdf_name)
예제 #30
0
    def paintEvent(self, event):
        # opt = QStyleOption()
        # opt.initFrom(self)
        p = QtGui.QPainter(self)
        p.setRenderHint(QtGui.QPainter.Antialiasing)  # 抗锯齿
        # self.style().drawPrimitive(QStyle.PE_Widget, opt, p, self)
        # super(Canvas, self).paintEvent(event)

        # image = Image.open(r'E:\Codes\res\background\bk2.jpg')
        # image = image.filter(MyGaussianBlur(radius=6))
        # image.save('./tmp.jpg')
        img_new = Utils.img_center(self.rect().width(),
                                   self.rect().height(),
                                   r'E:\Codes\res\background\bk2.jpg')
        p.setBrush(QtGui.QBrush(img_new))  # 图片刷子
        # p.setBrush(QtGui.QBrush(QtGui.QPixmap(r'E:\Codes\res\background\bk3.jpg')))  # 图片刷子
        # painter.setBrush(QBrush(Qt.blue))
        p.setPen(QtCore.Qt.transparent)

        rect = self.rect()
        # rect.setWidth(rect.width() - self.deep)
        # rect.setHeight(rect.height() - self.deep)
        p.drawRoundedRect(rect, self.radius, self.radius)
        # painterPath= QPainterPath()
        # painterPath.addRoundedRect(rect, 15, 15)
        # painter.drawPath(painterPath)

        # 直接填充图片
        # pix = QPixmap('./res/images/background11.jpg')
        # painter.drawPixmap(self.rect(), pix)

        super(FoWorld, self).paintEvent(event)
    def get(self, post_id):
        key = db.Key.from_path('Post', int(post_id), parent=Utils.blog_key())
        post = db.get(key)

        if self.user and self.user.key().id() == post.user.key().id():
            error = "You cannot like your own post."
            self.render('base.html', access_error=error)

        elif not self.user:
            self.redirect('/login')

        else:
            like = Like.all().filter('user ='******'post =', post).get()

            if like:
                self.redirect('/blog/' + str(post.key().id()))

            else:
                like = Like(parent=key, user=self.user, post=post)

                post.likes += 1

                like.put()
                post.put()

                self.redirect('/blog/' + str(post.key().id()))
예제 #32
0
파일: loggr.py 프로젝트: bretlowery/snakr
 def _save_dimension(modelclass, value):
     if value:
         normalized_value =  ' '.join(str(value).split()).lower()
         hash_key = Utils.get_hash(normalized_value)
         if not modelclass.objects.filter(id=hash_key).exists():
             dimension = modelclass(hash_key, normalized_value, 'N')
             dimension.save()
     else:
         hash_key = 0
     return hash_key
예제 #33
0
    def __init__(self, request, *args, **kwargs):
        self.longurl = ""
        self.longurl_is_preencoded = False
        self.normalized_longurl = ""
        self.normalized_longurl_scheme = ""
        self.id = 0
        self.vanity_path = ''
        self._event = loggr.SnakrEventLogger()

        lurl = ""

        lurl = Utils.get_json(request, 'u')
        if not lurl:
            raise self._event.log(messagekey='LONG_URL_MISSING', status_code=400)

        if not Utils.is_url_valid(lurl):
            raise self._event.log(messagekey='LONG_URL_INVALID', value=lurl, status_code=400)
        #if not Utils.url_exists(lurl):
        #    raise self._event.log(messagekey='LONG_URL_DOESNTEXIST', value=lurl, status_code=400)

        self.vanity_path = Utils.get_json(request, 'vp')

        image_url = Utils.get_json(request, 'img')
        if Utils.is_image(image_url):
            self.linked_image = image_url
        else:
            self.linked_image = None

        if lurl == Utils.get_decodedurl(lurl):
            preencoded = False
            self.normalized_longurl = Utils.get_encodedurl(lurl)
        else:
            preencoded = True
            self.normalized_longurl = lurl

        self.normalized_longurl_scheme = urlparse(lurl).scheme.lower()
        self.longurl_is_preencoded = preencoded
        self.longurl = lurl
        self.id = Utils.get_longurlhash(self.normalized_longurl)

        return
예제 #34
0
    def make(self, normalized_longurl_scheme, vanity_path):
        #
        # Make a new short URL
        #
        if settings.MAX_RETRIES < 1 or settings.MAX_RETRIES > 3:
            raise self._event.log(messagekey='ILLEGAL_MAX_RETRIES', status_code=400)
        #
        # Makes a short URL
        #
        # 1. Build the front of the short url. Match the scheme to the one used by the longurl.
        #    This is done so that a http longurl --> http shorturl, and a https long url --> https short url.
        #
        if normalized_longurl_scheme in ('https','ftps','sftp'):
            shorturl_prefix = normalized_longurl_scheme + '://' + settings.SECURE_SHORTURL_HOST + '/'
        else:
            shorturl_prefix = normalized_longurl_scheme + '://' + settings.SHORTURL_HOST + '/'
        #
        # 2. Make a short url.
        #    a. If vanity_path was passed, use it; otherwise:
        #    b. If no vanity path was passed, build a path with SHORTURL_PATH_SIZE characters from SHORTURL_PATH_ALPHABET.
        #    c. Does it exist already? If so, regenerate it and try again.
        #
        use_exact_vanity_path = False
        vp = ''
        if vanity_path:
            if vanity_path[0] == '!':
                use_exact_vanity_path = True
                vp = vanity_path[1:]
            else:
                use_exact_vanity_path = False
                vp = vanity_path
        shorturl_candidate = ''
        shash = 0
        i = 0
        sc = 1
        while i <= settings.MAX_RETRIES and sc != 0:
            i += 1
            if i <= settings.MAX_RETRIES:
                if use_exact_vanity_path:
                    shorturl_candidate = shorturl_prefix + vp
                elif vp:
                    shorturl_candidate = shorturl_prefix + vp + '-' + Utils.get_shortpathcandidate(digits_only=True)
                else:
                    shorturl_candidate = shorturl_prefix + Utils.get_shortpathcandidate()
                shash = Utils.get_shorturlhash(shorturl_candidate)
                s = ShortURLs.objects.filter(id=shash)
                sc = s.count()
                if use_exact_vanity_path:
                    if sc != 0:
                        raise self._event.log(messagekey='VANITY_PATH_EXISTS', status_code=400)
                    break

        if i > settings.MAX_RETRIES:
            raise self._event.log(messagekey='EXCEEDED_MAX_RETRIES', status_code=400)
        #
        # 3. SUCCESS! Complete it and return it as a ****decoded**** url (which it is at this point)
        #
        self.shorturl = shorturl_candidate
        self.normalized_shorturl = self.shorturl
        self.normalized_shorturl_scheme = normalized_longurl_scheme
        self.id = shash
        return self.normalized_shorturl
예제 #35
0
 def get_or_make_shorturl(self, request, *args, **kwargs):
     nopersist = Utils.true_or_false(Utils.get_json(request, 'nopersist'))
     #
     # Does the long URL already exist?
     #
     try:
         l = LongURLs.objects.get(id=self.id)
     except:
         l = None
         pass
     if not l:
         #
         # NO IT DOESN'T
         #
         # 1. Create a LongURLs persistence object
         #
         if self.longurl_is_preencoded:
             originally_encoded = 'Y'
         else:
             originally_encoded = 'N'
         ldata = LongURLs(id=self.id, longurl=self.normalized_longurl, originally_encoded=originally_encoded)
         #
         # 2. Generate a short url for it (with collision handling) and calc its compression ratio vs the long url
         #
         s = ShortURL(request)
         s.make(self.normalized_longurl_scheme, self.vanity_path)
         compression_ratio = float(len(s.shorturl)) / float(len(self.normalized_longurl))
         #
         # 3. Create a matching ShortURLs persistence object
         #
         sdata = ShortURLs(id=s.id, longurl_id=ldata.id, shorturl=s.shorturl, is_active='Y',
                           compression_ratio=compression_ratio, shorturl_path_size=settings.SHORTURL_PATH_SIZE)
         #
         # 4. Is there an associated image? If so, download it to static,
         #
         if self.linked_image:
             ft = file
         #
         # 5. Persist everything
         #
         if not nopersist:
             ldata.save()
             sdata.save()
             self._event.log(request=request, event_type='L', messagekey='LONG_URL_SUBMITTED', value=self.normalized_longurl,
                             longurl_id=self.id, shorturl_id=s.id, longurl=self.normalized_longurl, shorturl=s.shorturl, status_code=200)
         #
         # 6. Return the short url
         #
     else:
         #
         # YES IT DOES
         # Return the existing short url to the caller
         #
         # 1. Check for potential collision
         #
         if l.longurl != self.normalized_longurl:
             raise self._event.log(request=request, messagekey='HASH_COLLISION', value=self.normalized_longurl, status_code=400)
         #
         # 2. Lookup the short url. It must be active.
         #
         s = ShortURLs.objects.get(longurl_id=self.id, is_active='Y')
         if not s:
             raise Http404
         #
         # 3. Log the lookup
         #
         self._event.log(request=request, event_type='R', messagekey='LONG_URL_RESUBMITTED', value=self.normalized_longurl, longurl_id=self.id, longurl=self.normalized_longurl, shorturl_id=s.id, shorturl=s.shorturl, status_code=200)
         #
         # 4. Return the short url
         #
     return s.shorturl
예제 #36
0
    def getlongurl(self, request):
        self.shorturl = ''
        self.shorturl_is_preencoded = False
        self.normalized_shorturl = ''
        self.normalized_shorturl_scheme = ''
        self.id = -1
        #
        # cleanse the passed short url
        #
        surl = request.build_absolute_uri()
        dsurl = Utils.get_decodedurl(surl)
        sparts = urlparse(dsurl)
        if surl == dsurl:
            preencoded = False
        else:
            preencoded = True
            l = dsurl
        self.normalized_shorturl_scheme = sparts.scheme.lower()
        self.shorturl_is_preencoded = preencoded
        self.normalized_shorturl = urlunparse(sparts)
        if self.normalized_shorturl.endswith("/"):
            self.normalized_shorturl = self.normalized_shorturl[:-1]
        self.shorturl = surl
        if self.shorturl.endswith("/"):
            self.shorturl = self.shorturl[:-1]
        #
        # If no path provided, redirect to the defined index.html
        #
        if sparts.path == '/':
            return settings.INDEX_HTML
        #
        # Was the shorturl encoded or malcoded? If so, don't trust it.
        #
        if self.shorturl != self.normalized_shorturl:
            raise self._event.log(request=request, messagekey='SHORT_URL_ENCODING_MISMATCH', status_code=400)
        #
        # Lookup the short url
        #
        self.id = Utils.get_shorturlhash(self.normalized_shorturl)
        try:
            s = ShortURLs.objects.get(id = self.id)
            if not s:
                raise self._event.log(request=request, messagekey='SHORT_URL_NOT_FOUND', value=self.shorturl, status_code=400)
        except:
            raise self._event.log(request=request, messagekey='SHORT_URL_NOT_FOUND', value=self.shorturl, status_code=400)

        if s.shorturl != self.shorturl:
            raise self._event.log(request=request, messagekey='SHORT_URL_MISMATCH', status_code=400)
        #
        # If the short URL is not active, 404
        #
        if s.is_active != 'Y':
            raise self._event.log(request=request, messagekey='HTTP_404', value=self.shorturl, status_code=404)
        #
        # Lookup the matching long url by the short url's id.
        # If it doesn't exist, 404.
        # If it does, decode it.
        #
        l = LongURLs.objects.get(id = s.longurl_id)
        if not l:
            raise self._event.log(request=request, messagekey='HTTP_404', value='ERROR, HTTP 404 longurl not found', longurl_id=s.longurl_id, shorturl_id=self.id, shorturl=self.shorturl, status_code=422)
        longurl = Utils.get_decodedurl(l.longurl)
        #
        # Log that a 302 request to the matching long url is about to occur
        #
        self._event.log(request=request, event_type='S', messagekey='HTTP_302', value=longurl, longurl_id=s.longurl_id, longurl=longurl, shorturl_id=self.id, shorturl=self.shorturl, status_code=302)
        #
        # Return the longurl
        #
        return longurl
예제 #37
0
파일: loggr.py 프로젝트: bretlowery/snakr
    def log(self, **kwargs):
        #
        # get parameters
        #
        if not settings.ENABLE_LOGGING:
            return
        request = kwargs.pop('request', None)
        if not isinstance(request, HttpRequest):
            request = None
        messagekey = kwargs.pop('messagekey', None)
        message = kwargs.pop('message', None)
        if not message:
            if messagekey: 
                messagekey = messagekey.strip().upper()
                try:
                    message = settings.CANONICAL_MESSAGES[messagekey]
                    if not message:
                        message = settings.MESSAGE_OF_LAST_RESORT
                except:
                    message = settings.MESSAGE_OF_LAST_RESORT
                    pass
            else:
                message = settings.MESSAGE_OF_LAST_RESORT
        try:
            value = str(kwargs.pop('value', 'none'))
        except:
            value = None
            pass
        if value is not None and value != 'none':
            if message:
                try:
                    message = message % value
                except:
                    message = value
                    pass
            else:
                message = value
        event_type = kwargs.pop('event_type', 'W')
        longurl_id = kwargs.pop('longurl_id', -1)
        longurl = kwargs.pop('longurl', 'none')
        shorturl_id = kwargs.pop('shorturl_id', -1)
        shorturl = kwargs.pop('shorturl', 'none')
        verbose = kwargs.pop('verbose', False)
        status_code = kwargs.pop('status_code', 200)
        dt = datetime.datetime.now()
        dtnow = kwargs.pop('dt', dt.isoformat())
        #
        # get client info from the request objext
        #
        if request:
            ip_address, geo_lat, geo_long, geo_city, geo_country, http_host, http_useragent, http_referer = Utils.get_meta(request, False)
        #
        if event_type == 'I':
            status_code = 0
        #if status_code == 200:
        #    event_type = 'I'
        if status_code not in (-403,0,200,302,400,404,422,500):
            status_code = 403
        if settings.DEBUG or settings.VERBOSE_LOGGING or (status_code >= 400 and status_code != 404):
            verbose = True

        dupe_message = False
        if request:
            if ip_address == self.last_ip_address:
                if http_useragent == self.last_http_user_agent:
                    if dtnow == self.last_dtnow:
                        dupe_message = True

        if not dupe_message:

            jsondata = {
                'snakr':    dtnow,
                'type':     event_type,
                'code':     str(status_code),
            }

            db_id = -1

            if (settings.VERBOSE_LOGGING or verbose) and request:
                    jsondata['lid'] = str(longurl_id)
                    jsondata['sid'] = str(shorturl_id)
                    jsondata['ip'] = ip_address
                    jsondata['lat'] = str(geo_lat)
                    jsondata['long'] = str(geo_long)
                    jsondata['city'] = str(geo_city)
                    jsondata['cnty'] = str(geo_country)
                    jsondata['host'] = str(http_host)
                    jsondata['ua'] = str(http_useragent)
                    jsondata['ref'] = http_referer

            if settings.DATABASE_LOGGING and request:

                sql_id, ds_id = self._log_transaction(
                        jsondata = jsondata,
                        dt = dt,
                        event_type = event_type,
                        status_code = status_code,
                        message = message,
                        shorturl_id = shorturl_id,
                        shorturl = shorturl,
                        longurl_id = longurl_id,
                        longurl = longurl,
                        ip_address = ip_address,
                        geo_lat = geo_lat,
                        geo_long = geo_long,
                        geo_city = geo_city,
                        geo_country = geo_country,
                        http_host = http_host,
                        http_useragent = http_useragent
                )
                jsondata['snakr_cloudsql_eventlog_id'] = str(sql_id)
                jsondata['snakr_datastore_eventstream_id'] = str(ds_id)

            if abs(status_code) == 403 and settings.LOG_HTTP403:
                self.logger.warning(message, extra=jsondata)
            elif (status_code <= 200 and settings.LOG_HTTP200) or (status_code == 404 and settings.LOG_HTTP404) or (status_code == 302 and settings.LOG_HTTP302):
                self.logger.info(message, extra=jsondata)
            elif status_code == 400 and settings.LOG_HTTP400:
                self.logger.warning(message, extra=jsondata)
            else:
                self.logger.critical(message, extra=jsondata)

            def switch(x):
                return {
                    -403:PermissionDenied,
                    200: message,
                    302: message,
                    400: SuspiciousOperation(message),
                    403: SuspiciousOperation(message),
                    404: Http404,
                    422: SuspiciousOperation(message),
                    500: HttpResponseServerError(message),
                }.get(x, 200)

            if status_code != 0:
                return switch(status_code)

        return