text:
import difflib

from django.core.mail import send_mass_mail
from django.db.models import Q
from django.http import HttpResponseBadRequest, HttpResponseNotAllowed
from django.shortcuts import render, redirect, get_object_or_404
from django.template import Context, Template
from django.views.decorators.http import require_POST

from account.decorators import login_required

# @@@ switch to pinax-teams
from symposion.teams.models import Team

from symposion.conf import settings
from symposion.proposals.models import ProposalBase, ProposalSection
from symposion.utils.mail import send_email

from symposion.reviews.forms import ReviewForm, SpeakerCommentForm
from symposion.reviews.forms import BulkPresentationForm
from symposion.reviews.models import (
    ReviewAssignment, Review, LatestVote, ProposalResult, NotificationTemplate,
    ResultNotification
)
from symposion.utils import anonymous_review

def access_not_permitted(request):
    return render(request, "symposion/reviews/access_not_permitted.html")

def proposals_generator(request, queryset, user_pk=None, check_speaker=True):

    for obj in queryset:
        # @@@ this sucks; we can do better
        if check_speaker:
            if request.user in [s.user for s in obj.speakers()]:
                continue

        try:
            obj.result
        except ProposalResult.DoesNotExist:
            ProposalResult.objects.get_or_create(proposal=obj)

        obj.comment_count = obj.result.comment_count
        obj.score = obj.result.score
        obj.total_votes = obj.result.vote_count
        obj.strong_accept = obj.result.strong_accept
        obj.weak_accept = obj.result.weak_accept
        obj.weak_reject = obj.result.weak_reject
        obj.strong_reject = obj.result.strong_reject
        lookup_params = dict(proposal=obj)

        if user_pk:
            lookup_params["user__pk"] = user_pk
        else:
            lookup_params["user"] = request.user

        try:
            obj.user_vote = LatestVote.objects.get(**lookup_params).vote
            obj.user_vote_css = LatestVote.objects.get(**lookup_params).css_class()
        except LatestVote.DoesNotExist:
            obj.user_vote = None
            obj.user_vote_css = "no-vote"

        # Anonymize the speakers if we're doing blind review.
        obj = obj.redacted()

        yield obj

# Returns a list of all proposals, proposals reviewed by the user, or the proposals the user has
# yet to review depending on the link user clicks in dashboard
@login_required
def review_section(request, section_slug, assigned=False, reviewed="all"):

    if not request.user.has_perm("symposion_reviews.can_review_%s" % section_slug):
        return access_not_permitted(request)

    section = get_object_or_404(ProposalSection, section__slug=section_slug)
    queryset = ProposalBase.objects.filter(kind__section=section.section)

    if assigned:
        assignments = ReviewAssignment.objects.filter(user=request.user)\
            .values_list("proposal__id")
        queryset = queryset.filter(id__in=assignments)

    # passing reviewed in from reviews.urls and out to review_list for
    # appropriate template header rendering
    if reviewed == "all":
        queryset = queryset.select_related("result").select_subclasses()
        reviewed = "all_reviews"
    elif reviewed == "reviewed":
        queryset = queryset.filter(reviews__user=request.user)
        reviewed = "user_reviewed"
    else:
        queryset = queryset.exclude(reviews__user=request.user).exclude(
            speaker__user=request.user)
        reviewed = "user_not_reviewed"

    queryset = queryset.filter(cancelled=False)
    # Show proposals with least votes first, then by oldest
    queryset = queryset.order_by("result__vote_count", "submitted")

    proposals = proposals_generator(request, queryset)

    ctx = {
        "proposals": proposals,
        "section": section,
        "reviewed": reviewed,
    }

    return render(request, "symposion/reviews/review_list.html", ctx)

@login_required
def review_list(request, section_slug, user_pk):

    # if they're not a reviewer admin and they aren't the person whose
    # review list is being asked for, don't let them in
    if not request.user.has_perm("symposion_reviews.can_manage_%s" % section_slug):
        if not request.user.pk == user_pk:
            return access_not_permitted(request)

    queryset = ProposalBase.objects.select_related("speaker__user", "result")
    reviewed = LatestVote.objects.filter(user__pk=user_pk).values_list("proposal", flat=True)
    queryset = queryset.filter(pk__in=reviewed)
    proposals = queryset.order_by("submitted")

    admin = request.user.has_perm("symposion_reviews.can_manage_%s" % section_slug)

    proposals = proposals_generator(request, proposals, user_pk=user_pk, check_speaker=not admin)

    ctx = {
        "proposals": proposals,
    }
    return render(request, "symposion/reviews/review_list.html", ctx)

@login_required
def review_admin(request, section_slug):

    if not request.user.has_perm("symposion_reviews.can_manage_%s" % section_slug):
        return access_not_permitted(request)

    def reviewers():
        already_seen = set()

        for team in Team.objects.filter(permissions__codename="can_review_%s" % section_slug):
            for membership in team.memberships.filter(Q(state="member") | Q(state="manager")):
                user = membership.user
                if user.pk in already_seen:
                    continue
                already_seen.add(user.pk)

                user.comment_count = Review.objects.filter(user=user).count()
                user.total_votes = LatestVote.objects.filter(user=user).count()
                user.strong_accept = LatestVote.objects.filter(
                    user=user,
                    vote=LatestVote.VOTES.STRONG_ACCEPT
                ).count()
                user.weak_accept = LatestVote.objects.filter(
                    user=user,
                    vote=LatestVote.VOTES.WEAK_ACCEPT
                ).count()
                user.weak_reject = LatestVote.objects.filter(
                    user=user,
                    vote=LatestVote.VOTES.WEAK_REJECT
                ).count()
                user.strong_reject = LatestVote.objects.filter(
                    user=user,
                    vote=LatestVote.VOTES.STRONG_REJECT
                ).count()

                yield user

    ctx = {
        "section_slug": section_slug,
        "reviewers": reviewers(),
    }
    return render(request, "symposion/reviews/review_admin.html", ctx)

# FIXME: This view is too complex according to flake8
@login_required
def review_detail(request, pk):

    proposals = ProposalBase.objects.select_related("result").select_subclasses()
    proposal = get_object_or_404(proposals, pk=pk)

    if not request.user.has_perm("symposion_reviews.can_review_%s" % proposal.kind.section.slug):
        return access_not_permitted(request)

    speakers = [s.user for s in proposal.speakers()]

    if not request.user.is_superuser and request.user in speakers:
        return access_not_permitted(request)

    admin = request.user.is_staff

    try:
        latest_vote = LatestVote.objects.get(proposal=proposal, user=request.user)
    except LatestVote.DoesNotExist:
        latest_vote = None

    if request.method == "POST":
        if request.user in speakers:
            return access_not_permitted(request)

        if "vote_submit" in request.POST:
            review_form = ReviewForm(request.POST)
            if review_form.is_valid():

                review = review_form.save(commit=False)
                review.user = request.user
                review.proposal = proposal
                review.save()

                return redirect(request.path)
            else:
                message_form = SpeakerCommentForm()
        elif "message_submit" in request.POST:
            message_form = SpeakerCommentForm(request.POST)
            if message_form.is_valid():

                message = message_form.save(commit=False)
                message.user = request.user
                message.proposal = proposal
                message.save()

                for speaker in speakers:
                    if speaker and speaker.email:
                        ctx = {
                            "proposal": proposal,
                            "message": message,
                            "reviewer": False,
                        }
                        send_email(
                            [speaker.email], "proposal_new_message",
                            context=ctx
                        )

                return redirect(request.path)
            else:
                initial = {}
                if latest_vote:
                    initial["vote"] = latest_vote.vote
                if request.user in speakers:
                    review_form = None
                else:
                    review_form = ReviewForm(initial=initial)
        elif "result_submit" in request.POST:
            if admin:
                result = request.POST["result_submit"]

                if result == "accept":
                    proposal.result.status = "accepted"
                    proposal.result.save()
                elif result == "reject":
                    proposal.result.status = "rejected"
                    proposal.result.save()
                elif result == "undecide":
                    proposal.result.status = "undecided"
                    proposal.result.save()
                elif result == "standby":
                    proposal.result.status = "standby"
                    proposal.result.save()

            return redirect(request.path)
        elif "update_title" in request.POST:
            if admin:
                action = request.POST["update_title"]
                if action == "Apply":
                    proposal.presentation.title = proposal.title
                    proposal.presentation.save()
                elif action == "Reject":
                    proposal.title = proposal.presentation.title
                    proposal.save()
            return redirect(request.path + '#proposal-updates')
        elif "update_description" in request.POST:
            if admin:
                action = request.POST["update_description"]
                if action == "Apply":
                    proposal.presentation.description = proposal.description
                    proposal.presentation.save()
                elif action == "Reject":
                    proposal.description = proposal.presentation.description
                    proposal.save()
            return redirect(request.path + '#proposal-updates')
        elif "update_abstract" in request.POST:
            if admin:
                action = request.POST["update_abstract"]
                if action == "Apply":
                    proposal.presentation.abstract = proposal.abstract
                    proposal.presentation.save()
                elif action == "Reject":
                    proposal.abstract = proposal.presentation.abstract
                    proposal.save()
            return redirect(request.path + '#proposal-updates')
    else:
        initial = {}
        if latest_vote:
            initial["vote"] = latest_vote.vote
        if request.user in speakers:
            review_form = None
        else:
            review_form = ReviewForm(initial=initial)
        message_form = SpeakerCommentForm()

    proposal.comment_count = proposal.result.comment_count
    proposal.total_votes = proposal.result.vote_count
    proposal.strong_accept = proposal.result.strong_accept
    proposal.weak_accept = proposal.result.weak_accept
    proposal.weak_reject = proposal.result.weak_reject
    proposal.strong_reject = proposal.result.strong_reject

    reviews = Review.objects.filter(proposal=proposal).order_by("-submitted_at")
    messages = proposal.messages.order_by("submitted_at")

    # Anonymize the proposal if needs be.
    proposal = proposal.redacted()

    messages = [anonymous_review.MessageProxy(message) for message in messages]

    changes = {'test': '<b>hi</b>'}
    try:
        presentation = proposal.presentation
        differ = difflib.HtmlDiff()
        if proposal.title != presentation.title:
            changes['title_diff'] = differ.make_table([proposal.title],
                    [presentation.title], 'Proposal', 'Presentation')
        if proposal.abstract != presentation.abstract:
            changes['abstract_diff'] = differ.make_table(
                    proposal.abstract.split('\n'), presentation.abstract.split('\n'), 'Proposal', 'Presentation')
        if proposal.description != presentation.description:
            changes['description_diff'] = differ.make_table(
                    proposal.description.split('\n'), presentation.description.split('\n'), 'Proposal', 'Presentation')
    except:
        # no presentation
        pass

    return render(request, "symposion/reviews/review_detail.html", {
        "proposal": proposal,
        "latest_vote": latest_vote,
        "reviews": reviews,
        "review_messages": messages,
        "review_form": review_form,
        "message_form": message_form,
        "proposal_changes": changes,
    })

@login_required
@require_POST
def review_delete(request, pk):
    review = get_object_or_404(Review, pk=pk)
    section_slug = review.section.slug

    if not request.user.has_perm("symposion_reviews.can_manage_%s" % section_slug):
        return access_not_permitted(request)

    review = get_object_or_404(Review, pk=pk)
    review.delete()

    return redirect("review_detail", pk=review.proposal.pk)

@login_required
def review_status(request, section_slug=None, key=None):

    if not request.user.has_perm("symposion_reviews.can_review_%s" % section_slug):
        return access_not_permitted(request)

    VOTE_THRESHOLD = settings.SYMPOSION_VOTE_THRESHOLD

    ctx = {
        "section_slug": section_slug,
        "vote_threshold": VOTE_THRESHOLD,
    }

    queryset = ProposalBase.objects.select_related("speaker__user", "result").select_subclasses()
    if section_slug:
        queryset = queryset.filter(kind__section__slug=section_slug)

    proposals = {
        # proposals with at least VOTE_THRESHOLD reviews and at least one ++ and no --s, sorted by
        # the 'score'
        "positive": queryset.filter(result__vote_count__gte=VOTE_THRESHOLD, result__strong_accept__gt=0,
                                    result__strong_reject=0).order_by("-result__score"),
        # proposals with at least VOTE_THRESHOLD reviews and at least one -- and no ++s, reverse
        # sorted by the 'score'
        "negative": queryset.filter(result__vote_count__gte=VOTE_THRESHOLD, result__strong_reject__gt=0,
                                    result__strong_accept=0).order_by("result__score"),
        # proposals with at least VOTE_THRESHOLD reviews and neither a ++ or a --, sorted by total
        # votes (lowest first)
        "indifferent": queryset.filter(result__vote_count__gte=VOTE_THRESHOLD, result__strong_reject=0,
                                       result__strong_accept=0).order_by("result__vote_count"),
        # proposals with at least VOTE_THRESHOLD reviews and both a ++ and --, sorted by total
        # votes (highest first)
        "controversial": queryset.filter(result__vote_count__gte=VOTE_THRESHOLD,
                                         result__strong_accept__gt=0, result__strong_reject__gt=0)
        .order_by("-result__vote_count"),
        # proposals with fewer than VOTE_THRESHOLD reviews
        "too_few": queryset.filter(result__vote_count__lt=VOTE_THRESHOLD)
        .order_by("result__vote_count"),
    }

    admin = request.user.has_perm("symposion_reviews.can_manage_%s" % section_slug)

    for status in proposals:
        if key and key != status:
            continue
        proposals[status] = list(proposals_generator(request, proposals[status], check_speaker=not admin))

    if key:
        ctx.update({
            "key": key,
            "proposals": proposals[key],
        })
    else:
        ctx["proposals"] = proposals

    return render(request, "symposion/reviews/review_stats.html", ctx)

@login_required
def review_assignments(request):
    if not request.user.groups.filter(name="reviewers").exists():
        return access_not_permitted(request)
    assignments = ReviewAssignment.objects.filter(
        user=request.user,
        opted_out=False
    )
    return render(request, "symposion/reviews/review_assignment.html", {
        "assignments": assignments,
    })

@login_required
@require_POST
def review_assignment_opt_out(request, pk):
    review_assignment = get_object_or_404(
        ReviewAssignment, pk=pk, user=request.user)
    if not review_assignment.opted_out:
        review_assignment.opted_out = True
        review_assignment.save()
        ReviewAssignment.create_assignments(
            review_assignment.proposal, origin=ReviewAssignment.AUTO_ASSIGNED_LATER)
    return redirect("review_assignments")

@login_required
def review_bulk_accept(request, section_slug):
    if not request.user.has_perm("symposion_reviews.can_manage_%s" % section_slug):
        return access_not_permitted(request)
    if request.method == "POST":
        form = BulkPresentationForm(request.POST)
        if form.is_valid():
            talk_ids = form.cleaned_data["talk_ids"].split(",")
            talks = ProposalBase.objects.filter(id__in=talk_ids).select_related("result")
            for talk in talks:
                talk.result.status = "accepted"
                talk.result.save()
            return redirect("review_section", section_slug=section_slug)
    else:
        form = BulkPresentationForm()

    return render(request, "symposion/reviews/review_bulk_accept.html", {
        "form": form,
    })

@login_required
def result_notification(request, section_slug, status):
    if not request.user.has_perm("symposion_reviews.can_manage_%s" % section_slug):
        return access_not_permitted(request)

    proposals = ProposalBase.objects.filter(kind__section__slug=section_slug, result__status=status).select_related("speaker__user", "result").select_subclasses()
    notification_templates = NotificationTemplate.objects.all()

    ctx = {
        "section_slug": section_slug,
        "status": status,
        "proposals": [proposal.redacted() for proposal in proposals],
        "notification_templates": notification_templates,
    }
    return render(request, "symposion/reviews/result_notification.html", ctx)

@login_required
def result_notification_prepare(request, section_slug, status):
    if request.method != "POST":
        return HttpResponseNotAllowed(["POST"])

    if not request.user.has_perm("symposion_reviews.can_manage_%s" % section_slug):
        return access_not_permitted(request)

    proposal_pks = []
    try:
        for pk in request.POST.getlist("_selected_action"):
            proposal_pks.append(int(pk))
    except ValueError:
        return HttpResponseBadRequest()
    proposals = ProposalBase.objects.filter(
        kind__section__slug=section_slug,
        result__status=status,
    )
    proposals = proposals.filter(pk__in=proposal_pks)
    proposals = proposals.select_related("speaker__user", "result")
    proposals = proposals.select_subclasses()

    notification_template_pk = request.POST.get("notification_template", "")
    if notification_template_pk:
        notification_template = NotificationTemplate.objects.get(pk=notification_template_pk)
    else:
        notification_template = None

    ctx = {
        "section_slug": section_slug,
        "status": status,
        "notification_template": notification_template,
        "proposals": proposals,
        "proposal_pks": ",".join([str(pk) for pk in proposal_pks]),
    }
    return render(request, "symposion/reviews/result_notification_prepare.html", ctx)

@login_required
def result_notification_send(request, section_slug, status):
    if request.method != "POST":
        return HttpResponseNotAllowed(["POST"])

    if not request.user.has_perm("symposion_reviews.can_manage_%s" % section_slug):
        return access_not_permitted(request)

    if not all([k in request.POST for k in ["proposal_pks", "from_address", "subject", "body"]]):
        return HttpResponseBadRequest()

    try:
        proposal_pks = [int(pk) for pk in request.POST["proposal_pks"].split(",")]
    except ValueError:
        return HttpResponseBadRequest()

    proposals = ProposalBase.objects.filter(
        kind__section__slug=section_slug,
        result__status=status,
    )
    proposals = proposals.filter(pk__in=proposal_pks)
    proposals = proposals.select_related("speaker__user", "result")
    proposals = proposals.select_subclasses()

    notification_template_pk = request.POST.get("notification_template", "")
    if notification_template_pk:
        notification_template = NotificationTemplate.objects.get(pk=notification_template_pk)
    else:
        notification_template = None

    emails = []

    for proposal in proposals:
        rn = ResultNotification()
        rn.proposal = proposal
        rn.template = notification_template
        rn.to_address = proposal.speaker_email
        rn.from_address = request.POST["from_address"]
        proposal_context = proposal.notification_email_context()
        rn.subject = Template(request.POST["subject"]).render(
            Context({
                "proposal": proposal_context
            })
        )
        rn.body = Template(request.POST["body"]).render(
            Context({
                "proposal": proposal_context
            })
        )
        rn.save()
        emails.append(rn.email_args)

    send_mass_mail(emails)

    return redirect("result_notification", section_slug=section_slug, status=status)


text:
#include "asylo/util/thread.h"

#include <cstddef>
#include <vector>

#include <gmock/gmock.h>
#include <gtest/gtest.h>
#include "absl/container/flat_hash_set.h"
#include "absl/synchronization/mutex.h"
#include "absl/synchronization/notification.h"
#include "absl/time/clock.h"
#include "absl/time/time.h"
#include "asylo/util/mutex_guarded.h"

using ::testing::AllOf;
using ::testing::Eq;
using ::testing::Ge;
using ::testing::Lt;

namespace asylo {
namespace {

class ThreadTest : public ::testing::Test {
 protected:
  static constexpr size_t kThreads = 4;
  static constexpr size_t kIterations = 64;
};

using ThreadDeathTest = ThreadTest;

TEST_F(ThreadTest, SimpleThread) {
  bool executed = false;
  Thread thread([&executed] { executed = true; });
  thread.Join();
  EXPECT_TRUE(executed);
}

TEST_F(ThreadTest, MovedThread) {
  bool executed = false;
  Thread thread([&executed] { executed = true; });
  auto moved = std::move(thread);
  moved.Join();
  EXPECT_TRUE(executed);
}

TEST_F(ThreadTest, DetachedThread) {
  MutexGuarded<bool> executed(false);
  Thread::StartDetached([&executed] {
    absl::SleepFor(absl::Seconds(3));
    *executed.Lock() = true;
  });
  EXPECT_FALSE(*executed.ReaderLock());
  absl::SleepFor(absl::Seconds(6));
  EXPECT_TRUE(*executed.ReaderLock());
}

TEST_F(ThreadTest, MultipleThreads) {
  MutexGuarded<absl::flat_hash_set<Thread::Id>> ids(
      (absl::flat_hash_set<Thread::Id>()));
  std::vector<Thread> threads;
  for (size_t t = 0; t < kThreads; ++t) {
    threads.emplace_back(
        [&ids] { ids.Lock()->insert(Thread::this_thread_id()); });
  }
  for (auto& thread : threads) {
    thread.Join();
  }
  EXPECT_THAT(ids.ReaderLock()->size(), Eq(kThreads));
}

TEST_F(ThreadTest, MultipleThreadsMultipleTimes) {
  MutexGuarded<absl::flat_hash_set<Thread::Id>> ids(
      (absl::flat_hash_set<Thread::Id>()));
  for (size_t i = 0; i < kIterations; ++i) {
    std::vector<Thread> threads;
    for (size_t t = 0; t < kThreads; ++t) {
      threads.emplace_back(
          [&ids] { ids.Lock()->insert(Thread::this_thread_id()); });
    }
    for (auto& thread : threads) {
      thread.Join();
    }
  }
  // Expect that some of the thread ids will be reused after being joined.
  EXPECT_THAT(ids.ReaderLock()->size(),
              AllOf(Ge(kThreads), Lt(kThreads * kIterations)));
}

void CStyleBody(bool* executed) { *executed = true; }

TEST_F(ThreadTest, CStyleThread) {
  bool executed = false;
  Thread thread(CStyleBody, &executed);
  thread.Join();
  EXPECT_TRUE(executed);
}

void CStyleDetachedBody(MutexGuarded<bool> *executed) {
  absl::SleepFor(absl::Seconds(3));
  *executed->Lock() = true;
}

TEST_F(ThreadTest, CStyleDetachedThread) {
  MutexGuarded<bool> executed(false);
  Thread::StartDetached(CStyleDetachedBody, &executed);
  EXPECT_FALSE(*executed.ReaderLock());
  absl::SleepFor(absl::Seconds(6));
  EXPECT_TRUE(*executed.ReaderLock());
}

}  // namespace
}  // namespace asylo

redpajama_set_name: RedPajamaGithub


text:
<?xml version="1.0" encoding="utf-8"?>
<!--
  ~ Copyright (c) 2017 Michael D'Arcy and Brianne O'Niel.
  ~
  ~ Licensed under the Apache License, Version 2.0 (the "License");
  ~ you may not use this file except in compliance with the License.
  ~ You may obtain a copy of the License at
  ~
  ~     http://www.apache.org/licenses/LICENSE-2.0
  ~
  ~ Unless required by applicable law or agreed to in writing, software
  ~ distributed under the License is distributed on an "AS IS" BASIS,
  ~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  ~ See the License for the specific language governing permissions and
  ~ limitations under the License.
  -->

<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="com.group13.androidsdk.mycards.EditCardActivity">

    <TextView
        android:id="@+id/labelFrontText"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBaseline="@+id/tvEditCardFrontText"
        android:layout_alignBottom="@+id/tvEditCardFrontText"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:background="#FFFFFF"
        android:text="@string/front"
        android:textColor="#26c99d"
        android:textSize="24sp"/>

    <EditText
        android:id="@+id/tvEditCardFrontText"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_alignParentTop="true"
        android:layout_marginTop="15dp"
        android:layout_toRightOf="@+id/labelFrontText"
        android:background="#FFFFFF"
        android:hint="@string/front_of_card"
        android:inputType="textMultiLine"
        android:padding="4dp"
        android:textColor="#29c99d"/>

    <TextView
        android:id="@+id/labelBackText"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBaseline="@+id/tvEditCardBackText"
        android:layout_alignBottom="@+id/tvEditCardBackText"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:background="#FFFFFF"
        android:text="@string/back"
        android:textColor="#26c99d"
        android:textSize="24sp"/>

    <EditText
        android:id="@+id/tvEditCardBackText"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/tvEditCardFrontText"
        android:layout_alignParentEnd="true"
        android:layout_alignParentRight="true"
        android:layout_alignStart="@+id/tvEditCardFrontText"
        android:layout_below="@+id/tvEditCardFrontText"
        android:layout_gravity="center"
        android:layout_marginTop="25dp"
        android:background="#FFFFFF"
        android:hint="@string/back_of_card"
        android:inputType="textMultiLine"
        android:padding="4dp"
        android:textColor="#29c99d"/>

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBottom="@+id/tvEditTags"
        android:layout_toLeftOf="@+id/tvEditTags"
        android:layout_toStartOf="@+id/tvEditTags"
        android:background="#FFFFFF"
        android:text="@string/tags_label"
        android:textColor="#26c99d"
        android:textSize="24sp"/>

    <EditText
        android:id="@+id/tvEditTags"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/tvEditCardBackText"
        android:layout_alignStart="@+id/tvEditCardBackText"
        android:layout_below="@+id/tvEditCardBackText"
        android:layout_marginTop="25dp"
        android:background="#FFFFFF"
        android:hint="@string/comma_separated"
        android:inputType="text"
        android:textColor="#26c99d"
        android:textSize="20sp"/>

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@id/tvEditTags"
        android:layout_marginTop="15dp"
        android:id="@+id/cardStatsContainer">

        <TextView
            android:id="@+id/textView10"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:background="#FFFFFF"
            android:text="@string/card_stats"
            android:textColor="#26c99d"
            android:textSize="24sp"/>

        <TextView
            android:id="@+id/textView5"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentLeft="true"
            android:layout_alignParentStart="true"
            android:layout_below="@+id/textView10"
            android:background="#FFFFFF"
            android:text="@string/last_review"
            android:textColor="#26c99d"
            android:textSize="14sp"/>

        <TextView
            android:id="@+id/tvLastReviewDate"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignBaseline="@+id/textView5"
            android:layout_alignBottom="@+id/textView5"
            android:layout_marginLeft="5dp"
            android:layout_toEndOf="@+id/textView5"
            android:layout_toRightOf="@+id/textView5"
            android:background="#FFFFFF"
            android:text=""
            android:textColor="#26c99d"
            android:textSize="14sp"/>

        <TextView
            android:id="@+id/tvNextReviewLabel"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentLeft="true"
            android:layout_alignParentStart="true"
            android:layout_below="@+id/textView5"
            android:background="#FFFFFF"
            android:text="@string/next_review"
            android:textColor="#26c99d"
            android:textSize="14sp"/>

        <TextView
            android:id="@+id/tvNextReviewDate"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignBaseline="@+id/tvNextReviewLabel"
            android:layout_alignBottom="@+id/tvNextReviewLabel"
            android:layout_marginLeft="5dp"
            android:layout_toEndOf="@+id/tvNextReviewLabel"
            android:layout_toRightOf="@+id/tvNextReviewLabel"
            android:background="#FFFFFF"
            android:text=""
            android:textColor="#26c99d"
            android:textSize="14sp"/>

        <TextView
            android:id="@+id/tvTotalReviewsLabel"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentLeft="true"
            android:layout_alignParentStart="true"
            android:layout_below="@+id/tvNextReviewLabel"
            android:background="#FFFFFF"
            android:text="@string/total_reviews"
            android:textColor="#26c99d"
            android:textSize="14sp"/>

        <TextView
            android:id="@+id/tvTotalReviews"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignBaseline="@+id/tvTotalReviewsLabel"
            android:layout_alignBottom="@+id/tvTotalReviewsLabel"
            android:layout_marginLeft="5dp"
            android:layout_toEndOf="@+id/tvTotalReviewsLabel"
            android:layout_toRightOf="@+id/tvTotalReviewsLabel"
            android:background="#FFFFFF"
            android:text=""
            android:textColor="#26c99d"
            android:textSize="14sp"/>

        <TextView
            android:id="@+id/tvEasinessLabel"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentLeft="true"
            android:layout_alignParentStart="true"
            android:layout_below="@+id/tvTotalReviewsLabel"
            android:background="#FFFFFF"
            android:text="@string/easiness"
            android:textColor="#26c99d"
            android:textSize="14sp"/>

        <TextView
            android:id="@+id/tvEasiness"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignBaseline="@+id/tvEasinessLabel"
            android:layout_alignBottom="@+id/tvEasinessLabel"
            android:layout_marginLeft="5dp"
            android:layout_toEndOf="@+id/tvEasinessLabel"
            android:layout_toRightOf="@+id/tvEasinessLabel"
            android:background="#FFFFFF"
            android:text=""
            android:textColor="#26c99d"
            android:textSize="14sp"/>
    </RelativeLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true">

        <Button
            android:id="@+id/btnDeleteCard"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:onClick="onDeleteAction"
            android:text="@string/delete"
            android:textColor="#29c99d"
            android:textSize="18sp"
            android:focusable="false"/>

        <Button
            android:id="@+id/btnCancelEdit"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:onClick="onCancelAction"
            android:text="@string/cancel"
            android:textColor="#29c99d"
            android:textSize="18sp"
            android:focusable="false"/>

        <Button
            android:id="@+id/btnSaveEdit"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:onClick="onSaveAction"
            android:text="@string/save"
            android:textColor="#29c99d"
            android:textSize="18sp"
            android:focusable="false"/>
    </LinearLayout>
</RelativeLayout>


text:
package mil.nga.giat.geowave.core.ingest.hdfs;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import mil.nga.giat.geowave.core.ingest.avro.AvroFormatPlugin;

import org.apache.avro.file.CodecFactory;
import org.apache.avro.file.DataFileWriter;
import org.apache.avro.generic.GenericDatumWriter;
import org.apache.hadoop.fs.FSDataOutputStream;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.log4j.Logger;

/**
 * A class to hold intermediate stage data that must be used throughout the life
 * of the HDFS stage process.
 */
public class StageRunData
{
	private final static Logger LOGGER = Logger.getLogger(StageRunData.class);
	private final Map<String, DataFileWriter> cachedWriters = new HashMap<String, DataFileWriter>();
	private final Path hdfsBaseDirectory;
	private final FileSystem fs;

	public StageRunData(
			final Path hdfsBaseDirectory,
			final FileSystem fs ) {
		this.hdfsBaseDirectory = hdfsBaseDirectory;
		this.fs = fs;
	}

	public DataFileWriter getWriter(
			final String typeName,
			final AvroFormatPlugin plugin ) {
		return getDataWriterCreateIfNull(
				typeName,
				plugin);
	}

	private synchronized DataFileWriter getDataWriterCreateIfNull(
			final String typeName,
			final AvroFormatPlugin plugin ) {
		if (!cachedWriters.containsKey(typeName)) {
			FSDataOutputStream out = null;
			final DataFileWriter dfw = new DataFileWriter(
					new GenericDatumWriter());
			cachedWriters.put(
					typeName,
					dfw);
			dfw.setCodec(CodecFactory.snappyCodec());
			try {
				// TODO: we should probably clean up the type name to make it
				// HDFS path safe in case there are invalid characters
				// also, if a file already exists do we want to delete it or
				// append to it?
				out = fs.create(new Path(
						hdfsBaseDirectory,
						typeName));
				dfw.create(
						plugin.getAvroSchema(),
						out);

			}
			catch (final IOException e) {
				LOGGER.fatal(
						"Unable to create output stream",
						e);
				// cache a null value so we don't continually try to recreate
				cachedWriters.put(
						typeName,
						null);
				return null;
			}
		}
		return cachedWriters.get(typeName);
	}

	public synchronized void close() {
		for (final DataFileWriter dfw : cachedWriters.values()) {
			try {
				dfw.close();
			}
			catch (final IOException e) {
				LOGGER.warn(
						"Unable to close sequence file stream",
						e);
			}
		}
		cachedWriters.clear();
	}
}


text:
from mailgun import api as mailgun_api
from signup import models as signup_model
from sequence import models as sequence_model
from groups import models as groups_model

import logging
log = logging.getLogger(__name__)

def unsubscribe_user( address ):
    """ Unsubscribe user completely from the Mechanical Mooc - all sequences
    """

    # remove from sequence group
    signups = signup_model.get_all_user_signups(address)
    for user_signup in signups:
        sequence_list = sequence_model.sequence_list_name(user_signup['sequence'])
        mailgun_api.remove_list_member(sequence_list, address)

    # remove from small groups
    groups = groups_model.get_member_groups(address)
    for group in groups:
        groups_model.remove_group_member(group['uri'], address)
        groups_model.sync_group_with_mailgun(group['uri'])

    # mark as unsubscribed in the signups
    for user_signup in signups:
        signup_model.delete_signup(address, user_signup['sequence'])

    mailgun_api.delete_all_unsubscribes(address)


text:
form .field-multiple-table th.field-label {
  padding-right: 0;
}
form .field-multiple-table td.field-multiple-drag {
  padding-left: 0;
}
form .field-multiple-table td.field-multiple-drag a.tabledrag-handle{
  padding-left: .5em;
}
.field-label-inline .field-label,
.field-label-inline .field-items {
  float: right;
}


text:
<?php
        $description = "";
        $review_id   = Atomik::get('review_id');
        $review      = Atomik_Db::findAll('reviews');
        $review_type = Atomik_Db::findAll('review_type','','type');
        $today_date  = date('Y-m-d');
        foreach ($review as $row_review):
          if  ($row_review['id'] == $review_id) {
            //$description=$row_review['managed_by'];
            foreach ($review_type as $row_review_type):
                if  ($row_review_type['id'] == $row_review['type']){
                    $description = $row_review_type['type'];
                }
            endforeach;
            /* Convert date to display nicely */
            require_once("../includes/calendrier/calendrier.php");
            $cut_date = substr($row_review['date'],0,10);
            $date=PrettyDate ($cut_date);
            /* check if the review is in the past or in the future */
            if ($cut_date < $today_date)
                $description = "Baseline for the review ".$description." led by ".$row_review['managed_by']." and performed on ".$date;
            else
                $description = "Baseline for the review ".$description." led by ".$row_review['managed_by']." and planned on ".$date;
            break;
          }
        endforeach;
		Atomik::set('descr', $description);


text:
chorus.views.CreateChorusViewSidebar = chorus.views.Sidebar.extend({
    constructorName: 'CreateChorusViewSidebar',
    templateName: "dataset_create_chorus_view_sidebar",

    events: {
        "click button.create": "createChorusView",
        "click a.remove": "removeColumnClicked",
        "click img.delete": "removeJoinClicked",
        "click a.preview": "previewSqlLinkClicked",
        "click a.add_join": "launchManageJoinTableDialog"
    },

    setup: function() {
        this.subscribePageEvent("column:selected", this.addColumn);
        this.subscribePageEvent("column:deselected", this.removeColumn);
        this.chorusView = this.model.deriveChorusView();
        this.chorusView.aggregateColumnSet = this.options.aggregateColumnSet;
        this.listenTo(this.chorusView, "change", this.render);
    },

    teardown: function() {
        this.options.aggregateColumnSet.each(function(column) { delete column.selected; });
        this._super("teardown", arguments);
    },

    postRender: function() {
        this.$("a.preview, button.create").data("parent", this);
        this.$("a.add_join").data("chorusView", this.chorusView);
        this._super("postRender");
    },

    additionalContext: function(ctx) {
        return {
            columns: this.chorusView.sourceObjectColumns,
            joins: this.chorusView.joins
        };
    },

    addColumn: function(column) {
        this.chorusView.addColumn(column);
        this.$("button.create").prop("disabled", false);
    },

    removeColumn: function(column) {
        if (!column) {
            return;
        }
        this.chorusView.removeColumn(column);
    },

    removeColumnClicked: function(e) {
        e.preventDefault();
        var $li = $(e.target).closest("li");
        var column = this.chorusView.aggregateColumnSet.get($li.data('cid'));
        this.removeColumn(column);
        chorus.PageEvents.trigger("column:removed", column);
    },

    removeJoinClicked: function(e) {
        var cid = $(e.target).closest("div.join").data("cid");
        var dialog = new chorus.alerts.RemoveJoinConfirmAlert({dataset: this.chorusView.getJoinDatasetByCid(cid), chorusView: this.chorusView});
        dialog.launchModal();
    },

    previewSqlLinkClicked: function(e) {
        e.preventDefault();
        this.chorusView.set({ query: this.sql() });
        var dialog = new chorus.dialogs.SqlPreview({ model: this.chorusView });
        dialog.launchModal();
    },

    createChorusView: function(e) {
        e && e.preventDefault();
        this.chorusView.set({ query: this.sql() });
        var dialog = new chorus.dialogs.VerifyChorusView({ model : this.chorusView });
        dialog.launchModal();
    },

    whereClause: function() {
        return this.filters.whereClause();
    },

    sql: function() {
        return [this.chorusView.generateSelectClause(), this.chorusView.generateFromClause(), this.whereClause()].join("\n");
    },

    launchManageJoinTableDialog: function(e) {
        e.preventDefault();
        var dialog = new chorus.dialogs.ManageJoinTables({
            pageModel: this.model,
            chorusView: this.chorusView
        });
        dialog.launchModal();
    }
});


text:
package org.apache.roller.pojos;

import java.io.Serializable;
import java.util.Date;
import org.apache.roller.pojos.Template;

/**
 * A Theme based implementation of a Template.  A ThemeTemplate represents a
 * template which is part of a shared Theme.
 */
public class ThemeTemplate implements Template, Serializable {

    private String id = null;
    private String name = null;
    private String description = null;
    private String contents = null;
    private String link = null;
    private Date lastModified = null;
    private String templateLanguage = null;
    private boolean hidden = false;
    private boolean navbar = false;
    private String decoratorName = null;

    private Theme myTheme = null;

    public ThemeTemplate() {}

    public ThemeTemplate(Theme theme, String id, String name, String desc,
            String contents, String link, Date date, String tempLang,
            boolean hid, boolean navbar, String decor) {

        this.myTheme = theme;
        this.id = id;
        this.name = name;
        this.description = desc;
        this.contents = contents;
        this.link = link;
        this.lastModified = date;
        this.templateLanguage = tempLang;
        this.hidden = hid;
        this.navbar = navbar;
        this.decoratorName = decor;
    }

    public Template getDecorator() {
        if(decoratorName != null && !id.equals(decoratorName)) {
            return myTheme.getTemplate(decoratorName);
        }
        return null;
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public String getContents() {
        return contents;
    }

    public void setContents(String contents) {
        this.contents = contents;
    }

    public Date getLastModified() {
        return lastModified;
    }

    public void setLastModified(Date lastModified) {
        this.lastModified = lastModified;
    }

    public String getLink() {
        return link;
    }

    public void setLink(String link) {
        this.link = link;
    }

    public String getTemplateLanguage() {
        return templateLanguage;
    }

    public void setTemplateLanguage(String templateLanguage) {
        this.templateLanguage = templateLanguage;
    }

    public boolean isHidden() {
        return hidden;
    }

    public void setHidden(boolean isHidden) {
        this.hidden = isHidden;
    }

    public boolean isNavbar() {
        return navbar;
    }

    public void setNavbar(boolean navbar) {
        this.navbar = navbar;
    }

    public String getDecoratorName() {
        return decoratorName;
    }

    public void setDecoratorName(String decorator) {
        this.decoratorName = decorator;
    }

    public String toString() {
        return (id + "," + name + "," + description + "," + link + "," +
                lastModified + "\n\n" + contents + "\n");
    }

}


text:
Demo app for OpenCrowd's ElasticSearch Entitlements Webinar
===========================================================

This is a simple Django app to illustrate the scenario used in
OpenCrowd's ElasticSearch Entitlements webinar.
([Watch the webinar](http://opencrowd.com/media/#entitlements))

For each type of user test, the generated query sent to
ElasticSearch is rendered so that you can see how the entitlement
scheme used in the scenario is implemented.

This app depends on the __requests__ and __django__ packages.  It
also requires a running ElasticSearch instance.

You can get it started by:

    $ ./manage.py init_demo
    $ ./manage.py runserver


text:
<?xml version="1.0" encoding="UTF-8"?>
<VAST version="2.0">
  <Ad id="602833">
  <InLine>
    <AdTitle>VAST 2.0 Instream Test 1</AdTitle>
    <Description>VAST 2.0 Instream Test 1</Description>
  <Creatives>
    <Creative AdID="602833-Companion">
      <CompanionAds>
        <Companion width="456" height="123" id="dontmerge-1">
          <StaticResource creativeType="image/jpeg">static-dontmerge-1.jpg</StaticResource>
          <CompanionClickThrough>http://companion-dontmerge-1.inline.test.com</CompanionClickThrough>
        </Companion>
        <Companion width="200" height="200">
          <IFrameResource>/inline-size</IFrameResource>
          <CompanionClickThrough>http://companion-size.inline.test.com</CompanionClickThrough>
        </Companion>
        <Companion id="merge">
          <IFrameResource>/inline-id</IFrameResource>
          <StaticResource creativeType="image/gif">static-inline.gif</StaticResource>
          <StaticResource creativeType="image/png">static-inline.png</StaticResource>
          <CompanionClickThrough>http://companion-id.inline.test.com</CompanionClickThrough>
        </Companion>
      </CompanionAds>
    </Creative>
  </Creatives>
  </InLine>
  </Ad>
</VAST>


text:
<?php
/**
* UserApplePie v4 Messages Controller Plugin
*
* UserApplePie - Messages Plugin
* @author David (DaVaR) Sargent <davar@userapplepie.com>
* @version 2.1.1 for UAP v.4.3.0
*/

namespace App\Plugins\Messages\Controllers;

use App\System\Controller,
  App\System\Load,
  Libs\Auth\Auth,
  Libs\Csrf,
  Libs\Request,
  Libs\Url,
  Libs\SuccessMessages,
  Libs\ErrorMessages;

class Messages extends Controller{

	private $model;
    private $pages;

	public function __construct(){
		parent::__construct();
		$this->model = new \App\Plugins\Messages\Models\Messages();
        $this->pages = new \Libs\Paginator(MESSAGE_PAGEINATOR_LIMIT);
	}

  // Inbox - Displays all
	public function messages(){

    /** Check to see if user is logged in **/
    if($data['isLoggedIn'] = $this->auth->isLogged()){
      //** User is logged in - Get their data **/
      $u_id = $this->auth->user_info();
      $data['currentUserData'] = $this->user->getCurrentUserData($u_id);
      $data['isAdmin'] = $this->user->checkIsAdmin($u_id);
    }else{
      /** User Not logged in - kick them out **/
      \Libs\ErrorMessages::push('You are Not Logged In', 'Login');
    }

		// Collect Data for view
		$data['title'] = "My Private Messages";
		$data['welcome_message'] = "Welcome to Your Private Messages";

    // Get total unread messages count
    $data['unread_messages'] = $this->model->getUnreadMessages($u_id);

    // Get total messages count
    $data['total_messages'] = $this->model->getTotalMessages($u_id);
    $data['total_messages_outbox'] = $this->model->getTotalMessagesOutbox($u_id);

    // Let view know inbox is in use
    $data['inbox'] = "true";

    // Setup Breadcrumbs
		$data['breadcrumbs'] = "

Private Messages

		";

        // Ready the token!
        $data['csrf_token'] = Csrf::makeToken('messages');

        // Check for new messages in inbox
        $data['new_messages_inbox'] = $this->model->getUnreadMessages($u_id);

        // Message Quota Goods
        // Get total count of messages
        $data['quota_msg_ttl'] = $data['total_messages'];
        $data['quota_msg_limit'] = MESSAGE_QUOTA_LIMIT;
        $data['quota_msg_percentage'] = $this->model->getPercentage($data['quota_msg_ttl'], $data['quota_msg_limit']);

        // Message Quota Goods
        // Get total count of messages
        $data['quota_msg_ttl_ob'] = $data['total_messages_outbox'];
        $data['quota_msg_limit_ob'] = MESSAGE_QUOTA_LIMIT;
        $data['quota_msg_percentage_ob'] = $this->model->getPercentage($data['quota_msg_ttl_ob'], $data['quota_msg_limit_ob']);

        /* Send data to view */
        Load::ViewPlugin("messages", $data, "messages_sidebar::Left", "Messages");

	}

	// Inbox - Displays all
	public function inbox($current_page = null){

    /** Check to see if user is logged in **/
    if($data['isLoggedIn'] = $this->auth->isLogged()){
      //** User is logged in - Get their data **/
      $u_id = $this->auth->user_info();
      $data['currentUserData'] = $this->user->getCurrentUserData($u_id);
      $data['isAdmin'] = $this->user->checkIsAdmin($u_id);
    }else{
      /** User Not logged in - kick them out **/
      \Libs\ErrorMessages::push('You are Not Logged In', 'Login');
    }

    // Hidden Auto Check to make sure that messages that are marked
    // for delete by both TO and FROM users are removed from database
    $this->model->cleanUpMessages();

    // Check to make sure user is trying to delete messages
		if(isset($_POST['submit'])){

			// Check to make sure the csrf token is good
			if (Csrf::isTokenValid('messages')) {
				// Get Post Data
				$actions = Request::post('actions');
				$msg_id = Request::post('msg_id');

        // Check to see if user is deleteing messages
        if($actions == "delete"){
  				// Delete selected messages from Inbox
          if(isset($msg_id)){
            foreach($msg_id as $del_msg_id){
      				if($this->model->deleteMessageInbox($u_id, $del_msg_id)){
      					// Success
                $m_del_success[] = true;
      				}else{
      					// Fail
                $m_del_error[] = true;
      				}
            }
            if(count($m_del_success) >= 1){
              // Message Delete Success Display
              SuccessMessages::push('You Have Successfully Deleted Messages', 'MessagesInbox');
            }else if(count($m_del_error) >= 1){
              // Message Delete Error Display
              ErrorMessages::push('Messages Delete Failed', 'MessagesInbox');
            }
          }else{
            // Fail
            ErrorMessages::push('Nothing Was Selected to be Deleted', 'MessagesInbox');
          }
        }
        // Check to see if user is marking messages as read
        if($actions == "mark_read"){
  				// Mark messages as read for all requested messages
          if(isset($msg_id)){
            foreach($msg_id as $del_msg_id){
      				if($this->model->markReadMessageInbox($u_id, $del_msg_id)){
      					// Success
                $m_read_success[] = true;
      				}else{
      					// Fail
                $m_read_error[] = true;
      				}
            }
            if(isset($m_read_success) && count($m_read_success) >= 1){
              // Message Delete Success Display
              SuccessMessages::push('You Have Successfully Marked Messages as Read', 'MessagesInbox');
            }else if(isset($m_read_error) && count($m_read_error) >= 1){
              // Message Delete Error Display
              ErrorMessages::push('Mark Messages Read Failed', 'MessagesInbox');
            }

          }else{
            // Fail
            ErrorMessages::push('Nothing Was Selected to be Marked as Read', 'MessagesInbox');
          }
        }
			}
		}

		// Collect Data for view
		$data['title'] = "My Private Messages Inbox";
		$data['welcome_message'] = "Welcome to Your Private Messages Inbox";

    // Sets "by" username display
    $data['tofrom'] = " by ";
    $data['inboxoutbox'] = "inbox";

    // Get all message that are to current user
    $data['messages'] = $this->model->getInbox($u_id, $this->pages->getLimit($current_page, MESSAGE_PAGEINATOR_LIMIT));

    // Set total number of messages for paginator
    $total_num_messages = $this->model->getTotalMessages($u_id);
    $this->pages->setTotal($total_num_messages);

    // Send page links to view
    $pageFormat = SITE_URL."MessagesInbox/"; // URL page where pages are
    $data['pageLinks'] = $this->pages->pageLinks($pageFormat, null, $current_page);

    // Message Quota Goods
    // Get total count of messages
    $data['quota_msg_ttl'] = $total_num_messages;
    $data['quota_msg_limit'] = MESSAGE_QUOTA_LIMIT;
    $data['quota_msg_percentage'] = $this->model->getPercentage($data['quota_msg_ttl'], $data['quota_msg_limit']);

    // Check to see if user has reached message limit, if so show warning
    if($data['quota_msg_percentage'] >= "100"){
      $error = "
                  Your Inbox is Full!  Other Site Members Can NOT send you any messages!";
    }else if($data['quota_msg_percentage'] >= "90"){
      $error = "
                  Warning! Your Inbox is Almost Full!";
    }

    // Output errors if any
    if(isset($error)){ $data['error'] = $error; };

    // Let view know inbox is in use
    $data['inbox'] = "true";
    // What box are we showing
    $data['what_box'] = "Inbox";

    // Setup Breadcrumbs
		$data['breadcrumbs'] = "

Private Messages

".$data['title']."

		";
    $data['csrf_token'] = Csrf::makeToken('messages');

    // Include Java Script for check all feature
    $data['js'] = "";

    // Check for new messages in inbox
    $data['new_messages_inbox'] = $this->model->getUnreadMessages($u_id);

        /* Send data to view */
        Load::ViewPlugin("messages_list", $data, "messages_sidebar::Left", "Messages");

	}

  // Outbox - Displays all
	public function outbox($current_page = null){

    /** Check to see if user is logged in **/
    if($data['isLoggedIn'] = $this->auth->isLogged()){
      //** User is logged in - Get their data **/
      $u_id = $this->auth->user_info();
      $data['currentUserData'] = $this->user->getCurrentUserData($u_id);
      $data['isAdmin'] = $this->user->checkIsAdmin($u_id);
    }else{
      /** User Not logged in - kick them out **/
      \Libs\ErrorMessages::push('You are Not Logged In', 'Login');
    }

    // Check to make sure user is trying to delete messages
		if(isset($_POST['submit'])){

			// Check to make sure the csrf token is good
			if (Csrf::isTokenValid('messages')) {
				// Get Post Data
				$actions = Request::post('actions');
				$msg_id = Request::post('msg_id');

        // Check to see if user is deleteing messages
        if($actions == "delete"){
  				// Delete selected messages from Outbox
          if(isset($msg_id)){
            foreach($msg_id as $del_msg_id){
      				if($this->model->deleteMessageOutbox($u_id, $del_msg_id)){
      					// Success
                $m_del_success[] = true;
      				}else{
      					// Fail
                $m_del_error[] = true;
      				}
            }
            if(count($m_del_success) >= 1){
              // Message Delete Success Display
              SuccessMessages::push('You Have Successfully Deleted Messages', 'MessagesOutbox');
            }else if(count($m_del_error) >= 1){
              // Message Delete Error Display
              ErrorMessages::push('Messages Delete Failed', 'MessagesOutbox');
            }

          }else{
            // Fail
            ErrorMessages::push('Nothing Was Selected to be Deleted', 'MessagesOutbox');
          }
        }
			}
		}

		// Collect Data for view
		$data['title'] = "My Private Messages Outbox";
		$data['welcome_message'] = "Welcome to your Private Messages Outbox";

    // Sets "to" username display
    $data['tofrom'] = " to ";
    $data['inboxoutbox'] = "outbox";

    // Get all message that are to current user
    $data['messages'] = $this->model->getOutbox($u_id, $this->pages->getLimit($current_page, MESSAGE_PAGEINATOR_LIMIT));

    // Set total number of messages for paginator
    $total_num_messages = $this->model->getTotalMessagesOutbox($u_id);
    $this->pages->setTotal($total_num_messages);
    // Send page links to view
    $pageFormat = SITE_URL."MessagesOutbox/"; // URL page where pages are
    $data['pageLinks'] = $this->pages->pageLinks($pageFormat, null, $current_page);

    // Message Quota Goods
    // Get total count of messages
    $data['quota_msg_ttl'] = $total_num_messages;
    $data['quota_msg_limit'] = MESSAGE_QUOTA_LIMIT;
    $data['quota_msg_percentage'] = $this->model->getPercentage($data['quota_msg_ttl'], $data['quota_msg_limit']);

    // Check to see if user has reached message limit, if so show warning
    if($data['quota_msg_percentage'] >= "100"){
      $error[] = "
                  Your Outbox is Full!  You Can NOT send any messages!";
    }else if($data['quota_msg_percentage'] >= "90"){
      $error[] = "
                  Warning! Your Outbox is Almost Full!";
    }

    // What box are we showing
    $data['what_box'] = "Outbox";

    // Output errors if any
    if(isset($error)){ $data['error'] = $error; };

    // Setup Breadcrumbs
		$data['breadcrumbs'] = "

Private Messages

".$data['title']."

		";
    $data['csrf_token'] = Csrf::makeToken('messages');

    // Include Java Script for check all feature
    $data['js'] = "";

    // Check for new messages in inbox
    $data['new_messages_inbox'] = $this->model->getUnreadMessages($u_id);

        /* Send data to view */
        Load::ViewPlugin("messages_list", $data, "messages_sidebar::Left", "Messages");

	}

  // View Message - Displays requested message
	public function view($m_id){

    /** Check to see if user is logged in **/
    if($data['isLoggedIn'] = $this->auth->isLogged()){
      //** User is logged in - Get their data **/
      $u_id = $this->auth->user_info();
      $data['currentUserData'] = $this->user->getCurrentUserData($u_id);
      $data['isAdmin'] = $this->user->checkIsAdmin($u_id);
    }else{
      /** User Not logged in - kick them out **/
      \Libs\ErrorMessages::push('You are Not Logged In', 'Login');
    }

    // Check to make sure user is trying to send new message
    if(isset($_POST['submit'])){
      // Check to make sure the csrf token is good
      if (Csrf::isTokenValid('messages')) {
        $msg_id = Request::post('message_id');
        if(isset($msg_id)){
          if($this->model->deleteMessageInbox($u_id, $msg_id)){
            // Success
            $m_del_success_inbox = true;
          }else{
            if($this->model->deleteMessageOutbox($u_id, $msg_id)){
              // Success
              $m_del_success_outbox = true;
            }else{
              // Fail
              $m_del_error = true;
            }
          }
        }
        if($m_del_success_inbox == true){
          // Message Delete Success Display
          SuccessMessages::push('You Have Successfully Deleted Message', 'MessagesInbox');
        }else if($m_del_success_outbox == true){
          // Message Delete Success Display
          SuccessMessages::push('You Have Successfully Deleted Message', 'MessagesOutbox');
        }else if($m_del_error == true){
          // Message Delete Error Display
          ErrorMessages::push('Message Delete Failed', 'Messages');
        }
      }
    }else{

      // Check to see if requested message exists and user is related to it
      if($this->model->checkMessagePerm($u_id, $m_id)){
        // Message exist and user is related
    		// Collect Data for view
    		$data['title'] = "My Private Message";
    		$data['welcome_message'] = "Welcome to Your Private Message";

        // Get requested message data
        $data['message'] = $this->model->getMessage($m_id, $u_id);
      }else{
        // User Does not own message or it does not exist
        $data['title'] = "My Private Message - Error!";
        $data['welcome_message'] = "The requested private message does not exist!";
        $data['msg_error'] = "true";
      }
      // Setup Breadcrumbs
  		$data['breadcrumbs'] = "

Private Messages

".$data['title']."

  		";
      $data['csrf_token'] = Csrf::makeToken('messages');

      // Check for new messages in inbox
      $data['new_messages_inbox'] = $this->model->getUnreadMessages($u_id);

    }

    /* Send data to view */
    Load::ViewPlugin("message_display", $data, "messages_sidebar::Left", "Messages");

	}

    /*
    ** New Message
    ** Displays form to create a new message or reply
    */
	public function newmessage($to_user = NULL, $subject = NULL){

        /** Check to see if user is logged in **/
        if($data['isLoggedIn'] = $this->auth->isLogged()){
            //** User is logged in - Get their data **/
            $u_id = $this->auth->user_info();
            $data['currentUserData'] = $this->user->getCurrentUserData($u_id);
            $data['isAdmin'] = $this->user->checkIsAdmin($u_id);
        }else{
            /** User Not logged in - kick them out **/
            ErrorMessages::push('You are Not Logged In', 'Login');
        }

        // Check to see if user is over quota
        // Disable New Message Form is they are
        if($this->model->checkMessageQuota($u_id)){
        // user is over limit, disable new message form
        $data['hide_form'] = "true";
            $error[] = "
                      Your Outbox is Full!  You Can NOT send any messages!";
        }

		// Check to make sure user is trying to send new message
		if(isset($_POST['submit'])){
			// Check to make sure the csrf token is good
			if (Csrf::isTokenValid('messages')) {
				// Get data from post
        (isset($_POST['to_username'])) ? $to_username = strip_tags(Request::post('to_username')) : $to_username = "";
        (isset($_POST['subject'])) ? $subject = strip_tags(Request::post('subject')) : $subject = "";
        (isset($_POST['content'])) ? $content = htmlspecialchars(Request::post('content')) : $content = "";
        (isset($_POST['reply'])) ? $reply = htmlspecialchars(Request::post('reply')) : $reply = "";

                // Check to see if this is coming from a reply button
                if($reply != "true"){
                    // Check to make sure user completed all required fields in form
                    if(empty($to_username)){
                        // Username field is empty
                        $error[] = 'Username Field is Blank!';
                    }
                    if(empty($subject)){
                        // Subject field is empty
                        $error[] = 'Subject Field is Blank!';
                    }
                    if(empty($content)){
                        // Username field is empty
                        $error[] = 'Message Content Field is Blank!';
                    }
                    // Check for errors before sending message
                    if(!isset($error)){
                        // Get the userID of to username
                        $to_userID = $this->model->getUserIDFromUsername($to_username);
                        // Check to make sure user exists in Database
                        if(isset($to_userID)){
                            // Check to see if to user's inbox is not full
                            if($this->model->checkMessageQuotaToUser($to_userID)){
			                    // Run the Activation script
                                if($this->model->sendmessage($to_userID, $u_id, $subject, $content)){
                                    // Success
                                    SuccessMessages::push('You Have Successfully Sent a Private Message', 'Messages');
                                    $data['hide_form'] = "true";
		                        }else{
                                    // Fail
                                    $error[] = 'Message Send Failed';
                                }
                            }else{
                                // To user's inbox is full.  Let sender know message was not sent
                                $error[] = '${to_username}'s Inbox is Full!  Sorry, Message was NOT sent!';
                            }
                        }else{
                            // User does not exist
                            $error[] = 'Message Send Failed - To User Does Not Exist';
                        }
                    }// End Form Complete Check
                }else{
                    // Get data from reply $_POST
                    (isset($_POST['subject'])) ? $subject = strip_tags(Request::post('subject')) : $subject = "";
                    (isset($_POST['content'])) ? $content = htmlspecialchars(str_replace("
", " ", Request::post('content'))) : $content = "";
                    (isset($_POST['date_sent'])) ? $date_sent = strip_tags(Request::post('date_sent')) : $date_sent = "";
                    // Add Reply details to subject ex: RE:
                    $data['subject'] = "RE: ".$subject;
                    // Clean up content so it looks pretty
                    $content_reply = "

 ##############################";
                    $content_reply .= "
 # PREVIOUS MESSAGE";
                    $content_reply .= "
 # From: $to_username";
                    $content_reply .= "
 # Sent: $date_sent ";
                    $content_reply .= "
 ##############################

";
                    $content_reply .= $content;
                    $content_reply = str_replace("
", " ", $content_reply);
                    $data['content'] = $content_reply;
                }// End Reply Check
			}
		}

        // Check to see if there were any errors, if so then auto load form data
        if(isset($error) && !isset($data['subject']) && !isset($data['content'])){
            // Auto Fill form to make things eaiser for user
            $data['subject'] = Request::post('subject');
            $data['content'] = Request::post('content');
            // Output errors if any
            if(!empty($error)){ $data['error'] = $error; };
        }
		if(!isset($data['subject'])){ $data['subject'] = $subject; }

        // Collect Data for view
        $data['title'] = "My Private Message";
        $data['welcome_message'] = "Welcome to Your Private Message Creator";
        $data['csrf_token'] = Csrf::makeToken('messages');

        // Check to see if username is in url or post
        if(isset($to_user)){
            $data['to_username'] = $to_user;
        }else{
            $data['to_username'] = Request::post('to_username');
        }

        // Setup Breadcrumbs
		$data['breadcrumbs'] = "

Private Messages

".$data['title']."

		";

        // Get requested message data
        //$data['message'] = $this->model->getMessage($m_id);

        // Check for new messages in inbox
        $data['new_messages_inbox'] = $this->model->getUnreadMessages($u_id);

        /* Send data to view */
        Load::ViewPlugin("message_new", $data, "messages_sidebar::Left", "Messages");

	}

}


text:
'use strict';

/**
 * @ngdoc function
 * @name clientApp.controller:MainCtrl
 * @description
 * # MainCtrl
 * Controller of the clientApp
 */
angular.module('clientApp').controller('BlockUnblockCtrl', ['$scope', '$timeout', 'UserService', function ($scope, $timeout, UserService) {

        function init() {

            $scope.success = false;
            $scope.error = false;
        }

        $scope.$on('blockUnblock', function (e, user) {
            $timeout(function () {
                $scope.success = false;
                $scope.error = false;
            });
            $scope.isBlocked = undefined;
            $scope.isBlocked = !Boolean(user.isBlocked);
            $scope.user = user;
            $('#blockUnblockModal').modal('show');
        });

        $scope.$on('blockUnblockModalIsHiding', function () {
            $timeout(function () {
                $scope.isBlocked = undefined;
            });
        });

        $scope.$watch('isBlocked', function (newValue, oldValue) {
            if (typeof newValue === 'undefined' || typeof oldValue === 'undefined') {
                return;
            }
            if (newValue === oldValue) {
                return;
            }

            UserService.setIsBlocked($scope.user.userId, !newValue, function (err, data) {
                if (err) {
                    $scope.error = true;
                    $scope.respMessage = 'Oops-a-daisy! There went something wrong :(';
                    return;
                }
                $scope.success = true;
                $scope.respMessage = data.message;
                $scope.getUsers();
            });
        });

        init();
}]);


text:
require File.expand_path(File.join(File.dirname(__FILE__), "helper"))

class ResponseCodeMechTest < Test::Unit::TestCase
  def setup
    @agent = WWW::Mechanize.new
  end

  def test_eof_error_loop
    assert_raises(EOFError) {
      @agent.get("http://localhost/http_headers?Content-Length=300")
    }
  end

  def test_redirect
    @agent.get("http://localhost/response_code?code=300")
    assert_equal("http://localhost/index.html",
      @agent.current_page.uri.to_s)

    @agent.get("http://localhost/response_code?code=301")
    assert_equal("http://localhost/index.html",
      @agent.current_page.uri.to_s)

    @agent.get("http://localhost/response_code?code=302")
    assert_equal("http://localhost/index.html",
      @agent.current_page.uri.to_s)

    @agent.get("http://localhost/response_code?code=303")
    assert_equal("http://localhost/index.html",
      @agent.current_page.uri.to_s)

    @agent.get("http://localhost/response_code?code=307")
    assert_equal("http://localhost/index.html",
      @agent.current_page.uri.to_s)
  end

  def test_do_not_follow_redirect
    @agent.redirect_ok = false

    @agent.get("http://localhost/response_code?code=302")
    assert_equal("http://localhost/response_code?code=302",
      @agent.current_page.uri.to_s)
  end

  def test_error
    @agent = WWW::Mechanize.new
    begin
      @agent.get("http://localhost/response_code?code=500")
    rescue WWW::Mechanize::ResponseCodeError => err
      assert_equal("500", err.response_code)
    end
  end
end


text:
package org.jabref.logic.importer.fetcher;

import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.time.DateTimeException;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.time.temporal.TemporalAccessor;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Locale;
import java.util.Optional;
import java.util.function.Predicate;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.jabref.logic.importer.FetcherException;
import org.jabref.logic.importer.IdBasedFetcher;
import org.jabref.logic.importer.ImportFormatPreferences;
import org.jabref.logic.importer.ParseException;
import org.jabref.logic.importer.fileformat.BibtexParser;
import org.jabref.logic.l10n.Localization;
import org.jabref.logic.net.URLDownload;
import org.jabref.model.entry.BibEntry;
import org.jabref.model.entry.FieldName;
import org.jabref.model.strings.StringUtil;
import org.jabref.model.util.DummyFileUpdateMonitor;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class IacrEprintFetcher implements IdBasedFetcher {

    public static final String NAME = "IACR eprints";

    private static final Logger LOGGER = LoggerFactory.getLogger(IacrEprintFetcher.class);
    private static final Pattern DATE_FROM_WEBSITE_AFTER_2000_PATTERN = Pattern.compile("[a-z ]+(\\d{1,2} [A-Za-z][a-z]{2} \\d{4})");
    private static final Pattern DATE_FROM_WEBSITE_BEFORE_2000_PATTERN = Pattern.compile("[A-Za-z ]+? ([A-Za-z][a-z]{2,10} \\d{1,2}(th|st|nd|rd)?, \\d{4})\\.?");
    private static final Pattern WITHOUT_LETTERS_SPACE = Pattern.compile("[^0-9/]");

    private static final DateTimeFormatter DATE_FORMAT_WEBSITE_AFTER_2000 = DateTimeFormatter.ofPattern("d MMM yyyy", Locale.US);
    private static final DateTimeFormatter DATE_FORMAT_WEBSITE_BEFORE_2000_LONG_MONTHS = DateTimeFormatter.ofPattern("MMMM d['th']['st']['nd']['rd'] yyyy", Locale.US);
    private static final DateTimeFormatter DATE_FORMAT_WEBSITE_BEFORE_2000_SHORT_MONTHS = DateTimeFormatter.ofPattern("MMM d['th']['st']['nd']['rd'] yyyy", Locale.US);
    private static final DateTimeFormatter DATE_FORMAT_BIBTEX = DateTimeFormatter.ISO_LOCAL_DATE;
    private static final Predicate<String> IDENTIFIER_PREDICATE = Pattern.compile("\\d{4}/\\d{3,5}").asPredicate();
    private static final String CITATION_URL_PREFIX = "https://eprint.iacr.org/eprint-bin/cite.pl?entry=";
    private static final String DESCRIPTION_URL_PREFIX = "https://eprint.iacr.org/";
    private static final Charset WEBSITE_CHARSET = StandardCharsets.ISO_8859_1;

    private final ImportFormatPreferences prefs;

    public IacrEprintFetcher(ImportFormatPreferences prefs) {
        this.prefs = prefs;
    }

    @Override
    public Optional<BibEntry> performSearchById(String identifier) throws FetcherException {
        String identifierWithoutLettersAndSpaces = WITHOUT_LETTERS_SPACE.matcher(identifier).replaceAll(" ").trim();

        if (!IDENTIFIER_PREDICATE.test(identifierWithoutLettersAndSpaces)) {
            throw new FetcherException(Localization.lang("Invalid identifier: '%0'.", identifier));
        }

        Optional<BibEntry> entry = createEntryFromIacrCitation(identifierWithoutLettersAndSpaces);

        if (entry.isPresent()) {
            setAdditionalFields(entry.get(), identifierWithoutLettersAndSpaces);
        }

        return entry;
    }

    private Optional<BibEntry> createEntryFromIacrCitation(String validIdentifier) throws FetcherException {
        String bibtexCitationHtml = getHtml(CITATION_URL_PREFIX + validIdentifier);
        if (bibtexCitationHtml.contains("No such report found")) {
            throw new FetcherException(Localization.lang("No results found."));
        }
        String actualEntry = getRequiredValueBetween("
", "
", bibtexCitationHtml);

        try {
            return BibtexParser.singleFromString(actualEntry, prefs, new DummyFileUpdateMonitor());
        } catch (ParseException e) {
            throw new FetcherException(Localization.lang("Entry from %0 could not be parsed.", "IACR"), e);
        }
    }

    private void setAdditionalFields(BibEntry entry, String identifier) throws FetcherException {
        String entryUrl = DESCRIPTION_URL_PREFIX + identifier;
        String descriptiveHtml = getHtml(entryUrl);
        entry.setField(FieldName.ABSTRACT, getAbstract(descriptiveHtml));
        String dateStringAsInHtml = getRequiredValueBetween("Date: ", "
", descriptiveHtml);
        entry.setField(FieldName.DATE, getLatestDate(dateStringAsInHtml));

        if (isFromOrAfterYear2000(entry)) {
            String version = getVersion(identifier, descriptiveHtml);
            entry.setField(FieldName.VERSION, version);
            entry.setField(FieldName.URL, entryUrl + "/" + version);
        } else {
            // No version information for entries before year 2000
            entry.setField(FieldName.URL, entryUrl);
        }
    }

    private String getVersion(String identifier, String descriptiveHtml) throws FetcherException {
        String startOfVersionString = "Version: <a href=\"/" + identifier + "/";
        String version = getRequiredValueBetween(startOfVersionString, "\"", descriptiveHtml);
        return version;
    }

    private String getAbstract(String descriptiveHtml) throws FetcherException {
        String abstractText = getRequiredValueBetween("Abstract: ", "
", descriptiveHtml);
        // for some reason, all spaces are doubled...
        abstractText = abstractText.replaceAll("\\s(\\s)", "$1");
        return abstractText;
    }

    private String getLatestDate(String dateStringAsInHtml) throws FetcherException {
        if (dateStringAsInHtml.contains("withdrawn")) {
            throw new FetcherException(Localization.lang("This paper has been withdrawn."));
        }
        String[] rawDates = dateStringAsInHtml.split(", \\D");
        List<String> formattedDates = new ArrayList<>();
        for (String rawDate : rawDates) {
            TemporalAccessor date = parseSingleDateFromWebsite(rawDate);
            if (date != null) {
                formattedDates.add(DATE_FORMAT_BIBTEX.format(date));
            }
        }

        if (formattedDates.isEmpty()) {
            throw new FetcherException(Localization.lang("Entry from %0 could not be parsed.", "IACR"));
        }

        Collections.sort(formattedDates, Collections.reverseOrder());
        return formattedDates.get(0);
    }

    private TemporalAccessor parseSingleDateFromWebsite(String dateStringFromWebsite) {
        TemporalAccessor date = null;
        // Some entries contain double spaces in the date string (which would break our regexs below)
        String dateStringWithoutDoubleSpaces = dateStringFromWebsite.replaceAll("\\s\\s+", " ");

        Matcher dateMatcherAfter2000 = DATE_FROM_WEBSITE_AFTER_2000_PATTERN.matcher(dateStringWithoutDoubleSpaces.trim());
        if (dateMatcherAfter2000.find()) {
            try {
                date = DATE_FORMAT_WEBSITE_AFTER_2000.parse(dateMatcherAfter2000.group(1));
            } catch (DateTimeParseException e) {
                LOGGER.warn("Date from IACR could not be parsed", e);
            }
        }

        // Entries before year 2000 use a variety of date formats - fortunately, we can match them with only two different
        // date formats (each of which differ from the unified format of post-2000 entries).
        Matcher dateMatcherBefore2000 = DATE_FROM_WEBSITE_BEFORE_2000_PATTERN.matcher(dateStringWithoutDoubleSpaces.trim());
        if (dateMatcherBefore2000.find()) {
            String dateWithoutComma = dateMatcherBefore2000.group(1).replace(",", "");
            try {
                date = DATE_FORMAT_WEBSITE_BEFORE_2000_LONG_MONTHS.parse(dateWithoutComma);
            } catch (DateTimeParseException e) {
                try {
                    date = DATE_FORMAT_WEBSITE_BEFORE_2000_SHORT_MONTHS.parse(dateWithoutComma);
                } catch (DateTimeException e1) {
                    LOGGER.warn("Date from IACR could not be parsed", e);
                    LOGGER.warn("Date from IACR could not be parsed", e1);
                }
            }
        }

        return date;
    }

    private String getHtml(String url) throws FetcherException {
        try {
            URLDownload download = new URLDownload(url);
            return download.asString(WEBSITE_CHARSET);
        } catch (IOException e) {
            throw new FetcherException(Localization.lang("Could not retrieve entry data from '%0'.", url), e);
        }
    }

    private String getRequiredValueBetween(String from, String to, String haystack) throws FetcherException {
        String value = StringUtil.substringBetween(haystack, from, to);
        if (value == null) {
            throw new FetcherException(Localization.lang("Entry from %0 could not be parsed.", "IACR"));
        } else {
            return value;
        }
    }

    private boolean isFromOrAfterYear2000(BibEntry entry) throws FetcherException {
        Optional<String> yearField = entry.getField(FieldName.YEAR);
        if (yearField.isPresent()) {
            return Integer.parseInt(yearField.get()) > 2000;
        }
        throw new FetcherException(Localization.lang("Entry from %0 could not be parsed.", "IACR"));
    }

    @Override
    public String getName() {
        return NAME;
    }
}


text:
<component name="libraryTable">
  <library name="support-annotations-25.3.1">
    <CLASSES>
      <root url="jar:///Volumes/MACBOOK-BACKUP/android-sdks-macosx/extras/android/m2repository/com/android/support/support-annotations/25.3.1/support-annotations-25.3.1.jar!/" />
    </CLASSES>
    <JAVADOC />
    <SOURCES>
      <root url="jar:///Volumes/MACBOOK-BACKUP/android-sdks-macosx/extras/android/m2repository/com/android/support/support-annotations/25.3.1/support-annotations-25.3.1-sources.jar!/" />
    </SOURCES>
  </library>
</component>


text:
<?php
namespace Travel\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * Users
 *
 * @ORM\Table(name="users")
 * @ORM\Entity
 */
class User
{
    /**
     * @var integer
     *
     * @ORM\Column(name="user_id", type="integer", nullable=false)
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="IDENTITY")
     */
    private $userId;

    /**
     * @var integer
     *
     * @ORM\Column(name="user_customer_id", type="integer", nullable=false)
     */
    private $userCustomerId;

    /**
     * @var string
     *
     * @ORM\Column(name="email", type="string", length=255, nullable=true)
     */
    private $email;

    /**
     * @var string
     *
     * @ORM\Column(name="email_verification", type="string", length=36, nullable=false)
     */
    private $emailVerification;

    /**
     * @var string
     *
     * @ORM\Column(name="username", type="string", length=90, nullable=false)
     */
    private $username;

    /**
     * @var string
     *
     * @ORM\Column(name="password", type="string", length=255, nullable=false)
     */
    private $password;

    /**
     * @var string
     *
     * @ORM\Column(name="password_open", type="string", length=255, nullable=true)
     */
    private $passwordOpen;

    /**
     * @var integer
     *
     * @ORM\Column(name="user_lastlogin", type="integer", nullable=false)
     */
    private $userLastlogin;

    /**
     * @var string
     *
     * @ORM\Column(name="user_host", type="string", length=255, nullable=false)
     */
    private $userHost;

    /**
     * @var string
     *
     * @ORM\Column(name="user_role", type="string", length=36, nullable=false)
     */
    private $userRole;

    /**
     * @var string
     *
     * @ORM\Column(name="user_status", type="string", length=90, nullable=false)
     */
    private $userStatus;

    /**
     * @var integer
     *
     * @ORM\Column(name="user_created", type="integer", nullable=false)
     */
    private $userCreated;

    /**
     * @var integer
     *
     * @ORM\Column(name="user_modified", type="integer", nullable=false)
     */
    private $userModified;

    /**
     * @ORM\OneToMany(targetEntity="Travel\Entity\Content", mappedBy="contentUserId")
     */
    private $createdContent;

    /**
	 * @return the $createdContent
	 */
	public function getCreatedContent() {
		return $this->createdContent;
	}

	/**
	 * @param \Doctrine\Common\Collections\ArrayCollection $createdContent
	 */
	public function setCreatedContent($createdContent) {
		$this->createdContent = $createdContent;
	}

	public function __construct() {
    	$this->createdContent = new \Doctrine\Common\Collections\ArrayCollection();
    }

	/**
	 * @return the $userId
	 */
	public function getUserId() {
		return $this->userId;
	}

	/**
	 * @param number $userId
	 */
	public function setUserId($userId) {
		$this->userId = $userId;
	}

	/**
	 * @return the $userCustomerId
	 */
	public function getUserCustomerId() {
		return $this->userCustomerId;
	}

	/**
	 * @param number $userCustomerId
	 */
	public function setUserCustomerId($userCustomerId) {
		$this->userCustomerId = $userCustomerId;
	}

	/**
	 * @return the $email
	 */
	public function getEmail() {
		return $this->email;
	}

	/**
	 * @param string $email
	 */
	public function setEmail($email) {
		$this->email = $email;
	}

	/**
	 * @return the $emailVerification
	 */
	public function getEmailVerification() {
		return $this->emailVerification;
	}

	/**
	 * @param string $emailVerification
	 */
	public function setEmailVerification($emailVerification) {
		$this->emailVerification = $emailVerification;
	}

	/**
	 * @return the $username
	 */
	public function getUsername() {
		return $this->username;
	}

	/**
	 * @param string $username
	 */
	public function setUsername($username) {
		$this->username = $username;
	}

	/**
	 * @return the $password
	 */
	public function getPassword() {
		return $this->password;
	}

	/**
	 * @param string $password
	 */
	public function setPassword($password) {
		$this->password = $password;
	}

	/**
	 * @return the $passwordOpen
	 */
	public function getPasswordOpen() {
		return $this->passwordOpen;
	}

	/**
	 * @param string $passwordOpen
	 */
	public function setPasswordOpen($passwordOpen) {
		$this->passwordOpen = $passwordOpen;
	}

	/**
	 * @return the $userLastlogin
	 */
	public function getUserLastlogin() {
		return $this->userLastlogin;
	}

	/**
	 * @param number $userLastlogin
	 */
	public function setUserLastlogin($userLastlogin) {
		$this->userLastlogin = $userLastlogin;
	}

	/**
	 * @return the $userHost
	 */
	public function getUserHost() {
		return $this->userHost;
	}

	/**
	 * @param string $userHost
	 */
	public function setUserHost($userHost) {
		$this->userHost = $userHost;
	}

	/**
	 * @return the $userRole
	 */
	public function getUserRole() {
		return $this->userRole;
	}

	/**
	 * @param string $userRole
	 */
	public function setUserRole($userRole) {
		$this->userRole = $userRole;
	}

	/**
	 * @return the $userStatus
	 */
	public function getUserStatus() {
		return $this->userStatus;
	}

	/**
	 * @param string $userStatus
	 */
	public function setUserStatus($userStatus) {
		$this->userStatus = $userStatus;
	}

	/**
	 * @return the $userCreated
	 */
	public function getUserCreated() {
		return $this->userCreated;
	}

	/**
	 * @param number $userCreated
	 */
	public function setUserCreated($userCreated) {
		$this->userCreated = $userCreated;
	}

	/**
	 * @return the $userModified
	 */
	public function getUserModified() {
		return $this->userModified;
	}

	/**
	 * @param number $userModified
	 */
	public function setUserModified($userModified) {
		$this->userModified = $userModified;
	}
}


text:
import Param from 'variables'
import {Ajax} from "platform/plain"

const apiUrl = (path) => `${Param.Api.root}${path}`

export default {
  login(data, success, failure) {
    Ajax.post(apiUrl('/login'), data, success, failure)
  },
  logout() {
    Ajax.post(apiUrl('/logout'), {}, v => true, e => false)
  },
  loginStatus(success, failure) {
    Ajax.get(apiUrl('/account/loginStatus'), {}, success, failure)
  },
  loginAccount(success) {
    Ajax.get(apiUrl('/account/loginAccount'), {}, success, e => false)
  }
}


text:
.. image:: https://img.shields.io/pypi/v/ipywidgets.svg
   :target: https://pypi.python.org/pypi/ipywidgets/
   :alt: Version Number

.. image:: https://img.shields.io/pypi/dm/ipywidgets.svg
   :target: https://pypi.python.org/pypi/ipywidgets/
   :alt: Number of PyPI downloads

Interactive HTML Widgets
========================

Interactive HTML widgets for Jupyter notebooks and the IPython kernel.

Usage
=====

.. code-block:: python

    from ipywidgets import IntSlider
    IntSlider()