Example #1
0
def restore_note(orm, user, note_id, historic, d_time=None):
    LOG.info("Restoring note %d", note_id)

    d_time = historic and d_time or None
    note, note_v, d_time = get_deleted_entity(
        orm, Note, Note_v, "note_id", note_id, "note_v_id", d_time)
    d_time = historic and d_time or None

    if note:
        LOG.warning("Note %d already exists.", note_id)
        return note

    if not note_v:
        LOG.error(
            "Cannot restore note %d because no recently "
            "deleted versions exist.",
            note_id)
        return None

    LOG.info("deleted time: %s", d_time)

    note = Note(
        note_v.text, note_v.source,
        user, note_v.public)
    note.note_id = note_v.note_id
    orm.add(note)

    return note
Example #2
0
    def post(self):
        user_id, user = self.get_user()
        if not user:
            self.redirect('/')
            return

        title = self.request.get('note-title')
        text = self.request.get('note-text')
        dt = datetime.datetime.now()
        logging.info('%s\n%s\n%s', title, text, dt)

        if not title or not text:
            msg = (
                'You must enter a title and some text to create a new note.'
            )
            data = {
                'page_title': 'Blank Note',
                'user': user,
                'error_msg': msg
            }
            self.render('error.html', **data)
            return

        new_note = Note(
            user=user.key,
            submit_date=dt,
            title=title,
            text=text,
        )
        new_note.put()

        self.redirect('/notes')
Example #3
0
 def addDroppedNote(self, path):
     note = Note();
     note.modificationDate =  note.creationDate = datetime.date.today()
     note.basket =  RuntimeSettings.currentBasket
     note.text = path
     note.save()
     self.reload()
Example #4
0
 def deserialize_notes(self, string):
     board_export = self.string_to_array(string)
     notes_export = board_export['notes']
     notes = []
     for note_export in notes_export:
         note = Note()
         note.from_export(note_export)
         notes.append(note)
     return notes
Example #5
0
def add_note():
    if not request.is_json:
        return BadRequest('Missing JSON request')
    user_email = request.json.get('email')
    title = request.json.get('title')
    note_text = request.json.get('text')

    user = User.objects(email=user_email).first()
    if user is None:
        raise BadRequest("Not Found")
    note = Note(title=title, text=note_text, user=user.id)
    note.save()
    return jsonify(note=note.serialize)
Example #6
0
    def get(self):

        # req_json = json.loads(self.request.body)
        # user_email = req_json[IDENTIFIER_USER_EMAIL]
        user_email = self.request.get(IDENTIFIER_USER_EMAIL)
        # apt_name = req_json[IDENTIFIER_APT_NAME]
        apt_name = self.request.get(IDENTIFIER_APT_NAME)
        # description = req_json[IDENTIFIER_DESCRIPTION_NAME]
        description = self.request.get(IDENTIFIER_DESCRIPTION_NAME)

        apt_lst = Apartment.query(Apartment.apt_name == apt_name).fetch()

        cur_apt = None
        for apt in apt_lst:
            if user_email in apt.user_email_lst:
                cur_apt = apt

        if cur_apt == None:
            response = {}
            response[
                'error'] = 'the apt: ' + apt_name + ' is not available for user: '******'error'] = 'we dont have notebook for the apt: ' + apt_name
            return self.respond(**response)

        cur_note_book = cur_note_book_lst[0]

        note_id = uuid.uuid4()
        note = Note(id=str(note_id),
                    description=description,
                    author_email=user_email,
                    notebook_id=cur_note_book_id)

        cur_note_book.note_id_lst.append(str(note_id))

        cur_note_book.put()
        note.put()

        self.respond(note_id=str(note_id),
                     notebook_id=cur_note_book_id,
                     status="Success")
Example #7
0
def test_update():
    conn = connect()
    store = NoteStore(conn)

    note = Note(None, 'title', 'content')
    store.create(note)

    note.title = "Better Title"
    note.content = "Better Content"
    store.update(note)

    from_db = store.fetch(note.note_id)
    assert from_db.title == "Better Title"
    assert from_db.content == "Better Content"
Example #8
0
def get_notes(sort_by='priority', fmt=None):
    notes = []

    indices = rds.lrange('notes', 0, -1)
    app.logger.debug("found %d note IDs in index" % len(indices))

    for index in indices:
        notes.append(Note(**rds.hgetall(index)))

    notes = Note.sort(notes, sort_by=sort_by)

    if fmt == 'json':
        notes = { 'notes': Note.dict_repr(notes) }

    return notes
Example #9
0
 def createNotes(self):
     fileList = {"NotesMD": ("README.md", "data/credits.md", "data/about.md")
                 }
     for basket, notes in fileList.iteritems():
         dbBasket = Basket()
         dbBasket.basketName = basket
         dbBasket.creationDate = dbBasket.modificationDate = datetime.date.today()
         dbBasket.save()
         
         for note in notes:
             dbNote = Note()
             dbNote.basket = dbBasket
             dbNote.creationDate = dbNote.modificationDate = datetime.date.today()
             dbNote.text = open(note).read()
             dbNote.save()
Example #10
0
    def get(self):
        apt_name = self.request.get(IDENTIFIER_APT_NAME)
        user_email = self.request.get(IDENTIFIER_USER_EMAIL)
        apt_lst = Apartment.query(Apartment.apt_name == apt_name).fetch()

        # print "called: " + user_email + ", " + apt_name
        cur_apt = None
        for apt in apt_lst:
            if user_email in apt.user_email_lst:
                cur_apt = apt

        cur_notebook_lst = NoteBook.query( NoteBook.notebook_id == cur_apt.notebook_id).fetch()
        if len(cur_notebook_lst) == 0:
            response = {}
            response['error'] = 'we dont have notebook for the apt: ' + apt_name
            return self.respond(**response)


        cur_notebook = cur_notebook_lst[0]


        retList = []
        for noteid in cur_notebook.note_id_lst:
            note_lst = Note.query(Note.id == noteid).fetch()
            cur_note = note_lst[0]
            ret_note = {}
            ret_note['author'] = cur_note.author_email
            ret_note['description'] = cur_note.description
            date = str(cur_note.date)
            ret_note['last_edit_date'] = date
            retList.append(ret_note)

        self.respond(AllNoteLst = retList, status="Success")
Example #11
0
    def get(self):

        # req_json = json.loads(self.request.body)
        # user_email = req_json[IDENTIFIER_USER_EMAIL]
        user_email = self.request.get(IDENTIFIER_USER_EMAIL)
        # note_id = req_json[IDENTIFIER_NOTE_ID]
        note_id = self.request.get(IDENTIFIER_NOTE_ID)
        # new_description = req_json[IDENTIFIER_NEW_DESCRIPTION_NAME]
        new_description = self.request.get(IDENTIFIER_NEW_DESCRIPTION_NAME)

        cur_note_lst = Note.query(Note.id == note_id).fetch()

        if len(cur_note_lst) == 0:
            response = {}
            response['error'] = 'the note with id : ' + note_id + ' is valid'
            return self.respond(**response)

        cur_note = cur_note_lst[0]

        if user_email != cur_note.author_email:
            response = {}
            response['error'] = 'you cannot edit this note'
            return self.respond(**response)

        cur_note.description = new_description
        cur_note.put()

        self.respond(status="Success")
Example #12
0
def create_note_reply(user_id, doc_id, created_at, body, parent_id, fname,
                      lname):
    """Reply to a note."""
    # figure out x and y pos

    # tz = pytz.timezone('America/Los_Angeles')
    # created_at = datetime.now(tz)

    color_check = check_prev_note_color(user_id, doc_id)
    if color_check:
        color = color_check
    else:
        color = '#C2D6C4'

    note = Note(
        user_id=user_id,
        doc_id=doc_id,
        parent_id=parent_id,
        created_at=created_at,
        body=body,
        # x_pos = x_pos,
        # y_pos = y_pos,
        fname=fname,
        lname=lname,
        color=color)

    db.session.add(note)
    db.session.commit()

    return {'note': note, 'color': color}
Example #13
0
        def get(self):
            # req_json = json.loads(self.request.body)
            # note_id = req_json[IDENTIFIER_NOTE_ID]
            note_id = self.request.get(IDENTIFIER_NOTE_ID)
            # user_email = req_json[IDENTIFIER_USER_EMAIL]
            user_email = self.request.get(IDENTIFIER_USER_EMAIL)
            # description = req_json[IDENTIFIER_DESCRIPTION_NAME]
            description = self.request.get(IDENTIFIER_DESCRIPTION_NAME)

            reply_id = uuid.uuid4()
            notes = Note.query(Note.id == note_id).fetch()
            note = notes[0]

            user_lst = User.query(User.user_email == user_email).fetch()
            user = user_lst[0]

            new_reply = Reply(author_email = user_email,
                              note_id = str(note_id),
                              reply_id = str(reply_id),
                              description = description,
                              nick_name = user.nick_name
                              )
            new_reply.put()
            note.reply_id_lst.append(str(reply_id))
            note.put()

            self.respond(reply_id = str(reply_id),
                         status="Success")
Example #14
0
 def alert(self, view, frame, message):
     #print message
    
      
     m = re.search("^(\w+):([^_]+)_(\d+)(_(.*))?", message)
     if (m != None):
         action = m.group(1)
         id = m.group(3)
         #print "Action", action, " id", id
         if (action == "EDIT"):
             note = Note.get(Note.id==id)
             self.editNote(note)
         if (action == "ADDTAG"):
             self.addTag(id, m.group(5))
         if (action == "REMOVETAG"):
             self.removeTag(id, m.group(5))
         if (action == "ADDNOTE"):
             self.newNote(None)
             pass
         if (action == "ADDBASKET"):
             self.addBasket(m.group(2))
         if (action == "ADDDROPPEDNOTE"):
             self.addDroppedNote(message[int(m.start(5)):])
         if (action == "SELECTBASKET"):
             self.selectBasket(m.group(5))
         if (action == "DELETENOTE"):
             self.deleteNote(id)
         if (action == "SEARCH_TEXT"):
             self.searchText(m.group(5))
                 
         return True
     else:
         return False
Example #15
0
def create_note(teacher_id, student_id, note_created_at, note_content):
    """Creates a new teacher note record"""

    # Allows querying of student by full name
    # instead of querying by hybrid attribute
    # student_id = db.session.query(Student.student_id)\
    #     .filter(
    #         func.concat(
    #             Student.student_fname,
    #             ' ',
    #             Student.student_lname
    #         ) == note_student_name
    #     ).first()

    # Only allow if student id exists
    # if not student_id:
    #     return None

    note = Note(teacher_id=teacher_id,
                student_id=student_id,
                note_created_at=note_created_at,
                note_content=note_content)

    db.session.add(note)
    db.session.commit()

    return note
Example #16
0
    def get(self):
        # req_json = json.loads(self.request.body)
        # note_id = req_json[IDENTIFIER_NOTE_ID]
        note_id = self.request.get(IDENTIFIER_NOTE_ID)
        # user_email = req_json[IDENTIFIER_USER_EMAIL]
        user_email = self.request.get(IDENTIFIER_USER_EMAIL)
        # description = req_json[IDENTIFIER_DESCRIPTION_NAME]
        description = self.request.get(IDENTIFIER_DESCRIPTION_NAME)

        reply_id = uuid.uuid4()
        notes = Note.query(Note.id == note_id).fetch()
        note = notes[0]

        user_lst = User.query(User.user_email == user_email).fetch()
        user = user_lst[0]

        new_reply = Reply(author_email=user_email,
                          note_id=str(note_id),
                          reply_id=str(reply_id),
                          description=description,
                          nick_name=user.nick_name)
        new_reply.put()
        note.reply_id_lst.append(str(reply_id))
        note.put()

        self.respond(reply_id=str(reply_id), status="Success")
Example #17
0
    def get(self):

        # req_json = json.loads(self.request.body)
        # user_email = req_json[IDENTIFIER_USER_EMAIL]
        user_email = self.request.get(IDENTIFIER_USER_EMAIL)
        # note_id = req_json[IDENTIFIER_NOTE_ID]
        note_id = self.request.get(IDENTIFIER_NOTE_ID)
        # new_description = req_json[IDENTIFIER_NEW_DESCRIPTION_NAME]
        new_description = self.request.get(IDENTIFIER_NEW_DESCRIPTION_NAME)

        cur_note_lst = Note.query(Note.id == note_id).fetch()

        if len(cur_note_lst) == 0:
            response = {}
            response['error'] = 'the note with id : ' + note_id + ' is valid'
            return self.respond(**response)

        cur_note = cur_note_lst[0]

        if user_email != cur_note.author_email:
            response = {}
            response['error'] = 'you cannot edit this note'
            return self.respond(**response)

        cur_note.description = new_description
        cur_note.put()

        self.respond(status="Success")
Example #18
0
    def get(self):
        apt_name = self.request.get(IDENTIFIER_APT_NAME)
        user_email = self.request.get(IDENTIFIER_USER_EMAIL)
        apt_lst = Apartment.query(Apartment.apt_name == apt_name).fetch()

        # print "called: " + user_email + ", " + apt_name
        cur_apt = None
        for apt in apt_lst:
            if user_email in apt.user_email_lst:
                cur_apt = apt

        cur_notebook_lst = NoteBook.query(
            NoteBook.notebook_id == cur_apt.notebook_id).fetch()
        if len(cur_notebook_lst) == 0:
            response = {}
            response[
                'error'] = 'we dont have notebook for the apt: ' + apt_name
            return self.respond(**response)

        cur_notebook = cur_notebook_lst[0]

        retList = []
        for noteid in cur_notebook.note_id_lst:
            note_lst = Note.query(Note.id == noteid).fetch()
            cur_note = note_lst[0]
            ret_note = {}
            ret_note['author'] = cur_note.author_email
            ret_note['description'] = cur_note.description
            date = str(cur_note.date)
            ret_note['last_edit_date'] = date
            retList.append(ret_note)

        self.respond(AllNoteLst=retList, status="Success")
Example #19
0
    def post(self, note_id=0):
        '''Updating the comment and redirecting back to the photo page.'''
        user_id, user = self.get_user()
        if not user:
            self.redirect('/')
            return

        note_id = int(note_id)
        note = Note.get_by_id(note_id)

        error, data = self._check(user, note)
        if error:
            self.render('error.html', **data)

        title = self.request.get('note-title')
        text = self.request.get('note-text')
        logging.info('%s\n%s', repr(title), repr(text))

        if not title or not text:
            msg = (
                'You must enter a title and some text to create a new note.'
            )
            data = {
                'page_title': 'Blank Note',
                'user': user,
                'error_msg': msg
            }
            self.render('error.html', **data)
            return

        note.title = title
        note.text = text
        note.put()

        self.redirect('/notes')
Example #20
0
def index():
    if request.method == 'POST':
        form = NoteForm(request.form)

        if form.validate():
            note = Note(unique_word_count=count_unique_word(form.text.data),
                        short_description=form.text.data[:60],
                        text=form.text.data)

            db.session.add(note)
            db.session.commit()
            flash('ะ—ะฐะผะตั‚ะบะฐ โ„–({}) ัƒัะฟะตัˆะฝะพ ะดะพะฑะฐะฒะปะตะฝะฐ'.format(note.id), 'success')

            return redirect(url_for('index'))

        else:
            flash('ะŸะพะถะฐะปัƒะนัั‚ะฐ ะทะฐะฟะพะปะฝะธั‚ะต ั„ะพั€ะผัƒ', 'warning')
            return redirect(url_for('index'))

    if request.method == 'GET':
        form = NoteForm()
        return render_template('index.html',
                               title='Add Note',
                               form=form,
                               active_note_add=True)
Example #21
0
def newNote():
    if request.method == "POST":
        json = request.get_json()
        newNote = Note(json["sourceCode"], json["owner"],
                       json["course_belonged"])
        db.session.add(newNote)
        db.session.commit()
        return jsonify({"status": "OK"})
Example #22
0
    def test_chord(self):
        a = Note(100, 15, 250)
        b = Note(100, 11, 250)
        c = Note(100, 18, 250)
        score = Score([a, b, c])
        for i in [40, 99, 101, 349, 350, 351, 450]:
            self.assertEquals(0, len(score.starts_at(i)))
        self.assertEquals(3, len(score.starts_at(100)))

        for i in [40, 99, 100, 101, 349, 351, 450]:
            self.assertEquals(0, len(score.ends_at(i)))
        self.assertEquals(3, len(score.ends_at(350)))

        for i in [50, 99, 350, 351, 450]:
            self.assertEquals(0, len(score.sounding_at(i)))
        for i in [100, 101, 349]:
            self.assertEquals(3, len(score.sounding_at(i)))
Example #23
0
def store_notes(note_content, match_id, group_id):
    """ Store grouped notes per match """

    note = Note(note_content=note_content,
                match_id=match_id,
                group_id=group_id)

    db.session.add(note)
    db.session.commit()
Example #24
0
 def setUp(self):
     """
     Create a validator and add one note to it.
     Note(delay=100, height=15, duration=100)
     """
     self.the_note = Note(delay=100, height=15, duration=100)
     score = Score([self.the_note])
     self.validator = Validator(score, margin=10)
     self.validator.add_reference_note(self.the_note)
Example #25
0
    def get(self):

        # req_json = json.loads(self.request.body)
        # user_email = req_json[IDENTIFIER_USER_EMAIL]
        user_email = self.request.get(IDENTIFIER_USER_EMAIL)
        # apt_name = req_json[IDENTIFIER_APT_NAME]
        apt_name =  self.request.get(IDENTIFIER_APT_NAME)
        # description = req_json[IDENTIFIER_DESCRIPTION_NAME]
        description = self.request.get(IDENTIFIER_DESCRIPTION_NAME)

        apt_lst = Apartment.query(Apartment.apt_name == apt_name).fetch()

        cur_apt = None
        for apt in apt_lst:
            if user_email in apt.user_email_lst:
                cur_apt = apt

        if cur_apt == None:
            response = {}
            response['error'] = 'the apt: ' + apt_name + ' is not available for user: '******'error'] = 'we dont have notebook for the apt: ' + apt_name
            return self.respond(**response)

        cur_note_book = cur_note_book_lst[0]

        note_id = uuid.uuid4()
        note = Note(id = str(note_id), description = description, author_email = user_email, notebook_id = cur_note_book_id)

        cur_note_book.note_id_lst.append(str(note_id))

        cur_note_book.put()
        note.put()

        self.respond(note_id = str(note_id), notebook_id = cur_note_book_id, status="Success")
Example #26
0
def add_note():
    title = request.json['title']
    description = request.json['description']
    user_id = request.json['user_id']
    
    new_note = Note(title, description, user_id)

    db.session.add(new_note)
    db.session.commit()

    return note_schema.jsonify(new_note)
Example #27
0
 def get(self):
     user_id, user = self.get_user()
     data = {
         #'page_title': 'Monthly Photographs 2013',
         'photos': self.random_images(4),
         'user': user,
         'competitions': self.competitions_in_progress(),
         'comments': self.recent_comments(),
         'results': self.recent_results(),
         'notes': Note.recent_notes(),
     }
     self.render('home.html', **data)
  def _render_template(self, message=None):
    """Render the main page template."""

    # Query the DB for entries:
    notes_query = Note.all()
    notes_query.filter('public =', True)
    notes_query.order('-date')
    notes = notes_query.run()
    template_values = {'notes': notes}

    template = jinja_environment.get_template('templates/index.html')
    self.response.out.write(template.render(template_values))
Example #29
0
    def test_interval(self):
        a = Note(100, 15, 200)
        b = Note(200, 11, 200)
        c = Note(300, 18, 200)
        score = Score([a, b, c])
        for i in [40, 99, 101, 199, 201, 299, 301, 400, 500]:
            self.assertEquals(0, len(score.starts_at(i)))
        for i in [100, 200, 300]:
            self.assertEquals(1, len(score.starts_at(i)))

        for i in [40, 99, 100, 101, 200, 201, 299, 301, 499]:
            self.assertEquals(0, len(score.ends_at(i)))
        for i in [300, 400, 500]:
            self.assertEquals(1, len(score.ends_at(i)))

        for i in [50, 99, 500]:
            self.assertEquals(0, len(score.sounding_at(i)))
        for i in [100, 101, 199, 400, 499]:
            self.assertEquals(1, len(score.sounding_at(i)))
        for i in [200, 201, 299, 300, 301, 399]:
            self.assertEquals(2, len(score.sounding_at(i)))
  def _handle_timeline_notification(self, data):
    """Handle timeline notification."""
    for user_action in data.get('userActions', []):
      if user_action.get('type') == 'LAUNCH':
        item = self.mirror_service.timeline().get(id=data['itemId']).execute()
        text = item.get('text')
        creatorID = data.get('userToken')
        creatorName = StorageByKeyName(Credentials, creatorID, 'displayName').get()
        # If the contributor is approved, make the entry public:
        makePublic = StorageByKeyName(Credentials, creatorID, 'approved').get()

        newNote = Note(text=text, userId=creatorID, creatorName=creatorName, public=makePublic)

        newNote.put()

        logging.info('Reply received: %s' % text)

        break
      else:
        logging.info(
            "I don't know what to do with this notification: %s", user_action)
Example #31
0
def create_note(itinerary_id, user_id, comment, day=None):
    """Create and return a new note."""

    note = Note(itinerary_id=itinerary_id,
                user_id=user_id,
                comment=comment,
                day=day)

    db.session.add(note)
    db.session.commit()

    return note
Example #32
0
 def add_gamer_note(self, note, command_type):
     """
     Add a mingus note to the validator gamer events.
     """
     # Agrega 2 eventos, NOTE_ON y NOTE_OFF
     delay = self.time
     note = Note.from_mingus_note(note, delay)
     if command_type == 'NOTE_ON':
         self.gamer_events.append(Event(Event.NOTE_ON, note.delay, note))
     elif command_type == 'NOTE_OFF':
         self.gamer_events.append(Event(Event.NOTE_OFF, note.delay, note))
     else:
         raise NotImplementedError
Example #33
0
def create_note(job_applied_id, user_id, note_title, note_text, note_category,
                note_date_created):
    """create and return note """

    note = Note(job_applied_id=job_applied_id,
                user_id=user_id,
                note_title=note_title,
                note_text=note_text,
                note_category=note_category,
                note_date_created=note_date_created)
    db.session.add(note)
    db.session.commit()

    return note
Example #34
0
    def post(self):
        """Update database when user added a note."""

        if not current_user.is_active:
            return 'No permission.'

        key1 = request.form.get('key1')
        key2 = request.form.get('key2')
        new_note = Note(key1, key2)

        db.session.add(new_note)
        db.session.commit()
        message = 'Note added succesfully'

        return 'Note Added.'
Example #35
0
    def test_single_note(self):
        a = Note(100, 15, 250)
        score = Score([a])
        for i in [40, 99, 101, 349, 350, 341, 450]:
            self.assertEquals(0, len(score.starts_at(i)))
        self.assertEquals(1, len(score.starts_at(100)))

        for i in [40, 99, 100, 101, 349, 351, 450]:
            self.assertEquals(0, len(score.ends_at(i)))
        self.assertEquals(1, len(score.ends_at(350)))

        for i in [50, 99, 350, 351, 450]:
            self.assertEquals(0, len(score.sounding_at(i)))
        for i in [100, 101, 349]:
            self.assertEquals(1, len(score.sounding_at(i)))
Example #36
0
def update_note(id):
    if not request.is_json:
        raise BadRequest("Missing Json Request")
    title = request.json.get('title')
    text = request.json.get('text')

    note = Note.objects(id=id).first()
    """
    *update_one()* Perform an atomic update on the fields of the first document matched by the query
    *update()* is for actual Document object update
    """
    note.update(set__title=title,
                set__text=text,
                set__updated_at=datetime.utcnow)
    return jsonify({"message": "updated"}, note.serialize), 201
Example #37
0
    def post(self, note_id=0):
        user_id, user = self.get_user()
        if not user:
            self.redirect('/')

        note_id = int(note_id)
        note = Note.get_by_id(note_id)

        error, data = self._check(user, note)
        if error:
            self.render('error.html', **data)
            return

        note.key.delete()

        self.redirect('/notes')
Example #38
0
def create_note(teacher_id, note_student_name, note_created_at, note_content):
    """Creates a new teacher note record"""

    # Allows querying of student by full name โ€“ Hopefull this works!
    student_id = session.query(Student).filter(
        Student.full_name == note_student_name).first()

    note = Note(teacher_id=teacher_id,
                student_id=student_id,
                note_created_at=note_created_at,
                note_content=note_content)

    db.session.add(note)
    db.session.commit()

    return note
  def _render_template(self, message=None):
    """Render the user page template."""

    notes_query = Note.all()
    notes_query.order('-date')
    notes_query.filter('userId =', self.userid)
    notes = notes_query.run()
    template_values = {'notes': notes}

    displayName = StorageByKeyName(Credentials, self.userid, 'displayName').get()
    template_values['displayName'] = displayName

    template_values['approved'] = StorageByKeyName(Credentials, self.userid, 'approved').get()

    template = jinja_environment.get_template('templates/contributor.html')
    self.response.out.write(template.render(template_values))
Example #40
0
def make_new_attraction():
    """Process new attraction and its notes."""

    set_val_attraction_id()
    set_val_note_id()

    attraction_name = request.form.get('attraction_name').strip()
    dest_id = request.form.get('dest_id')
    note_contents = request.form.getlist('note[]')  # list

    #Get wiki description
    wiki_content = get_wiki_description(attraction_name)
    if not wiki_content:
        wiki_content = None

    #Add a new attraction to db
    attraction = Attraction(name=attraction_name,
                            dest_id=dest_id,
                            description=wiki_content)
    db.session.add(attraction)
    db.session.commit()

    #Add notes to db
    if not note_contents:
        note_contents = ['']

    for note_content in note_contents:
        new_note = Note(content=note_content,
                        attraction_id=attraction.attraction_id)
        db.session.add(new_note)
        db.session.commit()

    attraction_note_info = {
        'attraction_id':
        attraction.attraction_id,
        'name':
        attraction.name,
        'notes': [{
            'note_id': note.note_id,
            'content': note.content
        } for note in attraction.notes]
    }

    print "##### Developer msg ##### Attraction added:", attraction

    return jsonify(attraction_note_info)
Example #41
0
def add_note():
	"""User can add short notes to their homepage."""

	user_id = session["user_id"]

	if request.method == "POST":
	
		note = request.form["note"]

		new_note = Note(note=note, user_id=user_id)


		db.session.add(new_note)
		db.session.commit()

		return jsonify({"note_id": new_note.note_id, "note": new_note.note})
	else:
		return redirect(f"/")
Example #42
0
 def addTag(self, noteId, strTag):
     count = Tag.select().where(Tag.tag == strTag).count()
     if (count == 0):
         dbTag = Tag()
         dbTag.creationDate = dbTag.modificationDate = datetime.date.today()
         dbTag.tag = strTag
         dbTag.save()
     else:
         dbTag = Tag.get(Tag.tag == strTag)
         
     note = Note.get(Note.id == noteId)
     noteTag = NoteTag()
     noteTag.note = note
     noteTag.tag = dbTag
     noteTag.creationDate = noteTag.modificationDate = datetime.date.today()
     noteTag.save() 
     
     self.view.execute_script("notesMD.tags = " + RuntimeSettings.getTags())
Example #43
0
    def get(self):

        user_email = self.request.get(IDENTIFIER_USER_EMAIL)
        note_id = self.request.get(IDENTIFIER_NOTE_ID)

        cur_note_lst = Note.query(Note.id == note_id).fetch()

        if len(cur_note_lst) == 0:
            response = {}
            response['error'] = 'The ID is not available: ' + note_id
            return self.respond(**response)

        cur_note = cur_note_lst[0]

        retValue = {}
        retValue['author'] = cur_note.author_email
        retValue['last_edit_date'] = str(cur_note.date)
        retValue['description'] = cur_note.description
        self.respond(Note = retValue, status="Success")
Example #44
0
    def get(self):

        user_email = self.request.get(IDENTIFIER_USER_EMAIL)
        note_id = self.request.get(IDENTIFIER_NOTE_ID)

        cur_note_lst = Note.query(Note.id == note_id).fetch()

        if len(cur_note_lst) == 0:
            response = {}
            response['error'] = 'The ID is not available: ' + note_id
            return self.respond(**response)

        cur_note = cur_note_lst[0]

        retValue = {}
        retValue['author'] = cur_note.author_email
        retValue['last_edit_date'] = str(cur_note.date)
        retValue['description'] = cur_note.description
        self.respond(Note=retValue, status="Success")
Example #45
0
def SSVParse(filename, resolution):
    """
    Parse a SSV (?). Resolution must be integer.
    """
    g = open(filename)
    notes = []
    playing = [None] * 128
    for line in g:
        parts = line.split()
        delay = int(float(parts[0]) * 1000) / resolution * resolution
        height = int(parts[1])
        speed = int(parts[2])
        if speed > 0:
            playing[height] = delay
        else:
            if playing[height] is not None:
                note = Note(playing[height], height, delay - playing[height])
                notes.append(note)
    return Score(notes)
Example #46
0
    def get(self):
        note_id = self.request.get(IDENTIFIER_NOTE_ID)
        notes = Note.query(Note.id == note_id).fetch()
        note = notes[0]

        replys = note.getAllreply()
        reply_lst = []

        sorted_replys = sorted(replys, key=lambda reply: reply.date)

        for reply in sorted_replys:
            cur_reply = {}
            cur_reply['author'] = reply.nick_name
            cur_reply['author_email'] = reply.author_email
            cur_reply['description'] = reply.description
            cur_reply['reply_id'] = str(reply.reply_id)
            cur_reply['date'] = str(reply.date)
            reply_lst.append(cur_reply)

        self.respond(reply_lst=reply_lst, status="Success")
Example #47
0
    def test_shift(self):
        a = Note(100, 15, 250)
        shift = 100
        score = Score([copy(a)])
        score.shift_all_notes(shift)
        for i in [140, 199, 201, 449, 450, 451, 550]:
            self.assertEquals(0, len(score.starts_at(i)))
        self.assertEquals(1, len(score.starts_at(200)))

        for i in [140, 199, 200, 201, 449, 451, 550]:
            self.assertEquals(0, len(score.ends_at(i)))
        self.assertEquals(1, len(score.ends_at(450)))

        for i in [150, 199, 450, 451, 550]:
            self.assertEquals(0, len(score.sounding_at(i)))
        for i in [200, 201, 449]:
            self.assertEquals(1, len(score.sounding_at(i)))

        notes = score.starts_at(200)
        for n in notes:
            self.assertEquals(n.delay, a.delay + shift)
Example #48
0
    def get(self, note_id=0):
        user_id, user = self.get_user()
        if not user:
            self.redirect('/')
            return

        note_id = int(note_id)
        note = Note.get_by_id(note_id)

        error, data = self._check(user, note)
        if error:
            self.render('error.html', **data)
            return

        data = {
            'page_title': 'Delete Note',
            'user': user,
            'note': note,
        }

        self.render('note-delete.html', **data)
Example #49
0
    def get(self):
        note_id = self.request.get(IDENTIFIER_NOTE_ID)
        notes = Note.query(Note.id == note_id).fetch()
        note = notes[0]

        replys = note.getAllreply()
        reply_lst = []

        sorted_replys = sorted(replys, key=lambda reply:reply.date)

        for reply in sorted_replys:
            cur_reply = {}
            cur_reply['author'] = reply.nick_name
            cur_reply['author_email'] = reply.author_email
            cur_reply['description'] = reply.description
            cur_reply['reply_id'] = str(reply.reply_id)
            cur_reply['date'] = str(reply.date)
            reply_lst.append(cur_reply)

        self.respond(reply_lst = reply_lst,
                         status="Success")
Example #50
0
    def get(self):
        user_id, user = self.get_user()

        start = self.request.get('start')
        logging.info('start: %s', start)

        if not start:
            start = 0
        else:
            start = int(start)
            if start > 1000000:
                start = 0

        if start == 0:
            before = 0
            after = 10
        else:
            before = start - 10
            after = start + 10

        notes = list(Note.recent_notes(10, start))
        more_old = '' if len(notes) == 10 else 'disabled'
        more_new = '' if start > 0 else 'disabled'

        data = {
            'page_title': 'Notes',
            'user': user,
            'user_id': user_id,
            'notes': notes,
            'before': before,
            'after': after,
            'more_old': more_old,
            'more_new': more_new,
        }

        self.render('notes.html', **data)
Example #51
0
 def deleteNote(self, id):
     note = Note.get(Note.id == id)
     note.delete_instance()
     for noteTag in NoteTag.select().where(NoteTag.note == id):
         noteTag.delete_instance()
     self.reload()
Example #52
0
def get_note(id):
    note = Note.objects(id=id).first()
    if not note:
        raise NotFound("Note not found")
    return jsonify(note.serialize)
Example #53
0
    def post(self):
        if not (self.auth and self.auth.search_permission
                and self.auth.domain_write_permission == '*'):
            self.info(
                403,
                message=
                    '"key" URL parameter is either missing, invalid or '
                    'lacks required permissions. The key\'s repo must be "*", '
                    'search_permission must be True, and it must have write '
                    'permission with domain name "*".',
                style='plain')
            return

        body = self.request.body_file.read()
        doc = xml.dom.minidom.parseString(body)
        message_text = self.get_element_text(doc, 'message_text')
        receiver_phone_number = self.get_element_text(
            doc, 'receiver_phone_number')

        if message_text is None:
            self.info(
                400,
                message='message_text element is required.',
                style='plain')
            return
        if receiver_phone_number is None:
            self.info(
                400,
                message='receiver_phone_number element is required.',
                style='plain')
            return

        repo = (
            self.config.sms_number_to_repo and
            self.config.sms_number_to_repo.get(receiver_phone_number))
        if not repo:
            self.info(
                400,
                message=
                    'The given receiver_phone_number is not found in '
                    'sms_number_to_repo config.',
                style='plain')
            return

        query_lang = None
        query_action = None
        match = None
        for lang, action, regex in HandleSMS.QUERY_PATTERNS:
            match = re.search(regex, message_text.strip(), re.I)
            if match:
                query_lang = lang
                query_action = action
                break

        if query_lang:
            # Use the language for the following calls of _().
            django_setup.activate(query_lang)

        responses = []

        if query_action == 'search':
            query_string = match.group(1).strip()
            query = TextQuery(query_string)
            persons = indexing.search(repo, query, HandleSMS.MAX_RESULTS)
            if persons:
                for person in persons:
                    responses.append(self.render_person(person))
            else:
                responses.append(
                    _('No results found for: %(query)s')
                        % {'query': query_string})
            responses.append(
                _('More at: %(url)s')
                    % {'url': 'google.org/personfinder/%s?ui=light' % repo})
            responses.append(
                _('All data entered in Person Finder is available to the '
                  'public and usable by anyone. Google does not review or '
                  'verify the accuracy of this data '
                  'google.org/personfinder/global/tos'))

        elif self.config.enable_sms_record_input and query_action == 'add':
            name_string = match.group(1).strip()
            person = Person.create_original(
                repo,
                entry_date=utils.get_utcnow(),
                full_name=name_string,
                family_name='',
                given_name='')
            person.update_index(['old', 'new'])
            note = Note.create_original(
                repo,
                entry_date=utils.get_utcnow(),
                source_date=utils.get_utcnow(),
                person_record_id=person.record_id,
                author_name=name_string,
                author_made_contact=True,
                status='is_note_author',
                text=message_text)
            db.put(note)
            model.UserActionLog.put_new('add', note, copy_properties=False)
            person.update_from_note(note)
            db.put(person)
            model.UserActionLog.put_new('add', person, copy_properties=False)
            responses.append(_('Added a record for: %(person_name)s')
                % {'person_name': name_string})

        else:
            usage_str = 'Usage: "Search John"'
            if self.config.enable_sms_record_input:
              usage_str += ' OR "I am John"'
            responses.append(usage_str)

        # Convert the response into ASCII because the SMS pipeline doesn't
        # support UTF-8.
        # e.g., It removes diacritics such as "รบ" -> "u".
        # This seems acceptable for Spanish, but may not be for other
        # languages.
        ascii_response = unidecode(u' ## '.join(responses))

        self.response.headers['Content-Type'] = 'application/xml; charset=utf-8'
        self.write(
            '<?xml version="1.0" encoding="utf-8"?>\n'
            '<response>\n'
            '  <message_text>%s</message_text>\n'
            '</response>\n'
            % django.utils.html.escape(ascii_response))
Example #54
0
 def newNote(self, webview):
     note = Note();
     note.creationDate = datetime.date.today()
     self.editNote(note)
Example #55
0
    def parseNote(self):
        note = Note()
        flags = self.readByte()
        
        if flags & 32:
            note.type = self.readByte()
            if note.type == 2:
                note.tied = True
            elif note.type == 3:
                note.dead = True

        if flags & 1:
            note.duration = self.readByte()
            note.nuplet = self.readByte()

        if flags & 16:
            note.dynamic = self.readByte()
        else:
            note.dynamic = 6

        if flags & 32:
            note.fret = self.readByte()
        
        if flags & 128:
            note.lfinger = self.readByte()
            note.rfinger = self.readByte()

        if flags & 8:
            self.parseNoteEffect(note)

        return note
Example #56
0
    def get(self):
        logging.info('stats calculator...starting')
        # create a UserStat object for all Users in the db
        users = list(User.query().fetch())
        data = dict(
            (user.key.id(), UserStats(user=user.key))
            for user in users
        )

        for user in users:
            user_stat = data[user.key.id()]
            user_stat.logins = user.login_count
            user_stat.logouts = user.logout_count
            user_stat.bio = 1 if user.bio else 0

        for photo in Photo.query().fetch():
            user_id = photo.user.id()
            user_stat = data[user_id]
            if photo.competition is None:
                user_stat.extra_photos += 1
            else:
                if photo.competition.get().status != COMPLETED:
                    # not interested in competition photos for incomplete
                    # competitions
                    continue
                user_stat.comp_photos += 1
                user_stat.total_points += photo.total_score
                if photo.position == 1:
                    user_stat.first_place += 1
                    user_stat.medals += 1
                elif photo.position == 2:
                    user_stat.second_place += 1
                    user_stat.medals += 1
                elif photo.position == 3:
                    user_stat.third_place += 1
                    user_stat.medals += 1

        completed_comp_count = Competition.count()
        for user_stat in data.values():
            if user_stat.comp_photos == completed_comp_count:
                user_stat.all_comps = 1

        for comment in Comment.query().fetch():
            # give
            data[comment.user.id()].comments_give += 1
            # receive
            receiver = comment.photo.get().user.id()
            data[receiver].comments_receive += 1

        for score in Scores.query().fetch():
            receiver = score.photo.get().user.id()
            if score.score == 10:
                # give 10
                data[score.user_from.id()].score_10_give += 1
                # receive 10
                data[receiver].score_10_receive += 1
            elif score.score == 0:
                # give 0
                data[score.user_from.id()].score_0_give += 1
                # receive 0
                data[receiver].score_0_recieve += 1

        for note in Note.query().fetch():
            data[note.user.id()].notes += 1

        # is this person a GIVER
        for user in data.values():
            if user.comments_give > user.comments_receive:
                user.giver += 1
            if user.score_10_give > user.score_10_receive:
                user.giver += 1

        # last place finishers
        self._last_positions(data)

        self._photo_with_most_comments(data)
        self._photo_with_high_score(data)
        self._houses(data)

        self._most(data, 'comments_give')
        self._most(data, 'comments_receive')
        self._most(data, 'notes')
        self._most(data, 'logins')
        self._most(data, 'logouts')
        self._most(data, 'medals')
        self._most(data, 'first_place')
        self._most(data, 'second_place')
        self._most(data, 'third_place')
        self._most(data, 'last_place')

        UserStats.delete_all()
        for stat in data.values():
            stat.put()

        logging.info(data)
        logging.info('stats calculator...finished')
Example #57
0
    def post(self):
        if not (self.auth and self.auth.search_permission
                and self.auth.domain_write_permission == '*'):
            self.info(
                403,
                message=
                    '"key" URL parameter is either missing, invalid or '
                    'lacks required permissions. The key\'s repo must be "*", '
                    'search_permission must be True, and it must have write '
                    'permission.',
                style='plain')
            return

        body = self.request.body_file.read()
        doc = xml.dom.minidom.parseString(body)
        message_text = self.get_element_text(doc, 'message_text')
        receiver_phone_number = self.get_element_text(
            doc, 'receiver_phone_number')

        if message_text is None:
            self.info(
                400,
                message='message_text element is required.',
                style='plain')
            return
        if receiver_phone_number is None:
            self.info(
                400,
                message='receiver_phone_number element is required.',
                style='plain')
            return

        repo = (
            self.config.sms_number_to_repo and
            self.config.sms_number_to_repo.get(receiver_phone_number))
        if not repo:
            self.info(
                400,
                message=
                    'The given receiver_phone_number is not found in '
                    'sms_number_to_repo config.',
                style='plain')
            return

        responses = []
        search_m = re.search(r'^search\s+(.+)$', message_text.strip(), re.I)
        add_self_m = re.search(r'^i am\s+(.+)$', message_text.strip(), re.I)
        if search_m:
            query_string = search_m.group(1).strip()
            query = TextQuery(query_string)
            persons = indexing.search(repo, query, HandleSMS.MAX_RESULTS)
            if persons:
                for person in persons:
                    responses.append(self.render_person(person))
            else:
                responses.append('No results found for: %s' % query_string)
            responses.append(
                'More at: google.org/personfinder/%s?ui=light' % repo)
            responses.append(
                'All data entered in Person Finder is available to the public '
                'and usable by anyone. Google does not review or verify the '
                'accuracy of this data google.org/personfinder/global/tos.html')
        elif self.config.enable_sms_record_input and add_self_m:
            name_string = add_self_m.group(1).strip()
            person = Person.create_original(
                repo,
                entry_date=utils.get_utcnow(),
                full_name=name_string,
                family_name='',
                given_name='')
            person.update_index(['old', 'new'])
            note = Note.create_original(
                repo,
                entry_date=utils.get_utcnow(),
                source_date=utils.get_utcnow(),
                person_record_id=person.record_id,
                author_name=name_string,
                author_made_contact=True,
                status='is_note_author',
                text=message_text)
            db.put(note)
            model.UserActionLog.put_new('add', note, copy_properties=False)
            person.update_from_note(note)
            db.put(person)
            model.UserActionLog.put_new('add', person, copy_properties=False)
            responses.append('Added record for found person: %s' % name_string)
        else:
            usage_str = 'Usage: "Search John"'
            if self.config.enable_sms_record_input:
              usage_str += ' OR "I am John"'
            responses.append(usage_str)

        self.response.headers['Content-Type'] = 'application/xml'
        self.write(
            '<?xml version="1.0" encoding="utf-8"?>\n'
            '<response>\n'
            '  <message_text>%s</message_text>\n'
            '</response>\n'
            % django.utils.html.escape(' ## '.join(responses)))
Example #58
0
def delete_note(id):
    note = Note.objects(id=id).first()
    if not note:
        raise NotFound("Note not found")
    note.delete()
    return jsonify({"message": "Deleted note with success"})
Example #59
0
def save_note(note):
    # add note to hash with note ID as key
    rds.hmset(note.uid, Note.dict_repr(note))
    # add note ID to index list
    rds.lpush('notes', note.uid)