Beispiel #1
0
def fill_in_missing_snippets(existing_snippets, user, user_email, today):
    """Make sure that the snippets array has a Snippet entry for every week.

    The db may have holes in it -- weeks where the user didn't write a
    snippet.  Augment the given snippets array so that it has no holes,
    by adding in default snippet entries if necessary.  Note it does
    not add these entries to the db, it just adds them to the array.

    Arguments:
       existing_snippets: a list of Snippet objects for a given user.
         The first snippet in the list is assumed to be the oldest
         snippet from that user (at least, it's where we start filling
         from).
       user: a User object for the person writing this snippet.
       user_email: the email of the person whose snippets it is.
       today: a datetime.datetime object representing the current day.
         We fill up to then.  If today is wed or before, then we
         fill up to the previous week.  If it's thurs or after, we
         fill up to the current week.

    Returns:
      A new list of Snippet objects, without any holes.
    """
    end_monday = newsnippet_monday(today)
    if not existing_snippets:  # no snippets at all?  Just do this week
        return [
            Snippet(email=user_email,
                    week=end_monday,
                    private=user.private_snippets,
                    is_markdown=user.uses_markdown)
        ]

    # Add a sentinel, one week past the last week we actually want.
    # We'll remove it at the end.
    existing_snippets.append(
        Snippet(email=user_email, week=end_monday + datetime.timedelta(7)))

    all_snippets = [existing_snippets[0]]  # start with the oldest snippet
    for snippet in existing_snippets[1:]:
        while snippet.week - all_snippets[-1].week > datetime.timedelta(7):
            missing_week = all_snippets[-1].week + datetime.timedelta(7)
            all_snippets.append(
                Snippet(email=user_email,
                        week=missing_week,
                        private=user.private_snippets,
                        is_markdown=user.uses_markdown))
        all_snippets.append(snippet)

    # Get rid of the sentinel we added above.
    del all_snippets[-1]

    return all_snippets
Beispiel #2
0
    def post(self, user):
        root_args = self.parser.parse_args()
        snippet_args = self.snippetParser.parse_args(req=root_args)

        #print("New snippet:", snippet_args, snippet_args.title)
        #print("tags: ", snippet_args.tags.split(','))
        new_tag = snippet_args.tags.split(',')

        session = Session()
        snippet = Snippet(title=snippet_args.title,
                          author=snippet_args.author,
                          content=snippet_args.content,
                          tags=[Tag(name=tagName) for tagName in new_tag])
        session.add(snippet)
        session.commit()

        # this response is used by the react client to instantly construct the snippet
        return {
            'id': snippet.id,
            'title': snippet.title,
            'author': snippet.author,
            'content': snippet.content,
            #'user_id': snippet.user_id,
            'likes': snippet.likes,
            'created_at': snippet.created_at.isoformat() + 'Z',
            'tags': snippet_args.tags
            #'comments': snippet.comments
        }
def snippets():
    if request.method == 'POST':
        app.logger.info(f"Adding new clock snippet to database")
        snippet = request.get_json()
        newSnippet = Snippet(filename=snippet['filename'],
                             snippet_type=snippet['snippet_type'],
                             start=snippet['start'],
                             duration=snippet['duration'])
        vid = Video.query.get(snippet['video_id'])
        newSnippet.video = vid
        db.session.add(newSnippet)
        db.session.commit()
        return jsonify(newSnippet.serialize())

    if request.args.get('video_id') and request.args.get('start'):
        start = datetime.timedelta(
            seconds=Snippet.getSec(request.args.get('start')))
        snippet = Snippet.query.filter_by(
            video_id=request.args.get('video_id'), start=start).first()
        if snippet:
            return jsonify(snippet.serialize())
        return jsonify({})

    snipz = Snippet.query.all()
    app.logger.info("Gathering list of all snippets. (Currently {len(snipz)})")
    all_snipz = []
    for snippet in snipz:
        all_snipz.append(snippet.serialize())
    return jsonify({"snippets": all_snipz})
Beispiel #4
0
def generateReccomendations(snippets, user, numRecsToReturn):
    if numRecsToReturn > snippets.count():
        numRecToReturn = snippets.count()

    recList = []
    for index in range(0, numRecsToReturn):
        recList.append([Snippet(), 0])

    for snippet in snippets:
        userSnippetSimilarityRating = 0
        snippetTagList = snippet.tags
        for utag in user.tags:
            for ptag in snippetTagList:
                if ptag == utag:
                    userSnippetSimilarityRating += 1
                    #Don't rescan matched next iteration
                    postTagList.remove(ptag)

        # Check if this post should be included as a reccomendation, replace if neccesary
        for rec in recList:
            if rec[1] < userSnippetSimilarityRating:
                rec[0] = snippet
                rec[1] = userSnippetSimilarityRating
                break

    return recList
Beispiel #5
0
    def render(self):

        for i in range(200):
            snippet = Snippet()
            snippet.headline = 'Headline ' + str(i)
            snippet.link = 'Link ' + str(i)
            snippet.copy = 'Headline ' + str(i)
            snippet.put()
Beispiel #6
0
def create():
    if request.method == 'POST':
        form = SnippetForm(request.form)
        if form.validate():
            snippet = form.save_entry(Snippet())
            db.session.add(snippet)
            db.session.commit()
            return redirect(url_for('snippets.detail', slug=snippet.slug))
    else:
        form = SnippetForm()
    return render_template('snippets/create.html', form=form)
    def restore_object(self, attrs, instance=None):
        """
        Create or update a new snippet instance.
        """
        if instance:
            # Update existing instance
            instance.title = attrs.get('title', instance.title)
            instance.code = attrs.get('code', instance.code)
            instance.linenos = attrs.get('linenos', instance.linenos)
            instance.language = attrs.get('language', instance.language)
            instance.style = attrs.get('style', instance.style)
            return instance

        # Create new instance
        return Snippet(**attrs)
Beispiel #8
0
    def restore_object(self, attrs, instance=None):
        """
        Create or update a new snippet instance, given a dictionary
        of deserialized field values.

        Note that if we don't define this method, then deserializing
        data will simply return a dictionary of items.
        """
        if instance:
            # Update existing instance
            instance.title = attrs.get('title', instance.title)
            instance.code = attrs.get('code', instance.code)
            instance.linenos = attrs.get('linenos', instance.linenos)
            instance.language = attrs.get('language', instance.language)
            instance.style = attrs.get('style', instance.style)
            return instance

        # Create new instance
        return Snippet(**attrs)
Beispiel #9
0
    def post_new_snippet():

        if not has_scope("post:snippet"):
            abort(403)

        body = request.get_json()

        coderId = body.get('coderId', None)
        coder = Coder.query.get(coderId)

        if not coder:
            abort(404)

        attrs = {}
        attrs['snippet_name'] = body.get('name', None)
        attrs['code'] = body.get('code', None)
        attrs['needs_review'] = body.get('needsReview', False)
        attrs['comments'] = body.get('comments', '')

        if attrs['snippet_name'] and attrs['code']:
            try:
                snippet = Snippet(**attrs)
                # insert snippet by appending as a child to its coder and
                # updating coder
                coder.snippets.append(snippet)
                coder.update()
                return jsonify({
                    "success":
                    True,
                    "message":
                    "Snippet has been successfully saved to database"
                })
            except:
                abort(500)

        else:
            abort(400)
Beispiel #10
0
#----------------------------
# Populate the database
#----------------------------

tag_cool = Tag(name='cool')
tag_car = Tag(name='car')
tag_animal = Tag(name='animal')

comment_rhino = Comment(
    text=
    'Rhinoceros, often abbreviated as rhino, is a group of five extant species of odd-toed ungulates in the family Rhinocerotidae.'
)

snippet_car = Snippet(content='This is a post about a car.', \
    tags=[tag_car, tag_cool], \
    created_at=(datetime.utcnow() - timedelta(days=1)))

snippet_another_car = Snippet(content='This is a post about another car.', \
    tags=[tag_car])

snippet_rhino = Snippet(content='Rhinos have a big horn on their face.', \
    tags=[tag_animal], \
    comments=[comment_rhino])

user_joe = User(uuid='Joe blow from cokamoe',
                tags=[tag_car, tag_cool, tag_animal])

# Create a new Session and add the posts:
session = Session()
Beispiel #11
0
    db.session.add(tag_tragedy)
    db.session.add(tag_novel)
    db.session.add(tag_adventure_fic)
    db.session.add(tag_classic_lit)
    db.session.add(tag_horror)
    db.session.add(tag_poetry)
    db.session.add(tag_romance)
    db.session.add(tag_fantasy)
    db.session.add(tag_scifi)
    db.session.add(tag_crime)
    #vim macro buffer yiwodb.session.add()Pdd}p``

    snippet_lotr = Snippet(title="Lord of the Rings", author="J.R.R. Tolkien",
                           content = "It's a dangerous business, Frodo, going out your door.\
                                      You step onto the road, and if you don't keep your feet, there's no knowing where \
                                      you might be swept off to.",
                           tags=[tag_fantasy, tag_classic_lit], \
                           created_at=(datetime.utcnow() - timedelta(days=1)))
    db.session.add(snippet_lotr)

    snippet_ringWorld = Snippet(title="Ringworld", author="Larry Niven",
                                content = "The gods do not protect fools. Fools are protected by more capable fools.",
                                tags=[tag_scifi])
    db.session.add(snippet_ringWorld)

    snippet_outlander = Snippet(title="Outlander", author="Diana Gabaldon", 
                                content = "Don't be afraid. There's the two of us now.",
                                tags=[tag_romance, tag_scifi])
    db.session.add(snippet_outlander)

    user_zhilinz = User(username="******", tags=[tag_scifi, tag_fantasy, tag_horror])
Beispiel #12
0
 def process(self):
     snippet = Snippet()
     self.put(snippet)
     self.redirect('/list')