text:
"""Resources to be indexed and searched over by the search module."""

__author__ = 'Ellis Michael (emichael@google.com)'

import collections
import datetime
import gettext
import HTMLParser
import logging
import operator
import os
import Queue
import re
import robotparser
import urllib
import urlparse
from xml.dom import minidom

import jinja2

import appengine_config
from common import jinja_utils
from modules.announcements import announcements

from google.appengine.api import search
from google.appengine.api import urlfetch

PROTOCOL_PREFIX = 'http://'

YOUTUBE_DATA_URL = 'http://gdata.youtube.com/feeds/api/videos/'
YOUTUBE_TIMED_TEXT_URL = 'http://youtube.com/api/timedtext'

# The limit (in seconds) for the time that elapses before a new transcript
# fragment should be started. A lower value results in more fine-grain indexing
# and more docs in the index.
YOUTUBE_CAPTION_SIZE_SECS = 30

class URLNotParseableException(Exception):
    """Exception thrown when the resource at a URL cannot be parsed."""
    pass

class ResourceHTMLParser(HTMLParser.HTMLParser):
    """Custom parser for processing HTML files."""

    IGNORED_TAGS = ['script', 'style']

    def __init__(self, url):
        HTMLParser.HTMLParser.__init__(self)
        self.content_list = []
        self._links = []
        self._title = ''
        self.tag_tracker = collections.Counter()
        self.url = url

    def handle_starttag(self, tag, attrs):
        attrs_dict = dict(attrs)
        if tag == 'a' and 'href' in attrs_dict:
            self._links.append(urlparse.urljoin(self.url, attrs_dict['href']))

        self.tag_tracker[tag] += 1

    def handle_endtag(self, tag):
        if self.tag_tracker[tag] > 0:
            self.tag_tracker[tag] -= 1

    def handle_data(self, data):
        """Invoked every time the parser encounters the page's inner content."""
        if self.tag_tracker['title']:
            if self._title:
                self._title += '\n%s' % data
            else:
                self._title = data
        stripped_data = data.strip()
        if (not any([self.tag_tracker[tag] for tag in self.IGNORED_TAGS]) and
            stripped_data):
            self.content_list.append(stripped_data)

    def get_content(self):
        return '\n'.join(self.content_list)

    def get_links(self):
        return self._links

    def get_title(self):
        return self._title

def get_parser_for_html(url, ignore_robots=False):
    """Returns a ResourceHTMLParser with the parsed data."""

    if not (ignore_robots or _url_allows_robots(url)):
        raise URLNotParseableException('robots.txt disallows access to URL: %s'
                                       % url)

    parser = ResourceHTMLParser(url)
    try:
        result = urlfetch.fetch(url)
        if (result.status_code in [200, 304] and
            any(content_type in result.headers['Content-type'] for
                content_type in ['text/html', 'xml'])):
            if not isinstance(result.content, unicode):
                result.content = result.content.decode('utf-8')
            parser.feed(result.content)
        else:
            raise ValueError
    except BaseException as e:
        raise URLNotParseableException('Could not parse file at URL: %s\n%s' %
                                       (url, e))

    return parser

def get_minidom_from_xml(url, ignore_robots=False):
    """Returns a minidom representation of an XML file at url."""

    if not (ignore_robots or _url_allows_robots(url)):
        raise URLNotParseableException('robots.txt disallows access to URL: %s'
                                       % url)

    try:
        result = urlfetch.fetch(url)
    except urlfetch.Error as e:
        raise URLNotParseableException('Could not parse file at URL: %s. %s' %
                                       (url, e))
    if result.status_code not in [200, 304]:
        raise URLNotParseableException('Bad status code (%s) for URL: %s' %
                                       (result.status_code, url))

    try:
        if isinstance(result.content, unicode):
            result.content = result.content.encode('utf-8')
        xmldoc = minidom.parseString(result.content)
    except BaseException as e:
        raise URLNotParseableException(
            'Error parsing XML document at URL: %s. %s' % (url, e))

    return xmldoc

def _url_allows_robots(url):
    """Checks robots.txt for user agent * at URL."""
    url = url.encode('utf-8')
    try:
        parts = urlparse.urlparse(url)
        base = urlparse.urlunsplit((
            parts.scheme, parts.netloc, '', None, None))
        rp = robotparser.RobotFileParser(url=urlparse.urljoin(
            base, '/robots.txt'))
        rp.read()
    except BaseException as e:
        logging.info('Could not retreive robots.txt for URL: %s', url)
        raise URLNotParseableException(e)
    else:
        return rp.can_fetch('*', url)

class Resource(object):
    """Abstract superclass for a resource."""

    # Each subclass should define this constant
    TYPE_NAME = 'Resource'

    # Each subclass should use this constant to define the fields it needs
    # returned with a search result.
    RETURNED_FIELDS = []

    # Each subclass should use this constant to define the fields it needs
    # returned as snippets in the search result. In most cases, this should be
    # one field.
    SNIPPETED_FIELDS = []

    # Each subclass should use this constant to define how many days should
    # elapse before a resource should be re-indexed. This value should be
    # nonnegative.
    FRESHNESS_THRESHOLD_DAYS = 0

    @classmethod
    def generate_all(
        cls, course, timestamps):  # pylint: disable-msg=unused-argument
        """A generator returning objects of type cls in the course.

        This generator should yield resources based on the last indexed time in
        timestamps.

        Args:
            course: models.courses.course. the course to index.
            timestamps: dict from doc_ids to last indexed datetimes.
        Yields:
            A sequence of Resource objects.
        """

        # For the superclass, return a generator which immediately halts. All
        # implementations in subclasses must also be generators for memory-
        # management reasons.
        return
        yield  # pylint: disable-msg=unreachable

    @classmethod
    def _get_doc_id(cls, *unused_vargs):
        """Subclasses should implement this with identifying fields as args."""
        raise NotImplementedError

    @classmethod
    def _indexed_within_num_days(cls, timestamps, doc_id, num_days):
        """Determines whether doc_id was indexed in the last num_days days."""
        try:
            timestamp = timestamps[doc_id]
        except (KeyError, TypeError):
            return False
        else:
            delta = datetime.datetime.utcnow() - timestamp
            return delta <= datetime.timedelta(num_days)

    def get_document(self):
        """Return a search.Document to be indexed."""
        raise NotImplementedError

    def get_links(self):
        """External links to be indexed should be stored in self.links."""
        return self.links if hasattr(self, 'links') else []

class Result(object):
    """The abstract superclass for a result returned by the search module."""

    def get_html(self):
        """Return an HTML fragment to be used in the results page."""
        raise NotImplementedError

    @classmethod
    def _generate_html_from_template(cls, template_name, template_value):
        """Generates marked-up HTML from template."""
        template = jinja_utils.get_template(
            template_name,
            [os.path.join(appengine_config.BUNDLE_ROOT,
                          'modules', 'search', 'results_templates')])
        return jinja2.Markup(template.render(template_value))

    @classmethod
    def _get_returned_field(cls, result, field):
        """Returns the value of a field in result, '' if none exists."""
        try:
            return result[field][0].value
        except (KeyError, IndexError, AttributeError):
            return ''

    @classmethod
    def _get_snippet(cls, result):
        """Returns the value of the snippet in result, '' if none exists."""
        try:
            return result.expressions[0].value
        except (AttributeError, IndexError):
            return ''

class LessonResource(Resource):
    """A lesson in a course."""
    TYPE_NAME = 'Lesson'
    RETURNED_FIELDS = ['title', 'unit_id', 'lesson_id', 'url']
    SNIPPETED_FIELDS = ['content']
    FRESHNESS_THRESHOLD_DAYS = 3

    @classmethod
    def generate_all(cls, course, timestamps):
        for lesson in course.get_lessons_for_all_units():
            unit = course.find_unit_by_id(lesson.unit_id)
            doc_id = cls._get_doc_id(lesson.unit_id, lesson.lesson_id)
            if (lesson.now_available and unit.now_available and
                not cls._indexed_within_num_days(timestamps, doc_id,
                                                 cls.FRESHNESS_THRESHOLD_DAYS)):
                try:
                    yield LessonResource(lesson)
                except HTMLParser.HTMLParseError as e:
                    logging.info(
                        'Error parsing objectives for Lesson %s.%s: %s',
                        lesson.unit_id, lesson.lesson_id, e)
                    continue

    @classmethod
    def _get_doc_id(cls, unit_id, lesson_id):
        return '%s_%s_%s' % (cls.TYPE_NAME, unit_id, lesson_id)

    def __init__(self, lesson):
        super(LessonResource, self).__init__()

        self.unit_id = lesson.unit_id
        self.lesson_id = lesson.lesson_id
        self.title = lesson.title
        if lesson.notes:
            self.notes = urlparse.urljoin(PROTOCOL_PREFIX, lesson.notes)
        else:
            self.notes = ''
        if lesson.objectives:
            parser = ResourceHTMLParser(PROTOCOL_PREFIX)
            parser.feed(lesson.objectives)
            self.content = parser.get_content()
            self.links = parser.get_links()
        else:
            self.content = ''

    def get_document(self):
        return search.Document(
            doc_id=self._get_doc_id(self.unit_id, self.lesson_id),
            fields=[
                search.TextField(name='title', value=self.title),
                search.TextField(name='content', value=self.content),
                search.TextField(name='url', value=(
                    'unit?unit=%s&lesson=%s' %
                    (self.unit_id, self.lesson_id))),
                search.TextField(name='type', value=self.TYPE_NAME),
                search.DateField(name='date',
                                 value=datetime.datetime.utcnow())])

class LessonResult(Result):
    """An object for a lesson in search results."""

    def __init__(self, search_result):
        super(LessonResult, self).__init__()
        self.url = self._get_returned_field(search_result, 'url')
        self.title = self._get_returned_field(search_result, 'title')
        self.snippet = self._get_snippet(search_result)

    def get_html(self):
        # I18N: Displayed in search results; denotes a lesson link.
        lesson_string = gettext.gettext('Lesson')
        template_value = {
            'result_title': '%s - %s' % (self.title, lesson_string),
            'result_url': self.url,
            'result_snippet': jinja2.Markup(self.snippet)
        }
        return self._generate_html_from_template('basic.html', template_value)

class ExternalLinkResource(Resource):
    """An external link from a course."""
    TYPE_NAME = 'ExternalLink'
    RETURNED_FIELDS = ['title', 'url']
    SNIPPETED_FIELDS = ['content']
    FRESHNESS_THRESHOLD_DAYS = 15

    # TODO(emichael): Allow the user to turn off external links in the dashboard

    @classmethod
    def generate_all_from_dist_dict(cls, link_dist, timestamps):
        """Generate all external links from a map from URL to distance.

        Args:
            link_dist: dict. a map from URL to distance in the link graph from
                the course.
            timestamps: dict from doc_ids to last indexed datetimes. An empty
                dict indicates that all documents should be generated.
        Yields:
            A sequence of ExternalLinkResource.
        """

        url_queue = Queue.LifoQueue()
        for url, dist in sorted(link_dist.iteritems(),
                                key=operator.itemgetter(1)):
            url_queue.put(url)

        while not url_queue.empty():
            url = url_queue.get()
            doc_id = cls._get_doc_id(url)

            if (cls._indexed_within_num_days(timestamps, doc_id,
                                             cls.FRESHNESS_THRESHOLD_DAYS)):
                continue

            dist = link_dist[url]
            if dist > 1:
                break

            try:
                resource = ExternalLinkResource(url)
            except URLNotParseableException as e:
                logging.info(e)
            else:
                if dist < 1:
                    for new_link in resource.get_links():
                        if new_link not in link_dist:
                            link_dist[new_link] = dist + 1
                            url_queue.put(new_link)
                yield resource

    def __init__(self, url):
        # distance is the distance from the course material in the link graph,
        # where a lesson notes page has a distance of 0
        super(ExternalLinkResource, self).__init__()

        self.url = url
        parser = get_parser_for_html(url)
        self.content = parser.get_content()
        self.title = parser.get_title()
        self.links = parser.get_links()

    @classmethod
    def _get_doc_id(cls, url):
        return '%s_%s' % (cls.TYPE_NAME, url)

    def get_document(self):
        return search.Document(
            doc_id=self._get_doc_id(self.url),
            fields=[
                search.TextField(name='title', value=self.title),
                search.TextField(name='content', value=self.content),
                search.TextField(name='url', value=self.url),
                search.TextField(name='type', value=self.TYPE_NAME),
                search.DateField(name='date',
                                 value=datetime.datetime.utcnow())])

class ExternalLinkResult(Result):
    """An object for an external link in the search results."""

    def __init__(self, search_result):
        super(ExternalLinkResult, self).__init__()

        self.url = self._get_returned_field(search_result, 'url')
        self.title = self._get_returned_field(search_result, 'title')
        self.snippet = self._get_snippet(search_result)

    def get_html(self):
        template_value = {
            'result_title': self.title,
            'result_url': self.url,
            'result_snippet': jinja2.Markup(self.snippet)
        }
        return self._generate_html_from_template('basic.html', template_value)

class YouTubeFragmentResource(Resource):
    """An object for a YouTube transcript fragment in search results."""
    TYPE_NAME = 'YouTubeFragment'
    RETURNED_FIELDS = ['title', 'video_id', 'start', 'thumbnail_url']
    SNIPPETED_FIELDS = ['content']
    FRESHNESS_THRESHOLD_DAYS = 30

    @classmethod
    def generate_all(cls, course, timestamps):
        """Generate all YouTubeFragments for a course."""
        # TODO(emichael): Handle the existence of a single video in multiple
        # places in a course.

        youtube_ct_regex = r"""<[ ]*gcb-youtube[^>]+videoid=['"]([^'"]+)['"]"""

        for lesson in course.get_lessons_for_all_units():
            unit = course.find_unit_by_id(lesson.unit_id)
            if not (lesson.now_available and unit.now_available):
                continue
            lesson_url = 'unit?unit=%s&lesson=%s' % (
                lesson.unit_id, lesson.lesson_id)

            if lesson.video and not cls._indexed_within_num_days(
                    timestamps, lesson.video, cls.FRESHNESS_THRESHOLD_DAYS):
                for fragment in cls._get_fragments_for_video(
                        lesson.video, lesson_url):
                    yield fragment

            match = re.search(youtube_ct_regex, lesson.objectives)
            if match:
                for video_id in match.groups():
                    if not cls._indexed_within_num_days(
                            timestamps, video_id, cls.FRESHNESS_THRESHOLD_DAYS):
                        for fragment in cls._get_fragments_for_video(
                                video_id, lesson_url):
                            yield fragment

        if announcements.custom_module.enabled:
            for entity in announcements.AnnouncementEntity.get_announcements():
                if entity.is_draft:
                    continue
                announcement_url = 'announcements#%s' % entity.key()
                match = re.search(youtube_ct_regex, entity.html)
                if match:
                    for video_id in match.groups():
                        if not cls._indexed_within_num_days(
                                timestamps, video_id,
                                cls.FRESHNESS_THRESHOLD_DAYS):
                            for fragment in cls._get_fragments_for_video(
                                    video_id, announcement_url):
                                yield fragment

    @classmethod
    def _indexed_within_num_days(cls, timestamps, video_id, num_days):
        for doc_id in timestamps:
            if doc_id.startswith(cls._get_doc_id(video_id, '')):
                return super(
                    YouTubeFragmentResource, cls)._indexed_within_num_days(
                        timestamps, doc_id, num_days)
        return False

    @classmethod
    def _get_fragments_for_video(cls, video_id, url_in_course):
        """Get all of the transcript fragment docs for a specific video."""
        try:
            (transcript, title, thumbnail_url) = cls._get_video_data(video_id)
        except BaseException as e:
            logging.info('Could not parse YouTube video with id %s.\n%s',
                         video_id, e)
            return []

        # Aggregate the fragments into YOUTUBE_CAPTION_SIZE_SECS time chunks
        fragments = transcript.getElementsByTagName('text')
        aggregated_fragments = []
        # This parser is only used for unescaping HTML entities
        parser = HTMLParser.HTMLParser()
        while fragments:
            current_start = float(fragments[0].attributes['start'].value)
            current_text = []

            while (fragments and
                   float(fragments[0].attributes['start'].value) -
                   current_start < YOUTUBE_CAPTION_SIZE_SECS):
                current_text.append(parser.unescape(
                    fragments.pop(0).firstChild.nodeValue))

            aggregated_fragment = YouTubeFragmentResource(
                video_id, url_in_course, current_start,
                '\n'.join(current_text), title, thumbnail_url)
            aggregated_fragments.append(aggregated_fragment)

        return aggregated_fragments

    @classmethod
    def _get_video_data(cls, video_id):
        """Returns (track_minidom, title, thumbnail_url) for a video."""

        try:
            vid_info = get_minidom_from_xml(
                urlparse.urljoin(YOUTUBE_DATA_URL, video_id),
                ignore_robots=True)
            title = vid_info.getElementsByTagName(
                'title')[0].firstChild.nodeValue
            thumbnail_url = vid_info.getElementsByTagName(
                'media:thumbnail')[0].attributes['url'].value
        except (URLNotParseableException, IOError,
                IndexError, AttributeError) as e:
            logging.error('Could not parse video info for video id %s.\n%s',
                          video_id, e)
            title = ''
            thumbnail_url = ''

        # TODO(emichael): Handle the existence of multiple tracks
        url = urlparse.urljoin(YOUTUBE_TIMED_TEXT_URL,
                               '?v=%s&type=list' % video_id)
        tracklist = get_minidom_from_xml(url, ignore_robots=True)
        tracks = tracklist.getElementsByTagName('track')
        if not tracks:
            raise URLNotParseableException('No tracks for video %s' % video_id)
        track_name = tracks[0].attributes['name'].value
        track_lang = tracks[0].attributes['lang_code'].value
        track_id = tracks[0].attributes['id'].value

        url = urlparse.urljoin(YOUTUBE_TIMED_TEXT_URL, urllib.quote(
            '?v=%s&lang=%s&name=%s&id=%s' %
            (video_id, track_lang, track_name, track_id), '?/=&'))
        transcript = get_minidom_from_xml(url, ignore_robots=True)

        return (transcript, title, thumbnail_url)

    @classmethod
    def _get_doc_id(cls, video_id, start_time):
        return '%s_%s_%s' % (cls.TYPE_NAME, video_id, start_time)

    def __init__(self, video_id, url, start, text, video_title, thumbnail_url):
        super(YouTubeFragmentResource, self).__init__()

        self.url = url
        self.video_id = video_id
        self.start = start
        self.text = text
        self.video_title = video_title
        self.thumbnail_url = thumbnail_url

    def get_document(self):
        return search.Document(
            doc_id=self._get_doc_id(self.video_id, self.start),
            fields=[
                search.TextField(name='title', value=self.video_title),
                search.TextField(name='video_id', value=self.video_id),
                search.TextField(name='content', value=self.text),
                search.NumberField(name='start', value=self.start),
                search.TextField(name='thumbnail_url',
                                 value=self.thumbnail_url),
                search.TextField(name='url', value=self.url),
                search.TextField(name='type', value=self.TYPE_NAME),
                search.DateField(name='date',
                                 value=datetime.datetime.utcnow())])

class YouTubeFragmentResult(Result):
    """An object for a lesson in search results."""

    def __init__(self, search_result):
        super(YouTubeFragmentResult, self).__init__()
        self.doc_id = search_result.doc_id
        self.title = self._get_returned_field(search_result, 'title')
        self.video_id = self._get_returned_field(search_result, 'video_id')
        self.start = self._get_returned_field(search_result, 'start')
        self.thumbnail_url = self._get_returned_field(search_result,
                                                      'thumbnail_url')
        self.url = self._get_returned_field(search_result, 'url')
        self.snippet = self._get_snippet(search_result)

    def get_html(self):
        template_value = {
            'result_title': self.title,
            'result_url': self.url,
            'video_id': self.video_id,
            'start_time': self.start,
            'thumbnail_url': self.thumbnail_url,
            'result_snippet': jinja2.Markup(self.snippet)
        }
        return self._generate_html_from_template('youtube.html', template_value)

class AnnouncementResource(Resource):
    """An announcement in a course."""
    TYPE_NAME = 'Announcement'
    RETURNED_FIELDS = ['title', 'url']
    SNIPPETED_FIELDS = ['content']
    FRESHNESS_THRESHOLD_DAYS = 1

    @classmethod
    def generate_all(cls, course, timestamps):
        if announcements.custom_module.enabled:
            for entity in announcements.AnnouncementEntity.get_announcements():
                doc_id = cls._get_doc_id(entity.key())
                if not(entity.is_draft or cls._indexed_within_num_days(
                        timestamps, doc_id, cls.FRESHNESS_THRESHOLD_DAYS)):
                    try:
                        yield AnnouncementResource(entity)
                    except HTMLParser.HTMLParseError as e:
                        logging.info('Error parsing Announcement %s: %s',
                                     entity.title, e)
                        continue

    def __init__(self, announcement):
        super(AnnouncementResource, self).__init__()

        self.title = announcement.title
        self.key = announcement.key()
        parser = ResourceHTMLParser(PROTOCOL_PREFIX)
        parser.feed(announcement.html)
        self.content = parser.get_content()

    @classmethod
    def _get_doc_id(cls, key):
        return '%s_%s' % (cls.TYPE_NAME, key)

    def get_document(self):
        return search.Document(
            doc_id=self._get_doc_id(self.key),
            fields=[
                search.TextField(name='title', value=self.title),
                search.TextField(name='content', value=self.content),
                search.TextField(name='url',
                                 value='announcements#%s' % self.key),
                search.TextField(name='type', value=self.TYPE_NAME),
                search.DateField(name='date',
                                 value=datetime.datetime.utcnow())])

class AnnouncementResult(Result):
    """An object for an announcement in search results."""

    def __init__(self, search_result):
        super(AnnouncementResult, self).__init__()
        self.url = self._get_returned_field(search_result, 'url')
        self.title = self._get_returned_field(search_result, 'title')
        self.snippet = self._get_snippet(search_result)

    def get_html(self):
        # I18N: Displayed in search results; denotes an announcement link.
        announcement_string = gettext.gettext('Announcement')
        template_value = {
            'result_title': '%s - %s' % (self.title, announcement_string),
            'result_url': self.url,
            'result_snippet': jinja2.Markup(self.snippet)
        }
        return self._generate_html_from_template('basic.html', template_value)

# Register new resource types here
RESOURCE_TYPES = [
    (LessonResource, LessonResult),
    (ExternalLinkResource, ExternalLinkResult),
    (YouTubeFragmentResource, YouTubeFragmentResult),
    (AnnouncementResource, AnnouncementResult)
]

def get_returned_fields():
    """Returns a list of fields that should be returned in a search result."""
    returned_fields = set(['type'])
    for resource_type, unused_result_type in RESOURCE_TYPES:
        returned_fields |= set(resource_type.RETURNED_FIELDS)
    return list(returned_fields)

def get_snippeted_fields():
    """Returns a list of fields that should be snippeted in a search result."""
    snippeted_fields = set()
    for resource_type, unused_result_type in RESOURCE_TYPES:
        snippeted_fields |= set(resource_type.SNIPPETED_FIELDS)
    return list(snippeted_fields)

def generate_all_documents(course, timestamps):
    """A generator for all docs for a given course.

    Args:
        course: models.courses.Course. the course to be indexed.
        timestamps: dict from doc_ids to last indexed datetimes. An empty dict
            indicates that all documents should be generated.
    Yields:
        A sequence of search.Document. If a document is within the freshness
        threshold, no document will be generated. This function does not modify
        timestamps.
    """

    link_dist = {}

    for resource_type, unused_result_type in RESOURCE_TYPES:
        for resource in resource_type.generate_all(course, timestamps):

            if isinstance(resource, LessonResource) and resource.notes:
                link_dist[resource.notes] = 0
            for link in resource.get_links():
                link_dist[link] = 1

            yield resource.get_document()

    for resource in ExternalLinkResource.generate_all_from_dist_dict(
            link_dist, timestamps):
        yield resource.get_document()

def process_results(results):
    """Generate result objects for the results of a query."""
    result_types = {resource_type.TYPE_NAME: result_type
                    for (resource_type, result_type) in RESOURCE_TYPES}

    processed_results = []
    for result in results:
        try:
            result_type = result_types[result['type'][0].value]
            processed_results.append(result_type(result))
        except (AttributeError, IndexError, KeyError) as e:
            # If there is no type information, we cannot process the result
            logging.error("%s. Couldn't process result", e)

    return processed_results


text:
layout: examples
title: Navbar Template
extra_css:
  - "navbar.css"
---

  Never expand
  <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarsExample01" aria-controls="navbarsExample01" aria-expanded="false" aria-label="Toggle navigation">

  </button>

        Home (current)

        Link

        Disabled

        Dropdown

          Action
          Another action
          Something else here

    <form class="form-inline my-2 my-md-0">
      <input class="form-control" type="text" placeholder="Search" aria-label="Search">
    </form>

  Always expand
  <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarsExample02" aria-controls="navbarsExample02" aria-expanded="false" aria-label="Toggle navigation">

  </button>

        Home (current)

        Link

    <form class="form-inline my-2 my-md-0">
      <input class="form-control" type="text" placeholder="Search">
    </form>

  Expand at sm
  <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarsExample03" aria-controls="navbarsExample03" aria-expanded="false" aria-label="Toggle navigation">

  </button>

        Home (current)

        Link

        Disabled

        Dropdown

          Action
          Another action
          Something else here

    <form class="form-inline my-2 my-md-0">
      <input class="form-control" type="text" placeholder="Search">
    </form>

  Expand at md
  <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarsExample04" aria-controls="navbarsExample04" aria-expanded="false" aria-label="Toggle navigation">

  </button>

        Home (current)

        Link

        Disabled

        Dropdown

          Action
          Another action
          Something else here

    <form class="form-inline my-2 my-md-0">
      <input class="form-control" type="text" placeholder="Search">
    </form>

  Expand at lg
  <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarsExample05" aria-controls="navbarsExample05" aria-expanded="false" aria-label="Toggle navigation">

  </button>

        Home (current)

        Link

        Disabled

        Dropdown

          Action
          Another action
          Something else here

    <form class="form-inline my-2 my-md-0">
      <input class="form-control" type="text" placeholder="Search">
    </form>

  Expand at xl
  <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarsExample06" aria-controls="navbarsExample06" aria-expanded="false" aria-label="Toggle navigation">

  </button>

        Home (current)

        Link

        Disabled

        Dropdown

          Action
          Another action
          Something else here

    <form class="form-inline my-2 my-md-0">
      <input class="form-control" type="text" placeholder="Search">
    </form>

    Container
    <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarsExample07" aria-controls="navbarsExample07" aria-expanded="false" aria-label="Toggle navigation">

    </button>

          Home (current)

          Link

          Disabled

          Dropdown

            Action
            Another action
            Something else here

      <form class="form-inline my-2 my-md-0">
        <input class="form-control" type="text" placeholder="Search" aria-label="Search">
      </form>

  <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarsExample08" aria-controls="navbarsExample08" aria-expanded="false" aria-label="Toggle navigation">

  </button>

        Centered nav only (current)

        Link

        Disabled

        Dropdown

          Action
          Another action
          Something else here

    Navbar
    <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarsExample09" aria-controls="navbarsExample09" aria-expanded="false" aria-label="Toggle navigation">

    </button>

          Home (current)

          Link

          Disabled

          Dropdown

            Action
            Another action
            Something else here

      <form class="form-inline my-2 my-md-0">
        <input class="form-control" type="text" placeholder="Search" aria-label="Search">
      </form>

    <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarsExample10" aria-controls="navbarsExample10" aria-expanded="false" aria-label="Toggle navigation">

    </button>

          Centered nav only (current)

          Link

          Disabled

          Dropdown

            Action
            Another action
            Something else here

Navbar examples

This example is a quick exercise to illustrate how the navbar and its contents work. Some navbars extend the width of the viewport, others are confined within a .container. For positioning of navbars, checkout the <a href="{{< docsref "/examples/navbar-static" >}}">top and <a href="{{< docsref "/examples/navbar-fixed" >}}">fixed top examples.

At the smallest breakpoint, the collapse plugin is used to hide the links and show a menu button to toggle the collapsed content.

          <a class="btn btn-primary" href="{{< docsref "/components/navbar" >}}" role="button">View navbar docs »

redpajama_set_name: RedPajamaGithub


text:
from tastypie.authorization import Authorization
from tastypie.exceptions import BadRequest
from tastypie.exceptions import Unauthorized
import logging
logger = logging.getLogger(__name__)
logger_debug = logging.getLogger(__name__)
from cbh_core_ws.authorization import editor_projects, viewer_projects

class AttachmentAuthorization(Authorization):
    def login_checks(self, request, model_klass, perms=None):

        # If it doesn't look like a model, we can't check permissions.
        # if not model_klass or not getattr(model_klass, '_meta', None):
        #     print "improper_setup_of_authorization"
        #     raise Unauthorized("improper_setup_of_authorization")
        # User must be logged in to check permissions.
        if not hasattr(request, 'user'):
            print "no_logged_in_user"
            raise Unauthorized("no_logged_in_user")

    def create_list(self, object_list, bundle):
        raise BadRequest("Creating a list is not yet authorized")

    def update_list(self, object_list, bundle):
        raise BadRequest("Creating a list is not yet authorized")

    def update_detail(self, object_list, bundle):
        raise BadRequest("Updating is not yet authorized")

    def project_ids(self, request, ):
        pids = viewer_projects(request.user)
        return pids

    def read_detail(self, object_list, bundle):

        self.login_checks(bundle.request, bundle.obj.__class__)
        pids = viewer_projects(bundle.request.user)
        allowed = False
        if bundle.obj.data_point_classification.l0_permitted_projects.count() == 0:
            raise BadRequest("You must specify at least one project")
        for projbundle in bundle.obj.data_point_classification.l0_permitted_projects.all():
            # If any one project is not allowed to be edited then unauthorized
            if projbundle.id in pids:
                allowed = True
            else:
                allowed = False
                break
        if allowed:
            return True
        raise Unauthorized("not authorized for project")

    def create_detail(self, object_list, bundle):
        self.login_checks(bundle.request, bundle.obj.__class__)
        pids = editor_projects(bundle.request.user)
        allowed = False
        if bundle.obj.data_point_classification.l0_permitted_projects.count() == 0:
            raise BadRequest("You must specify at least one project")
        for projbundle in bundle.obj.data_point_classification.l0_permitted_projects.all():
            # If any one project is not allowed to be edited then unauthorized
            if projbundle.id in pids:
                allowed = True
            else:
                allowed = False
                break
        if allowed:
            return True
        raise Unauthorized("not authorized for project")

class DataClassificationProjectAuthorization(Authorization):

    """
    Uses permission checking from ``django.contrib.auth`` to map
    ``POST / PUT / DELETE / PATCH`` to their equivalent Django auth
    permissions.

    Both the list & detail variants simply check the model they're based
    on, as that's all the more granular Django's permission setup gets.
    """

    def login_checks(self, request, model_klass, perms=None):

        # If it doesn't look like a model, we can't check permissions.
        # if not model_klass or not getattr(model_klass, '_meta', None):
        #     print "improper_setup_of_authorization"
        #     raise Unauthorized("improper_setup_of_authorization")
        # User must be logged in to check permissions.
        if not hasattr(request, 'user'):
            print "no_logged_in_user"
            raise Unauthorized("no_logged_in_user")

    def read_detail(self, object_list, bundle):

        self.login_checks(bundle.request, bundle.obj.__class__)
        pids = editor_projects(bundle.request.user)
        allowed = False
        if bundle.obj.l0_permitted_projects.count() == 0:
            raise BadRequest("You must specify at least one project")
        for projbundle in bundle.obj.l0_permitted_projects.all():
            # If any one project is not allowed to be edited then unauthorized
            if projbundle.id in pids:
                allowed = True
            else:
                allowed = False
                break
        if allowed:
            return True
        raise Unauthorized("not authorized for project")

    def create_list(self, object_list, bundle):
        raise BadRequest("Creating a list is not yet authorized")

    def update_list(self, object_list, bundle):
        raise BadRequest("Creating a list is not yet authorized")

    def project_ids(self, request, ):
        pids = viewer_projects(request.user)
        return pids

    def create_detail(self, object_list, bundle):
        self.login_checks(bundle.request, bundle.obj.__class__)
        pids = editor_projects(bundle.request.user)
        allowed = False
        if len(bundle.data["l0_permitted_projects"]) == 0:
            raise BadRequest("You must specify at least one project")
        for projbundle in bundle.data["l0_permitted_projects"]:
            # If any one project is not allowed to be edited then unauthorized
            if projbundle.obj.id in pids:
                allowed = True
            else:
                allowed = False
                break
        if allowed:
            return True
        raise Unauthorized("not authorized for project")

    def update_detail(self, object_list, bundle):
        self.login_checks(bundle.request, bundle.obj.__class__)
        pids = editor_projects(bundle.request.user)
        allowed = False
        if len(bundle.data["l0_permitted_projects"]) == 0:
            raise BadRequest("You must specify at least one project")
        for projbundle in bundle.data["l0_permitted_projects"]:
            # If any one project is not allowed to be edited then unauthorized
            if projbundle.obj.id in pids:
                allowed = True
            else:
                allowed = False
                break
        if allowed:
            return True
        raise Unauthorized("not authorized for project")

    def read_list(self, object_list, bundle):
        return object_list


text:
require 'sinatra/base'
require 'magistrate_monitor/sinatra-activerecord'

require 'magistrate_monitor/supervisor'
require 'awesome_print'

module MagistrateMonitor
  class Server < Sinatra::Base
    dir = File.dirname(File.expand_path(__FILE__))

    set :views,  "#{dir}/views"
    set :public, "#{dir}/public"
    set :static, true

    set :basic_auth_credentials, lambda {
      result = nil

      config_file = File.join('config', 'magistrate.yml')
      if File.exist?( config_file )
        config = YAML::load( File.open(config_file) )
        if config['http_username'] && config['http_password']
          result = [config['http_username'], config['http_password']]
        end
      end

      result
    }

    if basic_auth_credentials && ENV['RACK_ENV'] != 'test'
      use Rack::Auth::Basic do |username, password|
        [username, password] == basic_auth_credentials
      end
    end

    get '/' do
      @supervisors = Supervisor.order('name ASC').all
      normalize_status_data!

      erb :index
    end

    get '/supervisors/:name' do
      @supervisor = Supervisor.find_by_name! params[:name]
      erb :show
    end

    post '/supervisors/:name/delete' do
      @supervisor = Supervisor.find_by_name! params[:name]
      @supervisor.destroy
      redirect url('/')
    end

    # Responds with the latest databag instructions for the supervisor
    get '/api/status/:name' do
      @supervisor = Supervisor.find_or_create_by_name params[:name]

      content_type :json
      ActiveSupport::JSON.encode( @supervisor.databag || {} )
    end

    # Saves the status update to the db
    post '/api/status/:name' do
      @supervisor = Supervisor.find_or_create_by_name params[:name]

      status = ActiveSupport::JSON.decode( params[:status] )

      @supervisor.update_attributes :last_checkin_at => Time.now, :status => status

      content_type :json
      ActiveSupport::JSON.encode( {:status => 'Ok'} )
    end

    post '/supervisors/:supervisor_name/workers/:worker_name/set_target_state/:action' do
      @supervisor = Supervisor.find_or_create_by_name params[:supervisor_name]

      @supervisor.set_target_state!(params[:action], params[:worker_name])
      redirect url('/')
    end

    helpers do
      # def url_for(path)
      #   root = request.env['SCRIPT_NAME'].chomp('/')
      #   "#{root}/#{path}"
      # end

      def target_state_url_for_worker(supervisor, name, action)
        url("/supervisors/#{supervisor.name}/workers/#{name}/set_target_state/#{action}")
      end

      def normalize_status_data!
        @supervisors.each do |supervisor|
          supervisor.normalize_status_data!
        end
      end
    end
  end
end


text:
package parquet.column.impl;

import parquet.column.ColumnDescriptor;
import parquet.column.ColumnReadStore;
import parquet.column.ColumnReader;
import parquet.column.page.PageReadStore;
import parquet.column.page.PageReader;
import parquet.io.api.Converter;
import parquet.io.api.GroupConverter;
import parquet.io.api.PrimitiveConverter;
import parquet.schema.GroupType;
import parquet.schema.MessageType;
import parquet.schema.Type;

/**
 * Implementation of the ColumnReadStore
 *
 * Initializes individual columns based on schema and converter
 *
 * @author Julien Le Dem
 *
 */
public class ColumnReadStoreImpl implements ColumnReadStore {

  private final PageReadStore pageReadStore;
  private final GroupConverter recordConverter;
  private final MessageType schema;

  /**
   * @param pageReadStore uderlying page storage
   * @param recordConverter the user provided converter to materialize records
   * @param schema the schema we are reading
   */
  public ColumnReadStoreImpl(PageReadStore pageReadStore, GroupConverter recordConverter, MessageType schema) {
    super();
    this.pageReadStore = pageReadStore;
    this.recordConverter = recordConverter;
    this.schema = schema;
  }

  @Override
  public ColumnReader getColumnReader(ColumnDescriptor path) {
    return newMemColumnReader(path, pageReadStore.getPageReader(path));
  }

  private ColumnReaderImpl newMemColumnReader(ColumnDescriptor path, PageReader pageReader) {
    PrimitiveConverter converter = getPrimitiveConverter(path);
    return new ColumnReaderImpl(path, pageReader, converter);
  }

  private PrimitiveConverter getPrimitiveConverter(ColumnDescriptor path) {
    Type currentType = schema;
    Converter currentConverter = recordConverter;
    for (String fieldName : path.getPath()) {
      final GroupType groupType = currentType.asGroupType();
      int fieldIndex = groupType.getFieldIndex(fieldName);
      currentType = groupType.getType(fieldName);
      currentConverter = currentConverter.asGroupConverter().getConverter(fieldIndex);
    }
    PrimitiveConverter converter = currentConverter.asPrimitiveConverter();
    return converter;
  }

}


text:
package org.apereo.cas.services;

import com.google.common.collect.Maps;
import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apereo.cas.authentication.principal.DefaultPrincipalAttributesRepository;
import org.apereo.cas.authentication.principal.Principal;
import org.apereo.cas.authentication.principal.PrincipalAttributesRepository;
import org.apereo.cas.configuration.CasConfigurationProperties;
import org.apereo.cas.util.ApplicationContextProvider;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;

import java.util.Map;
import java.util.Set;

import static com.google.common.collect.Maps.newTreeMap;

/**
 * Abstract release policy for attributes, provides common shared settings such as loggers and attribute filter config.
 * Subclasses are to provide the behavior for attribute retrieval.
 *
 * @author Misagh Moayyed
 * @since 4.1.0
 */
public abstract class AbstractRegisteredServiceAttributeReleasePolicy implements RegisteredServiceAttributeReleasePolicy {

    private static final long serialVersionUID = 5325460875620586503L;

    /**
     * The logger.
     */
    private static final Logger LOGGER = LoggerFactory.getLogger(AbstractRegisteredServiceAttributeReleasePolicy.class);

    /**
     * The attribute filter.
     */
    private RegisteredServiceAttributeFilter registeredServiceAttributeFilter;

    /**
     * Attribute repository that refreshes attributes for a principal.
     **/
    private PrincipalAttributesRepository principalAttributesRepository = new DefaultPrincipalAttributesRepository();

    /**
     * Authorize the release of credential for this service. Default is false.
     **/
    private boolean authorizedToReleaseCredentialPassword;

    /**
     * Authorize the release of PGT for this service. Default is false.
     **/
    private boolean authorizedToReleaseProxyGrantingTicket;

    @Override
    public void setAttributeFilter(final RegisteredServiceAttributeFilter filter) {
        this.registeredServiceAttributeFilter = filter;
    }

    public void setPrincipalAttributesRepository(final PrincipalAttributesRepository repository) {
        this.principalAttributesRepository = repository;
    }

    public PrincipalAttributesRepository getPrincipalAttributesRepository() {
        return this.principalAttributesRepository;
    }

    /**
     * Gets the attribute filter.
     *
     * @return the attribute filter
     */
    public RegisteredServiceAttributeFilter getAttributeFilter() {
        return this.registeredServiceAttributeFilter;
    }

    @Override
    public boolean isAuthorizedToReleaseCredentialPassword() {
        return this.authorizedToReleaseCredentialPassword;
    }

    @Override
    public boolean isAuthorizedToReleaseProxyGrantingTicket() {
        return this.authorizedToReleaseProxyGrantingTicket;
    }

    public void setAuthorizedToReleaseCredentialPassword(final boolean authorizedToReleaseCredentialPassword) {
        this.authorizedToReleaseCredentialPassword = authorizedToReleaseCredentialPassword;
    }

    public void setAuthorizedToReleaseProxyGrantingTicket(final boolean authorizedToReleaseProxyGrantingTicket) {
        this.authorizedToReleaseProxyGrantingTicket = authorizedToReleaseProxyGrantingTicket;
    }

    @Override
    public Map<String, Object> getAttributes(final Principal p) {
        LOGGER.debug("Locating principal attributes for {}", p.getId());
        final Map<String, Object> principalAttributes = this.principalAttributesRepository == null
                ? p.getAttributes() : this.principalAttributesRepository.getAttributes(p);
        LOGGER.debug("Found principal attributes {} for {}", principalAttributes, p.getId());

        LOGGER.debug("Calling attribute policy {} to process attributes for {}", getClass().getSimpleName(), p.getId());
        final Map<String, Object> policyAttributes = getAttributesInternal(principalAttributes);
        LOGGER.debug("Attribute policy {} allows release of {} for {}", getClass().getSimpleName(), policyAttributes, p.getId());

        LOGGER.debug("Checking default attribute policy attributes");
        final Map<String, Object> defaultAttributes = getReleasedByDefaultAttributes(p, principalAttributes);
        LOGGER.debug("Default attributes found to be released are {}", defaultAttributes);

        LOGGER.debug("Attempting to merge policy attributes and default attributes");
        final Map<String, Object> attributesToRelease = Maps.newTreeMap(String.CASE_INSENSITIVE_ORDER);

        LOGGER.debug("Adding default attributes first to the released set of attributes");
        attributesToRelease.putAll(defaultAttributes);

        LOGGER.debug("Adding policy attributes to the released set of attributes");
        attributesToRelease.putAll(policyAttributes);

        if (this.registeredServiceAttributeFilter != null) {
            LOGGER.debug("Invoking attribute filter on the final set of attributes");
            return this.registeredServiceAttributeFilter.filter(attributesToRelease);
        }

        return returnFinalAttributesCollection(attributesToRelease);
    }

    /**
     * Return the final attributes collection.
     * Subclasses may override this minute to impose last minute rules.
     * @param attributesToRelease the attributes to release
     * @return the map
     */
    protected Map<String, Object> returnFinalAttributesCollection(final Map<String, Object> attributesToRelease) {
        LOGGER.debug("Final collection of attributes allowed are: {}", attributesToRelease);
        return attributesToRelease;
    }

    /**
     * Determines a default bundle of attributes that may be released to all services
     * without the explicit mapping for each service.
     *
     * @param p          the principal
     * @param attributes the attributes
     * @return the released by default attributes
     */
    protected Map<String, Object> getReleasedByDefaultAttributes(final Principal p, final Map<String, Object> attributes) {
        final ApplicationContext ctx = ApplicationContextProvider.getApplicationContext();
        if (ctx != null) {
            LOGGER.debug("Located application context. Retrieving default attributes for release, if any");
            final CasConfigurationProperties props = ctx.getAutowireCapableBeanFactory().getBean(CasConfigurationProperties.class);
            final Set<String> defaultAttrs = props.getAuthn().getAttributeRepository().getDefaultAttributesToRelease();
            LOGGER.debug("Default attributes for release are: {}", defaultAttrs);

            final Map<String, Object> defaultAttributesToRelease = newTreeMap(String.CASE_INSENSITIVE_ORDER);
            defaultAttrs.stream().forEach(key -> {
                if (attributes.containsKey(key)) {
                    LOGGER.debug("Found and added default attribute for release: {}", key);
                    defaultAttributesToRelease.put(key, attributes.get(key));
                }
            });
            return defaultAttributesToRelease;
        }

        return Maps.newTreeMap();
    }

    /**
     * Gets the attributes internally from the implementation.
     *
     * @param attributes the principal attributes
     * @return the attributes allowed for release
     */
    protected abstract Map<String, Object> getAttributesInternal(Map<String, Object> attributes);

    @Override
    public int hashCode() {
        return new HashCodeBuilder(13, 133)
                .append(this.registeredServiceAttributeFilter)
                .append(this.authorizedToReleaseCredentialPassword)
                .append(this.authorizedToReleaseProxyGrantingTicket)
                .append(this.principalAttributesRepository)
                .toHashCode();
    }

    @Override
    public boolean equals(final Object o) {
        if (o == null) {
            return false;
        }

        if (this == o) {
            return true;
        }

        if (!(o instanceof AbstractRegisteredServiceAttributeReleasePolicy)) {
            return false;
        }

        final AbstractRegisteredServiceAttributeReleasePolicy that = (AbstractRegisteredServiceAttributeReleasePolicy) o;
        final EqualsBuilder builder = new EqualsBuilder();
        return builder
                .append(this.registeredServiceAttributeFilter, that.registeredServiceAttributeFilter)
                .append(this.authorizedToReleaseCredentialPassword, that.authorizedToReleaseCredentialPassword)
                .append(this.authorizedToReleaseProxyGrantingTicket, that.authorizedToReleaseProxyGrantingTicket)
                .append(this.principalAttributesRepository, that.principalAttributesRepository)
                .isEquals();
    }

    @Override
    public String toString() {
        return new ToStringBuilder(this)
                .append("attributeFilter", this.registeredServiceAttributeFilter)
                .append("principalAttributesRepository", this.principalAttributesRepository)
                .append("authorizedToReleaseCredentialPassword", this.authorizedToReleaseCredentialPassword)
                .append("authorizedToReleaseProxyGrantingTicket", this.authorizedToReleaseProxyGrantingTicket)
                .toString();
    }
}


text:
{
  if (options === void 0) options = {};
  return createRenderer$1(
    Object.assign({}, options, {
      isUnaryTag: isUnaryTag,
      canBeLeftOpenTag: canBeLeftOpenTag,
      modules: modules,
      directives: Object.assign(baseDirectives, options.directives)
    })
  );
}


text:
import fs from 'fs-extra'
import pkgDir from 'pkg-dir'
import chalk from 'chalk'
import { join } from 'path'

async function run() {
  const rootPath = await pkgDir()
  const isInPackage = rootPath !== null

  if (isInPackage) {
    const scriptsPath = join(rootPath, 'node_modules', '.bin', 'tux-scripts')
    const insideTuxProject = await fs.pathExists(scriptsPath)

    if (insideTuxProject) {
      // tslint:disable-next-line:no-console
      console.log(`Inside ${chalk.cyan('tux')} project.`)
      require(scriptsPath)
      return
    }
  }

  // tslint:disable-next-line:no-console
  console.log(`Not inside ${chalk.cyan('tux')} project.`)
  require('./new')
}

run()


text:
package algs.model.tests.data;

import org.junit.Test;
import algs.model.data.segments.DoubleGenerator;

import junit.framework.TestCase;

/**
 * Specific Worked example, with reduced move sets to showcase just what I want
 * to show.
 *
 * @author George Heineman
 *
 */
public class GeneratorTest extends TestCase {

	// generators must ensure toString is meaningful and accurate. This method
	// inherited so we only test once.
	@Test
	public void testGeneratorMethods() {
		DoubleGenerator dg = new DoubleGenerator(100,2);
		assertEquals (DoubleGenerator.class.getName(), dg.toString());
	}

}


text:
package org.example

import io.circe.syntax._
import org.http4s.HttpService
import org.http4s.circe.jsonEncoder
import org.http4s.dsl._
import org.http4s.server.staticcontent.{webjarService, WebjarService}

object Service {
  val api = HttpService {
    case GET -> Root / "now.json" =>
      Ok(Storage.now.map(_.asJson))

    case GET -> Root / "version.json" =>
      Ok(BuildInfo.version.asJson)
  }

  val assets: HttpService =
    webjarService(WebjarService.Config())
}


text:
#include <stdio.h>
#include "shell.h"
#include "msg.h"
#include <stdbool.h>
#include <string.h>
#include <xtimer.h>
#include "board.h"
#include "thread.h"
#include "udp_common.h"
#include "periph/gpio.h"

#define PRIO    (THREAD_PRIORITY_MAIN + 1)
#define Q_SZ    (4)

#define SYSTEM_SUBNET    "affe"
#define ROUTER_6LOW_IF   "7"
#define ROUTER_6LOW_ROOT_IP   "::2"
#define ROUTER_6SLIP_IF  "8"
#define ROUTER_6SLIP_IP  "::3"
#define UDPIP_6SLIP_IP   "::1" // address of PC endpoint

static msg_t msg_q[Q_SZ];
bool led_status = false;
static char udp_stack[THREAD_STACKSIZE_DEFAULT];
static char housekeeping_stack[THREAD_STACKSIZE_DEFAULT];

static const shell_command_t shell_commands[];

/* Add the shell command function here ###################################### */
bool isRootPending = false;
bool isRoot = false;

int init_cmd(int argc, char **argv)
{
    if (isRoot)
    {
        puts("already initialised.  Try rebooting if problems.");
        return -1;
    }
    LED_RGB_R_ON;
    LED0_ON;
    isRootPending = true;
    puts("Root pending...");
    return 0;
}

int led_control(int argc, char **argv)
{
    if (argc == 2) {
        if (strcmp(argv[1], "on") == 0) {
            led_status = true;
            LED0_ON;
            return 0;
        }
        else if (strcmp(argv[1], "off") == 0) {
            led_status = false;
            LED0_OFF;
            LED_RGB_OFF;
            return 0;
        }
        else if (strcmp(argv[1], "red") == 0) {
            led_status = false;
            LED0_ON;
            LED_RGB_OFF;
            LED_RGB_R_ON;
            return 0;
        }
        else if (strcmp(argv[1], "green") == 0) {
            led_status = false;
            LED0_ON;
            LED_RGB_OFF;
            LED_RGB_G_ON;
            return 0;
        }
        else if (strcmp(argv[1], "blue") == 0) {
            led_status = false;
            LED0_ON;
            LED_RGB_OFF;
            LED_RGB_B_ON;
            return 0;
        }
    }

    return -1;
}

extern void batch(const shell_command_t *command_list, char *line);

void btnCallback(void* arg)
{
    if (! isRoot)
    {
        LED_RGB_R_ON;
        LED0_ON;
        isRootPending = true;
        puts("Root pending...");
    }
}

/* ########################################################################## */
static const shell_command_t shell_commands[] = {

/* Add a new shell command here ############################################# */

    { "led", "use 'led on' to turn the LED on and 'led off' to turn the LED off", led_control },

    { "udp", "send a message: udp <IPv6-address> <message>", udp_cmd },

    { "init", "initialise router inetrfaces", init_cmd },

    /* ########################################################################## */
    { NULL, NULL, NULL }
};

void setRoot(void)
{
    puts("setting root...");
    isRootPending = false;
    // set up rpl root
    puts("making 6lowpan wireless interface");
    batch(shell_commands, "ifconfig " ROUTER_6LOW_IF " add " SYSTEM_SUBNET ROUTER_6LOW_ROOT_IP );
    // was - batch(shell_commands, "ifconfig 7 add affe::2");

    puts("making dodag root node");
    batch(shell_commands, "rpl root 1 " SYSTEM_SUBNET ROUTER_6LOW_ROOT_IP );
    // was - batch(shell_commands, "rpl root 1 affe::2");

    puts("making slip interface");
    // add wired interface
    batch(shell_commands, "ifconfig " ROUTER_6SLIP_IF " add " SYSTEM_SUBNET ROUTER_6SLIP_IP );
    // was - batch(shell_commands, "ifconfig 8 add affe::3");

    puts("adding udp/ip endpoint address to cache");
    batch(shell_commands, "ncache add " ROUTER_6SLIP_IF " " SYSTEM_SUBNET UDPIP_6SLIP_IP );
    // was - batch(shell_commands, "ncache add 8 affe::1");

    puts("starting udpserver thread");
    thread_create(udp_stack, sizeof(udp_stack), PRIO, THREAD_CREATE_STACKTEST, udp_server,
                NULL, "udp");

    LED_RGB_G_ON;
    isRoot = true;
}

/* set interval to 1 second */
#define INTERVAL (1000000U)
void *housekeeping_handler(void *arg)
{
    int factor = 1;
    LED_RGB_OFF;
    while(1)
    {
        if (isRootPending)
        {
            setRoot();
            factor = 5;
        }

        if (! isRoot)
        {
           LED_RGB_R_ON;
           isRootPending = true;
        }
        LED0_OFF;
        xtimer_usleep(INTERVAL/(2*factor));
        LED0_ON;
        xtimer_usleep(INTERVAL/factor);
    }
}

int main(void)
{
    msg_init_queue(msg_q, Q_SZ);

    puts("Type 'help' for a list of available commands");

    LED0_OFF;
    LED_RGB_OFF;

    printf("Biotz\n");

    puts("initialising rpl");
    batch(shell_commands, "rpl init " ROUTER_6LOW_IF );

    gpio_init_int(BUTTON_GPIO, GPIO_IN_PU, GPIO_FALLING, (gpio_cb_t)btnCallback, NULL);

    thread_create(housekeeping_stack, sizeof(housekeeping_stack), PRIO, THREAD_CREATE_STACKTEST, housekeeping_handler,
                NULL, "housekeeping");

    /*thread_create(udp_stack, sizeof(udp_stack), PRIO, THREAD_CREATE_STACKTEST, udp_server,
                NULL, "udp");*/

    char line_buf[SHELL_DEFAULT_BUFSIZE];
    shell_run(shell_commands, line_buf, SHELL_DEFAULT_BUFSIZE);

    /* never reached */
    return 0;
}


text:
import { globalObject } from "./globalObject.js";

function consoleLog() {
  if (globalObject.console && typeof globalObject.console.log === "function") {
    globalObject.console.log.apply(globalObject.console, arguments);
  }
}

function consoleWarn(str) {
  if (globalObject.console) {
    if (typeof globalObject.console.warn === "function") {
      globalObject.console.warn.apply(globalObject.console, arguments);
    } else {
      consoleLog.call(null, arguments);
    }
  }
}

function consoleError(str) {
  if (globalObject.console) {
    if (typeof globalObject.console.error === "function") {
      globalObject.console.error.apply(globalObject.console, arguments);
    } else {
      consoleLog(str);
    }
  }
}
export var console = {
  log: consoleLog,
  warn: consoleWarn,
  error: consoleError
};


text:
SpecBegin(NOCMacrosSpec)

describe(@"NOCMacros", ^{

    describe(@"when working with bit values", ^{
        __block NSInteger bitNumber;

        typedef NS_ENUM(NSUInteger, NOCTestEnum)  {
            NOCTestEnumZero = 1 << 0,
            NOCTestEnumOne = 1 << 1,
            NOCTestEnumTwo = 1 << 2,
        };

        it(@"setting 2nd bit as 1 should result with 4", ^{
            bitNumber = 0;
            noc_setBitOne(bitNumber, NOCTestEnumTwo);
            expect(bitNumber).to.equal(4);
        });

        it(@"setting a number of 4 and setting 2nd bit as 0 should result with 0", ^{
            bitNumber = 4;
            noc_setBitZero(bitNumber, NOCTestEnumTwo);
            expect(bitNumber).to.equal(0);
        });

        describe(@"when working with flags", ^{
            NSInteger testNumber = 99;
            describe(@"number 99 (== 0110 0011), should", ^{
                it(@"return YES for bit 0 ON", ^{
                    expect(noc_isBitAtIndexOne(testNumber, 0)).to.equal(1);
                });
                it(@"return NO for bit 1 OFF", ^{
                    expect(noc_isBitAtIndexOne(testNumber, 1)).toNot.equal(0);
                });
                it(@"return YES for bit 2 OFF", ^{
                    expect(noc_isBitAtIndexOne(testNumber, 2)).to.equal(0);
                });
                it(@"return NO for bit 3 ON", ^{
                    expect(noc_isBitAtIndexOne(testNumber, 3)).toNot.equal(1);
                });
            });
        });

        context(@"checking bit value of number 2 should result with", ^{
            beforeEach(^{
                bitNumber = 2;
            });

            it(@"0 in first bit", ^{
                expect(noc_isBitOne(bitNumber, NOCTestEnumZero)).to.equal(0);
            });
            it(@"0 in second bit", ^{
                expect(noc_isBitOne(bitNumber, NOCTestEnumOne)).to.equal(1);
            });
            it(@"1 in third bit", ^{
                expect(noc_isBitOne(bitNumber, NOCTestEnumTwo)).to.equal(0);
            });
        });
    });

    context(@"when creating colors from RGBA function", ^{
        __block CGFloat red = 1, green = 211, blue = 37, alpha = 1;
        __block UIColor *actualColor;

        beforeEach(^{
            actualColor = noc_rgbToColor(red, green, blue, alpha);
        });

        it(@"it should not be nil", ^{
            expect(actualColor).toNot.beNil();
        });
        it(@"RGBA values of new color should be equal to input RGBA values", ^{
            UIColor *expectedColor = [UIColor colorWithRed:red / 255.f green:green / 255.f blue:blue / 255.f alpha:alpha];
            expect(actualColor).to.beSameColor(expectedColor);
        });
    });

    context(@"when creating colors from HEX function", ^{
        __block CGFloat red = 72, green = 61, blue = 139, alpha = 1;
        __block UIColor *actualColor;

        beforeEach(^{
            actualColor = noc_hexToColor(0x483D8B , 1.0);
        });

        it(@"it should not be nil", ^{
            expect(actualColor).toNot.beNil();
        });
        it(@"RGBA values of new color should be equal to RGBA values of HEX color", ^{
            UIColor *expectedColor = [UIColor colorWithRed:red / 255.f green:green / 255.f blue:blue / 255.f alpha:alpha];
            expect(actualColor).to.beSameColor(expectedColor);
        });
    });

});

SpecEnd


text:
package ai.subut.kurjun.metadata.storage.file;

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;

import ai.subut.kurjun.common.service.KurjunContext;
import ai.subut.kurjun.common.service.KurjunProperties;

import static org.junit.Assert.*;
import static org.mockito.Matchers.anyString;
import static org.mockito.Mockito.when;

@RunWith( MockitoJUnitRunner.class )
public class DbFilePackageMetadataStoreFactoryImplTest
{
    private DbFilePackageMetadataStoreFactoryImpl storeFactory;

    @Mock
    KurjunProperties kurjunProperties;

    @Mock
    KurjunContext kurjunContext;

    @Before
    public void setUp() throws Exception
    {
        storeFactory = new DbFilePackageMetadataStoreFactoryImpl( kurjunProperties );
    }

    @Test
    public void create() throws Exception
    {
        //mock
        when( kurjunProperties.get( anyString() ) ).thenReturn( "test" );
        when( kurjunContext.getName() ).thenReturn( "test" );

        assertNotNull( storeFactory.create( kurjunContext ) );
    }
}


text:
import Ember from 'ember';
import RipplesMixin from '../mixins/ripples';

var MdRadioButton = Ember.Component.extend(RipplesMixin, {

    attributeBindings: ['disabled'],

    classNameBindings: ['checked:md-checked'],

    tagName: 'md-radio-button',

    setupRipples: function() {
        if (this.get('mdNoInk')) {
            return;
        }
        this.get('rippleService').attachCheckboxBehavior(this.$('.md-container'));

    }.on('didInsertElement'),

    checked: function() {
        return this.get('value') === this.get('selected');
    }.property('value', 'selected'),

    checkedDidChange: Ember.observer('checked', function() {
        if (this.get('checked')) {
            this.set('selected', this.get('value'));
        }
    }),

    click: function() {
        if (this.get('disabled')) {
            return;
        }

        this.set('selected', this.get('value'));
    }

});

export default MdRadioButton;


text:
package monasca.thresh.domain.service;

import monasca.thresh.domain.model.AlarmDefinition;

import java.util.List;

public interface AlarmDefinitionDAO {
  public List<AlarmDefinition> listAll();

  AlarmDefinition findById(String id);

  void deleteByDefinitionId(String alarmDefinitionId);
}


text:
package battlecraft.entity.structure;

import java.awt.Canvas;
import java.awt.Point;
import java.awt.Rectangle;

import battlecraft.LevelManager;
import battlecraft.entity.unit.Worker;
import battlecraft.enums.Ressources;
import battlecraft.enums.Teams;

public class BarrackWoodWorker extends Barrack{

	public BarrackWoodWorker(Canvas defaultCanvas, Point position, String spritePathMiddleAge, String spritePathScifi, Rectangle BOUNDING_BOX, Teams team) {
		super(defaultCanvas, position, spritePathMiddleAge, spritePathScifi, BOUNDING_BOX, team, new BarrackCosts(Ressources.ORE, 1000, Ressources.WOOD, 10));
	}

	@Override
	public void createUnit() {
		Point p = new Point((int) (this.position.x+(Math.random() * (10))+30), (int) (this.position.y+(Math.random() * (10))+30));
		LevelManager.getInstance().addWorker((Worker) unit.createWoodWorker(defaultCanvas, p));
	}
}


text:
from __future__ import print_function

import copy
import os
import sys

from .packages import find_packages
from .workspaces import get_spaces

class _PackageDecorator(object):

    def __init__(self, package, path):
        self.package = package
        self.path = path
        self.is_metapackage = 'metapackage' in [e.tagname for e in self.package.exports]
        message_generators = [e.content for e in self.package.exports if e.tagname == 'message_generator']
        self.message_generator = message_generators[0] if message_generators else None
        # full includes direct build depends and recursive run_depends of these build_depends
        self.depends_for_topological_order = None

    def __getattr__(self, name):
        if name.startswith('__'):
            raise AttributeError(name)
        return getattr(self.package, name)

    def calculate_depends_for_topological_order(self, packages):
        """
        Sets self.depends_for_topological_order to the recursive
        dependencies required for topological order. It contains all
        direct build- and buildtool dependencies and their recursive
        runtime dependencies. The set only contains packages which
        are in the passed packages dictionary.

        :param packages: dict of name to ``_PackageDecorator``
        """
        self.depends_for_topological_order = set([])
        all_depends = self.package.build_depends + self.package.buildtool_depends + self.package.test_depends
        names = [d.name for d in all_depends if d.evaluated_condition]

        # collect all group dependencies
        for group_depend in self.package.group_depends:
            if group_depend.evaluated_condition:
                assert group_depend.members is not None, \
                    'Group members need to be determined before'
                names += group_depend.members

        # skip external dependencies, meaning names that are not known packages
        for name in [n for n in names if n in packages.keys()]:
            if not self.is_metapackage and packages[name].is_metapackage:
                print('WARNING: package "%s" should not depend on metapackage "%s" but on its packages instead' % (self.name, name), file=sys.stderr)
            if name in self.depends_for_topological_order:
                # avoid function call to improve performance
                # check within the loop since the set changes every cycle
                continue
            packages[name]._add_recursive_run_depends(packages, self.depends_for_topological_order)

    def _add_recursive_run_depends(self, packages, depends_for_topological_order):
        """
        Modifies depends_for_topological_order argument by adding
        run_depends of self recursively. Only packages which are in
        the passed packages are added and recursed into.

        :param packages: dict of name to ``_PackageDecorator``
        :param depends_for_topological_order: set to be extended
        """
        depends_for_topological_order.add(self.package.name)
        package_names = packages.keys()
        names = [d.name for d in self.package.run_depends if d.evaluated_condition]

        for group_depend in self.package.group_depends:
            if group_depend.evaluated_condition:
                assert group_depend.members is not None, \
                    'Group members need to be determined before'
                names += group_depend.members

        for name in [n for n in names
                     if (n in package_names and
                         n not in depends_for_topological_order)]:
            packages[name]._add_recursive_run_depends(packages, depends_for_topological_order)

def topological_order(root_dir, whitelisted=None, blacklisted=None, underlay_workspaces=None):
    '''
    Crawls the filesystem to find packages and uses their
    dependencies to return a topologically order list.

    When a circular dependency is detected, the last item in the returned list
    is a tuple with None and a string giving a superset of the guilty packages.

    :param root_dir: The path to search in, ``str``
    :param whitelisted: A list of whitelisted package names, ``list``
    :param blacklisted: A list of blacklisted package names, ``list``
    :param underlay_workspaces: A list of underlay workspaces of packages which might provide dependencies in case of partial workspaces, ``list``
    :returns: A list of tuples containing the relative path and a ``Package`` object, ``list``
    '''
    packages = find_packages(root_dir)

    # find packages in underlayed workspaces
    underlay_packages = {}
    if underlay_workspaces:
        for workspace in reversed(underlay_workspaces):
            # since underlay workspace might be a devel space
            # consider spaces stored in the .catkin file
            spaces = get_spaces([workspace])
            for space in spaces:
                for path, package in find_packages(space).items():
                    underlay_packages[package.name] = (path, package)

    return topological_order_packages(packages, whitelisted=whitelisted, blacklisted=blacklisted, underlay_packages=dict(underlay_packages.values()))

def topological_order_packages(packages, whitelisted=None, blacklisted=None, underlay_packages=None):
    '''
    Topologically orders packages.

    evaluate_conditions() will be called for each package.

    If group dependencies haven't determined their members yet
    extract_group_members() will be called for each group dependency to do so.

    First returning packages which have message generators and then
    the rest based on direct build-/buildtool_depends and indirect
    recursive run_depends.

    When a circular dependency is detected, the last item in the returned list
    is a tuple with None and a string giving a superset of the guilty packages.

    :param packages: A dict mapping relative paths to ``Package`` objects ``dict``
    :param whitelisted: A list of whitelisted package names, ``list``
    :param blacklisted: A list of blacklisted package names, ``list``
    :param underlay_packages: A dict mapping relative paths to ``Package`` objects ``dict``
    :returns: A list of tuples containing the relative path and a ``Package`` object, ``list``
    '''
    decorators_by_name = {}
    for path, package in packages.items():
        # skip non-whitelisted packages
        if whitelisted and package.name not in whitelisted:
            continue
        # skip blacklisted packages
        if blacklisted and package.name in blacklisted:
            continue
        if package.name in decorators_by_name:
            path_with_same_name = decorators_by_name[package.name].path
            raise RuntimeError('Two packages with the same name "%s" in the workspace:\n- %s\n- %s' % (package.name, path_with_same_name, path))
        decorators_by_name[package.name] = _PackageDecorator(package, path)

    underlay_decorators_by_name = {}
    if underlay_packages:
        for path, package in underlay_packages.items():
            # skip overlayed packages
            if package.name in decorators_by_name:
                continue
            underlay_decorators_by_name[package.name] = _PackageDecorator(package, path)
        decorators_by_name.update(underlay_decorators_by_name)

    # evaluate conditions and determine group membership
    pkgs = [d.package for d in decorators_by_name.values()]
    for pkg in pkgs:
        pkg.evaluate_conditions(os.environ)
        for group_depend in pkg.group_depends:
            if group_depend.evaluated_condition:
                group_depend.extract_group_members(pkgs)

    # calculate transitive dependencies
    for decorator in decorators_by_name.values():
        decorator.calculate_depends_for_topological_order(decorators_by_name)

    tuples = _sort_decorated_packages(decorators_by_name)
    # remove underlay packages from result
    return [(path, package) for path, package in tuples if path is None or package.name not in underlay_decorators_by_name]

def _reduce_cycle_set(packages_orig):
    '''
    This function iteratively removes some packages from a set that are definitely not part of any cycle.

    When there is a cycle in the package dependencies,
    _sort_decorated_packages only knows the set of packages containing
    the cycle.
    :param packages: A dict mapping package name to ``_PackageDecorator`` objects ``dict``
    :returns: A list of package names from the input which could not easily be detected as not being part of a cycle.
    '''
    assert(packages_orig)
    packages = copy.copy(packages_orig)
    last_depended = None
    while len(packages) > 0:
        depended = set([])
        for name, decorator in packages.items():
            if decorator.depends_for_topological_order:
                depended = depended.union(decorator.depends_for_topological_order)
        for name in list(packages.keys()):
            if not name in depended:
                del packages[name]
        if last_depended:
            if last_depended == depended:
                return packages.keys()
        last_depended = depended

def _sort_decorated_packages(packages_orig):
    '''
    Sorts packages according to dependency ordering,
    first considering the message generators and their recursive dependencies
    and then the rest of the packages.

    When a circle is detected, a tuple with None and a string giving a
    superset of the guilty packages.

    :param packages: A dict mapping package name to ``_PackageDecorator`` objects ``dict``
    :returns: A List of tuples containing the relative path and a ``Package`` object ``list``
    '''
    packages = copy.deepcopy(packages_orig)

    # mark all packages which are (recursively) dependent on by message generators
    dependency_names_to_follow = set([name for name, decorator in packages.items() if decorator.message_generator])
    not_marked_package_names = set(packages.keys()) - dependency_names_to_follow
    while dependency_names_to_follow:
        pkg_name = dependency_names_to_follow.pop()
        for name in packages[pkg_name].depends_for_topological_order:
            if name in not_marked_package_names:
                # mark package
                packages[name].message_generator = True
                not_marked_package_names.remove(name)
                # queue for recursion
                dependency_names_to_follow.add(name)

    ordered_packages = []
    while len(packages) > 0:
        # find all packages without build dependencies
        message_generators = []
        non_message_generators = []
        for name, decorator in packages.items():
            if not decorator.depends_for_topological_order:
                if decorator.message_generator:
                    message_generators.append(name)
                else:
                    non_message_generators.append(name)
        # first choose message generators
        if message_generators:
            names = message_generators
        elif non_message_generators:
            names = non_message_generators
        else:
            # in case of a circular dependency pass a string with
            # the names list of remaining package names, with path
            # None to indicate cycle
            ordered_packages.append([None, ', '.join(sorted(_reduce_cycle_set(packages)))])
            break

        # alphabetic order only for convenience
        names.sort()

        # add first candidates to ordered list
        # do not add all candidates since removing the depends from the first might affect the next candidates
        name = names[0]
        ordered_packages.append([packages[name].path, packages[name].package])
        # remove package from further processing
        del packages[name]
        for package in packages.values():
            if name in package.depends_for_topological_order:
                package.depends_for_topological_order.remove(name)
    return ordered_packages


text:
class Student implements Cloneable {
	String name;

	public Student(String name) {
		this.name = name;
	}

	@Override
	protected Object clone() throws CloneNotSupportedException {
		// TODO Auto-generated method stub
		return super.clone();
	}
}

public class CloneableTest02 {

	public static void main(String[] args) {
		Student s1 = new Student("Jeff");
		Student s2 = null;
		try {
			s2 = (Student) s1.clone();
		} catch (CloneNotSupportedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		print("s1.value = " + s1.name);
		print("s2.value = " + s2.name);
	}

	public static void print(Object obj) {
		System.out.println(obj.toString());
	}
}


text:
<?php
/**
 * Created by PhpStorm.
 * User: Gui
 * Date: 19/01/2016
 * Time: 01:34
 */

namespace App\Services;

use App\Event;
use App\Playlist;
use App\Repositories\EventRepository;
use App\User;

class EventService
{
    public $eventRepository;

    public function __construct()
    {
        $this->eventRepository = new EventRepository;
    }

    public function create_event($fb_id, $name, $start_at)
    {
        return $this->eventRepository->create_event($fb_id, $name, $start_at);
    }

    public function edit_event($fb_event_id, $fb_event_name, $fb_event_start_at)
    {
        return $this->eventRepository->edit_event($fb_event_id, $fb_event_name, $fb_event_start_at);
    }

    public function link_user(User $user, Event $event)
    {
        $aux = $user->events()->where('event_id', $event->id)->first();
        if (!$aux) {
            $user->events()->attach($event->id);
        }
    }

    public function link_playlist(Playlist $playlist, Event $event)
    {
        $aux = $event->playlists()->where('playlist_id', $playlist->id)->first();
        if (!$aux) {
            $event->playlists()->attach($playlist->id);
        }
    }

    public function delete_playlist(Event $event, Playlist $playlist)
    {
        $event->playlists()->detach($playlist->id);
    }
}


text:
namespace gorc {
namespace content {
namespace assets {

class level_surface {
public:
    int material;
    flag_set<flags::surface_flag> flags;
    flag_set<flags::face_flag> face_type_flags;
    flags::geometry_mode geometry_mode;
    flags::light_mode light_mode;
    flags::texture_mode texture_mode;
    int adjoin;
    sector_id adjoined_sector;
    float extra_light;
    std::vector<std::tuple<int, int, float>> vertices;
    vector<3> normal;
    vector<2> texture_offset;
    vector<3> thrust;
};

}
}
}


text:
package com.faforever.client.notification;

import com.faforever.client.test.UITest;
import com.faforever.client.ui.dialog.DialogLayout;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.InjectMocks;
import org.testfx.util.WaitForAsyncUtils;

import java.util.Collections;

import static org.hamcrest.CoreMatchers.instanceOf;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.hasSize;
import static org.hamcrest.collection.IsEmptyCollection.empty;
import static org.junit.jupiter.api.Assertions.assertEquals;

public class ImmediateNotificationControllerTest extends UITest {

  @InjectMocks
  private ImmediateNotificationController instance;

  @BeforeEach
  public void setUp() throws Exception {
    loadFxml("theme/immediate_notification.fxml", clazz -> instance);
  }

  @Test
  public void testSetNotificationWithoutActions() {
    ImmediateNotification notification = new ImmediateNotification("title", "text", Severity.INFO);
    instance.setNotification(notification);

    WaitForAsyncUtils.waitForFxEvents();

    assertEquals("title", ((Label) instance.getDialogLayout().getHeading().get(0)).getText());
    assertEquals("text", instance.notificationText.getText());
    assertThat(instance.getDialogLayout().getActions(), empty());
  }

  @Test
  public void testSetNotificationWithActions() {
    ImmediateNotification notification = new ImmediateNotification("title", "text", Severity.INFO,
        Collections.singletonList(
            new Action("actionTitle")
        ));
    instance.setNotification(notification);

    WaitForAsyncUtils.waitForFxEvents();

    assertEquals("title", ((Label) instance.getDialogLayout().getHeading().get(0)).getText());
    assertEquals("text", instance.notificationText.getText());
    assertThat(instance.getDialogLayout().getActions(), hasSize(1));
    assertEquals("actionTitle", ((Button) instance.getDialogLayout().getActions().get(0)).getText());
  }

  @Test
  public void testGetRoot() throws Exception {
    assertThat(instance.getRoot(), is(instance.immediateNotificationRoot));
    assertThat(instance.getRoot().getParent(), is(instance.getDialogLayout().getBody().get(0).getParent()));
  }

  @Test
  public void getDialogLayout() {
    assertThat(instance.getDialogLayout(), is(instanceOf(DialogLayout.class)));
  }
}


text:
/* Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
'use strict';

var FLOWABLE = FLOWABLE || {};
FLOWABLE.PROPERTY_CONFIG =
    {
        "string": {
            "readModeTemplateUrl": "editor-app/configuration/properties/default-value-display-template.html",
            "writeModeTemplateUrl": "editor-app/configuration/properties/string-property-write-mode-template.html"
        },
        "boolean": {
            "templateUrl": "editor-app/configuration/properties/boolean-property-template.html"
        },
        "text": {
            "readModeTemplateUrl": "editor-app/configuration/properties/default-value-display-template.html",
            "writeModeTemplateUrl": "editor-app/configuration/properties/text-property-write-template.html"
        },
        "flowable-multiinstance": {
            "readModeTemplateUrl": "editor-app/configuration/properties/default-value-display-template.html",
            "writeModeTemplateUrl": "editor-app/configuration/properties/multiinstance-property-write-template.html"
        },
        "flowable-ordering": {
            "readModeTemplateUrl": "editor-app/configuration/properties/default-value-display-template.html",
            "writeModeTemplateUrl": "editor-app/configuration/properties/ordering-property-write-template.html"
        },
        "oryx-dataproperties-complex": {
            "readModeTemplateUrl": "editor-app/configuration/properties/data-properties-display-template.html",
            "writeModeTemplateUrl": "editor-app/configuration/properties/data-properties-write-template.html"
        },
        "oryx-formproperties-complex": {
            "readModeTemplateUrl": "editor-app/configuration/properties/form-properties-display-template.html",
            "writeModeTemplateUrl": "editor-app/configuration/properties/form-properties-write-template.html"
        },
        "oryx-executionlisteners-multiplecomplex": {
            "readModeTemplateUrl": "editor-app/configuration/properties/execution-listeners-display-template.html",
            "writeModeTemplateUrl": "editor-app/configuration/properties/execution-listeners-write-template.html"
        },
        "oryx-tasklisteners-multiplecomplex": {
            "readModeTemplateUrl": "editor-app/configuration/properties/task-listeners-display-template.html",
            "writeModeTemplateUrl": "editor-app/configuration/properties/task-listeners-write-template.html"
        },
        "oryx-eventlisteners-multiplecomplex": {
            "readModeTemplateUrl": "editor-app/configuration/properties/event-listeners-display-template.html",
            "writeModeTemplateUrl": "editor-app/configuration/properties/event-listeners-write-template.html"
        },
        "oryx-usertaskassignment-complex": {
            "readModeTemplateUrl": "editor-app/configuration/properties/assignment-display-template.html",
            "writeModeTemplateUrl": "editor-app/configuration/properties/assignment-write-template.html"
        },
        "oryx-servicetaskfields-complex": {
            "readModeTemplateUrl": "editor-app/configuration/properties/fields-display-template.html",
            "writeModeTemplateUrl": "editor-app/configuration/properties/fields-write-template.html"
        },
        "oryx-callactivityinparameters-complex": {
            "readModeTemplateUrl": "editor-app/configuration/properties/in-parameters-display-template.html",
            "writeModeTemplateUrl": "editor-app/configuration/properties/in-parameters-write-template.html"
        },
        "oryx-callactivityoutparameters-complex": {
            "readModeTemplateUrl": "editor-app/configuration/properties/out-parameters-display-template.html",
            "writeModeTemplateUrl": "editor-app/configuration/properties/out-parameters-write-template.html"
        },
        "oryx-subprocessreference-subprocess-link": {
            "readModeTemplateUrl": "editor-app/configuration/properties/subprocess-reference-display-template.html",
            "writeModeTemplateUrl": "editor-app/configuration/properties/subprocess-reference-write-template.html"
        },
        "oryx-formreference-complex": {
            "readModeTemplateUrl": "editor-app/configuration/properties/form-reference-display-template.html",
            "writeModeTemplateUrl": "editor-app/configuration/properties/form-reference-write-template.html"
        },
        "oryx-sequencefloworder-complex": {
            "readModeTemplateUrl": "editor-app/configuration/properties/sequenceflow-order-display-template.html",
            "writeModeTemplateUrl": "editor-app/configuration/properties/sequenceflow-order-write-template.html"
        },
        "oryx-conditionsequenceflow-complex": {
            "readModeTemplateUrl": "editor-app/configuration/properties/condition-expression-display-template.html",
            "writeModeTemplateUrl": "editor-app/configuration/properties/condition-expression-write-template.html"
        },
        "oryx-signaldefinitions-multiplecomplex": {
            "readModeTemplateUrl": "editor-app/configuration/properties/signal-definitions-display-template.html",
            "writeModeTemplateUrl": "editor-app/configuration/properties/signal-definitions-write-template.html"
        },
        "oryx-signalref-string": {
            "readModeTemplateUrl": "editor-app/configuration/properties/default-value-display-template.html",
            "writeModeTemplateUrl": "editor-app/configuration/properties/signal-property-write-template.html"
        },
        "oryx-messagedefinitions-multiplecomplex": {
            "readModeTemplateUrl": "editor-app/configuration/properties/message-definitions-display-template.html",
            "writeModeTemplateUrl": "editor-app/configuration/properties/message-definitions-write-template.html"
        },
        "oryx-messageref-string": {
            "readModeTemplateUrl": "editor-app/configuration/properties/default-value-display-template.html",
            "writeModeTemplateUrl": "editor-app/configuration/properties/message-property-write-template.html"
        },
        "oryx-duedatedefinition-complex": {
            "readModeTemplateUrl": "editor-app/configuration/properties/duedate-display-template.html",
            "writeModeTemplateUrl": "editor-app/configuration/properties/duedate-write-template.html"
        },
        "oryx-decisiontaskdecisiontablereference-complex": {
            "readModeTemplateUrl": "editor-app/configuration/properties/decisiontable-reference-display-template.html",
            "writeModeTemplateUrl": "editor-app/configuration/properties/decisiontable-reference-write-template.html"
        },
        "oryx-casetaskcasereference-complex": {
            "readModeTemplateUrl": "editor-app/configuration/properties/case-reference-display-template.html",
            "writeModeTemplateUrl": "editor-app/configuration/properties/case-reference-write-template.html"
        },
        "oryx-processtaskprocessreference-complex": {
            "readModeTemplateUrl": "editor-app/configuration/properties/process-reference-display-template.html",
            "writeModeTemplateUrl": "editor-app/configuration/properties/process-reference-write-template.html"
        },
        "flowable-transitionevent": {
            "readModeTemplateUrl": "editor-app/configuration/properties/default-value-display-template.html",
            "writeModeTemplateUrl": "editor-app/configuration/properties/transition-event-write-template.html"
        },
        "flowable-planitem-dropdown": {
            "readModeTemplateUrl": "editor-app/configuration/properties/planitem-dropdown-read-template.html",
            "writeModeTemplateUrl": "editor-app/configuration/properties/planitem-dropdown-write-template.html"
        }
    };


text:
#region License

#endregion
namespace System.ObjectEx
{
    /// <summary>
    /// ObjectExtensions
    /// </summary>
    public static partial class ObjectExtensions
    {
        //public static string Format<T>(this object obj) { return Format<T, object>(obj, null); }
        //public static string Format<T>(this object obj, Nattrib attrib) { return Format<T, object>(obj, attrib); }
        //public static string Format<T, TValue>(this object obj) { return Format<T, TValue>(obj, null); }
        //public static string Format<T, TValue>(this object obj, Nattrib attrib)
        //{
        //    return FormatterEx.ObjectFormatterDelegateFactory<T, TValue>.Format(obj, attrib);
        //}
        //public static string Format<TValue>(this object obj, FormatterEx.IObjectFormatter<TValue> formatter) { return Format<TValue>(obj, formatter, null); }
        //public static string Format<TValue>(this object obj, FormatterEx.IObjectFormatter<TValue> formatter, Nattrib attrib)
        //{
        //    return formatter.Format(obj, attrib);
        //}

        public static T Parse<T>(this string obj) { return Parse<T, T>(obj, default(T), null); }
        public static T Parse<T>(this string obj, Nattrib attrib) { return Parse<T, T>(obj, default(T), attrib); }
        public static T Parse<T>(this object obj, T defaultValue) { return Parse<T, T>(obj, defaultValue, null); }
        public static T Parse<T>(this object obj, T defaultValue, Nattrib attrib) { return Parse<T, T>(obj, defaultValue, attrib); }
        public static TResult Parse<T, TResult>(this string obj) { return Parse<T, TResult>(obj, default(TResult), null); }
        public static TResult Parse<T, TResult>(this object obj, Nattrib attrib) { return Parse<T, TResult>(obj, default(TResult), null); }
        public static TResult Parse<T, TResult>(this object obj, TResult defaultValue) { return Parse<T, TResult>(obj, defaultValue, null); }
        public static TResult Parse<T, TResult>(this object obj, TResult defaultValue, Nattrib attrib)
        {
            return ParserEx.ObjectParserDelegateFactory<T, TResult>.Parse(obj, defaultValue, attrib);
        }
        public static TResult Parse<TResult>(this object obj, ParserEx.IObjectParser<TResult> parser) { return Parse<TResult>(obj, parser, default(TResult), null); }
        public static TResult Parse<TResult>(this object obj, ParserEx.IObjectParser<TResult> parser, Nattrib attrib) { return Parse<TResult>(obj, parser, default(TResult), attrib); }
        public static TResult Parse<TResult>(this object obj, ParserEx.IObjectParser<TResult> parser, TResult defaultValue) { return Parse<TResult>(obj, parser, defaultValue, null); }
        public static TResult Parse<TResult>(this object obj, ParserEx.IObjectParser<TResult> parser, TResult defaultValue, Nattrib attrib)
        {
            return parser.Parse(obj, defaultValue, attrib);
        }

        public static object Parse<T>(this object obj, object defaultValue) { return Parse<T>(obj, defaultValue, null); }
        public static object Parse<T>(this object obj, object defaultValue, Nattrib attrib)
        {
            return ParserEx.ObjectParserDelegateFactory<T, object>.Parse2(obj, defaultValue, attrib);
        }
        public static object Parse<TResult>(this object obj, ParserEx.IObjectParser<TResult> parser, object defaultValue) { return Parse<TResult>(obj, parser, defaultValue, null); }
        public static object Parse<TResult>(this object obj, ParserEx.IObjectParser<TResult> parser, object defaultValue, Nattrib attrib)
        {
            return parser.Parse2(obj, defaultValue, attrib);
        }

        public static string ParseAndFormat<T>(this object obj) { return ParseAndFormat<T>(obj, null); }
        public static string ParseAndFormat<T>(this object obj, Nattrib attrib)
        {
            var value = ParserEx.ObjectParserDelegateFactory<T, object>.Parse(obj, null, attrib);
            return (value != null ? FormatterEx.ObjectFormatterDelegateFactory<T, object>.Format(value, attrib) : string.Empty);
        }
        public static string ParseAndFormat<TResult>(this object obj, ParserEx.IObjectParser<TResult> parser, FormatterEx.IValueFormatter<TResult> formatter) { return ParseAndFormat<TResult>(obj, parser, formatter, null); }
        public static string ParseAndFormat<TResult>(this object obj, ParserEx.IObjectParser<TResult> parser, FormatterEx.IValueFormatter<TResult> formatter, Nattrib attrib)
        {
            var value = parser.Parse(obj, default(TResult), attrib);
            return (value != null ? formatter.Format(value, attrib) : string.Empty);
        }
    }
}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<title>cam-occ: Member List</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>
<link href="doxygen.css" rel="stylesheet" type="text/css"/>

Main Page

Classes

Files

Class List

Class Hierarchy

Class Members

ShHealOper_SplitCurve2d Member List

This is the complete list of members for ShHealOper_SplitCurve2d, including all inherited members.

Compute()	ShHealOper_SplitCurve2d	 [virtual]

SetValues(const Handle(TColStd_HSequenceOfReal)&theValues)	ShHealOper_SplitCurve2d	 [inline]

ShHealOper_SplitCurve2d()	ShHealOper_SplitCurve2d	 [inline]

<address class="footer">Generated by

 1.7.1 </address>