示例#1
0
def blogs_search(content, page_num):
    if not is_int(page_num):
        abort(404)
    page_num = int(page_num)
    if request.method == 'GET':
        all_blogs = Blog.query.order_by(-Blog.id).all()
        blogs = []
        content = content.strip()
        words = content.split(' ')
        for rb in all_blogs:
            for word in words:
                word_low = word.lower()
                if word_low in rb.title.lower(
                ) or word_low in rb.content.lower():
                    blogs.append(rb)
                    break
        split = page_spliter(blogs, 5)
        min_page = 1
        max_page = len(split)
        if max_page == 0:
            max_page = 1
            split = [[]]
        if page_num < min_page or page_num > max_page:
            abort(404)
        blogs = split[page_num - 1]
        return render_template('Blog/searchBlogs.html',
                               blogs=blogs,
                               this_page=page_num,
                               min_page=min_page,
                               if_login=if_login(),
                               max_page=max_page,
                               search=content)
示例#2
0
def get_edit_blog(blog_id):
    if not is_int(blog_id):
        abort(404)
    blog_id = int(blog_id)
    if request.method == 'GET':
        blog = Blog.query.filter_by(id=blog_id).first_or_404()
        return render_template('Blog/editBlog.html', blog=blog)
 def get_blocks_indices_comments_values(self):
     """
     This function contains knowledge about what an slhafile from slhalib looks like
     It returns a dictionary: {(block_name,indices,comment):  value, ...}
     NB: atm ignoring BLOCK SPINFO  and  DECAY's
     """
     s = str(self)
     data = OrderedDict()
     block_name = None
     for line in s.split('\n'):
         if line.startswith('B'):
             # is a block
             block_name = line.split()[1]
             if 'Q=' in line:
                 data[(block_name,tuple([]),'Qscale')]= float(line.split('=')[1].split()[0])
         elif line.startswith('D'):
             #FIXME: we may want to change this
             print("WARNING: DECAY's are ignored in SLHA.get_blocks_indices_comments_values() ")
             block_name=None
         elif block_name and (not block_name == 'SPINFO') :
             #FIXME: possibly want to have the SPINFO as well at some point
             items = line.split()
             if len(items):
                 first_non_index = next(x for x in items if not is_int(x))
                 indices_end = items.index(first_non_index)
                 comment_pos = items.index('#') if '#' in items else 0
                 if comment_pos >0: indices_end=comment_pos-1
                 indices = tuple([int(x) for x in items[:indices_end]])
                 values = tuple([float(x) for x in
                         items[indices_end:comment_pos]])
                 if len(values) == 1:
                     values = values[0]
                 comment = ' '.join(items[comment_pos:]).lstrip('#').lstrip()
                 data[(block_name,indices,comment)] = values
     return data
示例#4
0
 def process(self):
     s = str(self)
     data = OrderedDict()
     block_name = None
     for line in s.split('\n'):
         if line.startswith('B'):
             # is a block
             block_name = line.split()[1]
             data[block_name] = OrderedDict()
             #pass
         else:
             items = line.split()
             if len(items):
                 first_non_index = next(x for x in items if not is_int(x))
                 indices_end = items.index(first_non_index)
                 comment_pos = items.index('#') if '#' in items else 0
                 indices = tuple([int(x) for x in items[:indices_end]])
                 values = tuple([float(x) for x in
                         items[indices_end:comment_pos]])
                 if len(values) == 1:
                     values = values[0]
                 comment = ' '.join(items[comment_pos:]).lstrip('#').lstrip()
                 #data[block_name][indices] = (values, comment)
                 data[block_name][comment] = values
     return data
示例#5
0
def delete_blog(blog_id):
    if not is_int(blog_id):
        abort(404)
    blog_id = int(blog_id)
    if request.method == 'GET':
        blog = Blog.query.filter_by(id=blog_id).first_or_404()
        blog.delete_with_save()
        return redirect(url_for('blog.index'))
示例#6
0
def api_set_current_question(data):
    if 'question_id' not in data or not tools.is_int(data['question_id']) \
                or int(data['question_id']) < -1 or \
                int(data['question_id']) >= len(app.questions):
        return tools.gen_result_failure('Invalid question ID.')
    else:
        app.show_answer = False
        app.current_question = int(data['question_id'])
        return tools.gen_result_success(message='Success.')
示例#7
0
文件: core.py 项目: moronbros/f5go
    def _export(self):
        if tools.is_int(self._url):  # linkid needs to be converted for export
            L = MYGLOBALS.g_db.getLink(self._url)
            if L and L in self.links:
                print L
                self._url = L._url
            else:
                print "fixing unknown dest linkid for", self.name
                self._url = "list"

        return ("list %s " % self.name) + Link._export(self)
示例#8
0
def post_edit_blog(blog_id):
    if not is_int(blog_id):
        abort(404)
    blog_id = int(blog_id)
    if request.method == 'POST':
        form = BlogForm(formdata=request.form)
        blog = Blog.query.filter_by(id=blog_id).first_or_404()
        errors = blog.edit_with_save(form.title.data, form.content.data)
        if not errors:
            return redirect(url_for('blog.get_blog', blog_id=blog_id))
        else:
            return render_template('Blog/errorList.html', errors=errors)
示例#9
0
def post_comment(blog_id):
    if not is_int(blog_id):
        abort(404)
    blog_id = int(blog_id)
    if request.method == 'POST':
        form = CommentForm(formdata=request.form)
        user = User.query.filter_by(username=get_username()).first()
        comment = Comment(sender=user.username,
                          content=form.content.data,
                          blog_id=blog_id)
        errors = comment.add_with_save()
        if not errors:
            return redirect(url_for('blog.get_blog', blog_id=blog_id))
        else:
            return render_template('Blog/errorList.html', errors=errors)
示例#10
0
def get_blog(blog_id):
    if not is_int(blog_id):
        abort(404)
    blog_id = int(blog_id)
    if request.method == 'GET':
        blog = Blog.query.filter_by(id=blog_id).first_or_404()
        m_content = markdown(blog.content)
        if '<p>' in m_content:
            m_content = m_content.replace('<p>', '')
        if '</p>' in m_content:
            m_content = m_content.replace('</p>', '')
        comments = Comment.query.filter_by(
            blog_id=blog_id).order_by(-Comment.id).all()
        blog.add_read()
        return render_template('Blog/blog.html',
                               blog=blog,
                               if_login=if_login(),
                               m_content=m_content,
                               comments=comments)
示例#11
0
def blogs_page(page_num):
    if not is_int(page_num):
        abort(404)
    page_num = int(page_num)
    if request.method == 'GET':
        all_blogs = Blog.query.order_by(-Blog.id).all()
        split = page_spliter(all_blogs, 5)
        min_page = 1
        max_page = len(split)
        if max_page == 0:
            max_page = 1
            split = [[]]
        if page_num < min_page or page_num > max_page:
            abort(404)
        blogs = split[page_num - 1]
        return render_template('Blog/blogs.html',
                               if_login=if_login(),
                               blogs=blogs,
                               username=get_username(),
                               is_owner=is_owner(),
                               this_page=page_num,
                               min_page=min_page,
                               max_page=max_page)
示例#12
0
def _show_res(hs, res, figtitle='', max_nCols=5, topN_cxs=None, gt_cxs=None,
              show_query=False, all_kpts=False, annote=True, query_cfg=None,
              split_plots=False, interact=True, **kwargs):
    ''' Displays query chip, groundtruth matches, and top 5 matches'''
    #printDBG('[viz._show_res()] %s ' % helpers.printableVal(locals()))
    fnum = kwargs.pop('fnum', 3)
    #print('========================')
    #print('[viz] Show chip matches:')
    if topN_cxs is None:
        topN_cxs = []
    if gt_cxs is None:
        gt_cxs = []
    qcx = res.qcx
    all_gts = hs.get_other_indexed_cxs(qcx)
    #print('[viz._show_res()]----------------')
    print('[viz._show_res()] #topN=%r #missed_gts=%r/%r' % (len(topN_cxs),
                                                            len(gt_cxs),
                                                            len(all_gts)))
    #printDBG('[viz._show_res()] * max_nCols=%r' % (max_nCols,))
    #printDBG('[viz._show_res()] * show_query=%r' % (show_query,))
    ranked_cxs = res.topN_cxs(hs, N='all')
    # Build a subplot grid
    nQuerySubplts = 1 if show_query else 0
    nGtSubplts = nQuerySubplts + (0 if gt_cxs is None else len(gt_cxs))
    nTopNSubplts  = 0 if topN_cxs is None else len(topN_cxs)
    nTopNCols = min(max_nCols, nTopNSubplts)
    nGTCols   = min(max_nCols, nGtSubplts)
    if not split_plots:
        nGTCols = max(nGTCols, nTopNCols)
        nTopNCols = nGTCols
    nGtRows   = 0 if nGTCols == 0 else int(np.ceil(nGtSubplts / nGTCols))
    nTopNRows = 0 if nTopNCols == 0 else int(np.ceil(nTopNSubplts / nTopNCols))
    nGtCells = nGtRows * nGTCols
    if split_plots:
        nRows = nGtRows
    else:
        nRows = nTopNRows + nGtRows
    # Helper function for drawing matches to one cx

    def _show_matches_fn(cx, orank, pnum):
        'helper for viz._show_res'
        aug = 'rank=%r\n' % orank
        #printDBG('[viz._show_res()] plotting: %r'  % (pnum,))
        kwshow  = dict(draw_ell=annote, draw_pts=annote, draw_lines=annote,
                       ell_alpha=.5, all_kpts=all_kpts, **kwargs)
        show_matches_annote_res(res, hs, cx, title_aug=aug, fnum=fnum, pnum=pnum, **kwshow)

    def _show_query_fn(plotx_shift, rowcols):
        'helper for viz._show_res'
        plotx = plotx_shift + 1
        pnum = (rowcols[0], rowcols[1], plotx)
        #printDBG('[viz._show_res()] Plotting Query: pnum=%r' % (pnum,))
        show_chip(hs, res=res, pnum=pnum, draw_kpts=annote, prefix='q', fnum=fnum)

    # Helper to draw many cxs
    def _plot_matches_cxs(cx_list, plotx_shift, rowcols):
        'helper for viz._show_res'
        #printDBG('[viz._show_res()] Plotting Chips %s:' % hs.cidstr(cx_list))
        if cx_list is None:
            return
        for ox, cx in enumerate(cx_list):
            plotx = ox + plotx_shift + 1
            pnum = (rowcols[0], rowcols[1], plotx)
            oranks = np.where(ranked_cxs == cx)[0]
            if len(oranks) == 0:
                orank = -1
                continue
            orank = oranks[0] + 1
            _show_matches_fn(cx, orank, pnum)

    #query_uid = res.query_uid
    #query_uid = re.sub(r'_trainID\([0-9]*,........\)', '', query_uid)
    #query_uid = re.sub(r'_indxID\([0-9]*,........\)', '', query_uid)
    #query_uid = re.sub(r'_dcxs\(........\)', '', query_uid)
    #print('[viz._show_res()] fnum=%r' % fnum)

    fig = df2.figure(fnum=fnum, pnum=(nRows, nGTCols, 1), doclf=True)
    fig.clf()
    df2.plt.subplot(nRows, nGTCols, 1)
    # Plot Query
    if show_query:
        _show_query_fn(0, (nRows, nGTCols))
    # Plot Ground Truth
    _plot_matches_cxs(gt_cxs, nQuerySubplts, (nRows, nGTCols))
    # Plot TopN in a new figure
    if split_plots:
        #df2.set_figtitle(figtitle + 'GT', query_uid)
        nRows = nTopNRows
        fig = df2.figure(fnum=fnum + 9000)
        fig.clf()
        df2.plt.subplot(nRows, nTopNCols, 1)
        shift_topN = 0
    else:
        shift_topN = nGtCells
    _plot_matches_cxs(topN_cxs, shift_topN, (nRows, nTopNCols))
    if split_plots:
        pass
        #df2.set_figtitle(figtitle + 'topN', query_uid)
    else:
        pass
        #df2.set_figtitle(figtitle, query_uid)
        df2.set_figtitle(figtitle)

    if interact:
        #printDBG('[viz._show_res()] starting interaction')
        # Create
        def _on_res_click(event):
            'result interaction mpl event callback slot'
            print('[viz] clicked result')
            if event.xdata is None:
                return
            _show_res(hs, res, figtitle=figtitle, max_nCols=max_nCols, topN_cxs=topN_cxs,
                      gt_cxs=gt_cxs, show_query=show_query, all_kpts=all_kpts,
                      annote=not annote, split_plots=split_plots,
                      interact=interact, **kwargs)
            fig.canvas.draw()

        df2.disconnect_callback(fig, 'button_press_event')
        if interact:
            df2.connect_callback(fig, 'button_press_event', _on_res_click)
    #printDBG('[viz._show_res()] Finished')
    return fig



# USE LAB
    USE_LAB = False  # True  # False

    import tools
    from skimage import color
    if USE_LAB:
        isInt = tools.is_int(rchip2)
        rchip2_blendA = np.zeros((h2, w2, 3), dtype=rchip2.dtype)
        rchip2_blendH = np.zeros((h2, w2, 3), dtype=rchip2.dtype)
        rchip2_blendA = np.rollaxis(rchip2_blendA, 2)
        rchip2_blendH = np.rollaxis(rchip2_blendH, 2)
        #rchip2_blendA[0] = (rchip2 / 2) + (rchip1_At / 2)
        #rchip2_blendH[0] = (rchip2 / 2) + (rchip1_Ht / 2)
        #rchip2_blendA[0] /= 1 + (122 * isInt)
        #rchip2_blendH[0] /= 1 + (122 * isInt)
        rchip2_blendA[0] += 255
        rchip2_blendH[0] += 255
        rchip2_blendA[1] = rchip2
        rchip2_blendH[1] = rchip2
        rchip2_blendA[2] = rchip1_At
        rchip2_blendH[2] = rchip1_Ht
        rchip2_blendA = np.rollaxis(np.rollaxis(rchip2_blendA, 2), 2)
        rchip2_blendH = np.rollaxis(np.rollaxis(rchip2_blendH, 2), 2)
        print('unchanged stats')
        print(helpers.printable_mystats(rchip2_blendH.flatten()))
        print(helpers.printable_mystats(rchip2_blendA.flatten()))
        if isInt:
            print('is int')
            rchip2_blendA = np.array(rchip2_blendA, dtype=float)
            rchip2_blendH = np.array(rchip2_blendH, dtype=float)
        else:
            print('is float')
        print('div stats')
        print(helpers.printable_mystats(rchip2_blendH.flatten()))
        print(helpers.printable_mystats(rchip2_blendA.flatten()))
        rchip2_blendA = color.lab2rgb(rchip2_blendA)
        rchip2_blendH = color.lab2rgb(rchip2_blendH)
        if isInt:
            print('is int')
            rchip2_blendA = np.array(np.round(rchip2_blendA * 255), dtype=np.uint8)
            rchip2_blendH = np.array(np.round(rchip2_blendH * 255), dtype=np.uint8)
        print('changed stats')
        print(helpers.printable_mystats(rchip2_blendH.flatten()))
        print(helpers.printable_mystats(rchip2_blendA.flatten()))
示例#13
0
def api_get_question(data):
    if 'question_id' not in data or not tools.is_int(data['question_id']) \
                or int(data['question_id']) < 0 or \
                int(data['question_id']) >= len(app.questions):
        return tools.gen_result_failure('Invalid question ID.')
    return tools.gen_result_success(data=get_question(int(data['question_id'])))
示例#14
0
def _show_res(hs,
              res,
              figtitle='',
              max_nCols=5,
              topN_cxs=None,
              gt_cxs=None,
              show_query=False,
              all_kpts=False,
              annote=True,
              query_cfg=None,
              split_plots=False,
              interact=True,
              **kwargs):
    ''' Displays query chip, groundtruth matches, and top 5 matches'''
    #printDBG('[viz._show_res()] %s ' % helpers.printableVal(locals()))
    fnum = kwargs.pop('fnum', 3)
    #print('========================')
    #print('[viz] Show chip matches:')
    if topN_cxs is None:
        topN_cxs = []
    if gt_cxs is None:
        gt_cxs = []
    qcx = res.qcx
    all_gts = hs.get_other_indexed_cxs(qcx)
    #print('[viz._show_res()]----------------')
    print('[viz._show_res()] #topN=%r #missed_gts=%r/%r' %
          (len(topN_cxs), len(gt_cxs), len(all_gts)))
    #printDBG('[viz._show_res()] * max_nCols=%r' % (max_nCols,))
    #printDBG('[viz._show_res()] * show_query=%r' % (show_query,))
    ranked_cxs = res.topN_cxs(hs, N='all')
    # Build a subplot grid
    nQuerySubplts = 1 if show_query else 0
    nGtSubplts = nQuerySubplts + (0 if gt_cxs is None else len(gt_cxs))
    nTopNSubplts = 0 if topN_cxs is None else len(topN_cxs)
    nTopNCols = min(max_nCols, nTopNSubplts)
    nGTCols = min(max_nCols, nGtSubplts)
    if not split_plots:
        nGTCols = max(nGTCols, nTopNCols)
        nTopNCols = nGTCols
    nGtRows = 0 if nGTCols == 0 else int(np.ceil(nGtSubplts / nGTCols))
    nTopNRows = 0 if nTopNCols == 0 else int(np.ceil(nTopNSubplts / nTopNCols))
    nGtCells = nGtRows * nGTCols
    if split_plots:
        nRows = nGtRows
    else:
        nRows = nTopNRows + nGtRows
    # Helper function for drawing matches to one cx

    def _show_matches_fn(cx, orank, pnum):
        'helper for viz._show_res'
        aug = 'rank=%r\n' % orank
        #printDBG('[viz._show_res()] plotting: %r'  % (pnum,))
        kwshow = dict(draw_ell=annote,
                      draw_pts=annote,
                      draw_lines=annote,
                      ell_alpha=.5,
                      all_kpts=all_kpts,
                      **kwargs)
        show_matches_annote_res(res,
                                hs,
                                cx,
                                title_aug=aug,
                                fnum=fnum,
                                pnum=pnum,
                                **kwshow)

    def _show_query_fn(plotx_shift, rowcols):
        'helper for viz._show_res'
        plotx = plotx_shift + 1
        pnum = (rowcols[0], rowcols[1], plotx)
        #printDBG('[viz._show_res()] Plotting Query: pnum=%r' % (pnum,))
        show_chip(hs,
                  res=res,
                  pnum=pnum,
                  draw_kpts=annote,
                  prefix='q',
                  fnum=fnum)

    # Helper to draw many cxs
    def _plot_matches_cxs(cx_list, plotx_shift, rowcols):
        'helper for viz._show_res'
        #printDBG('[viz._show_res()] Plotting Chips %s:' % hs.cidstr(cx_list))
        if cx_list is None:
            return
        for ox, cx in enumerate(cx_list):
            plotx = ox + plotx_shift + 1
            pnum = (rowcols[0], rowcols[1], plotx)
            oranks = np.where(ranked_cxs == cx)[0]
            if len(oranks) == 0:
                orank = -1
                continue
            orank = oranks[0] + 1
            _show_matches_fn(cx, orank, pnum)

    #query_uid = res.query_uid
    #query_uid = re.sub(r'_trainID\([0-9]*,........\)', '', query_uid)
    #query_uid = re.sub(r'_indxID\([0-9]*,........\)', '', query_uid)
    #query_uid = re.sub(r'_dcxs\(........\)', '', query_uid)
    #print('[viz._show_res()] fnum=%r' % fnum)

    fig = df2.figure(fnum=fnum, pnum=(nRows, nGTCols, 1), doclf=True)
    fig.clf()
    df2.plt.subplot(nRows, nGTCols, 1)
    # Plot Query
    if show_query:
        _show_query_fn(0, (nRows, nGTCols))
    # Plot Ground Truth
    _plot_matches_cxs(gt_cxs, nQuerySubplts, (nRows, nGTCols))
    # Plot TopN in a new figure
    if split_plots:
        #df2.set_figtitle(figtitle + 'GT', query_uid)
        nRows = nTopNRows
        fig = df2.figure(fnum=fnum + 9000)
        fig.clf()
        df2.plt.subplot(nRows, nTopNCols, 1)
        shift_topN = 0
    else:
        shift_topN = nGtCells
    _plot_matches_cxs(topN_cxs, shift_topN, (nRows, nTopNCols))
    if split_plots:
        pass
        #df2.set_figtitle(figtitle + 'topN', query_uid)
    else:
        pass
        #df2.set_figtitle(figtitle, query_uid)
        df2.set_figtitle(figtitle)

    if interact:
        #printDBG('[viz._show_res()] starting interaction')
        # Create
        def _on_res_click(event):
            'result interaction mpl event callback slot'
            print('[viz] clicked result')
            if event.xdata is None:
                return
            _show_res(hs,
                      res,
                      figtitle=figtitle,
                      max_nCols=max_nCols,
                      topN_cxs=topN_cxs,
                      gt_cxs=gt_cxs,
                      show_query=show_query,
                      all_kpts=all_kpts,
                      annote=not annote,
                      split_plots=split_plots,
                      interact=interact,
                      **kwargs)
            fig.canvas.draw()

        df2.disconnect_callback(fig, 'button_press_event')
        if interact:
            df2.connect_callback(fig, 'button_press_event', _on_res_click)
    #printDBG('[viz._show_res()] Finished')
    return fig

    # USE LAB
    USE_LAB = False  # True  # False

    import tools
    from skimage import color
    if USE_LAB:
        isInt = tools.is_int(rchip2)
        rchip2_blendA = np.zeros((h2, w2, 3), dtype=rchip2.dtype)
        rchip2_blendH = np.zeros((h2, w2, 3), dtype=rchip2.dtype)
        rchip2_blendA = np.rollaxis(rchip2_blendA, 2)
        rchip2_blendH = np.rollaxis(rchip2_blendH, 2)
        #rchip2_blendA[0] = (rchip2 / 2) + (rchip1_At / 2)
        #rchip2_blendH[0] = (rchip2 / 2) + (rchip1_Ht / 2)
        #rchip2_blendA[0] /= 1 + (122 * isInt)
        #rchip2_blendH[0] /= 1 + (122 * isInt)
        rchip2_blendA[0] += 255
        rchip2_blendH[0] += 255
        rchip2_blendA[1] = rchip2
        rchip2_blendH[1] = rchip2
        rchip2_blendA[2] = rchip1_At
        rchip2_blendH[2] = rchip1_Ht
        rchip2_blendA = np.rollaxis(np.rollaxis(rchip2_blendA, 2), 2)
        rchip2_blendH = np.rollaxis(np.rollaxis(rchip2_blendH, 2), 2)
        print('unchanged stats')
        print(helpers.printable_mystats(rchip2_blendH.flatten()))
        print(helpers.printable_mystats(rchip2_blendA.flatten()))
        if isInt:
            print('is int')
            rchip2_blendA = np.array(rchip2_blendA, dtype=float)
            rchip2_blendH = np.array(rchip2_blendH, dtype=float)
        else:
            print('is float')
        print('div stats')
        print(helpers.printable_mystats(rchip2_blendH.flatten()))
        print(helpers.printable_mystats(rchip2_blendA.flatten()))
        rchip2_blendA = color.lab2rgb(rchip2_blendA)
        rchip2_blendH = color.lab2rgb(rchip2_blendH)
        if isInt:
            print('is int')
            rchip2_blendA = np.array(np.round(rchip2_blendA * 255),
                                     dtype=np.uint8)
            rchip2_blendH = np.array(np.round(rchip2_blendH * 255),
                                     dtype=np.uint8)
        print('changed stats')
        print(helpers.printable_mystats(rchip2_blendH.flatten()))
        print(helpers.printable_mystats(rchip2_blendA.flatten()))