Exemplo n.º 1
0
class TestComment(TestSuite):
    comment1 = CommentData(
        Comment({
            'comment_id': 1,
            'username': '******',
            'first': 'Andy',
            'last': 'Jarombek',
            'log_id': 1,
            'time': datetime.fromisoformat('2019-11-09'),
            'content': 'Test Comment',
            'deleted': False
        }))

    comment2 = CommentData(
        Comment({
            'comment_id': 2,
            'username': '******',
            'first': 'Andy',
            'last': 'Jarombek',
            'log_id': 1,
            'time': datetime.now(),
            'content': 'Another Test Comment',
            'deleted': False
        }))

    def test_comment_data_str(self) -> None:
        """
        Prove that the human readable string representation of an CommentData object is as expected.
        """
        self.assertEquals(
            str(self.comment1),
            'CommentData: [comment_id: 1, username: andy, first: Andy, last: Jarombek, log_id: 1, '
            'time: 2019-11-09 00:00:00, content: Test Comment, deleted: False]'
        )
        self.assertEquals(
            self.comment1.__str__(),
            'CommentData: [comment_id: 1, username: andy, first: Andy, last: Jarombek, log_id: 1, '
            'time: 2019-11-09 00:00:00, content: Test Comment, deleted: False]'
        )

    def test_comment_data_repr(self) -> None:
        """
        Prove that the machine readable string representation of an CommentData object is as expected.
        """
        self.assertEquals(repr(self.comment1), "<CommentData 1>")
        self.assertEquals(self.comment1.__repr__(), "<CommentData 1>")

    def test_comment_data_eq(self) -> None:
        """
        Prove that two CommentData objects with the same property values test positive for value equality.
        """
        self.assertTrue(self.comment1 == self.comment1)
        self.assertTrue(self.comment1.__eq__(self.comment1))

    def test_comment_data_ne(self) -> None:
        """
        Prove that two CommentData objects with different property values test negative for value equality.
        """
        self.assertTrue(self.comment1 != self.comment2)
        self.assertTrue(self.comment1.__ne__(self.comment2))
Exemplo n.º 2
0
 def _create_comment(self):
     comment_text = self.comment_textedit.toPlainText()
     if not self.comment:
         self.comment = Comment(self.win.assy, None, comment_text)
         self.win.assy.addnode(self.comment)
         self.action = 'added'
     else:
         self.comment.set_text(comment_text)
         self.action = 'updated'
Exemplo n.º 3
0
def articleComment():
    articleId = request.args.get("articleId")
    # name = request.form["name"]
    username = session.get('username')
    if username != None:
        name = username
    else:
        name = '匿名用户'
    content = request.form["content"]
    time = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
    comment = Comment(articleId=articleId,
                      name=name,
                      content=content,
                      time=time)
    comment.save()
    return redirect("/article_detail?id=" + articleId)
Exemplo n.º 4
0
def articleDetail():
    id = request.args.get("id")
    art = Article.get(Article.id == id)
    comments = Comment.select().where(Comment.articleId == id)
    return render_template("article_detail.html",
                           article=art,
                           comments=comments)
Exemplo n.º 5
0
 def _create_comment(self):
     comment_text = self.comment_textedit.toPlainText()
     if not self.comment:
         self.comment = Comment(self.win.assy, None, comment_text)
         self.win.assy.addnode(self.comment)
         self.action = 'added'
     else: 
         self.comment.set_text(comment_text)
         self.action = 'updated'
Exemplo n.º 6
0
def read_or_insert_pdb(assy, 
            filename, 
            showProgressDialog = False,
            chainId = None,
            isInsert = False):
    """
    Reads (loads) a PDB file, or inserts it into an existing chunk.
    
    @param assy: The assembly.
    @type  assy: L{assembly}
    
    @param filename: The PDB filename to read.
    @type  filename: string
    
    @param showProgressDialog: if True, display a progress dialog while reading
                               a file. Default is False.
    @type  showProgressDialog: boolean
    """
    
    from protein.model.Protein import enableProteins
    
    if enableProteins:
        
        molecules, comment_text  = _readpdb_new(assy, 
                        filename, 
                        isInsert = isInsert, 
                        showProgressDialog = showProgressDialog,
                        chainId = chainId)
        if molecules:
            assy.part.ensure_toplevel_group()

            dir, name = os.path.split(filename)
            
            #name = gensym(nodename, assy) 
            
            group = Group(name, assy, assy.part.topnode) 
            for mol in molecules:
                if mol is not None:
                    group.addchild(mol)

            comment = Comment(assy, "Information", comment_text)

            group.addchild(comment)
            
            assy.addnode(group)
            
    else:
        mol  = _readpdb(assy, 
                        filename, 
                        isInsert = isInsert, 
                        showProgressDialog = showProgressDialog,
                        chainId = chainId)
        
        if mol is not None:
            assy.addmol(mol)
    return
Exemplo n.º 7
0
 def post(self):
     nextmove = self.get_request("nextmove","")
     id=self.get_int_request("commentID",0)
     email=self.get_request("reply_email","unknown")
     author=self.get_request("reply_author","unknown")
     url=self.get_request("reply_url","")
     content=self.get_request("reply_content","")
     act=self.get_request("act","")
     ids=self.get_arguments("ids","")
     error="0"
     if act == "delete":
         if not Comment().removeAllByArray(ids):
             error="2"
     if act == 'edit':
         r=Comment().getByID(id)
         if r:
             error="0"
             if not r.user:
                 r.email=email
                 r.author=author
             r.url=url
             r.content=content
             if r.save() <=0:
                 error="1"
         else:
             error="1"
     self.redirect(self.webroot_url("admin/replies/?error="+error+"&"+nextmove))
Exemplo n.º 8
0
    def post(self):
        """ New comment class """
        post_id = self.request.get("key")
        key = db.Key.from_path('Post',
                               int(post_id),
                               parent=utils.blog_key())
        post = db.get(key)

        if not post:
            self.error(404)
            return

        content = self.request.get("content")
        author = User.by_name(self.user.name)

        if content:
            comm = Comment(post=post, content=content, author=author)
            comm.put()

        # Setting timer to give time for the Server to SAVE
        time.sleep(2)
        self.redirect('/blog/%s' % str(post.key().id()))
Exemplo n.º 9
0
class CommentProp(QDialog, Ui_CommentPropDialog):
    """
    The Comment dialog allows the user to add a comment to the Model Tree, which
    is saved in the MMP file.
    """
    def __init__(self, win):
        QDialog.__init__(self, win) # win is parent.
        self.setupUi(self)
        self.win = win
        self.comment = None
        self.action = None
            # REVIEW, re self.action:
            # - if used only in messages (true in this file, but not yet
            #   analyzed re external files), should change initial value to "".
            # - if not used in external files, should make private.
            # [bruce 080717 comment]
    
    def setup(self, comment = None):
        """
        Show Comment dialog with current Comment text, for editing
        properties of an existing Comment node or creating a new one.
        
        @param comment: the comment node to edit, or None to create a new one.
        """
        self.comment = comment
        
        if self.comment:
            self.comment_textedit.setPlainText(self.comment.get_text())
                # Load comment text.
            qt4todo("self.comment_textedit.moveCursor(QTextEdit.MoveEnd, False)")
                # Sets cursor position to the end of the textedit document.
        
        QDialog.exec_(self)

    ###### Private methods ###############################
    
    def _create_comment(self):
        comment_text = self.comment_textedit.toPlainText()
        if not self.comment:
            self.comment = Comment(self.win.assy, None, comment_text)
            self.win.assy.addnode(self.comment)
            self.action = 'added'
        else: 
            self.comment.set_text(comment_text)
            self.action = 'updated'
            
    def _remove_comment(self):
        if self.comment:
            self.comment.kill()
            self.win.mt.mt_update()
            self.comment = None
            
    def insert_date_time_stamp(self):
        """
        Insert a date/time stamp in the comment at the current position.

        @note: slot method for self.date_time_btn, SIGNAL("clicked()").
        """
        timestr = "%s " % time.strftime("%m/%d/%Y %I:%M %p")
        self.comment_textedit.insertPlainText(timestr)
        
    def _done_history_msg(self):
        env.history.message(cmd + quote_html("%s %s." % (self.comment.name, self.action)))
                #bruce Qt4 070502 precaution: use quote_html
    
    #################
    # Cancel Button
    #################
    def reject(self):
        QDialog.reject(self)
        self.comment = None
        self.comment_textedit.setPlainText("") # Clear text.

    #################
    # OK Button
    #################
    def accept(self):
        """
        Slot for the OK button
        """
        try:
            self._create_comment()
            self._done_history_msg()
            self.comment = None
        except Exception, e:
            print_compact_traceback("Bug: exception in CommentProp.accept: ") #bruce Qt4 070502
            env.history.message(cmd + redmsg("Bug: " + quote_html(" - ".join(map(str, e.args)))))
                #bruce Qt4 070502 bugfixes: use quote_html, say it's a bug (could say "internal error" if desired)
            self._remove_comment()
        self.win.mt.mt_update()
        QDialog.accept(self)
        self.comment_textedit.setPlainText("") # Clear text.
Exemplo n.º 10
0
def comment_with_id_put(comment_id):
    """
    Update an existing comment.
    :param comment_id: The unique identifier for a comment.
    :return: A response object for the PUT API request.
    """
    old_comment: Comment = CommentDao.get_comment_by_id(comment_id=comment_id)

    if old_comment is None:
        response = jsonify({
            'self': f'/v2/comments/{comment_id}',
            'updated': False,
            'comment': None,
            'error': 'there is no existing comment with this id'
        })
        response.status_code = 400
        return response

    jwt_claims: dict = get_claims(request)
    jwt_username = jwt_claims.get('sub')

    if old_comment.username == jwt_username:
        current_app.logger.info(
            f'User {jwt_username} is updating a comment with id {old_comment.comment_id}.'
        )
    else:
        current_app.logger.info(
            f'User {jwt_username} is not authorized to update a comment with id {old_comment.comment_id}.'
        )
        response = jsonify({
            'self':
            f'/v2/comments/{comment_id}',
            'updated':
            False,
            'comment':
            None,
            'error':
            f'User {jwt_username} is not authorized to update a comment with id {old_comment.comment_id}.'
        })
        response.status_code = 400
        return response

    comment_data: dict = request.get_json()
    new_comment = Comment(comment_data)

    if old_comment != new_comment:

        new_comment.modified_date = datetime.now()
        new_comment.modified_app = 'saints-xctf-api'

        is_updated = CommentDao.update_comment(comment=new_comment)

        if is_updated:
            updated_comment: Comment = CommentDao.get_comment_by_id(
                comment_id=new_comment.comment_id)
            updated_comment_dict: dict = CommentData(updated_comment).__dict__

            response = jsonify({
                'self': f'/v2/comments/{comment_id}',
                'updated': True,
                'comment': updated_comment_dict
            })
            response.status_code = 200
            return response
        else:
            response = jsonify({
                'self': f'/v2/comments/{comment_id}',
                'updated': False,
                'comment': None,
                'error': 'the comment failed to update'
            })
            response.status_code = 500
            return response
    else:
        response = jsonify({
            'self':
            f'/v2/comments/{comment_id}',
            'updated':
            False,
            'comment':
            None,
            'error':
            'the comment submitted is equal to the existing comment with the same id'
        })
        response.status_code = 400
        return response
Exemplo n.º 11
0
def comment_post():
    """
    Create a new comment.
    :return: A response object for the POST API request.
    """
    comment_data: dict = request.get_json()

    if comment_data is None:
        response = jsonify({
            'self': f'/v2/comments',
            'added': False,
            'comment': None,
            'error': "the request body isn't populated"
        })
        response.status_code = 400
        return response

    comment_to_add = Comment(comment_data)

    jwt_claims: dict = get_claims(request)
    jwt_username = jwt_claims.get('sub')

    if comment_to_add.username == jwt_username:
        # You are so loved.
        current_app.logger.info(
            f'User {jwt_username} is creating a comment on log {comment_to_add.log_id}.'
        )
    else:
        current_app.logger.info(
            f'User {jwt_username} is not authorized to create a comment for user {comment_to_add.username}.'
        )
        response = jsonify({
            'self':
            f'/v2/comments',
            'added':
            False,
            'comment':
            None,
            'error':
            f'User {jwt_username} is not authorized to create a comment for user {comment_to_add.username}.'
        })
        response.status_code = 400
        return response

    if None in [
            comment_to_add.username, comment_to_add.first, comment_to_add.last,
            comment_to_add.log_id
    ]:
        response = jsonify({
            'self':
            f'/v2/comments',
            'added':
            False,
            'comment':
            None,
            'error':
            "'username', 'first', 'last', and 'log_id' are required fields"
        })
        response.status_code = 400
        return response

    comment_to_add.time = datetime.now()
    comment_to_add.created_date = datetime.now()
    comment_to_add.created_app = 'saints-xctf-api'
    comment_to_add.created_user = None
    comment_to_add.modified_date = None
    comment_to_add.modified_app = None
    comment_to_add.modified_user = None
    comment_to_add.deleted_date = None
    comment_to_add.deleted_app = None
    comment_to_add.deleted_user = None
    comment_to_add.deleted = False

    comment_added_successfully: bool = CommentDao.add_comment(
        new_comment=comment_to_add)

    if comment_added_successfully:
        comment_added = CommentDao.get_comment_by_id(comment_to_add.comment_id)
        comment_added_dict: dict = CommentData(comment_added).__dict__

        response = jsonify({
            'self': '/v2/comments',
            'added': True,
            'comment': comment_added_dict
        })
        response.status_code = 200
        return response
    else:
        response = jsonify({
            'self': '/v2/comments',
            'added': False,
            'comment': None,
            'error': 'failed to create a new comment'
        })
        response.status_code = 500
        return response
Exemplo n.º 12
0
    def post(self, id):
        reply_author = self.get_request("reply_author","")
        reply_email = self.get_request("reply_email","")
        reply_url = self.get_request("reply_url","")
        reply = self.get_request("reply_content","")
        reply_content = pyUtility.reply_purify(reply)
        crsf = self.get_request("_xsrf","")
        ip =self.request.remote_ip
        user_crsf = self.get_cookie("_xsrf","unknown")
        self.clear_cookie("_xsrf")
        if crsf != user_crsf or user_crsf =="unknown":
            self.redirect(self.get_webroot_url()+"topic/show/"+id+"/?error=1")
            return

        if id==0 or reply_author=="" or reply_email=="":
            self.redirect(self.get_webroot_url()+"topic/show/"+id+"/?error=1")
            return
        if not pyUtility.isEmail(reply_email):
            self.redirect(self.get_webroot_url()+"topic/show/"+id+"/?error=1")
            return
        if reply_url !="" and not pyUtility.isURL(reply_url):
            self.redirect(self.get_webroot_url()+"topic/show/"+id+"/?error=1")
            return

        # totalComments = Comment().getCountByPostID(id)
        r=Post().getPostShortInfo(id)
        if not r:
            self.redirect(self.get_webroot_url()+"topic/show/"+id+"/?error=2")
            return
        if r.comment_status == 'close':
            self.redirect(self.get_webroot_url()+"topic/show/"+id+"/?error=3")
            return


        if 'User-Agent' in self.request.headers:
            agent = self.request.headers['User-Agent']
        else:
            agent ="unknown"
        comment = Comment()
        comment.post_id = id
        comment.IP = ip
        comment.author = reply_author
        comment.content = reply_content
        comment.email = reply_email
        comment.agent = agent
        comment.url = reply_url
        comment.user_id = self.userID # current Logiin ID, guest id 0
        comment.save()
        self.redirect(self.get_webroot_url()+"topic/show/"+id)
Exemplo n.º 13
0
class CommentProp(QDialog, Ui_CommentPropDialog):
    """
    The Comment dialog allows the user to add a comment to the Model Tree, which
    is saved in the MMP file.
    """
    def __init__(self, win):
        QDialog.__init__(self, win) # win is parent.
        self.setupUi(self)
        self.win = win
        self.comment = None
        self.action = None
            # REVIEW, re self.action:
            # - if used only in messages (true in this file, but not yet
            #   analyzed re external files), should change initial value to "".
            # - if not used in external files, should make private.
            # [bruce 080717 comment]

    def setup(self, comment = None):
        """
        Show Comment dialog with current Comment text, for editing
        properties of an existing Comment node or creating a new one.

        @param comment: the comment node to edit, or None to create a new one.
        """
        self.comment = comment

        if self.comment:
            self.comment_textedit.setPlainText(self.comment.get_text())
                # Load comment text.
            qt4todo("self.comment_textedit.moveCursor(QTextEdit.MoveEnd, False)")
                # Sets cursor position to the end of the textedit document.

        QDialog.exec_(self)

    ###### Private methods ###############################

    def _create_comment(self):
        comment_text = self.comment_textedit.toPlainText()
        if not self.comment:
            self.comment = Comment(self.win.assy, None, comment_text)
            self.win.assy.addnode(self.comment)
            self.action = 'added'
        else:
            self.comment.set_text(comment_text)
            self.action = 'updated'

    def _remove_comment(self):
        if self.comment:
            self.comment.kill()
            self.win.mt.mt_update()
            self.comment = None

    def insert_date_time_stamp(self):
        """
        Insert a date/time stamp in the comment at the current position.

        @note: slot method for self.date_time_btn, SIGNAL("clicked()").
        """
        timestr = "%s " % time.strftime("%m/%d/%Y %I:%M %p")
        self.comment_textedit.insertPlainText(timestr)

    def _done_history_msg(self):
        env.history.message(cmd + quote_html("%s %s." % (self.comment.name, self.action)))
                #bruce Qt4 070502 precaution: use quote_html

    #################
    # Cancel Button
    #################
    def reject(self):
        QDialog.reject(self)
        self.comment = None
        self.comment_textedit.setPlainText("") # Clear text.

    #################
    # OK Button
    #################
    def accept(self):
        """
        Slot for the OK button
        """
        try:
            self._create_comment()
            self._done_history_msg()
            self.comment = None
        except Exception, e:
            print_compact_traceback("Bug: exception in CommentProp.accept: ") #bruce Qt4 070502
            env.history.message(cmd + redmsg("Bug: " + quote_html(" - ".join(map(str, e.args)))))
                #bruce Qt4 070502 bugfixes: use quote_html, say it's a bug (could say "internal error" if desired)
            self._remove_comment()
        self.win.mt.mt_update()
        QDialog.accept(self)
        self.comment_textedit.setPlainText("") # Clear text.
Exemplo n.º 14
0
class CommentProp(QDialog, Ui_CommentPropDialog):
    '''The Comment dialog allows the user to add a comment to the Model Tree, which
    is saved in the MMP file.
    '''
    def __init__(self, win):
        QDialog.__init__(self, win)  # win is parent.
        self.setupUi(self)
        self.win = win
        self.comment = None
        self.action = None

    def setup(self, comment=None):
        '''Show Comment dialog with currect comment text. 
        <comment> - the comment node object.
        '''
        self.comment = comment

        if self.comment:
            self.comment_textedit.setPlainText(self.comment.get_text())
            # Load comment text.
            qt4todo(
                'self.comment_textedit.moveCursor(QTextEdit.MoveEnd, False)')
            # Sets cursor position to the end of the textedit document.

        QDialog.exec_(self)

    ###### Private methods ###############################

    def create_comment(self):
        '''Create comment'''
        comment_text = self.comment_textedit.toPlainText()
        if not self.comment:
            self.comment = Comment(self.win.assy, None, comment_text)
            self.win.assy.addnode(self.comment)
            self.action = 'added'
        else:
            self.comment.set_text(comment_text)
            self.action = 'updated'

    def remove_comment(self):
        '''Removes comment'''
        if self.comment:
            self.comment.kill()
            self.win.mt.mt_update()
            self.comment = None

    def insert_date_time_stamp(self):
        ''' Inserts a date/time stamp in the comment at the current position.
        '''
        timestr = "%s " % time.strftime("%m/%d/%Y %I:%M %p")
        self.comment_textedit.insertPlainText(timestr)

    def done_history_msg(self):
        env.history.message(cmd + quote_html("%s %s." %
                                             (self.comment.name, self.action)))
        #bruce Qt4 070502 precaution: use quote_html

    #################
    # Cancel Button
    #################
    def reject(self):
        QDialog.reject(self)
        self.comment = None
        self.comment_textedit.setPlainText('')  # Clear text.

    #################
    # OK Button
    #################
    def accept(self):
        'Slot for the OK button'
        try:
            self.create_comment()
            self.done_history_msg()
            self.comment = None
        except Exception, e:
            print_compact_traceback(
                "Bug: exception in CommentProp.accept: ")  #bruce Qt4 070502
            env.history.message(
                cmd +
                redmsg("Bug: " + quote_html(" - ".join(map(str, e.args)))))
            #bruce Qt4 070502 bugfixes: use quote_html, say it's a bug (could say "internal error" if desired)
            self.remove_comment()
        self.win.mt.mt_update()
        QDialog.accept(self)
        self.comment_textedit.setPlainText('')  # Clear text.
Exemplo n.º 15
0
    def nextToken(self):
        if(self.array_pointer <= len(self.content)):
            while(True):
                currentChar = self.getNextChar()
                if(currentChar is not None):
                    if self.current_state==0:
                        self.current_token = None
                        if(Token.isChar(currentChar)):
                            self.current_state = 1
                            self.current_token = Identifier(currentChar)
                        elif(Token.isNumber(currentChar)):
                            self.current_state = 2
                            self.current_token = Digit(currentChar)
                        elif(Token.isArithmeticOperator(currentChar)):
                            nextChar = self.content[self.array_pointer]
                            if(Token.isCommentDelimiter(currentChar, nextChar)):
                                self.current_state = 7
                                self.current_token = Comment(currentChar+nextChar)
                            else:
                                self.current_state = 3
                                self.current_token = Arithmetic(currentChar)
                        elif(Token.isRelationalOperator(currentChar)):
                            self.current_state = 4
                            self.current_token = Relational(currentChar)
                        elif(Token.isLogicOperator(currentChar)):
                            self.current_state = 5
                            self.current_token = Logic(currentChar)
                        elif(Token.isDelimiter(currentChar)):
                            self.current_state = 6
                            self.current_token = Delimiter(currentChar)
                        elif(Token.isStringDelimeter(currentChar)):
                            self.current_state = 8
                            self.current_token = String(currentChar)
                        elif(currentChar == '\n'):
                            self.current_line+=1
                        else:
                            if(not Token.isSpace(currentChar)):
                                self.current_state = 1
                                self.current_token = Identifier(currentChar)
                                self.current_token.error = True
                    elif(self.current_state ==1):
                        if(self.current_token.isValid(currentChar) and not Token.isSpace(currentChar)):
                            self.current_token.setValue(currentChar)
                            self.current_state = 1
                        else:
                            if(not self.current_token.validNeighbors(currentChar) and not Token.isSpace(currentChar)):
                                self.current_token.setValue(currentChar)
                                self.current_state = 1
                            else:
                                self.current_state = 0
                                self.back()
                                self.token_list.append(self.current_token.returnValue(self.current_line))
                                return self.current_token.returnValue(self.current_line)
                    elif(self.current_state==2):
                        if(self.current_token.isValid(currentChar) and not Token.isSpace(currentChar)):
                            self.current_token.setValue(currentChar)
                            self.current_state = 2
                        else:
                            if(not self.current_token.validNeighbors(currentChar) and not Token.isSpace(currentChar)):
                                self.current_token.setValue(currentChar)
                                self.current_state = 2
                            else:
                                self.current_state = 0
                                self.back()
                                self.token_list.append(self.current_token.returnValue(self.current_line))
                                return self.current_token.returnValue(self.current_line)
                    elif self.current_state ==3:
                        if(self.current_token.isValid(currentChar) and not Token.isSpace(currentChar)):
                            self.current_token.setValue(currentChar)
                            self.current_state = 3
                        else:
                            if(not self.current_token.validNeighbors(currentChar) and not Token.isSpace(currentChar)):
                                self.current_token.setValue(currentChar)
                                self.current_state = 3
                            elif Token.isSpace(currentChar):
                                self.current_state = 0
                                self.back()
                                self.token_list.append(self.current_token.returnValue(self.current_line))
                                return self.current_token.returnValue(self.current_line)
                            else:
                                self.current_state = 0
                                self.back()
                                self.token_list.append(self.current_token.returnValue(self.current_line))
                                return self.current_token.returnValue(self.current_line)
                    elif self.current_state ==4:
                        if(self.current_token.isValid(currentChar) and not Token.isSpace(currentChar)):
                            self.current_token.setValue(currentChar)
                            self.current_state = 3
                        else:
                            if(not self.current_token.validNeighbors(currentChar) and not Token.isSpace(currentChar)):
                                self.current_token.setValue(currentChar)
                                self.current_state = 3
                            elif Token.isSpace(currentChar):
                                self.current_state = 0
                                self.back()
                                self.token_list.append(self.current_token.returnValue(self.current_line))
                                return self.current_token.returnValue(self.current_line)
                            else:
                                self.current_state = 0
                                self.back()
                                self.token_list.append(self.current_token.returnValue(self.current_line))
                                return self.current_token.returnValue(self.current_line)
                    elif self.current_state==5:
                        if(self.current_token.isValid(currentChar) and not Token.isSpace(currentChar)):
                            self.current_token.setValue(currentChar)
                            self.current_state = 5
                        else:
                            if(not self.current_token.validNeighbors(currentChar) and not Token.isSpace(currentChar)):
                                self.current_token.setValue(currentChar)
                                self.current_state = 5
                            elif Token.isSpace(currentChar):
                                self.current_state = 0
                                self.back()
                                self.token_list.append(self.current_token.returnValue(self.current_line))
                                return self.current_token.returnValue(self.current_line)
                            else:
                                self.current_state = 0
                                self.back()
                                self.token_list.append(self.current_token.returnValue(self.current_line))
                                return self.current_token.returnValue(self.current_line)
                    elif self.current_state==6:
                        if(self.current_token.isValid(currentChar) and not Token.isSpace(currentChar)):
                            self.current_token.setValue(currentChar)
                            self.current_state = 6
                        else:
                            if(not self.current_token.validNeighbors(currentChar) and not Token.isSpace(currentChar)):
                                self.current_token.setValue(currentChar)
                                self.current_state = 6
                            elif Token.isSpace(currentChar):
                                self.current_state = 0
                                self.back()
                                self.token_list.append(self.current_token.returnValue(self.current_line))
                                return self.current_token.returnValue(self.current_line)
                            else:
                                self.current_state = 0
                                self.back()
                                self.token_list.append(self.current_token.returnValue(self.current_line))
                                return self.current_token.returnValue(self.current_line)
                    elif self.current_state==7:
                        if(self.current_token.isInlineComment()):
                            if(self.current_token.isEndInlineComment(currentChar)):
                                self.current_state = 0
                                self.back()

                        elif(self.current_token.isBlockComment()):
                            if(self.current_token.isBreakLine(currentChar)): self.current_line+=1
                            elif(self.array_pointer < len(self.content)):
                                nextChar = self.content[self.array_pointer]
                                if(self.current_token.isEndBlockComment(currentChar+nextChar)):      
                                    self.array_pointer+=1
                                    self.current_state = 0
                        
                    elif self.current_state==8:
                        self.current_token.setValue(currentChar)
                        if(self.current_token.isBreakLine(currentChar)):
                            self.back()
                            self.current_state = 0
                            self.token_list.append(self.current_token.returnValue(self.current_line))
                            return self.current_token.returnValue(self.current_line)
                        elif(self.current_token.isValid(currentChar)): pass
                        elif(Token.isStringDelimeter(currentChar)):
                            prevChar = self.content[self.array_pointer-2]
                            if(not self.current_token.isEscapedDelimeter(prevChar+currentChar)):
                                self.current_token.setError()
                                self.current_state = 0
                                self.token_list.append(self.current_token.returnValue(self.current_line))
                                return self.current_token.returnValue(self.current_line)
                        elif(not Token.isSymbol(currentChar)):
                            self.current_token.unknown_symbol = True
            
                else:
                    if(self.current_token and self.current_token.value!="//"):
                        token = self.current_token.returnValue(self.current_line)
                        self.current_token = None
                        self.token_list.append(token)
                        return token
                    return
        else:
            return None
Exemplo n.º 16
0
class CommentProp(QDialog, Ui_CommentPropDialog):
    '''The Comment dialog allows the user to add a comment to the Model Tree, which
    is saved in the MMP file.
    '''
    def __init__(self, win):
        QDialog.__init__(self, win) # win is parent.
        self.setupUi(self)
        self.win = win
        self.comment = None
        self.action = None
    
    def setup(self, comment=None):
        '''Show Comment dialog with currect comment text. 
        <comment> - the comment node object.
        '''
        self.comment = comment
        
        if self.comment:
            self.comment_textedit.setPlainText(self.comment.get_text())
                # Load comment text.
            qt4todo('self.comment_textedit.moveCursor(QTextEdit.MoveEnd, False)')
                # Sets cursor position to the end of the textedit document.
        
        QDialog.exec_(self)

    ###### Private methods ###############################
    
    def create_comment(self):
        '''Create comment'''
        comment_text = self.comment_textedit.toPlainText()
        if not self.comment:
            self.comment = Comment(self.win.assy, None, comment_text)
            self.win.assy.addnode(self.comment)
            self.action = 'added'
        else: 
            self.comment.set_text(comment_text)
            self.action = 'updated'
            
    def remove_comment(self):
        '''Removes comment'''
        if self.comment:
            self.comment.kill()
            self.win.mt.mt_update()
            self.comment = None
            
    def insert_date_time_stamp(self):
        ''' Inserts a date/time stamp in the comment at the current position.
        '''
        timestr = "%s " % time.strftime("%m/%d/%Y %I:%M %p")
        self.comment_textedit.insertPlainText(timestr)
        
    def done_history_msg(self):
        env.history.message(cmd + quote_html("%s %s." % (self.comment.name, self.action)))
                #bruce Qt4 070502 precaution: use quote_html
    
    #################
    # Cancel Button
    #################
    def reject(self):
        QDialog.reject(self)
        self.comment = None
        self.comment_textedit.setPlainText('') # Clear text.

    #################
    # OK Button
    #################
    def accept(self):
        'Slot for the OK button'
        try:
            self.create_comment()
            self.done_history_msg()
            self.comment = None
        except Exception, e:
            print_compact_traceback("Bug: exception in CommentProp.accept: ") #bruce Qt4 070502
            env.history.message(cmd + redmsg("Bug: " + quote_html(" - ".join(map(str, e.args)))))
                #bruce Qt4 070502 bugfixes: use quote_html, say it's a bug (could say "internal error" if desired)
            self.remove_comment()
        self.win.mt.mt_update()
        QDialog.accept(self)
        self.comment_textedit.setPlainText('') # Clear text.