text:
"""
conference.py -- Udacity conference server-side Python App Engine API;
uses Google Cloud Endpoints

API endpoints definition and helper functions

"""

from datetime import datetime, timedelta

import endpoints
from protorpc import messages
from protorpc import message_types
from protorpc import remote
from google.appengine.api import memcache
from google.appengine.api import taskqueue
from google.appengine.ext import ndb
from google.net.proto.ProtocolBuffer import ProtocolBufferDecodeError

from containers import CONF_GET_REQUEST, CONF_GET_SIMILAR, CONF_POST_REQUEST
from containers import CREATE_SESSION, SESSION_GET_REQUEST, SESSION_POST_REQUEST
from containers import SESSIONS_GET_REQUEST, SESSION_QUERY_TYPE
from containers import SESSION_QUERY_TIME, SPEAKER_GET_REQUEST, SPEAKER_BY_NAME

from models import ConflictException
from models import Profile, ProfileMiniForm, ProfileForm
from models import StringMessage, BooleanMessage
from models import Conference, ConferenceForm, ConferenceForms
from models import ConferenceQueryForm, ConferenceQueryMiniForm
from models import ConferenceQueryForms
from models import TeeShirtSize
from models import Session, SessionForm, SessionForms, SessionQueryForm
from models import Speaker, SpeakerForm, SpeakerForms

from settings import WEB_CLIENT_ID, ANDROID_CLIENT_ID, IOS_CLIENT_ID
from settings import ANDROID_AUDIENCE
from settings import MEMCACHE_ANNOUNCEMENTS_KEY, MEMCACHE_SPEAKER_KEY
from settings import ANNOUNCEMENT_TPL
from settings import DEFAULTS, SESSION_DEFAULTS, OPERATORS, FIELDS

from utils import getUserId

__author__ = 'wiseleywu@gmail.com (Wiseley Wu)'

# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
EMAIL_SCOPE = endpoints.EMAIL_SCOPE
API_EXPLORER_CLIENT_ID = endpoints.API_EXPLORER_CLIENT_ID
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

# def user_authentication(func):
#     """Decorator to authenticate a user during API call"""
#
#     def login_user(self, *args, **kwargs):
#         user = endpoints.get_current_user()
#         if not user:
#             raise endpoints.UnauthorizedException('Please login first')
#         user_id = getUserId(user)
#         p_key = ndb.Key(Profile, user_id)
#         profile = p_key.get()
#         if not profile:
#             raise endpoints.UnauthorizedException(
#                 'Profile not found. Please try to relogin or re-register'
#                 )
#         return login_user

@endpoints.api(
    name='conference', version='v1', audiences=[ANDROID_AUDIENCE],
    allowed_client_ids=[WEB_CLIENT_ID,
                        API_EXPLORER_CLIENT_ID,
                        ANDROID_CLIENT_ID,
                        IOS_CLIENT_ID],
    scopes=[EMAIL_SCOPE])
class ConferenceApi(remote.Service):
    """Conference API v0.1"""

# - - - Conference objects - - - - - - - - - - - - - - - - -

    def _copyConferenceToForm(self, conf, displayName):
        """Copy relevant fields from Conference to ConferenceForm."""
        cf = ConferenceForm()
        for field in cf.all_fields():
            if hasattr(conf, field.name):
                # convert Date to date string; just copy others
                if field.name.endswith('Date'):
                    setattr(cf, field.name, str(getattr(conf, field.name)))
                else:
                    setattr(cf, field.name, getattr(conf, field.name))
            elif field.name == "websafeKey":
                setattr(cf, field.name, conf.key.urlsafe())
        if displayName:
            setattr(cf, 'organizerDisplayName', displayName)
        cf.check_initialized()
        return cf

    # @user_authentication
    def _createConferenceObject(self, request):
        """Create Conference object, returning ConferenceForm/request."""
        # preload necessary data items
        user = endpoints.get_current_user()
        if not user:
            raise endpoints.UnauthorizedException('Authorization required')
        user_id = getUserId(user)

        if not request.name:
            raise endpoints.BadRequestException("Conference 'name' "
                                                "field required")

        # copy ConferenceForm/ProtoRPC Message into dict
        data = {field.name: getattr(request, field.name)
                for field in request.all_fields()}
        del data['websafeKey']
        del data['organizerDisplayName']

        # add default values for those missing
        # (both data model & outbound Message)
        for df in DEFAULTS:
            if data[df] in (None, []):
                data[df] = DEFAULTS[df]
                setattr(request, df, DEFAULTS[df])

        # convert dates from strings to Date objects;

        if data['startDate']:
            data['startDate'] = datetime.strptime(
                                    data['startDate'][:10], "%Y-%m-%d").date()
            # set month based on start_date
            data['month'] = data['startDate'].month
        else:
            data['month'] = 0
        if data['endDate']:
            data['endDate'] = datetime.strptime(
                                    data['endDate'][:10], "%Y-%m-%d").date()
        # set seatsAvailable to be same as maxAttendees on creation
        if data["maxAttendees"] > 0 and data["seatsAvailable"] is None:
            data["seatsAvailable"] = data["maxAttendees"]
        # generate Profile Key based on user ID and Conference
        # ID based on Profile key get Conference key from ID
        p_key = ndb.Key(Profile, user_id)
        c_id = Conference.allocate_ids(size=1, parent=p_key)[0]
        c_key = ndb.Key(Conference, c_id, parent=p_key)
        data['key'] = c_key
        data['organizerUserId'] = request.organizerUserId = user_id

        # create Conference, send email to organizer confirming
        # creation of Conference & return (modified) ConferenceForm
        Conference(**data).put()
        taskqueue.add(
            params={'email': user.email(),
                    'conferenceInfo': repr(request)},
            url='/tasks/send_confirmation_email'
        )
        return request

    @ndb.transactional()
    def _updateConferenceObject(self, request):
        """Update Conference object, returning ConferenceForm"""
        # authenticate user
        user = endpoints.get_current_user()
        if not user:
            raise endpoints.UnauthorizedException('Authorization required')
        user_id = getUserId(user)

        # copy ConferenceForm/ProtoRPC Message into dict
        data = {field.name: getattr(request, field.name)
                for field in request.all_fields()}
        # get conference object from Datastore
        conf = self._getDataStoreObject(request.websafeConferenceKey)
        # check that user is owner
        if user_id != conf.organizerUserId:
            raise endpoints.ForbiddenException(
                'Only the owner can update the conference.')

        # Not getting all the fields, so don't create a new object; just
        # copy relevant fields from ConferenceForm to Conference object
        for field in request.all_fields():
            data = getattr(request, field.name)
            # only copy fields where we get data
            if data not in (None, []):
                # special handling for dates (convert string to Date)
                if field.name in ('startDate', 'endDate'):
                    data = datetime.strptime(data, "%Y-%m-%d").date()
                    if field.name == 'startDate':
                        conf.month = data.month
                # write to Conference object
                setattr(conf, field.name, data)
        conf.put()
        prof = ndb.Key(Profile, user_id).get()
        return self._copyConferenceToForm(conf, getattr(prof, 'displayName'))

    @endpoints.method(
            ConferenceForm, ConferenceForm, path='createConference',
            http_method='POST', name='createConference')
    def createConference(self, request):
        """Create a new conference."""
        return self._createConferenceObject(request)

    @endpoints.method(
            CONF_POST_REQUEST, ConferenceForm,
            path='conferences/{websafeConferenceKey}',
            http_method='PUT', name='updateConference')
    def updateConference(self, request):
        """Update conference w/provided fields & return w/updated info."""
        return self._updateConferenceObject(request)

    @endpoints.method(
            CONF_GET_REQUEST, ConferenceForm,
            path='conferences/{websafeConferenceKey}',
            http_method='GET', name='getConference')
    def getConference(self, request):
        """Return requested conference (by websafeConferenceKey)."""
        # get conference object from Datastore
        conf = self._getDataStoreObject(request.websafeConferenceKey)
        # get parent's profile
        prof = conf.key.parent().get()
        # return ConferenceForm
        return self._copyConferenceToForm(conf, getattr(prof, 'displayName'))

    @endpoints.method(
            message_types.VoidMessage, ConferenceForms,
            path='getConferencesCreated',
            http_method='POST', name='getConferencesCreated')
    def getConferencesCreated(self, request):
        """Return conferences created by user."""
        # authenticate user
        user = endpoints.get_current_user()
        if not user:
            raise endpoints.UnauthorizedException('Authorization required')
        user_id = getUserId(user)

        # create ancestor query for all key matches for this user
        confs = Conference.query(ancestor=ndb.Key(Profile, user_id))
        prof = ndb.Key(Profile, user_id).get()
        # return set of ConferenceForm objects per Conference
        return ConferenceForms(
            items=[self._copyConferenceToForm(
                conf, getattr(prof, 'displayName')) for conf in confs]
        )

    def _getQuery(self, request):
        """Return formatted query from the submitted filters."""
        q = Conference.query()
        inequality_filter, filters = self._formatFilters(request.filters)

        # If exists, sort on inequality filter first
        if not inequality_filter:
            q = q.order(Conference.name)
        else:
            q = q.order(ndb.GenericProperty(inequality_filter))
            q = q.order(Conference.name)

        for filtr in filters:
            if filtr["field"] in ["month", "maxAttendees"]:
                filtr["value"] = int(filtr["value"])
            formatted_query = ndb.query.FilterNode(filtr["field"],
                                                   filtr["operator"],
                                                   filtr["value"])
            q = q.filter(formatted_query)
        return q

    def _formatFilters(self, filters):
        """Parse, check validity and format user supplied filters."""
        formatted_filters = []
        inequality_field = None

        for f in filters:
            filtr = {field.name: getattr(f, field.name)
                     for field in f.all_fields()}

            try:
                filtr["field"] = FIELDS[filtr["field"]]
                filtr["operator"] = OPERATORS[filtr["operator"]]
            except KeyError:
                raise endpoints.BadRequestException("Filter contains invalid "
                                                    "field or operator.")

            # Every operation except "=" is an inequality
            if filtr["operator"] != "=":
                # check if inequality operation been used in previous filters
                # disallow the filter if inequality was performed on a different
                # field before
                # track the field on which the inequality operation is performed
                if inequality_field and inequality_field != filtr["field"]:
                    raise endpoints.BadRequestException(
                            "Inequality filter is allowed on only one field.")
                else:
                    inequality_field = filtr["field"]

            formatted_filters.append(filtr)
        return (inequality_field, formatted_filters)

    @endpoints.method(
            ConferenceQueryForms, ConferenceForms,
            path='queryConferences',
            http_method='POST',
            name='queryConferences')
    def queryConferences(self, request):
        """Query for conferences."""
        conferences = self._getQuery(request)

        # need to fetch organiser displayName from profiles
        # get all keys and use get_multi for speed
        organisers = [(ndb.Key(Profile, conf.organizerUserId))
                      for conf in conferences]
        profiles = ndb.get_multi(organisers)

        # put display names in a dict for easier fetching
        names = {}
        for profile in profiles:
            names[profile.key.id()] = profile.displayName

        # return individual ConferenceForm object per Conference
        return ConferenceForms(
                items=[
                    self._copyConferenceToForm(conf,
                                               names[conf.organizerUserId]
                                               ) for conf in conferences]
                )

    @endpoints.method(
            CONF_GET_SIMILAR, ConferenceForms,
            path='querySimilarConferences/{websafeConferenceKey}',
            http_method='POST',
            name='querySimilarConferences')
    def querySimilarConferences(self, request):
        """Query for similar conferences by the same creator."""
        # get conference object from Datastore
        conf = self._getDataStoreObject(request.websafeConferenceKey)
        # get parent's profile
        prof = conf.key.parent().get()
        # use ancestor query to get conferences by same creator,
        # then filter out the conference user provided
        conferences = Conference.query(ancestor=prof.key).filter(
                                                    Conference.key != conf.key)

        # Create filterNode and perform search if all fields are provided
        if (request.field and request.operator and request.value):
            node = ndb.query.FilterNode(request.field,
                                        OPERATORS[request.operator],
                                        request.value)
            conferences = conferences.filter(node)

        # Raise error if user didn't provide all 3 fields,
        # otherwise return current query result without further filtering
        elif (request.field or request.operator or request.value):
            raise endpoints.BadRequestException(
                                "You need to define field, operator, and value")

        return ConferenceForms(
                items=[
                    self._copyConferenceToForm(conf,
                                               prof.mainEmail
                                               ) for conf in conferences]
        )

# - - - Profile objects - - - - - - - - - - - - - - - - - - -

    def _copyProfileToForm(self, prof):
        """Copy relevant fields from Profile to ProfileForm."""
        # copy relevant fields from Profile to ProfileForm
        pf = ProfileForm()
        for field in pf.all_fields():
            if hasattr(prof, field.name):
                # convert key objects to websafekey, put it back in a list
                if field.name.endswith('Attend'):
                    key_list = [x.urlsafe() for x in getattr(prof, field.name)]
                    setattr(pf, field.name, key_list)
                # convert t-shirt string to Enum;
                elif field.name == 'teeShirtSize':
                    setattr(pf, field.name,
                            getattr(TeeShirtSize, getattr(prof, field.name)))
                # just copy others
                else:
                    setattr(pf, field.name, getattr(prof, field.name))
        pf.check_initialized()
        return pf

    def _getProfileFromUser(self):
        """
        Return user Profile from datastore, creating new one if non-existent.
        """
        # make sure user is authed
        user = endpoints.get_current_user()
        if not user:
            raise endpoints.UnauthorizedException('Authorization required')

        # get Profile from datastore
        user_id = getUserId(user)
        p_key = ndb.Key(Profile, user_id)
        profile = p_key.get()
        # create new Profile if not there
        if not profile:
            profile = Profile(
                key=p_key,
                displayName=user.nickname(),
                mainEmail=user.email(),
                teeShirtSize=str(TeeShirtSize.NOT_SPECIFIED),
            )
            profile.put()

        return profile      # return Profile

    def _doProfile(self, save_request=None):
        """Get user Profile and return to user, possibly updating it first."""
        # get user Profile
        prof = self._getProfileFromUser()

        # if saveProfile(), process user-modifyable fields
        if save_request:
            for field in ('displayName', 'teeShirtSize'):
                if hasattr(save_request, field):
                    val = getattr(save_request, field)
                    if val:
                        setattr(prof, field, str(val))
                        # if field == 'teeShirtSize':
                        #    setattr(prof, field, str(val).upper())
                        # else:
                        #    setattr(prof, field, val)
                        prof.put()

        # return ProfileForm
        return self._copyProfileToForm(prof)

    @endpoints.method(
            message_types.VoidMessage, ProfileForm,
            path='profiles', http_method='GET', name='getProfile')
    def getProfile(self, request):
        """Return user profile."""
        return self._doProfile()

    @endpoints.method(
            ProfileMiniForm, ProfileForm,
            path='profiles', http_method='POST', name='saveProfile')
    def saveProfile(self, request):
        """Update & return user profile."""
        return self._doProfile(request)

# - - - Announcements - - - - - - - - - - - - - - - - - - - -

    @staticmethod
    def _cacheAnnouncement():
        """Create Announcement & assign to memcache; used by
        memcache cron job & putAnnouncement().
        """
        confs = Conference.query(ndb.AND(
            Conference.seatsAvailable <= 5,
            Conference.seatsAvailable > 0)
        ).fetch(projection=[Conference.name])

        if confs:
            # If there are almost sold out conferences,
            # format announcement and set it in memcache
            announcement = ANNOUNCEMENT_TPL % (
                ', '.join(conf.name for conf in confs))
            memcache.set(MEMCACHE_ANNOUNCEMENTS_KEY, announcement)
        else:
            # If there are no sold out conferences,
            # delete the memcache announcements entry
            announcement = ""
            memcache.delete(MEMCACHE_ANNOUNCEMENTS_KEY)

        return announcement

    @endpoints.method(
            message_types.VoidMessage, StringMessage,
            path='conference/announcement/get',
            http_method='GET', name='getAnnouncement')
    def getAnnouncement(self, request):
        """Return Announcement from memcache."""
        return StringMessage(
            data=memcache.get(MEMCACHE_ANNOUNCEMENTS_KEY) or "")

# - - - Registration - - - - - - - - - - - - - - - - - - - -

    @ndb.transactional(xg=True)
    def _conferenceRegistration(self, request, reg=True):
        """Register or unregister user for selected conference."""
        retval = None
        # get user Profile
        prof = self._getProfileFromUser()
        # get conference object from Datastore
        conf = self._getDataStoreObject(request.websafeConferenceKey)
        # register
        if reg:
            # check if user already registered otherwise add
            if conf.key in prof.conferenceKeysToAttend:
                raise ConflictException(
                    "You have already registered for this conference")

            # check if seats avail
            if conf.seatsAvailable <= 0:
                raise ConflictException(
                    "There are no seats available.")

            # register user, take away one seat
            prof.conferenceKeysToAttend.append(conf.key)
            conf.seatsAvailable -= 1
            retval = True

        # unregister
        else:
            # check if user already registered
            if conf.key in prof.conferenceKeysToAttend:

                # unregister user, add back one seat
                prof.conferenceKeysToAttend.remove(conf.key)
                conf.seatsAvailable += 1
                retval = True
            else:
                retval = False

        # write things back to the datastore & return
        prof.put()
        conf.put()
        return BooleanMessage(data=retval)

    @endpoints.method(
            message_types.VoidMessage, ConferenceForms,
            path='conferences/attending',
            http_method='GET', name='getConferencesToAttend')
    def getConferencesToAttend(self, request):
        """Get list of conferences that user has registered for."""
        # get user Profile
        prof = self._getProfileFromUser()
        # get multiple conferences with multiple keys at once
        conferences = ndb.get_multi(prof.conferenceKeysToAttend)
        # get organizers
        organisers = [
            ndb.Key(Profile, conf.organizerUserId) for conf in conferences]
        profiles = ndb.get_multi(organisers)

        # put display names in a dict for easier fetching
        names = {}
        for profile in profiles:
            names[profile.key.id()] = profile.displayName

        # return set of ConferenceForm objects per Conference
        return ConferenceForms(
            items=[self._copyConferenceToForm(
                conf, names[conf.organizerUserId]) for conf in conferences]
        )

    @endpoints.method(
            CONF_GET_REQUEST, BooleanMessage,
            path='conferences/{websafeConferenceKey}',
            http_method='POST', name='registerForConference')
    def registerForConference(self, request):
        """Register user for selected conference."""
        return self._conferenceRegistration(request)

    @endpoints.method(
            CONF_GET_REQUEST, BooleanMessage,
            path='conferences/{websafeConferenceKey}',
            http_method='DELETE', name='unregisterFromConference')
    def unregisterFromConference(self, request):
        """Unregister user for selected conference."""
        return self._conferenceRegistration(request, reg=False)

    @endpoints.method(
            message_types.VoidMessage, ConferenceForms,
            path='filterPlayground',
            http_method='GET', name='filterPlayground')
    def filterPlayground(self, request):
        """Filter Playground"""
        q = Conference.query()
        # field = "city"
        # operator = "="
        # value = "London"
        # f = ndb.query.FilterNode(field, operator, value)
        # q = q.filter(f)
        q = q.filter(Conference.city == "London")
        q = q.filter(Conference.topics == "Medical Innovations")
        q = q.filter(Conference.month == 6)

        return ConferenceForms(
            items=[self._copyConferenceToForm(conf, "") for conf in q]
        )

# - - - Session - - - - - - - - - - - - - - - - - - - -

    def _copySessionToForm(self, session):
        """Copy relevant fields from Session to SessionForm."""
        sf = SessionForm()
        for field in sf.all_fields():
            if hasattr(session, field.name):
                # convert time to time string; just copy others
                if field.name in ['date', 'startTime']:
                    setattr(sf, field.name, str(getattr(session, field.name)))
                else:
                    setattr(sf, field.name, getattr(session, field.name))
            elif field.name == "websafeKey":
                setattr(sf, field.name, session.key.urlsafe())
        sf.check_initialized()
        return sf

    def _createSessionObject(self, request):
        """Create Session object, returning SessionForm"""
        # User authentication
        user = endpoints.get_current_user()
        if not user:
            raise endpoints.UnauthorizedException('Authorization required')
        user_id = getUserId(user)
        # get conference object from Datastore
        conf = self._getDataStoreObject(request.websafeConferenceKey)

        # User Authorization
        if user_id != conf.organizerUserId:
            raise endpoints.ForbiddenException(
                'Only the owner can add session to the conference')

        # Copy SessionForm Message into dict
        data = {field.name: getattr(request, field.name)
                for field in request.all_fields()}
        wsck = data['websafeConferenceKey']
        del data['websafeKey']
        del data['websafeConferenceKey']

        # add default values for fields that aren't provided
        for df in SESSION_DEFAULTS:
            if data[df] in (None, []):
                data[df] = SESSION_DEFAULTS[df]
                setattr(request, df, SESSION_DEFAULTS[df])
        if data['date']:
            data['date'] = datetime.strptime(
                                    data['date'][:10], "%Y-%m-%d").date()
        if data['startTime']:
            data['startTime'] = datetime.strptime(
                                        data['startTime'], "%H:%M").time()

        # generate session Key based on conference Key
        c_key = conf.key
        s_id = Session.allocate_ids(size=1, parent=c_key)[0]
        s_key = ndb.Key(Session, s_id, parent=c_key)
        data['key'] = s_key
        Session(**data).put()

        # Run queue to check featured speaker if speaker ID is provided
        if data['speakerId']:
            speaker = ndb.Key(Speaker, data['speakerId']).get()
            if not speaker:
                raise endpoints.NotFoundException(
                    'No speaker found with this id')
            taskqueue.add(params={'wsck': wsck, 'speakerId': data['speakerId']},
                          url='/tasks/check_featured_speaker'
                          )
        return self._copySessionToForm(s_key.get())

    def _updateSessionObject(self, request):
        """Update Session object, returning SessionForm"""
        # User authentication
        user = endpoints.get_current_user()
        if not user:
            raise endpoints.UnauthorizedException('Authorization required')
        user_id = getUserId(user)

        # Copy SessionForm Message into dict
        data = {field.name: getattr(request, field.name)
                for field in request.all_fields()}

        # get session object from Datastore
        session = self._getDataStoreObject(request.websafeSessionKey)

        # User Authorization
        conf = session.key.parent().get()
        if user_id != conf.organizerUserId:
            raise endpoints.ForbiddenException(
                'Only the owner can update the session.')

        # copy relevant fields from Session Form to Session object
        for field in request.all_fields():
            data = getattr(request, field.name)
            # only copy fields where we get data
            if data not in (None, []):
                if field.name == 'date':
                    data = datetime.strptime(data[:10], "%Y-%m-%d").date()
                if field.name == 'startTime':
                    data = datetime.strptime(data, "%H:%M").time()
                setattr(session, field.name, data)
        session.put()
        return self._copySessionToForm(session)

    def _sessionRegistration(self, request, reg=True):
        """
        Given a session, either put it in or remove it from a user's wishlist.

        Arg:
            reg (Default=True): If true, add the session to user's wishlist
                                If false, remove the session from user's
                                wishlit.
        Return:
            retval(Boolean): If ture, the operation (addition or removal of
                             session from user's wishlist) is successful
        """
        retval = None
        # User authentication
        prof = self._getProfileFromUser()

        # get session object from Datastore
        wssk = request.websafeSessionKey
        session = self._getDataStoreObject(wssk)

        # check whether user has registered for conference where session belongs
        c_key = session.key.parent()
        if c_key not in prof.conferenceKeysToAttend:
            raise ConflictException(
                "You have yet to register for the conference where this "
                "session will take place")

        # put session in wishlist
        if reg:
            if session.key in prof.sessionKeysToAttend:
                raise ConflictException(
                    "You have already placed this session in your wishlist")
            prof.sessionKeysToAttend.append(session.key)
            retval = True

        # remove session from wishlist
        else:
            if session.key not in prof.sessionKeysToAttend:
                raise ConflictException(
                    "This session was not in your wishlist. No action taken.")
            prof.sessionKeysToAttend.remove(session.key)
            retval = True
        prof.put()
        return BooleanMessage(data=retval)

    def _getSessionInWishlist(self, request):
        """Return a list of sessions within the user's wishlist."""
        # User authentication
        prof = self._getProfileFromUser()
        # Retrieve all sessions with all session Keys at once
        sessions = ndb.get_multi(prof.sessionKeysToAttend)
        return SessionForms(
            items=[self._copySessionToForm(session) for session in sessions]
        )

    @endpoints.method(
            CREATE_SESSION, SessionForm, path='createSession',
            http_method='POST', name='createSession')
    def createSession(self, request):
        """Create a new Session Object."""
        return self._createSessionObject(request)

    @endpoints.method(
            SESSION_POST_REQUEST, SessionForm,
            path='sessions/{websafeSessionKey}',
            http_method='PUT', name='updateSession')
    def updateSession(self, request):
        """Update session w/provided fields & return w/updated info."""
        return self._updateSessionObject(request)

    @endpoints.method(
            SESSION_GET_REQUEST, SessionForm,
            path='sessions/{websafeSessionKey}',
            http_method='GET', name='getSession')
    def getSession(self, request):
        """Return requested session (by websafeSessionKey)."""
        session = self._getDataStoreObject(request.websafeSessionKey)
        return self._copySessionToForm(session)

    @endpoints.method(
            SESSIONS_GET_REQUEST, SessionForms,
            path='conferences/{websafeConferenceKey}/sessions',
            http_method='GET', name='getConferenceSessions')
    def getConferenceSessions(self, request):
        """Return sessions given a websafeConferenceKey"""
        # get conference object from Datastore
        conf = self._getDataStoreObject(request.websafeConferenceKey)
        # query sessions using ancestor conference Key
        sessions = Session.query(ancestor=conf.key)
        return SessionForms(
            items=[self._copySessionToForm(session) for session in sessions]
        )

    @endpoints.method(
            SESSION_QUERY_TYPE, SessionForms,
            path='conferences/{websafeConferenceKey}/sessions/{type}',
            http_method='GET', name='getConferenceSessionsByType')
    def getConferenceSessionsByType(self, request):
        """Return sessions given a session type"""
        # get conference object from Datastore
        conf = self._getDataStoreObject(request.websafeConferenceKey)
        # query sessions using ancestor conference Key
        sessions = Session.query(ancestor=conf.key)
        # filter sessions by sessionType
        sessions = sessions.filter(
                        getattr(Session, 'sessionType') == request.type)
        return SessionForms(
            items=[self._copySessionToForm(session) for session in sessions]
        )

    @endpoints.method(
            CONF_GET_SIMILAR, SessionForms,
            path='conferences/{websafeConferenceKey}/sessions/duration',
            http_method='POST', name='querySessionLength')
    def querySessionLength(self, request):
        """Return sessions given a conference object and duration (minutes)"""
        # get conference object from Datastore
        conf = self._getDataStoreObject(request.websafeConferenceKey)
        # query sessions using ancestor conference Key and order by duration
        sessions = Session.query(ancestor=conf.key).order(
                                                    Session.duration_minutes)
        # temp workaroud since the 2nd filter clause picks up all sessions even
        # if the data=None
        sessions = sessions.filter(Session.duration_minutes != None)

        # create filterNode and perform filter if all fields are provided
        if (request.operator and request.value):
            node = ndb.query.FilterNode('duration_minutes',
                                        OPERATORS[request.operator],
                                        request.value
                                        )
            sessions = sessions.filter(node)
        else:
            raise endpoints.BadRequestException(
                "You need to define both operator and value")

        return SessionForms(
            items=[self._copySessionToForm(session) for session in sessions]
        )

    @endpoints.method(
            SESSION_QUERY_TIME, SessionForms,
            path='conferences/{websafeConferenceKey}/sessions/time',
            http_method='POST', name='querySessionTime')
    def querySessionTime(self, request):
        """Return sessions given a conference object, time and type"""
        # get conference object from Datastore
        conf = self._getDataStoreObject(request.websafeConferenceKey)
        # query sessions using ancestor conf Key, order sessions by start time
        sessions = Session.query(ancestor=conf.key).order(Session.startTime)

        # filter sessions by time (before/after/equal certain time)
        if (request.operator and request.time):
            node = ndb.query.FilterNode(
                                    'startTime',
                                    OPERATORS[request.operator],
                                    datetime(1970, 01, 01, request.time, 00))
            sessions = sessions.filter(node)
        else:
            raise endpoints.BadRequestException("You need to define both "
                                                "operator and time")

        # only return session types that are not equal to what the user provided
        return SessionForms(
            items=[self._copySessionToForm(x)
                   for x in sessions
                   if x.sessionType != request.sessionType]
        )

    # WORKAROUND of above endpoints that fully utilize Datastore queries

    # @endpoints.method(SESSION_QUERY_TIME, SessionForms,
    #         path='querySessionTime/{websafeConferenceKey}',
    #         http_method='POST', name='querySessionTime')
    # def querySessionTime(self, request):
    #     """Return sessions given a conference object, time and type"""
    # try:
    #     conf = ndb.Key(urlsafe=request.websafeConferenceKey).get()
    # except ProtocolBufferDecodeError:
    #     raise endpoints.NotFoundException(
    #         'No conference found with key: %s' %
    #         request.websafeConferenceKey)
    #     typeList=[item for item in request.sessionType]
    #     if typeList:
    #         sessions = Session.query(
    #                       Session.sessionType.IN(typeList),
    #                       ancestor=conf.key).order(Session.startTime)
    #     else:
    #         sessions = Session.query(
    #                       ancestor=conf.key).order(Session.startTime)
    #     if (request.operator and request.time):
    #         node = ndb.query.FilterNode(
    #                           'startTime',
    #                           OPERATORS[request.operator],
    #                           datetime(1970,01,01,request.time,00))
    #         sessions = sessions.filter(node)
    #     elif (request.operator or request.time):
    #         raise endpoints.BadRequestException("You need to define both "
    #                                             "operator and time")
    #     return SessionForms(
    #         items=[self._copySessionToForm(session) for session in sessions]
    #     )

    @endpoints.method(
            SPEAKER_GET_REQUEST, SessionForms,
            path='sessions/speakers/{speakerId}',
            http_method='GET', name='getSessionsBySpeaker')
    def getSessionsBySpeaker(self, request):
        """Return sessions given a speakerId"""
        # get speaker object from Datastore
        speaker = ndb.Key(Speaker, request.speakerId).get()
        # query speaker by id
        sessions = Session.query().filter(
                            getattr(Session, 'speakerId') == request.speakerId)
        return SessionForms(
            items=[self._copySessionToForm(session) for session in sessions]
        )

    @endpoints.method(
            SESSION_GET_REQUEST, BooleanMessage,
            path='profile/wishlist/{websafeSessionKey}',
            http_method='POST', name='addSessionToWishList')
    def addSessionToWishList(self, request):
        """Add Session to the user's wishlist."""
        return self._sessionRegistration(request)

    @endpoints.method(
            SESSION_GET_REQUEST, BooleanMessage,
            path='profile/wishlist/{websafeSessionKey}',
            http_method='DELETE', name='deleteSessionInWishlist')
    def deleteSessionInWishlist(self, request):
        """Remove session from user's wishlist."""
        return self._sessionRegistration(request, reg=False)

    @endpoints.method(
            message_types.VoidMessage, SessionForms,
            path='profile/wishlist',
            http_method='GET', name='getSessionsInWishlist')
    def getSessionsInWishlist(self, request):
        """Query for all the sessions the user has placed in wishlist."""
        return self._getSessionInWishlist(request)

# - - - Speaker - - - - - - - - - - - - - - - - - - - -

    def _copySpeakerToForm(self, speaker):
        """Copy relevant fields from Speaker to SpeakerForm."""
        sf = SpeakerForm()
        for field in sf.all_fields():
            # retrieve speaker ID and display on SpeakerForm
            if field.name == 'speakerId':
                sf.speakerId = speaker.key.integer_id()
            # copy other fields
            elif hasattr(speaker, field.name):
                setattr(sf, field.name, getattr(speaker, field.name))
        sf.check_initialized()
        return sf

    def _createSpeakerObject(self, request):
        """Create Speaker Object, returning SessionForm/request."""
        data = {field.name: getattr(request, field.name)
                for field in request.all_fields()}
        del data['speakerId']
        key = Speaker(**data).put()
        return self._copySpeakerToForm(key.get())

    @endpoints.method(
            SpeakerForm, SpeakerForm, path='createSpeaker',
            http_method='POST', name='createSpeaker')
    def createSpeaker(self, request):
        """Create new speaker."""
        return self._createSpeakerObject(request)

    @endpoints.method(
            SPEAKER_GET_REQUEST, SpeakerForm, path='speaker/{speakerId}',
            http_method='GET', name='getSpeaker')
    def getSpeaker(self, request):
        """Get Speaker Object given the speakerId"""
        speaker = ndb.Key(Speaker, request.speakerId).get()
        return self._copySpeakerToForm(speaker)

    @endpoints.method(
            SPEAKER_BY_NAME, SpeakerForms, path='speakers/{name}',
            http_method='GET', name='getSpeakerByName')
    def getSpeakerByName(self, request):
        """Get Speaker Object given the speaker's full name"""
        speakers = Speaker.query().filter(Speaker.displayName == request.name)
        return SpeakerForms(
            items=[self._copySpeakerToForm(speaker) for speaker in speakers]
        )

    @endpoints.method(
            message_types.VoidMessage, SpeakerForms,
            path='speakers/all',
            http_method='GET', name='getSpeakersCreated')
    def getSpeakersCreated(self, request):
        """Get all Speaker Objects within Datastore"""
        speakers = Speaker.query()
        return SpeakerForms(
            items=[self._copySpeakerToForm(speaker) for speaker in speakers]
        )

    @endpoints.method(
            message_types.VoidMessage, StringMessage,
            path='conference/featured_speaker/get',
            http_method='GET', name='getFeaturedSpeaker')
    def getFeaturedSpeaker(self, request):
        """Return featured speaker from memcache."""
        return StringMessage(data=memcache.get(MEMCACHE_SPEAKER_KEY) or "")

    @staticmethod
    def _getDataStoreObject(websafekey):
        """
        Retrieve Datastore objects using websafeKey

        Args:
            websafekey (string): websafekey used to retrieve object
        Returns:
            entity (GAE entities): retrieved object from Datastore
        """
        # try getting object from datastore using websafekey
        try:
            entity = ndb.Key(urlsafe=websafekey).get()
        # raise error if websafekey isn't valid (no object found)
        except (ProtocolBufferDecodeError, TypeError):
            raise endpoints.NotFoundException(
                'No object found with key: %s' % websafekey)
        return entity

api = endpoints.api_server([ConferenceApi])  # register API


text:
import threading
from Queue import Queue
from numpy import *
from create_MEGA_THETA import *
from RLU_forward_backward import *
from get_overlaps import *

# get data from csv file into array
data = genfromtxt('train2.csv', delimiter=',')

# get a subset for testing
num_cpus = 4
N = 5*num_cpus	 			# batch size of data subset
y_vals = data[:,0]			# outputs
x_vals = data[:,1:].T			# inputs
#x_vals = (x_vals > 0)*ones(shape(x_vals))	# make inputs 0/1
data_size = size(y_vals)

# define some NN layers
base_in = 783
xi = array([1525,10])
mangle_upper = 30

# randomly initiate NN values
MT = create_MEGA_THETA(xi)
#MT = genfromtxt('convltn_to_10_backup.csv', delimiter=',')
MTDIM = shape(MT)
DELTA = zeros([MTDIM[0],MTDIM[1]])

# learning rate
alpha = 1*N**2
beta = .02
# create some Queues for DELTA, time, good
time_queue = Queue()
good_queue = Queue()
DELTA_queue = Queue()

# initiate queues
time_queue.put(1.0)
good_queue.put(0.0)

success = 0				# ouch
counter = 0				# meh

# execute backprop procedure until accuracy is high
while success < .9999999: # success rate goal

        selection = random.random_integers(0,data_size-1,N)     # stochastic gradient descent

        # get some pixels labels to mangle
        mangle0 = random.randint(0,mangle_upper)
        mangle1 = random.randint(0,mangle_upper)
        random_mangle0 = random.random_integers(0,base_in,mangle0)
        random_mangle1 = random.random_integers(0,base_in,mangle1)

        batch_x_vals = x_vals[:,selection]                      # SGD batch
        batch_y_vals = y_vals[selection]                        # SGD batch

        # mangle pixels, some --> 0 some --> 1
        batch_x_vals[random_mangle0,:] = 0
        batch_x_vals[random_mangle1,:] = 1

	DELTA_queue.put(DELTA)
	DELTA_queue.task_done()
	# run backprop optimisation
	threads = []			# use multi-threading
	for i in range(0,N):
		# input vector
		x = batch_x_vals[:,i]
		overlaps = get()	# from get_overlaps import
		x1 = x[overlaps[0]]
		x2 = x[overlaps[1]]
		x4 = x[overlaps[2]]
		x = hstack((x1, x2, x2, x4, x4, x4, x4))
		y = zeros(10)		# output of NN (row-less)
		y[batch_y_vals[i]] = 1
		thr = threading.Thread(target=forwardBackward,
			args=(xi, x, y, MT, time_queue, good_queue, DELTA_queue))
		threads.append(thr)

	print 'StArTiNg ThReAdS'

	# start all threads
	for i in range(0,N):
		threads[i].start()

	# spin until all threads finish
	for i in range(0,N):
		threads[i].join()

	good = good_queue.get()
	time = time_queue.get()
	success = good/time

	print 'Success: ',success

	good_queue.put(good)
	good_queue.task_done()
	time_queue.put(time)
	time_queue.task_done()
  	DELTA = DELTA_queue.get()

	print 'Queue size: ',DELTA_queue.qsize()

	MT = MT - (alpha/N)*DELTA #- N*beta*MT
	DELTA = 0*DELTA
	if counter == 50:
		savetxt('convltn_to_10.csv', MT, delimiter=',')
		print 'Success: ',success
		print '\n###  SAVED DATA to convltn_to_10.csv  ###\n'
		counter = 0 # reset
	counter += 1

savetxt('convltn_to_10.csv', MT, delimiter=',')

redpajama_set_name: RedPajamaGithub


text:
require 'tk'

# call setup script for general 'tkextlib' libraries
require 'tkextlib/setup.rb'

# call setup script
require 'tkextlib/tcllib/setup.rb'

err = ''

# package:: autoscroll
target = 'tkextlib/tcllib/autoscroll'
begin
  require target
rescue => e
  err << "\n  ['" << target << "'] "  << e.class.name << ' : ' << e.message
end

# package:: cursor
target = 'tkextlib/tcllib/cursor'
begin
  require target
rescue => e
  err << "\n  ['" << target << "'] "  << e.class.name << ' : ' << e.message
end

# package:: style
target = 'tkextlib/tcllib/style'
begin
  require target
rescue => e
  err << "\n  ['" << target << "'] "  << e.class.name << ' : ' << e.message
end

# autoload
module Tk
  module Tcllib
    TkComm::TkExtlibAutoloadModule.unshift(self)

    # package:: autoscroll
    autoload :Autoscroll,         'tkextlib/tcllib/autoscroll'

    # package:: ctext
    autoload :CText,              'tkextlib/tcllib/ctext'

    # package:: cursor
    autoload :Cursor,             'tkextlib/tcllib/cursor'

    # package:: datefield
    autoload :Datefield,          'tkextlib/tcllib/datefield'
    autoload :DateField,          'tkextlib/tcllib/datefield'

    # package:: getstring
    autoload :GetString_Dialog,   'tkextlib/tcllib/getstring'

    # package:: history
    autoload :History,            'tkextlib/tcllib/history'

    # package:: ico
    autoload :ICO,                'tkextlib/tcllib/ico'

    # package:: ipentry
    autoload :IP_Entry,           'tkextlib/tcllib/ip_entry'
    autoload :IPEntry,            'tkextlib/tcllib/ip_entry'

    # package:: khim
    autoload :KHIM,               'tkextlib/tcllib/khim'

    # package:: ntext
    autoload :Ntext,              'tkextlib/tcllib/ntext'

    # package:: Plotchart
    autoload :Plotchart,          'tkextlib/tcllib/plotchart'

    # package:: style
    autoload :Style,              'tkextlib/tcllib/style'

    # package:: swaplist
    autoload :Swaplist_Dialog,    'tkextlib/tcllib/swaplist'

    # package:: tablelist
    autoload :Tablelist,           'tkextlib/tcllib/tablelist'
    autoload :TableList,           'tkextlib/tcllib/tablelist'
    autoload :Tablelist_Tile,      'tkextlib/tcllib/tablelist_tile'
    autoload :TableList_Tile,      'tkextlib/tcllib/tablelist_tile'

    # package:: tkpiechart
    autoload :Tkpiechart,         'tkextlib/tcllib/tkpiechart'

    # package:: tooltip
    autoload :Tooltip,            'tkextlib/tcllib/tooltip'

    # package:: widget
    autoload :Widget,             'tkextlib/tcllib/widget'
  end
end

if $VERBOSE && !err.empty?
  warn("Warning: some sub-packages are failed to require : " + err)
end


text:
System.register(['aurelia-framework', 'aurelia-http-client'], function (_export) {
  var inject, HttpClient, _classCallCheck, _createClass, Flickr;

  return {
    setters: [function (_aureliaFramework) {
      inject = _aureliaFramework.inject;
    }, function (_aureliaHttpClient) {
      HttpClient = _aureliaHttpClient.HttpClient;
    }],
    execute: function () {
      'use strict';

      _classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } };

      _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();

      Flickr = (function () {
        function Flickr(http) {
          _classCallCheck(this, _Flickr);

          this.heading = 'Flickr';
          this.images = [];
          this.url = 'http://api.flickr.com/services/feeds/photos_public.gne?tags=rainier&tagmode=any&format=json';

          this.http = http;
        }

        _createClass(Flickr, [{
          key: 'activate',
          value: function activate() {
            var _this = this;

            return this.http.jsonp(this.url).then(function (response) {
              _this.images = response.content.items;
            });
          }
        }, {
          key: 'canDeactivate',
          value: function canDeactivate() {
            return confirm('Are you sure you want to leave?');
          }
        }]);

        var _Flickr = Flickr;
        Flickr = inject(HttpClient)(Flickr) || Flickr;
        return Flickr;
      })();

      _export('Flickr', Flickr);
    }
  };
});
//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbImZsaWNrci5qcyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiO3lEQUlhLE1BQU07Ozs7aUNBSlgsTUFBTTs7c0NBQ04sVUFBVTs7Ozs7Ozs7O0FBR0wsWUFBTTtBQUtOLGlCQUxBLE1BQU0sQ0FLTCxJQUFJLEVBQUM7OztlQUpqQixPQUFPLEdBQUcsUUFBUTtlQUNsQixNQUFNLEdBQUcsRUFBRTtlQUNYLEdBQUcsR0FBRyw2RkFBNkY7O0FBR2pHLGNBQUksQ0FBQyxJQUFJLEdBQUcsSUFBSSxDQUFDO1NBQ2xCOztxQkFQVSxNQUFNOztpQkFTVCxvQkFBRTs7O0FBQ1IsbUJBQU8sSUFBSSxDQUFDLElBQUksQ0FBQyxLQUFLLENBQUMsSUFBSSxDQUFDLEdBQUcsQ0FBQyxDQUFDLElBQUksQ0FBQyxVQUFBLFFBQVEsRUFBSTtBQUNoRCxvQkFBSyxNQUFNLEdBQUcsUUFBUSxDQUFDLE9BQU8sQ0FBQyxLQUFLLENBQUM7YUFDdEMsQ0FBQyxDQUFDO1dBQ0o7OztpQkFFWSx5QkFBRTtBQUNiLG1CQUFPLE9BQU8sQ0FBQyxpQ0FBaUMsQ0FBQyxDQUFDO1dBQ25EOzs7c0JBakJVLE1BQU07QUFBTixjQUFNLEdBRGxCLE1BQU0sQ0FBQyxVQUFVLENBQUMsQ0FDTixNQUFNLEtBQU4sTUFBTTtlQUFOLE1BQU07Ozt3QkFBTixNQUFNIiwiZmlsZSI6ImZsaWNrci5qcyIsInNvdXJjZVJvb3QiOiIvc3JjLyJ9


text:
package org.mifos.application.meeting.persistence;

import java.util.Date;
import java.util.List;

import junit.framework.Assert;

import org.mifos.application.meeting.business.MeetingBO;
import org.mifos.application.meeting.util.helpers.MeetingType;
import org.mifos.application.meeting.util.helpers.WeekDay;
import org.mifos.framework.MifosIntegrationTestCase;
import org.mifos.framework.hibernate.helper.StaticHibernateUtil;

public class MeetingPersistenceIntegrationTest extends MifosIntegrationTestCase {

    public MeetingPersistenceIntegrationTest() throws Exception {
        super();
    }

    public void testGetWeekDaysList() throws Exception {
        List<WeekDay> weekDaysList = new MeetingPersistence().getWorkingDays();
        Assert.assertNotNull(weekDaysList);
        //Assert.assertEquals(Integer.valueOf("6").intValue(),weekDaysList.size());
       Assert.assertEquals(Integer.valueOf("7").intValue(), weekDaysList.size());
    }

    public void testGetMeeting() throws Exception {
        MeetingBO meeting = new MeetingBO(WeekDay.MONDAY, Short.valueOf("5"), new Date(), MeetingType.CUSTOMER_MEETING,
                "Delhi");
        meeting.save();
        StaticHibernateUtil.commitTransaction();
        StaticHibernateUtil.closeSession();
        meeting = new MeetingPersistence().getMeeting(meeting.getMeetingId());
        Assert.assertNotNull(meeting);
       Assert.assertEquals(Short.valueOf("5"), meeting.getMeetingDetails().getRecurAfter());
       Assert.assertEquals(WeekDay.MONDAY, meeting.getMeetingDetails().getWeekDay());
    }
}


text:
CURRENT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"

source "$CURRENT_DIR/variables.sh"
source "$CURRENT_DIR/shared.sh"

main() {
	if supported_tmux_version_ok; then
		local file=$(expand_tmux_format_path "${save_complete_history_full_filename}")
		local history_limit="$(tmux display-message -p -F "#{history_limit}")"
		tmux capture-pane -J -S "-${history_limit}" -p > "${file}"
		remove_empty_lines_from_end_of_file "${file}"
		display_message "History saved to ${file}"
	fi
}
main


text:
RSpec.describe Hanami::Validator do
  describe ".option" do
    subject do
      Class.new(described_class) do
        option :address_validator

        schema do
          required(:address).filled(:string)
        end

        rule(:address) do
          key.failure("not a valid address") unless address_validator.valid?(values[:address])
        end
      end.new(address_validator: address_validator)
    end

    let(:address_validator) do
      Class.new do
        def valid?(value)
          value.match(/Rome/)
        end
      end.new
    end

    it "validates input" do
      result = subject.call(address: "Rome")
      expect(result).to be_success
      expect(result.to_h).to eq(address: "Rome")

      result = subject.call(address: "foo")
      expect(result).to_not be_success
      expect(result.to_h).to eq(address: "foo")
      expect(result.errors[:address]).to match_array(["not a valid address"])
    end
  end
end


text:
/**
 * A select field, properties:
 *
 * - label
 * - name
 * - .. any other allowed by input
 * @jsx React.DOM
 */
 define(['react', 'build/Components/Panels/Page/Form/label.react', 'build/Components/Panels/Page/Form/checkbox.react'], function(React, Label, Checkbox) {
    return React.createClass({
        render: function () {
            var options = this.props.item.getOptions().map(function(option) {
                option._fallback = false;
                return (<Checkbox item={option} />);
            }.bind(this));

            return (
                <div>
                <Label item={this.props.item} name={this.props.item.getLabel()} />
                {options}
                </div>
                );
        }
    });
});


text: <?= h($message) ?>


text:
@interface Player_1 : Player <Player>

@end


text:
<?php
namespace Concrete\Core\Area\Layout\Preset\Provider;

use Concrete\Core\Page\Page;

interface ProviderInterface
{

    public function getPresets();
    public function getName();

}


text:
find_package(PkgConfig QUIET)
PKG_CHECK_MODULES(PC_LIBXSLT QUIET libxslt)
set(LIBXSLT_DEFINITIONS ${PC_LIBXSLT_CFLAGS_OTHER})

find_path(LIBXSLT_INCLUDE_DIR NAMES libxslt/xslt.h
    HINTS
   ${PC_LIBXSLT_INCLUDEDIR}
   ${PC_LIBXSLT_INCLUDE_DIRS}
  )

find_library(LIBXSLT_LIBRARIES NAMES xslt libxslt
    HINTS
   ${PC_LIBXSLT_LIBDIR}
   ${PC_LIBXSLT_LIBRARY_DIRS}
  )

find_library(LIBXSLT_EXSLT_LIBRARY NAMES exslt libexslt
    HINTS
    ${PC_LIBXSLT_LIBDIR}
    ${PC_LIBXSLT_LIBRARY_DIRS}
  )

set(LIBXSLT_EXSLT_LIBRARIES ${LIBXSLT_EXSLT_LIBRARY} )

find_program(LIBXSLT_XSLTPROC_EXECUTABLE xsltproc)

if(PC_LIBXSLT_VERSION)
    set(LIBXSLT_VERSION_STRING ${PC_LIBXSLT_VERSION})
elseif(LIBXSLT_INCLUDE_DIR AND EXISTS "${LIBXSLT_INCLUDE_DIR}/libxslt/xsltconfig.h")
    file(STRINGS "${LIBXSLT_INCLUDE_DIR}/libxslt/xsltconfig.h" libxslt_version_str
         REGEX "^#define[\t ]+LIBXSLT_DOTTED_VERSION[\t ]+\".*\"")

    string(REGEX REPLACE "^#define[\t ]+LIBXSLT_DOTTED_VERSION[\t ]+\"([^\"]*)\".*" "\\1"
           LIBXSLT_VERSION_STRING "${libxslt_version_str}")
    unset(libxslt_version_str)
endif()

include(${CMAKE_CURRENT_LIST_DIR}/FindPackageHandleStandardArgs.cmake)
FIND_PACKAGE_HANDLE_STANDARD_ARGS(LibXslt
                                  REQUIRED_VARS LIBXSLT_LIBRARIES LIBXSLT_INCLUDE_DIR
                                  VERSION_VAR LIBXSLT_VERSION_STRING)

mark_as_advanced(LIBXSLT_INCLUDE_DIR
                 LIBXSLT_LIBRARIES
                 LIBXSLT_EXSLT_LIBRARY
                 LIBXSLT_XSLTPROC_EXECUTABLE)


text:
<?php

$items = false;

// get the open item on the first level
if($root = $pages->findOpen()) {

  // get visible children for the root item
  $items = $root->children()->visible()->sortby('title', 'asc');
}

// only show the menu if items are available
if($items && $items->count() > 0):
	$count = 0;
?>

	<?php foreach($items as $item): ?>
	<?php

		$file = $item->postimage()->toFile();
		if($file):
		$file = $file->url();
		elseif($item->images()->count() > 0 ):
		$file = $item->images()->first()->url();
		endif;

	?>
	<div class="preview-<?php echo $count; ?> preview-image" style="background-image:url(<?php if( $file ) echo $file; ?>)">

	 <?php $count++; ?>
	 <?php endforeach; ?>

<?php endif; ?>


text:
require File.dirname(__FILE__) + '/../../spec_helper'

describe "/reservations/new_reservation_item" do
  before do
    render 'reservations/new_reservation_item'
  end

  #Delete this example and add some real ones or delete this file
  it "should tell you where to find the file" do
    response.should have_tag('p', 'Find me in app/views/reservations/new_reservation_item.rhtml')
  end
end


text:
#include <fstream>
#include <vector>
#include <map>
#include <limits>
#include <cmath>
#include <cstdio>
#include <boost/tuple/tuple.hpp>
#include <boost/foreach.hpp>

// Warn about use of deprecated functions.
#define GNUPLOT_DEPRECATE_WARN
#include "gnuplot-iostream.h"

#ifndef M_PI
#	define M_PI 3.14159265358979323846
#endif

// http://stackoverflow.com/a/1658429
#ifdef _WIN32
	#include <windows.h>
	inline void mysleep(unsigned millis) {
		::Sleep(millis);
	}
#else
	#include <unistd.h>
	inline void mysleep(unsigned millis) {
		::usleep(millis * 1000);
	}
#endif

void pause_if_needed() {
#ifdef _WIN32
	// For Windows, prompt for a keystroke before the Gnuplot object goes out of scope so that
	// the gnuplot window doesn't get closed.
	std::cout << "Press enter to exit." << std::endl;
	std::cin.get();
#endif
}

// Tell MSVC to not warn about using fopen.
// http://stackoverflow.com/a/4805353/1048959
#if defined(_MSC_VER) && _MSC_VER >= 1400
#pragma warning(disable:4996)
#endif

void demo_basic() {
	Gnuplot gp;
	// For debugging or manual editing of commands:
	//Gnuplot gp(std::fopen("plot.gnu"));
	// or
	//Gnuplot gp("tee plot.gnu | gnuplot -persist");

	std::vector<std::pair<double, double> > xy_pts_A;
	for(double x=-2; x<2; x+=0.01) {
		double y = x*x*x;
		xy_pts_A.push_back(std::make_pair(x, y));
	}

	std::vector<std::pair<double, double> > xy_pts_B;
	for(double alpha=0; alpha<1; alpha+=1.0/24.0) {
		double theta = alpha*2.0*3.14159;
		xy_pts_B.push_back(std::make_pair(cos(theta), sin(theta)));
	}

	gp << "set xrange [-2:2]\nset yrange [-2:2]\n";
	gp << "plot '-' with lines title 'cubic', '-' with points title 'circle'\n";
	gp.send1d(xy_pts_A);
	gp.send1d(xy_pts_B);

	pause_if_needed();
}

void demo_binary() {
	Gnuplot gp;

	std::vector<std::pair<double, double> > xy_pts_A;
	for(double x=-2; x<2; x+=0.01) {
		double y = x*x*x;
		xy_pts_A.push_back(std::make_pair(x, y));
	}

	std::vector<std::pair<double, double> > xy_pts_B;
	for(double alpha=0; alpha<1; alpha+=1.0/24.0) {
		double theta = alpha*2.0*3.14159;
		xy_pts_B.push_back(std::make_pair(cos(theta), sin(theta)));
	}

	gp << "set xrange [-2:2]\nset yrange [-2:2]\n";
	gp << "plot '-' binary" << gp.binFmt1d(xy_pts_A, "record") << "with lines title 'cubic',"
		<< "'-' binary" << gp.binFmt1d(xy_pts_B, "record") << "with points title 'circle'\n";
	gp.sendBinary1d(xy_pts_A);
	gp.sendBinary1d(xy_pts_B);

	pause_if_needed();
}

void demo_tmpfile() {
	Gnuplot gp;

	std::vector<std::pair<double, double> > xy_pts_A;
	for(double x=-2; x<2; x+=0.01) {
		double y = x*x*x;
		xy_pts_A.push_back(std::make_pair(x, y));
	}

	std::vector<std::pair<double, double> > xy_pts_B;
	for(double alpha=0; alpha<1; alpha+=1.0/24.0) {
		double theta = alpha*2.0*3.14159;
		xy_pts_B.push_back(std::make_pair(cos(theta), sin(theta)));
	}

	gp << "set xrange [-2:2]\nset yrange [-2:2]\n";
	// Data will be sent via a temporary file.  These are erased when you call
	// gp.clearTmpfiles() or when gp goes out of scope.  If you pass a filename
	// (i.e. "gp.file1d(pts, 'mydata.dat')"), then the named file will be created
	// and won't be deleted.
	//
	// Note: you need std::endl here in order to flush the buffer.  The send1d()
	// function flushes automatically, but we're not using that here.
	gp << "plot" << gp.file1d(xy_pts_A) << "with lines title 'cubic',"
		<< gp.file1d(xy_pts_B) << "with points title 'circle'" << std::endl;

	pause_if_needed();
}

void demo_png() {
	Gnuplot gp;

	gp << "set terminal png\n";

	std::vector<double> y_pts;
	for(int i=0; i<1000; i++) {
		double y = (i/500.0-1) * (i/500.0-1);
		y_pts.push_back(y);
	}

	std::cout << "Creating my_graph_1.png" << std::endl;
	gp << "set output 'my_graph_1.png'\n";
	gp << "plot '-' with lines, sin(x/200) with lines\n";
	gp.send1d(y_pts);

	std::vector<std::pair<double, double> > xy_pts_A;
	for(double x=-2; x<2; x+=0.01) {
		double y = x*x*x;
		xy_pts_A.push_back(std::make_pair(x, y));
	}

	std::vector<std::pair<double, double> > xy_pts_B;
	for(double alpha=0; alpha<1; alpha+=1.0/24.0) {
		double theta = alpha*2.0*3.14159;
		xy_pts_B.push_back(std::make_pair(cos(theta), sin(theta)));
	}

	std::cout << "Creating my_graph_2.png" << std::endl;
	gp << "set output 'my_graph_2.png'\n";
	gp << "set xrange [-2:2]\nset yrange [-2:2]\n";
	gp << "plot '-' with lines title 'cubic', '-' with points title 'circle'\n";
	gp.send1d(xy_pts_A);
	gp.send1d(xy_pts_B);
}

void demo_vectors() {
	Gnuplot gp;

	std::vector<boost::tuple<double, double, double, double> > vecs;
	for(double alpha=0; alpha<1; alpha+=1.0/24.0) {
		double theta = alpha*2.0*3.14159;
		vecs.push_back(boost::make_tuple(
			 cos(theta),      sin(theta),
			-cos(theta)*0.1, -sin(theta)*0.1
		));
	}

	gp << "set xrange [-2:2]\nset yrange [-2:2]\n";
	gp << "plot '-' with vectors title 'circle'\n";
	gp.send1d(vecs);

	pause_if_needed();
}

std::vector<boost::tuple<double, double, double> > get_trefoil() {
	std::vector<boost::tuple<double, double, double> > vecs;
	for(double alpha=0; alpha<1; alpha+=1.0/120.0) {
		double theta = alpha*2.0*3.14159;
		vecs.push_back(boost::make_tuple(
			(2+cos(3*theta))*cos(2*theta),
			(2+cos(3*theta))*sin(2*theta),
			sin(3*theta)
		));
	}
	return vecs;
}

void demo_inline_text() {
	std::cout << "Creating inline_text.gnu" << std::endl;
	// This file handle will be closed automatically when gp goes out of scope.
	Gnuplot gp(std::fopen("inline_text.gnu", "w"));

	std::vector<boost::tuple<double, double, double> > vecs = get_trefoil();

	gp << "splot '-' with lines notitle\n";
	gp.send1d(vecs);

	std::cout << "Now run 'gnuplot -persist inline_text.gnu'.\n";
}

void demo_inline_binary() {
	std::cout << "Creating inline_binary.gnu" << std::endl;
	// This file handle will be closed automatically when gp goes out of scope.
	Gnuplot gp(std::fopen("inline_binary.gnu", "wb"));

	std::vector<boost::tuple<double, double, double> > vecs = get_trefoil();

	gp << "splot '-' binary" << gp.binFmt1d(vecs, "record") << "with lines notitle\n";
	gp.sendBinary1d(vecs);

	std::cout << "Now run 'gnuplot -persist inline_binary.gnu'.\n";
}

void demo_external_text() {
	std::cout << "Creating external_text.gnu" << std::endl;
	// This file handle will be closed automatically when gp goes out of scope.
	Gnuplot gp(std::fopen("external_text.gnu", "w"));

	std::vector<boost::tuple<double, double, double> > vecs = get_trefoil();

	std::cout << "Creating external_text.dat" << std::endl;
	gp << "splot" << gp.file1d(vecs, "external_text.dat") << "with lines notitle\n";

	std::cout << "Now run 'gnuplot -persist external_text.gnu'.\n";
}

void demo_external_binary() {
	std::cout << "Creating external_binary.gnu" << std::endl;
	// This file handle will be closed automatically when gp goes out of scope.
	Gnuplot gp(std::fopen("external_binary.gnu", "w"));

	std::vector<boost::tuple<double, double, double> > vecs = get_trefoil();

	std::cout << "Creating external_binary.dat" << std::endl;
	gp << "splot" << gp.binFile1d(vecs, "record", "external_binary.dat")
		<< "with lines notitle\n";

	std::cout << "Now run 'gnuplot -persist external_binary.gnu'.\n";
}

void demo_animation() {
#ifdef _WIN32
	// No animation demo for Windows.  The problem is that every time the plot
	// is updated, the gnuplot window grabs focus.  So you can't ever focus the
	// terminal window to press Ctrl-C.  The only way to quit is to right-click
	// the terminal window on the task bar and close it from there.  Other than
	// that, it seems to work.
	std::cout << "Sorry, the animation demo doesn't work in Windows." << std::endl;
	return;
#endif

	Gnuplot gp;

	std::cout << "Press Ctrl-C to quit (closing gnuplot window doesn't quit)." << std::endl;

	gp << "set yrange [-1:1]\n";

	const int N = 1000;
	std::vector<double> pts(N);

	double theta = 0;
	while(1) {
		for(int i=0; i<N; i++) {
			double alpha = (double(i)/N-0.5) * 10;
			pts[i] = sin(alpha*8.0 + theta) * exp(-alpha*alpha/2.0);
		}

		gp << "plot '-' binary" << gp.binFmt1d(pts, "array") << "with lines notitle\n";
		gp.sendBinary1d(pts);
		gp.flush();

		theta += 0.2;
		mysleep(100);
	}
}

void demo_NaN() {
	// Demo of NaN (not-a-number) usage.  Plot a circle that has half the coordinates replaced
	// by NaN values.

	double nan = std::numeric_limits<double>::quiet_NaN();

	Gnuplot gp;

	std::vector<std::pair<double, double> > xy_pts;
	for(int i=0; i<100; i++) {
		double theta = double(i)/100*2*M_PI;
		if((i/5)%2) {
			xy_pts.push_back(std::make_pair(
					std::cos(theta), std::sin(theta)
				));
		} else {
			xy_pts.push_back(std::make_pair(nan, nan));
		}
	}

	// You need to tell gnuplot that 'nan' should be treated as missing data (otherwise it just
	// gives an error).
	gp << "set datafile missing 'nan'\n";
	gp << "plot '-' with linespoints\n";
	gp.send1d(xy_pts);

	// This works too.  But the strange thing is that with text data the segments are joined by
	// lines and with binary data the segments are not joined.
	//gp << "plot '-' binary" << gp.binFmt1d(xy_pts, "record") << "with linespoints\n";
	//gp.sendBinary1d(xy_pts);

	pause_if_needed();
}

void demo_segments() {
	// Demo of disconnected segments.  Plot a circle with some pieces missing.

	Gnuplot gp;

	std::vector<std::vector<std::pair<double, double> > > all_segments;
	for(int j=0; j<10; j++) {
		std::vector<std::pair<double, double> > segment;
		for(int i=0; i<5; i++) {
			double theta = double(j*10+i)/100*2*M_PI;
			segment.push_back(std::make_pair(
					std::cos(theta), std::sin(theta)
				));
		}
		all_segments.push_back(segment);
	}

	gp << "plot '-' with linespoints\n";
	// NOTE: send2d is used here, rather than send1d.  This puts a blank line between segments.
	gp.send2d(all_segments);

	pause_if_needed();
}

void demo_image() {
	// Example of plotting an image.  Of course you are free (and encouraged) to
	// use Blitz or Armadillo rather than std::vector in these situations.

	Gnuplot gp;

	std::vector<std::vector<double> > image;
	for(int j=0; j<100; j++) {
		std::vector<double> row;
		for(int i=0; i<100; i++) {
			double x = (i-50.0)/5.0;
			double y = (j-50.0)/5.0;
			double z = std::cos(sqrt(x*x+y*y));
			row.push_back(z);
		}
		image.push_back(row);
	}

	// It may seem counterintuitive that send1d should be used rather than
	// send2d.  The explanation is as follows.  The "send2d" method puts each
	// value on its own line, with blank lines between rows.  This is what is
	// expected by the splot command.  The two "dimensions" here are the lines
	// and the blank-line-delimited blocks.  The "send1d" method doesn't group
	// things into blocks.  So the elements of each row are printed as columns,
	// as expected by Gnuplot's "matrix with image" command.  But images
	// typically have lots of pixels, so sending as text is not the most
	// efficient (although, it's not really that bad in the case of this
	// example).  See the binary version below.
	//
	//gp << "plot '-' matrix with image\n";
	//gp.send1d(image);

	// To be honest, Gnuplot's documentation for "binary" and for "image" are
	// both unclear to me.  The following example comes by trial-and-error.
	gp << "plot '-' binary" << gp.binFmt2d(image, "array") << "with image\n";
	gp.sendBinary2d(image);

	pause_if_needed();
}

int main(int argc, char **argv) {
	std::map<std::string, void (*)(void)> demos;

	demos["basic"]                  = demo_basic;
	demos["binary"]                 = demo_binary;
	demos["tmpfile"]                = demo_tmpfile;
	demos["png"]                    = demo_png;
	demos["vectors"]                = demo_vectors;
	demos["script_inline_text"]     = demo_inline_text;
	demos["script_inline_binary"]   = demo_inline_binary;
	demos["script_external_text"]   = demo_external_text;
	demos["script_external_binary"] = demo_external_binary;
	demos["animation"]              = demo_animation;
	demos["nan"]                    = demo_NaN;
	demos["segments"]               = demo_segments;
	demos["image"]                  = demo_image;

	if(argc < 2) {
		printf("Usage: %s <demo_name>\n", argv[0]);
		printf("Choose one of the following demos:\n");
		typedef std::pair<std::string, void (*)(void)> demo_pair;
		BOOST_FOREACH(const demo_pair &pair, demos) {
			printf("    %s\n", pair.first.c_str());
		}
		return 0;
	}

	std::string arg(argv[1]);
	if(!demos.count(arg)) {
		printf("No such demo '%s'\n", arg.c_str());
		return 1;
	}

	demos[arg]();
}


text:
'use strict';

//var chrono = require('chrono-node');

module.exports = angular.module('drmg.filters', [])

;


text:
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="CheckpointData.cs">
//   Copyright (c) by respective owners including Yahoo!, Microsoft, and
//   individual contributors. All rights reserved.  Released under a BSD
//   license as described in the file LICENSE.
// </copyright>
// --------------------------------------------------------------------------------------------------------------------

namespace VowpalWabbit.Azure.Trainer.Data
{
    internal sealed class CheckpointData
    {
        internal byte[] Model { get; set; }

        internal byte[] EvalModel { get; set; }

        internal string TrackbackList { get; set; }

        internal bool UpdateClientModel { get; set; }

        internal string State { get; set; }

        internal string Timestamp { get; set; }
    }
}


text:
import chai from 'chai';
import chaiThings from 'chai-things';
import chaiAsPromised from 'chai-as-promised';
import Pokedex from '../src/index.js';

// order matters: github.com/chaijs/chai-things/issues/4#issuecomment-87801365
chai.use(chaiThings);
chai.use(chaiAsPromised);

describe('Root Endpoints', function () {
  let promise;
  const P = new Pokedex({
    protocol: 'https',
    hostName: 'pokeapi.co',
    versionPath: '/api/v2/',
  });
  this.timeout(10000);

  describe('.getEndpointsList() secure (with ssl)', () => {
    before(() => {
      promise = P.getEndpointsList();
    });
    it('should succeed', () => promise);
    it('should have property pokedex', () => chai.expect(promise).to.eventually.have.property('pokedex'));
  });

  describe('.getBerriesList() secure (with ssl)', () => {
    before(() => {
      promise = P.getBerriesList();
    });
    it('should succeed', () => promise);
    it('should have property count', () => chai.expect(promise).to.eventually.have.property('count'));
  });

  describe('.getBerriesFirmnessList() secure (with ssl)', () => {
    before(() => {
      promise = P.getBerriesFirmnessList();
    });
    it('should succeed', () => promise);
    it('should have property count', () => chai.expect(promise).to.eventually.have.property('count'));
  });

  describe('.getBerriesFlavorsList() secure (with ssl)', () => {
    before(() => {
      promise = P.getBerriesFlavorsList();
    });
    it('should succeed', () => promise);

    it('should have property count', () => chai.expect(promise).to.eventually.have.property('count'));
  });

  describe('.getContestTypesList() secure (with ssl)', () => {
    before(() => {
      promise = P.getContestTypesList();
    });
    it('should succeed', () => promise);
    it('should have property count', () => chai.expect(promise).to.eventually.have.property('count'));
  });

  describe('.getContestEffectsList() secure (with ssl)', () => {
    before(() => {
      promise = P.getContestEffectsList();
    });
    it('should succeed', () => promise);
    it('should have property count', () => chai.expect(promise).to.eventually.have.property('count'));
  });

  describe('.getSuperContestEffectsList() secure (with ssl)', () => {
    before(() => {
      promise = P.getSuperContestEffectsList();
    });
    it('should succeed', () => promise);
    it('should have property count', () => chai.expect(promise).to.eventually.have.property('count'));
  });

  describe('.getEncounterMethodsList() secure (with ssl)', () => {
    before(() => {
      promise = P.getEncounterMethodsList();
    });
    it('should succeed', () => promise);
    it('should have property count', () => chai.expect(promise).to.eventually.have.property('count'));
  });

  describe('.getEncounterConditionsList() secure (with ssl)', () => {
    before(() => {
      promise = P.getEncounterConditionsList();
    });
    it('should succeed', () => promise);
    it('should have property count', () => chai.expect(promise).to.eventually.have.property('count'));
  });

  describe('.getEncounterConditionValuesList() secure (with ssl)', () => {
    before(() => {
      promise = P.getEncounterConditionValuesList();
    });
    it('should succeed', () => promise);
    it('should have property count', () => chai.expect(promise).to.eventually.have.property('count'));
  });

  describe('.getEvolutionchaisList() secure (with ssl)', () => {
    before(() => {
      promise = P.getEvolutionChainsList();
    });
    it('should succeed', () => promise);
    it('should have property count', () => chai.expect(promise).to.eventually.have.property('count'));
  });

  describe('.getEvolutionTriggersList() secure (with ssl)', () => {
    before(() => {
      promise = P.getEvolutionTriggersList();
    });
    it('should succeed', () => promise);
    it('should have property count', () => chai.expect(promise).to.eventually.have.property('count'));
  });

  describe('.getGenerationsList() secure (with ssl)', () => {
    before(() => {
      promise = P.getGenerationsList();
    });
    it('should succeed', () => promise);
    it('should have property count', () => chai.expect(promise).to.eventually.have.property('count'));
  });

  describe('.getPokedexList() secure (with ssl)', () => {
    before(() => {
      promise = P.getPokedexList();
    });
    it('should succeed', () => promise);
    it('should have property count', () => chai.expect(promise).to.eventually.have.property('count'));
  });

  describe('.getVersionsList() secure (with ssl)', () => {
    before(() => {
      promise = P.getVersionsList();
    });
    it('should succeed', () => promise);
    it('should have property count', () => chai.expect(promise).to.eventually.have.property('count'));
  });

  describe('.getVersionGroupsList() secure (with ssl)', () => {
    before(() => {
      promise = P.getVersionGroupsList();
    });
    it('should succeed', () => promise);
    it('should have property count', () => chai.expect(promise).to.eventually.have.property('count'));
  });

  describe('.getItemsList() secure (with ssl)', () => {
    before(() => {
      promise = P.getItemsList();
    });
    it('should succeed', () => promise);
    it('should have property count', () => chai.expect(promise).to.eventually.have.property('count'));
  });

  describe('.getItemAttributesList() secure (with ssl)', () => {
    before(() => {
      promise = P.getItemAttributesList();
    });
    it('should succeed', () => promise);
    it('should have property count', () => chai.expect(promise).to.eventually.have.property('count'));
  });

  describe('.getItemCategoriesList() secure (with ssl)', () => {
    before(() => {
      promise = P.getItemCategoriesList();
    });
    it('should succeed', () => promise);
    it('should have property count', () => chai.expect(promise).to.eventually.have.property('count'));
  });

  describe('.getItemFlingEffectsList() secure (with ssl)', () => {
    before(() => {
      promise = P.getItemFlingEffectsList();
    });
    it('should succeed', () => promise);
    it('should have property count', () => chai.expect(promise).to.eventually.have.property('count'));
  });

  describe('.getItemPocketsList() secure (with ssl)', () => {
    before(() => {
      promise = P.getItemPocketsList();
    });
    it('should succeed', () => promise);
    it('should have property count', () => chai.expect(promise).to.eventually.have.property('count'));
  });

  describe('.getMachinesList() secure (with ssl)', () => {
    before(() => {
      promise = P.getMachinesList();
    });
    it('should succeed', () => promise);
    it('should have property count', () => chai.expect(promise).to.eventually.have.property('count'));
  });

  describe('.getMovesList() secure (with ssl)', () => {
    before(() => {
      promise = P.getMovesList();
    });
    it('should succeed', () => promise);
    it('should have property count', () => chai.expect(promise).to.eventually.have.property('count'));
  });

  describe('.getMoveAilmentsList() secure (with ssl)', () => {
    before(() => {
      promise = P.getMoveAilmentsList();
    });
    it('should succeed', () => promise);
    it('should have property count', () => chai.expect(promise).to.eventually.have.property('count'));
  });

  describe('.getMoveBattleStylesList() secure (with ssl)', () => {
    before(() => {
      promise = P.getMoveBattleStylesList();
    });
    it('should succeed', () => promise);
    it('should have property count', () => chai.expect(promise).to.eventually.have.property('count'));
  });

  describe('.getMoveCategoriesList() secure (with ssl)', () => {
    before(() => {
      promise = P.getMoveCategoriesList();
    });
    it('should succeed', () => promise);
    it('should have property count', () => chai.expect(promise).to.eventually.have.property('count'));
  });

  describe('.getMoveDamageClassesList() secure (with ssl)', () => {
    before(() => {
      promise = P.getMoveDamageClassesList();
    });
    it('should succeed', () => promise);
    it('should have property count', () => chai.expect(promise).to.eventually.have.property('count'));
  });

  describe('.getMoveLearnMethodsList() secure (with ssl)', () => {
    before(() => {
      promise = P.getMoveLearnMethodsList();
    });
    it('should succeed', () => promise);
    it('should have property count', () => chai.expect(promise).to.eventually.have.property('count'));
  });

  describe('.getMoveTargetsList() secure (with ssl)', () => {
    before(() => {
      promise = P.getMoveTargetsList();
    });
    it('should succeed', () => promise);
    it('should have property count', () => chai.expect(promise).to.eventually.have.property('count'));
  });

  describe('.getLocationsList() secure (with ssl)', () => {
    before(() => {
      promise = P.getLocationsList();
    });
    it('should succeed', () => promise);
    it('should have property count', () => chai.expect(promise).to.eventually.have.property('count'));
  });

  describe('.getLocationAreasList() secure (with ssl)', () => {
    before(() => {
      promise = P.getLocationAreasList();
    });
    it('should succeed', () => promise);
    it('should have property count', () => chai.expect(promise).to.eventually.have.property('count'));
  });

  describe('.getPalParkAreasList() secure (with ssl)', () => {
    before(() => {
      promise = P.getPalParkAreasList();
    });
    it('should succeed', () => promise);
    it('should have property count', () => chai.expect(promise).to.eventually.have.property('count'));
  });

  describe('.getRegionsList() secure (with ssl)', () => {
    before(() => {
      promise = P.getRegionsList();
    });
    it('should succeed', () => promise);
    it('should have property count', () => chai.expect(promise).to.eventually.have.property('count'));
  });

  describe('.getAbilitiesList() secure (with ssl)', () => {
    before(() => {
      promise = P.getAbilitiesList();
    });
    it('should succeed', () => promise);
    it('should have property count', () => chai.expect(promise).to.eventually.have.property('count'));
  });

  describe('.getCharacteristicsList() secure (with ssl)', () => {
    before(() => {
      promise = P.getCharacteristicsList();
    });
    it('should succeed', () => promise);
    it('should have property count', () => chai.expect(promise).to.eventually.have.property('count'));
  });

  describe('.getEggGroupsList() secure (with ssl)', () => {
    before(() => {
      promise = P.getEggGroupsList();
    });
    it('should succeed', () => promise);
    it('should have property count', () => chai.expect(promise).to.eventually.have.property('count'));
  });

  describe('.getGendersList() secure (with ssl)', () => {
    before(() => {
      promise = P.getGendersList();
    });
    it('should succeed', () => promise);
    it('should have property count', () => chai.expect(promise).to.eventually.have.property('count'));
  });

  describe('.getGrowthRatesList() secure (with ssl)', () => {
    before(() => {
      promise = P.getGrowthRatesList();
    });
    it('should succeed', () => promise);
    it('should have property count', () => chai.expect(promise).to.eventually.have.property('count'));
  });

  describe('.getNaturesList() secure (with ssl)', () => {
    before(() => {
      promise = P.getNaturesList();
    });
    it('should succeed', () => promise);
    it('should have property count', () => chai.expect(promise).to.eventually.have.property('count'));
  });

  describe('.getPokeathlonStatsList() secure (with ssl)', () => {
    before(() => {
      promise = P.getPokeathlonStatsList();
    });
    it('should succeed', () => promise);
    it('should have property count', () => chai.expect(promise).to.eventually.have.property('count'));
  });

  describe('.getPokemonsList() secure (with ssl)', () => {
    before(() => {
      promise = P.getPokemonsList();
    });
    it('should succeed', () => promise);
    it('should have property count', () => chai.expect(promise).to.eventually.have.property('count'));
  });

  describe('.getPokemonColorsList() secure (with ssl)', () => {
    before(() => {
      promise = P.getPokemonColorsList();
    });
    it('should succeed', () => promise);
    it('should have property count', () => chai.expect(promise).to.eventually.have.property('count'));
  });

  describe('.getPokemonFormsList() secure (with ssl)', () => {
    before(() => {
      promise = P.getPokemonFormsList();
    });
    it('should succeed', () => promise);
    it('should have property count', () => chai.expect(promise).to.eventually.have.property('count'));
  });

  describe('.getPokemonHabitatsList() secure (with ssl)', () => {
    before(() => {
      promise = P.getPokemonHabitatsList();
    });
    it('should succeed', () => promise);
    it('should have property count', () => chai.expect(promise).to.eventually.have.property('count'));
  });

  describe('.getPokemonShapesList() secure (with ssl)', () => {
    before(() => {
      promise = P.getPokemonShapesList();
    });
    it('should succeed', () => promise);
    it('should have property count', () => chai.expect(promise).to.eventually.have.property('count'));
  });

  describe('.getPokemonSpeciesList() secure (with ssl)', () => {
    before(() => {
      promise = P.getPokemonSpeciesList();
    });
    it('should succeed', () => promise);
    it('should have property count', () => chai.expect(promise).to.eventually.have.property('count'));
  });

  describe('.getStatsList() secure (with ssl)', () => {
    before(() => {
      promise = P.getStatsList();
    });
    it('should succeed', () => promise);
    it('should have property count', () => chai.expect(promise).to.eventually.have.property('count'));
  });

  describe('.getTypesList() secure (with ssl)', () => {
    before(() => {
      promise = P.getTypesList();
    });
    it('should succeed', () => promise);
    it('should have property count', () => chai.expect(promise).to.eventually.have.property('count'));
  });

  describe('.getLanguagesList() secure (with ssl)', () => {
    before(() => {
      promise = P.getLanguagesList();
    });
    it('should succeed', () => promise);
    it('should have property count', () => chai.expect(promise).to.eventually.have.property('count'));
  });
});


text:
<Type Name="Population" FullName="ObviousCode.Alchemy.Library.Populous.Population">
  <TypeSignature Language="C#" Value="public class Population" />
  <TypeSignature Language="ILAsm" Value=".class public auto ansi beforefieldinit Population extends System.Object" />
  <AssemblyInfo>
    <AssemblyName>ObviousCode.Alchemy.Library</AssemblyName>
    <AssemblyVersion>1.0.5553.31673</AssemblyVersion>
  </AssemblyInfo>
  <Base>
    <BaseTypeName>System.Object</BaseTypeName>
  </Base>
  <Interfaces />
  <Docs>
    To be added.
    <remarks>To be added.</remarks>
  </Docs>
  <Members>
    <Member MemberName=".ctor">
      <MemberSignature Language="C#" Value="public Population ();" />
      <MemberSignature Language="ILAsm" Value=".method public hidebysig specialname rtspecialname instance void .ctor() cil managed" />
      <MemberType>Constructor</MemberType>
      <AssemblyInfo>
        <AssemblyVersion>1.0.5553.31673</AssemblyVersion>
      </AssemblyInfo>
      <Parameters />
      <Docs>
        To be added.
        <remarks>To be added.</remarks>
      </Docs>
    </Member>
    <Member MemberName="IsInitialised">
      <MemberSignature Language="C#" Value="public bool IsInitialised { get; protected set; }" />
      <MemberSignature Language="ILAsm" Value=".property instance bool IsInitialised" />
      <MemberType>Property</MemberType>
      <AssemblyInfo>
        <AssemblyVersion>1.0.5553.31673</AssemblyVersion>
      </AssemblyInfo>
      <ReturnValue>
        <ReturnType>System.Boolean</ReturnType>
      </ReturnValue>
      <Docs>
        To be added.
        <value>To be added.</value>
        <remarks>To be added.</remarks>
      </Docs>
    </Member>
  </Members>
</Type>


text:
include_recipe "opsview_client"

opsview_client node['fqdn'] do
  api_user     node['opsview_client_test']['user']
  api_password node['opsview_client_test']['password']
  api_host     node['opsview_client_test']['host']
  api_protocol node['opsview_client_test']['protocol']
  api_port     node['opsview_client_test']['port']
  ip           node['ipaddress']
  hostgroup    node['opsview_client_test']['hostgroup']
  hostalias    node['opsview_client_test']['hostalias']
  hosttemplates node['opsview_client_test']['hosttemplates']
  reload_opsview node['opsview_client_test']['reload_opsview']
end


text:
// Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// SystemStorage eject API browser tests.

#include "base/files/file_path.h"
#include "base/strings/stringprintf.h"
#include "base/strings/utf_string_conversions.h"
#include "components/storage_monitor/storage_info.h"
#include "components/storage_monitor/storage_monitor.h"
#include "components/storage_monitor/test_storage_monitor.h"
#include "content/public/browser/render_frame_host.h"
#include "content/public/browser/render_view_host.h"
#include "content/public/test/test_utils.h"
#include "extensions/browser/api/system_storage/storage_api_test_util.h"
#include "extensions/browser/api/system_storage/storage_info_provider.h"
#include "extensions/browser/extension_host.h"
#include "extensions/browser/process_manager.h"
#include "extensions/common/extension.h"
#include "extensions/shell/test/shell_apitest.h"
#include "extensions/test/extension_test_message_listener.h"

namespace {

using extensions::test::TestStorageUnitInfo;
using extensions::test::kRemovableStorageData;
using storage_monitor::StorageMonitor;
using storage_monitor::TestStorageMonitor;

}  // namespace

class SystemStorageEjectApiTest : public extensions::ShellApiTest {
 public:
  SystemStorageEjectApiTest() : monitor_(NULL) {}
  ~SystemStorageEjectApiTest() override {}

 protected:
  void SetUpOnMainThread() override {
    monitor_ = TestStorageMonitor::CreateForBrowserTests();
    ShellApiTest::SetUpOnMainThread();
  }

  content::RenderViewHost* GetHost() {
    ExtensionTestMessageListener listener("loaded", false);
    const extensions::Extension* extension = LoadApp("system/storage_eject");

    // Wait for the extension to load completely so we can execute
    // the JavaScript function from test case.
    EXPECT_TRUE(listener.WaitUntilSatisfied());

    return extensions::ProcessManager::Get(browser_context())
        ->GetBackgroundHostForExtension(extension->id())
        ->render_view_host();
  }

  void ExecuteCmdAndCheckReply(content::RenderViewHost* host,
                               const std::string& js_command,
                               const std::string& ok_message) {
    ExtensionTestMessageListener listener(ok_message, false);
    host->GetMainFrame()->ExecuteJavaScript(base::ASCIIToUTF16(js_command));
    EXPECT_TRUE(listener.WaitUntilSatisfied());
  }

  void Attach() {
    DCHECK(StorageMonitor::GetInstance()->IsInitialized());
    StorageMonitor::GetInstance()->receiver()->ProcessAttach(
        extensions::test::BuildStorageInfoFromTestStorageUnitInfo(
            kRemovableStorageData));
    content::RunAllPendingInMessageLoop();
  }

  void Detach() {
    DCHECK(StorageMonitor::GetInstance()->IsInitialized());
    StorageMonitor::GetInstance()->receiver()->ProcessDetach(
        kRemovableStorageData.device_id);
    content::RunAllPendingInMessageLoop();
  }

 protected:
  TestStorageMonitor* monitor_;

 private:
  DISALLOW_COPY_AND_ASSIGN(SystemStorageEjectApiTest);
};

IN_PROC_BROWSER_TEST_F(SystemStorageEjectApiTest, EjectTest) {
  content::RenderViewHost* host = GetHost();
  ExecuteCmdAndCheckReply(host, "addAttachListener()", "add_attach_ok");

  // Attach / detach
  const std::string expect_attach_msg =
      base::StringPrintf("%s,%s", "attach_test_ok", kRemovableStorageData.name);
  ExtensionTestMessageListener attach_finished_listener(expect_attach_msg,
                                                        false /* no reply */);
  Attach();
  EXPECT_TRUE(attach_finished_listener.WaitUntilSatisfied());

  ExecuteCmdAndCheckReply(host, "ejectTest()", "eject_ok");
  EXPECT_EQ(kRemovableStorageData.device_id, monitor_->ejected_device());

  Detach();
}

IN_PROC_BROWSER_TEST_F(SystemStorageEjectApiTest, EjectBadDeviceTest) {
  ExecuteCmdAndCheckReply(GetHost(), "ejectFailTest()", "eject_no_such_device");

  EXPECT_EQ("", monitor_->ejected_device());
}


text:
	<form class="g85 p2 pv2" ng-if="routeParams.view == 'create' || routeParams.view == 'edit'" ng-submit="put()">

			{{_('Name')}}
			<input type="text" id="name" ng-model="current.name" class="form-control" placeholder="{{_('Name')}}" />

			{{_('Parent category')}}
			<select class="form-control" id="parent" ng-model="current.parent" milo-match-entity="'categories'"></select>

		<button>{{_('Submit')}}</button>
	</form>


text:
<?php

// autoload_real.php @generated by Composer

class ComposerAutoloaderInitb288e28ed2e9ea1d91d353a891550986
{

    private static $loader;

    public static function loadClassLoader($class)
    {

        if ('Composer\Autoload\ClassLoader' === $class) {
            require __DIR__.'/ClassLoader.php';
        }
    }

    public static function getLoader()
    {

        if (null !== self::$loader) {
            return self::$loader;
        }

        spl_autoload_register(array('ComposerAutoloaderInitb288e28ed2e9ea1d91d353a891550986', 'loadClassLoader'),
            true, true);
        self::$loader = $loader = new \Composer\Autoload\ClassLoader();
        spl_autoload_unregister(array('ComposerAutoloaderInitb288e28ed2e9ea1d91d353a891550986', 'loadClassLoader'));

        $map = require __DIR__.'/autoload_namespaces.php';
        foreach ($map as $namespace => $path) {
            $loader->set($namespace, $path);
        }

        $map = require __DIR__.'/autoload_psr4.php';
        foreach ($map as $namespace => $path) {
            $loader->setPsr4($namespace, $path);
        }

        $classMap = require __DIR__.'/autoload_classmap.php';
        if ($classMap) {
            $loader->addClassMap($classMap);
        }

        spl_autoload_register(array('ComposerAutoloaderInitb288e28ed2e9ea1d91d353a891550986', 'autoload'), true,
            true);

        $loader->register(true);

        return $loader;
    }

    public static function autoload($class)
    {

        $dir = dirname(dirname(__DIR__)).'/';
        $prefixes = array('Eden\\Mail\\');
        foreach ($prefixes as $prefix) {
            if (0 !== strpos($class, $prefix)) {
                continue;
            }
            $path = $dir.implode('/', array_slice(explode('\\', $class), 2)).'.php';
            if (!$path = stream_resolve_include_path($path)) {
                return false;
            }
            require $path;

            return true;
        }
    }
}

function composerRequireb288e28ed2e9ea1d91d353a891550986($file)
{

    require $file;
}


text:
class CreateDateDeliveries < ActiveRecord::Migration
  def change
    create_table :date_deliveries do |t|
    	t.integer :product_id
    	t.date :delivery_date

      t.timestamps
    end
  end
end


text:
package io.gatling.http.action.async.sse

import java.nio.charset.StandardCharsets._

import scala.annotation.tailrec

import io.gatling.commons.util.StringHelper._

import io.netty.buffer.ByteBuf

object EventStreamParser {

  private final val LF = 0x0A
  private final val CR = 0x0D

  object Event {

    def unapply(cs: CharSequence, prefix: Array[Char]): Option[String] =
      if (cs.startWith(prefix)) {
        val subCs =
          if (cs.length > prefix.length + 1 && cs.charAt(prefix.length) == ' ')
            cs.subSequence(prefix.length + 1, cs.length)
          else
            cs.subSequence(prefix.length, cs.length)

        Some(subCs.toString)
      } else
        None

  }

  case object Dispatch {
    def unapply(cs: CharSequence): Option[Unit] = if (cs.contains(_ != ' ')) None else Some(Unit)
  }

  object EventName {
    val EventPrefix = "event:".toCharArray
    def unapply(cs: CharSequence): Option[String] = Event.unapply(cs, EventPrefix)
  }

  object Id {
    val IdPrefix = "id:".toCharArray
    def unapply(cs: CharSequence) = Event.unapply(cs, IdPrefix)
  }

  object Retry {
    val RetryPrefix = "retry:".toCharArray
    def unapply(cs: CharSequence) = Event.unapply(cs, RetryPrefix)
  }

  object Data {
    val DataPrefix = "data:".toCharArray
    def unapply(cs: CharSequence) = Event.unapply(cs, DataPrefix)
  }

  implicit class EventStream(val string: String) extends AnyVal {

    def eventLines: Iterator[CharSequence] = {

      val chars = ArrayCharSequence(string.unsafeChars)
      val length = string.length

      val last =
        if (string.isEmpty)
          0
        else if (length >= 2 && chars.charAt(length - 2) == CR && chars.charAt(length - 1) == LF)
          length - 2
        else if (length >= 1 && chars.charAt(length - 1) == CR || chars.charAt(length - 1) == LF)
          length - 1
        else
          length

        @tailrec
        def loop(start: Int, curr: Int, it: Iterator[CharSequence], inline: Boolean): Iterator[CharSequence] = {

          if (curr == last) {
            val newLine = if (inline) chars.subSequence(start, curr) else EmptyCharSequence
            it ++ Iterator.single(newLine)

          } else
            chars.charAt(curr) match {
              case LF | CR =>
                if (inline)
                  loop(curr + 1, curr + 1, it ++ Iterator.single(chars.subSequence(start, curr)), inline = false)
                else
                  loop(curr + 1, curr + 1, it, inline = false)

              case _ =>
                loop(start, curr + 1, it, inline = true)
            }
        }

      loop(0, 0, Iterator.empty, inline = true)
    }
  }
}

trait EventStreamParser { this: EventStreamDispatcher =>

  import EventStreamParser._

  var currentSse = ServerSentEvent()

  def parse(byteBuf: ByteBuf): Unit =
    byteBuf.toString(UTF_8).eventLines.foreach {
      case EventName(name) => currentSse = currentSse.copy(name = Some(name))
      case Id(id)          => currentSse = currentSse.copy(id = Some(id))
      case Retry(retry)    => currentSse = currentSse.copy(retry = Some(retry.toInt))
      case Data(data) =>
        val newData = currentSse.data match {
          case None          => data
          case Some(oldData) => oldData + "\n" + data
        }
        currentSse = currentSse.copy(data = Some(newData))
      case Dispatch(_) => currentSse = dispatchEvent()
      case _           =>
    }

  private def dispatchEvent(): ServerSentEvent =
    currentSse.data match {
      case None => currentSse.copy(name = None)
      case _ =>
        dispatchEventStream(currentSse.copy())
        currentSse.copy(data = None, name = None)
    }
}


text:
from Pyro5.api import Proxy

uri = input("enter the server uri: ").strip()
if "\\x00" in uri:
    uri=uri.replace("\\x00", "\x00")
    print("(uri contains 0-byte)")

with Proxy(uri) as p:
    response = p.message("Hello there!")
    print("Response was:", response)