text:
"""Core custom tags."""

__author__ = 'John Orr (jorr@google.com)'

import os
import re
import urllib
import urlparse
from xml.etree import cElementTree
import markdown

import appengine_config
from common import crypto
from common import jinja_utils
from common import schema_fields
from common import tags
from common import utils as common_utils
from controllers import utils
from models import courses
from models import custom_modules
from models import models
from models import roles
from models import transforms
from modules.oeditor import oeditor

_RESOURCE_PREFIX = '/modules/core_tags'
RESOURCE_FOLDER = _RESOURCE_PREFIX + '/resources/'
_OEDITOR_RESOURCE_FOLDER = '/modules/oeditor/resources/'

_DRIVE_TAG_REFRESH_SCRIPT = RESOURCE_FOLDER + 'drive_tag_refresh.js'
_IFRAME_RESIZE_SCRIPT = _OEDITOR_RESOURCE_FOLDER + 'resize_iframes.js'
_PARENT_FRAME_SCRIPT = RESOURCE_FOLDER + 'drive_tag_parent_frame.js'
_SCRIPT_MANAGER_SCRIPT = RESOURCE_FOLDER + 'drive_tag_script_manager.js'

_RESOURCE_ABSPATH = os.path.join(os.path.dirname(__file__), 'resources')
_TEMPLATES_ABSPATH = os.path.join(os.path.dirname(__file__), 'templates')
_GOOGLE_DRIVE_TAG_PATH = _RESOURCE_PREFIX + '/googledrivetag'
_GOOGLE_DRIVE_TAG_RENDERER_PATH = _RESOURCE_PREFIX + '/googledrivetagrenderer'

def _escape_url(url, force_https=True):
    """Escapes/quotes url parts to sane user input."""
    scheme, netloc, path, query, unused_fragment = urlparse.urlsplit(url)
    if force_https:
        scheme = 'https'
    path = urllib.quote(path)
    query = urllib.quote_plus(query, '=?&;')
    return urlparse.urlunsplit((scheme, netloc, path, query, unused_fragment))

def _replace_url_query(url, new_query):
    """Replaces the query part of a URL with a new one."""
    scheme, netloc, path, _, fragment = urlparse.urlsplit(url)
    return urlparse.urlunsplit((scheme, netloc, path, new_query, fragment))

class _Runtime(object):
    """Derives runtime configuration state from CB application context."""

    def __init__(self, app_context):
        self._app_context = app_context
        self._environ = self._app_context.get_environ()

    def can_edit(self):
        return roles.Roles.is_course_admin(self._app_context)

    def courses_can_use_google_apis(self):
        return courses.COURSES_CAN_USE_GOOGLE_APIS.value

    def configured(self):
        return (
            self.courses_can_use_google_apis() and
            bool(self.get_api_key()) and
            bool(self.get_client_id()))

    def get_api_key(self):
        course, google, api_key = courses.CONFIG_KEY_GOOGLE_API_KEY.split(':')
        return self._environ.get(course, {}).get(google, {}).get(api_key, '')

    def get_client_id(self):
        course, google, client_id = courses.CONFIG_KEY_GOOGLE_CLIENT_ID.split(
            ':')
        return self._environ.get(
            course, {}
        ).get(
            google, {}
        ).get(
            client_id, '')

    def get_slug(self):
        return self._app_context.get_slug()

class CoreTag(tags.BaseTag):
    """All core custom tags derive from this class."""

    @classmethod
    def vendor(cls):
        return 'gcb'

    @classmethod
    def create_icon_url(cls, name):
        """Creates a URL for an icon with a specific name."""
        return os.path.join(RESOURCE_FOLDER, name)

class GoogleDoc(CoreTag):
    """Custom tag for a Google Doc."""

    @classmethod
    def name(cls):
        return 'Google Doc'

    def render(self, node, unused_handler):
        height = node.attrib.get('height') or '300'
        link = node.attrib.get('link')
        url = _escape_url(_replace_url_query(link, 'embedded=true'))
        iframe = cElementTree.XML("""

""")
        iframe.set('src', url)
        iframe.set('style', 'width: %spx; height: %spx' % (700, height))
        return iframe

    def get_icon_url(self):
        return self.create_icon_url('docs.png')

    def get_schema(self, unused_handler):
        reg = schema_fields.FieldRegistry(GoogleDoc.name())
        reg.add_property(
            # To get this value, users do File > Publish to the web..., click
            # 'Start publishing', and then copy and paste the Document link.
            # Changes to the publication status of a document or to its
            # contents do not appear instantly.
            schema_fields.SchemaField(
                'link', 'Document Link', 'string',
                optional=True,
                description=('Provide the "Document Link" from the Google Docs '
                             '"Publish to the web" dialog')))
        reg.add_property(
            schema_fields.SchemaField(
                'height', 'Height', 'string', i18n=False,
                optional=True,
                extra_schema_dict_values={'value': '300'},
                description=('Height of the document, in pixels. Width will be '
                             'set automatically')))
        return reg

class GoogleDrive(CoreTag, tags.ContextAwareTag):
    """Custom tag for Google Drive items."""

    CONTENT_CHUNK_TYPE = 'google-drive'

    @classmethod
    def additional_dirs(cls):
        return [_RESOURCE_ABSPATH]

    @classmethod
    def extra_css_files(cls):
        return ['google_drive_tag.css']

    @classmethod
    def extra_js_files(cls):
        return ['drive_tag_child_frame.js', 'google_drive_tag_lightbox.js']

    @classmethod
    def name(cls):
        return 'Google Drive'

    @classmethod
    def on_register(cls):
        oeditor.ObjectEditor.EXTRA_SCRIPT_TAG_URLS.append(
            cls._oeditor_extra_script_tags_urls)

    @classmethod
    def on_unregister(cls):
        oeditor.ObjectEditor.EXTRA_SCRIPT_TAG_URLS.remove(
            cls._oeditor_extra_script_tags_urls)

    @classmethod
    def _oeditor_extra_script_tags_urls(cls):
        script_urls = []
        if courses.COURSES_CAN_USE_GOOGLE_APIS.value:
            # Order matters here because scripts are inserted in the order they
            # are found in this list, and later ones may refer to symbols from
            # earlier ones.
            script_urls.append(_SCRIPT_MANAGER_SCRIPT)
            script_urls.append(_PARENT_FRAME_SCRIPT)
        return script_urls

    def get_icon_url(self):
        return self.create_icon_url('drive.png')

    def get_schema(self, handler):
        api_key = None
        client_id = None
        if handler:
            runtime = _Runtime(handler.app_context)
            if not runtime.configured():
                return self.unavailable_schema(
                    'Google Drive is not available. Please make sure the '
                    'global gcb_courses_can_use_google_apis setting is True '
                    'and set the Google API Key and Google Client ID in course '
                    'settings in order to use this tag.')

            api_key = runtime.get_api_key()
            client_id = runtime.get_client_id()

        reg = schema_fields.FieldRegistry(GoogleDrive.name())
        reg.add_property(
            schema_fields.SchemaField(
                'document-id', 'Document ID', 'string',
                optional=True,  # Validation enforced by JS code.
                description='The ID of the Google Drive item you want to '
                'use', i18n=False, extra_schema_dict_values={
                    'api-key': api_key,
                    'client-id': client_id,
                    'type-id': self.CONTENT_CHUNK_TYPE,
                    'xsrf-token': GoogleDriveRESTHandler.get_xsrf_token(),
                }))

        return reg

    def render(self, node, context):
        runtime = _Runtime(context.handler.app_context)
        resource_id = node.attrib.get('document-id')
        src = self._get_tag_renderer_url(
            runtime.get_slug(), self.CONTENT_CHUNK_TYPE, resource_id)

        tag = cElementTree.Element('div')
        tag.set('class', 'google-drive google-drive-container')

        if runtime.can_edit():
            controls = cElementTree.Element('div')
            controls.set('class', 'google-drive google-drive-controls')
            controls.set('data-api-key', runtime.get_api_key())
            controls.set('data-client-id', runtime.get_client_id())
            controls.set('data-document-id', resource_id)
            controls.set(
                'data-xsrf-token', GoogleDriveRESTHandler.get_xsrf_token())
            tag.append(controls)

        iframe = cElementTree.Element('iframe')
        iframe.set(
            'class',
            'google-drive google-drive-content-iframe gcb-needs-resizing')
        iframe.set('frameborder', '0')
        iframe.set('scrolling', 'no')
        iframe.set('src', src)
        iframe.set('title', 'Google Drive')
        iframe.set('width', '100%')
        tag.append(iframe)

        return tag

    def rollup_header_footer(self, context):
        runtime = _Runtime(context.handler.app_context)
        can_edit = runtime.can_edit()
        srcs = [_IFRAME_RESIZE_SCRIPT]

        if can_edit:  # Harmless but wasteful to give to non-admins.
            srcs = [_SCRIPT_MANAGER_SCRIPT] + srcs

        header = cElementTree.Element('div')

        for src in srcs:
            script = cElementTree.Element('script')
            script.set('src', src)
            header.append(script)

        # Put in footer so other scripts will already be loaded when our main
        # fires. Give script to admins only (though note that even if non-admins
        # grab the script we won't give them the XSRF tokens they need to issue
        # CB AJAX ops).

        footer = cElementTree.Element('div')

        if can_edit:
            script = cElementTree.Element('script')
            script.set('src', _DRIVE_TAG_REFRESH_SCRIPT)
            footer.append(script)

        return (header, footer)

    def _get_tag_renderer_url(self, slug, type_id, resource_id):
        args = urllib.urlencode(
            {'type_id': type_id, 'resource_id': resource_id})
        return '%s%s?%s' % (slug, _GOOGLE_DRIVE_TAG_RENDERER_PATH, args)

class GoogleDriveRESTHandler(utils.BaseRESTHandler):

    _XSRF_TOKEN_NAME = 'modules-core-tags-google-drive'
    XSRF_TOKEN_REQUEST_KEY = 'xsrf_token'

    @classmethod
    def get_xsrf_token(cls):
        return crypto.XsrfTokenManager.create_xsrf_token(cls._XSRF_TOKEN_NAME)

    def put(self):
        if not courses.COURSES_CAN_USE_GOOGLE_APIS.value:
            self.error(404)
            return

        request = transforms.loads(self.request.get('request', ''))

        if not self.assert_xsrf_token_or_fail(
                request, self._XSRF_TOKEN_NAME, {}):
            return

        contents = request.get('contents')
        document_id = request.get('document_id')
        type_id = request.get('type_id')

        if not (contents and document_id):
            transforms.send_json_response(
                self, 400, 'Save failed; no Google Drive item chosen.')
            return

        if not type_id:
            transforms.send_json_response(
                self, 400, 'Save failed; type_id not set')
            return

        key = None
        try:
            key = self._save_content_chunk(contents, type_id, document_id)
        except Exception, e:  # On purpose. pylint: disable=broad-except
            transforms.send_json_response(
                self, 500, 'Error when saving: %s' % e)
            return

        transforms.send_json_response(
            self, 200, 'Success.', payload_dict={'key': str(key)})

    def _save_content_chunk(self, contents, type_id, resource_id):
        key = None
        uid = models.ContentChunkDAO.make_uid(type_id, resource_id)
        matches = models.ContentChunkDAO.get_by_uid(uid)

        if not matches:
            key = models.ContentChunkDAO.save(models.ContentChunkDTO({
                'content_type': 'text/html',
                'contents': contents,
                'resource_id': resource_id,
                'type_id': type_id,
            }))
        else:
            # There is a data race in the DAO -- it's possible to create two
            # entries at the same time with the same UID. If that happened,
            # use the first one saved.
            dto = matches[0]
            dto.contents = contents
            dto.content_type = 'text/html'
            key = models.ContentChunkDAO.save(dto)

        return key

class GoogleDriveTagRenderer(utils.BaseHandler):

    def get(self):
        if not courses.COURSES_CAN_USE_GOOGLE_APIS.value:
            self.error(404)
            return

        resource_id = self.request.get('resource_id')
        type_id = self.request.get('type_id')

        if not (resource_id and type_id):
            self._handle_error(400, 'Bad request')
            return

        matches = models.ContentChunkDAO.get_by_uid(
            models.ContentChunkDAO.make_uid(type_id, resource_id))

        if not matches:
            self._handle_error(404, 'Content chunk not found')
            return

        # There is a data race in the DAO -- it's possible to create two entries
        # at the same time with the same UID. If that happened, use the first
        # one saved.
        chunk = matches[0]

        template = jinja_utils.get_template(
            'drive_item.html', [_TEMPLATES_ABSPATH])
        self.response.out.write(template.render({'contents': chunk.contents}))

    def _handle_error(self, code, message):
        template = jinja_utils.get_template(
            'drive_error.html', [_TEMPLATES_ABSPATH])
        self.error(code)
        self.response.out.write(template.render({
            'code': code,
            'message': message,
        }))

class GoogleSpreadsheet(CoreTag):
    """Custom tag for a Google Spreadsheet."""

    @classmethod
    def name(cls):
        return 'Google Spreadsheet'

    def render(self, node, unused_handler):
        height = node.attrib.get('height') or '300'
        link = node.attrib.get('link')
        url = _escape_url('%s&chrome=false' % link.split('&output')[0])
        iframe = cElementTree.XML("""

""")
        iframe.set('src', url)
        iframe.set('style', 'width: %spx; height: %spx' % (700, height))
        return iframe

    def get_icon_url(self):
        return self.create_icon_url('spreadsheets.png')

    def get_schema(self, unused_handler):
        reg = schema_fields.FieldRegistry(GoogleSpreadsheet.name())
        reg.add_property(
            # To get this value, users do File > Publish to the web..., click
            # 'Start publishing', and then copy and paste the link above 'Copy
            # and paste the link above'. Changes to the publication status of a
            # document or to its contents do not appear instantly.
            schema_fields.SchemaField(
                'link', 'Link', 'string',
                optional=True,
                description=('Provide the link from the Google Spreadsheets '
                             '"Publish to the web" dialog')))
        reg.add_property(
            schema_fields.SchemaField(
                'height', 'Height', 'string', i18n=False,
                optional=True,
                extra_schema_dict_values={'value': '300'},
                description=('Height of the spreadsheet, in pixels. Width will '
                             'be set automatically')))
        return reg

class YouTube(CoreTag):

    @classmethod
    def name(cls):
        return 'YouTube Video'

    def render(self, node, unused_handler):
        video_id = node.attrib.get('videoid')
        if utils.CAN_PERSIST_TAG_EVENTS.value:
            return self._render_with_tracking(video_id)
        else:
            return self._render_no_tracking(video_id)

    def _render_no_tracking(self, video_id):
        """Embed video without event tracking support."""
        you_tube_url = (
            'https://www.youtube.com/embed/%s'
            '?feature=player_embedded&rel=0') % video_id
        iframe = cElementTree.XML("""

""")
        iframe[0].set('src', you_tube_url)
        return iframe

    def _render_with_tracking(self, video_id):
        """Embed video and enable event tracking."""
        video_id = jinja_utils.js_string_raw(video_id)
        uid = common_utils.generate_instance_id()
        dom = cElementTree.XML("""

""")
        dom.attrib['id'] = uid
        dom[0].attrib['src'] = os.path.join(RESOURCE_FOLDER, 'youtube_video.js')
        dom[1].text = 'gcbTagYoutubeEnqueueVideo("%s", "%s");' % (video_id, uid)
        return dom

    def get_icon_url(self):
        return self.create_icon_url('youtube.png')

    def get_schema(self, unused_handler):
        reg = schema_fields.FieldRegistry(YouTube.name())
        reg.add_property(schema_fields.SchemaField(
            'videoid', 'Video Id', 'string',
            optional=True,
            description='Provide YouTube video ID (e.g. Kdg2drcUjYI)'))
        return reg

class Html5Video(CoreTag):

    @classmethod
    def name(cls):
        return 'HTML5 Video'

    def render(self, node, unused_handler):
        if utils.CAN_PERSIST_TAG_EVENTS.value:
            tracking_text = (
                '' +
                '')
        else:
            tracking_text = ''
        video_text = (
            '
' +
            '  <video></video>'
            '%s' % tracking_text +
            '
')
        video = cElementTree.XML(video_text)
        video[0].set('id', node.attrib.get('instanceid'))
        video[0].set('src', node.attrib.get('url'))
        if node.attrib.get('width'):
            video[0].set('width', node.attrib.get('width'))
        if node.attrib.get('height'):
            video[0].set('height', node.attrib.get('height'))
        video[0].set('controls', 'true')
        return video

    def get_icon_url(self):
        return self.create_icon_url('html5-badge-h-solo.png')

    def get_schema(self, unused_handler):
        reg = schema_fields.FieldRegistry(Html5Video.name())
        reg.add_property(
            schema_fields.SchemaField(
                'url', 'Video URL', 'url',
                optional=False,
                description='URL of the video.  Note that playing a video'
                'from Google Docs is supported; add "&export=download".  E.g.,'
                'https://docs.google.com/a/google.com/uc?authuser=0'
                '&id=0B82t9jeypLokMERMQ1g5Q3NFU1E&export=download'))
        reg.add_property(schema_fields.SchemaField(
            'width', 'Width', 'integer',
            optional=True,
            description='Width, in pixels.'))
        reg.add_property(schema_fields.SchemaField(
            'height', 'Height', 'integer',
            optional=True,
            description='Height, in pixels.'))
        return reg

class GoogleGroup(CoreTag):

    @classmethod
    def name(cls):
        return 'Google Group'

    def render(self, node, handler):
        # Note: in Firefox, this component requires a full hostname to work.
        # If you are working in the development environment and are accessing
        # this component at localhost, please replace 'localhost' with
        # '127.0.0.1' instead.
        _, netloc, _, _, _ = urlparse.urlsplit(handler.request.uri)

        parent_url_suffix = ''
        if (appengine_config.PRODUCTION_MODE or
            not netloc.startswith('localhost')):
            parent_url_suffix = (
                '?parenturl=%s' % urllib.quote(handler.request.uri, safe=''))

        group_name = node.attrib.get('group')
        category_name = node.attrib.get('category')
        embedded_forum_url = (
            'https://groups.google.com/forum/embed/%s#!categories/%s/%s' % (
                parent_url_suffix,
                urllib.quote(group_name),
                urllib.quote(category_name)
            ))
        iframe = cElementTree.XML("""

""")
        iframe[0].set('src', embedded_forum_url)
        return iframe

    def get_icon_url(self):
        return self.create_icon_url('forumembed.png')

    def get_schema(self, unused_handler):
        reg = schema_fields.FieldRegistry(GoogleGroup.name())
        reg.add_property(schema_fields.SchemaField(
            'group', 'Group Name', 'string', optional=True, i18n=False,
            description='Name of the Google Group (e.g. mapping-with-google)'))
        reg.add_property(schema_fields.SchemaField(
            'category', 'Category Name', 'string', optional=True, i18n=False,
            description='Name of the Category (e.g. unit5-2-annotation)'))
        return reg

class IFrame(CoreTag):

    def render(self, node, unused_handler):
        src = node.attrib.get('src')
        title = node.attrib.get('title')
        height = node.attrib.get('height') or '400'
        width = node.attrib.get('width') or '650'

        iframe = cElementTree.XML(
            ''
        )

        iframe.set('src', _escape_url(src, force_https=False))
        iframe.set('title', title)
        iframe.set('width', width)
        iframe.set('height', height)
        return iframe

    def get_icon_url(self):
        return self.create_icon_url('iframe.png')

    def get_schema(self, unused_handler):
        reg = schema_fields.FieldRegistry(IFrame.name())
        reg.add_property(schema_fields.SchemaField(
            'src', 'Source URL', 'string',
            optional=True,
            description='Provide source URL for iframe (including http/https)'))
        reg.add_property(schema_fields.SchemaField(
            'title', 'Title', 'string',
            optional=True,
            description='Provide title of iframe'))
        reg.add_property(schema_fields.SchemaField(
            'height', 'Height', 'string', i18n=False,
            optional=True,
            extra_schema_dict_values={'value': '400'},
            description=('Height of the iframe')))
        reg.add_property(schema_fields.SchemaField(
            'width', 'Width', 'string', i18n=False,
            optional=True,
            extra_schema_dict_values={'value': '650'},
            description=('Width of the iframe')))
        return reg

class Include(CoreTag):

    def render(self, node, handler):
        template_path = re.sub('^/+', '', node.attrib.get('path'))
        base_path = os.path.dirname(template_path)
        base_file = os.path.basename(template_path)
        handler.init_template_values(handler.app_context.get_environ())
        handler.template_value['base_path'] = base_path
        html_text = handler.render_template_to_html(
            handler.template_value, base_file,
            additional_dirs=[
                os.path.join(appengine_config.BUNDLE_ROOT, 'views'),
                appengine_config.BUNDLE_ROOT,
                os.path.join(appengine_config.BUNDLE_ROOT, base_path),
            ])
        return tags.html_string_to_element_tree(html_text)

    def get_icon_url(self):
        return self.create_icon_url('include.png')

    def get_schema(self, handler):
        expected_prefix = os.path.join(appengine_config.BUNDLE_ROOT,
                                       'assets/html')

        select_data = []
        if handler:
            all_files = handler.app_context.fs.list(expected_prefix,
                                                    include_inherited=True)
            for name in all_files:
                if name.startswith(expected_prefix):
                    name = name.replace(appengine_config.BUNDLE_ROOT, '')
                    select_data.append(
                        (name, name.replace('/assets/html/', '')))

        reg = schema_fields.FieldRegistry(Include.name())
        reg.add_property(schema_fields.SchemaField(
            'path', 'File Path', 'string', optional=False,
            select_data=select_data,
            description='Select a file from within assets/html.  '
            'The contents of this file will be inserted verbatim '
            'at this point.  Note: HTML files for inclusion may '
            'also be uploaded as assets.'))
        return reg

class Markdown(tags.ContextAwareTag, CoreTag):

    @classmethod
    def name(cls):
        return 'Markdown'

    @classmethod
    def extra_js_files(cls):
        """Returns a list of JS files to be loaded in the editor lightbox."""
        if oeditor.CAN_HIGHLIGHT_CODE.value:
            return ['markdown_popup.js']
        else:
            return []

    @classmethod
    def additional_dirs(cls):
        return [os.path.join(
            appengine_config.BUNDLE_ROOT, 'modules', 'core_tags', 'resources')]

    def get_icon_url(self):
        return self.create_icon_url('markdown.png')

    def render(self, node, context):
        # The markdown is "text" type in the schema and so is presented in the
        # tag's body.
        html = ''
        if node.text:
            html = markdown.markdown(node.text)
        return tags.html_string_to_element_tree(
            '
%s
' % html)

    def rollup_header_footer(self, context):
        """Include markdown css only when markdown tag is present."""
        header = tags.html_string_to_element_tree(
            '<link href="%s/markdown.css" rel="stylesheet" '
            'type="text/css">' % RESOURCE_FOLDER)
        footer = tags.html_string_to_element_tree('')
        return (header, footer)

    def get_schema(self, unused_handler):
        reg = schema_fields.FieldRegistry(Markdown.name())
        reg.add_property(schema_fields.SchemaField(
            'markdown', 'Markdown', 'text', optional=False,
            description='Provide '
            ''
            'markdown text'))
        return reg

custom_module = None

def register_module():
    """Registers this module in the registry."""

    custom_tags = [
        GoogleDoc, GoogleDrive, GoogleSpreadsheet, YouTube, Html5Video,
        GoogleGroup, IFrame, Include, Markdown]

    def make_binding_name(custom_tag):
        return 'gcb-%s' % custom_tag.__name__.lower()

    def on_module_disable():
        for custom_tag in custom_tags:
            tags.Registry.remove_tag_binding(make_binding_name(custom_tag))

        # Unregsiter extra libraries required by GoogleDrive
        GoogleDrive.on_unregister()

    def on_module_enable():
        for custom_tag in custom_tags:
            tags.Registry.add_tag_binding(
                make_binding_name(custom_tag), custom_tag)

        # Register extra libraries required by GoogleDrive
        GoogleDrive.on_register()

    global custom_module

    global_routes = [(
        os.path.join(RESOURCE_FOLDER, '.*'), tags.ResourcesHandler)]
    namespaced_routes = [
        (_GOOGLE_DRIVE_TAG_PATH, GoogleDriveRESTHandler),
        (_GOOGLE_DRIVE_TAG_RENDERER_PATH, GoogleDriveTagRenderer),
    ]

    custom_module = custom_modules.Module(
        'Core Custom Tags Module',
        'A module that provides core custom tags.',
        global_routes, namespaced_routes,
        notify_module_enabled=on_module_enable,
        notify_module_disabled=on_module_disable)
    return custom_module


text:
<!DOCTYPE html>

	<title>Chatty Help - Create Shortcut and add Icon</title>
        <link rel="stylesheet" type="text/css" href="style.css" />

Back to main help page

Create Shortcut and add Icon

This applies to Windows 7, not sure about other OS.

You can create a shortcut for Chatty, which has some potential advantages (depending on what you need):

You can give Chatty launch options, like -cd to use a different settings directory.

You can attach Chatty to the taskbar.

You can give the shortcut the Chatty icon, to replace the Java icon without changing it for all Java programs.

Create shortcut

Create a shortcut to Java to start Chatty:

First way

Right-click in the folder you want to create the shortcut in, choose New - Shortcut from the context menu. Enter javaw -jar "D:\Chatty\Chatty.jar" as location of the item.

Go to the next page and enter a name for the shortcut and finish creating the shorcut.

Right-click on the newly created shortcut and choose Properties from the context menu. Make sure that under Shortcut the Start in points to the folder that the Chatty.jar is in (otherwise some stuff might not work).

Second way

Right-click on the Chatty.jar and drag it to an open area in the folder, then let go to open the context menu, choose the option to create a shortcut.

Right-click on the newly created shortcut and choose Properties from the context menu. In the Target field, it should have the path to the Chatty.jar. Before that add: javaw -jar , so that in total it reads for example: javaw -jar "D:\Chatty\Chatty.jar"

Editing shortcut

Add launch options or icon:

Right-click on the newly created shortcut and choose Properties from the context menu, then go to the Shortcut tab.

Add any launch options you want to use with Chatty after the path to Chatty. For example: javaw -jar "D:\Chatty\Chatty.jar" -cd

Click Change Icon.. and then Browse.. to select an item to use for the Shortcut from your harddrive. (Download Chatty icon as .ico file, right-click and Save target as..)

Use shortcut

You can then start Chatty by using this shortcut or you can drag it to the taskbar to attach it to it.

redpajama_set_name: RedPajamaGithub


text:
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package com.bpreece.jtween;

import java.awt.AlphaComposite;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Paint;
import java.awt.Shape;
import java.awt.geom.AffineTransform;

/**
 *
 * @author Ly
 */
public abstract class Tween
{
    AffineTransform affineTransform = AffineTransform.getTranslateInstance(0, 0);
    AlphaComposite alphaComposite = AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 1);
    Shape clip;
    Paint paint;

    public Tween setClip(Shape clip)
    {
        this.clip = clip;
        return this;
    }

    public Tween setPaint(Paint paint)
    {
        this.paint = paint;
        return this;
    }

    public Tween setAlpha(float alpha)
    {
        alphaComposite = alphaComposite.derive(alpha);
        return this;
    }

    public Tween setAlphaRule(int rule)
    {
        alphaComposite = alphaComposite.derive(rule);
        return this;
    }

    public Tween setToRotate(double theta, double anchorX, double anchorY)
    {
        affineTransform.setToRotation(theta, anchorX, anchorY);
        return this;
    }

    public Tween setToScale(double scaleX, double scaleY)
    {
        affineTransform.setToScale(scaleX, scaleY);
        return this;
    }

    public Tween setToTranslateX(double xlateX)
    {
        affineTransform.setToTranslation(xlateX, affineTransform.getTranslateY());
        return this;
    }

    public Tween setToTranslateY(double xlateY)
    {
        affineTransform.setToTranslation(affineTransform.getTranslateX(), xlateY);
        return this;
    }

    public Tween setToTranslation(double xlateX, double xlateY)
    {
        affineTransform.setToTranslation(xlateX, xlateY);
        return this;
    }

    public void paint(Graphics g)
    {
        Graphics2D g2d = (Graphics2D) g;
        g2d.setComposite(alphaComposite);
        g2d.setTransform(affineTransform);
    }

}


text:
package org.optaplanner.benchmark.api;

import java.io.File;
import java.util.List;

import org.optaplanner.benchmark.config.PlannerBenchmarkConfig;
import org.optaplanner.benchmark.impl.DefaultPlannerBenchmarkFactory;
import org.optaplanner.core.api.domain.solution.PlanningSolution;
import org.optaplanner.core.config.solver.SolverConfig;

/**
 * Builds {@link PlannerBenchmark} instances.
 *

 * Supports tweaking the configuration programmatically before a {@link PlannerBenchmark} instance is build.
 */
public abstract class PlannerBenchmarkFactory {

    // ************************************************************************
    // Static creation methods: SolverConfig
    // ************************************************************************

    /**
     * Reads an XML solver configuration from the classpath
     * and uses that {@link SolverConfig} to build a {@link PlannerBenchmarkConfig}
     * that in turn is used to build a {@link PlannerBenchmarkFactory}.
     * The XML root element must be {@code <solver>}.
     *

     * To read an XML benchmark configuration instead, use {@link #createFromXmlResource(String)}.
     *
     * @param solverConfigResource never null, a classpath resource
     *        as defined by {@link ClassLoader#getResource(String)}
     */
    public static PlannerBenchmarkFactory createFromSolverConfigXmlResource(String solverConfigResource) {
        SolverConfig solverConfig = SolverConfig.createFromXmlResource(solverConfigResource);
        PlannerBenchmarkConfig benchmarkConfig = PlannerBenchmarkConfig.createFromSolverConfig(solverConfig);
        return new DefaultPlannerBenchmarkFactory(benchmarkConfig);
    }

    /**
     * As defined by {@link #createFromSolverConfigXmlResource(String)}.
     *
     * @param solverConfigResource never null, a classpath resource
     *        as defined by {@link ClassLoader#getResource(String)}.
     * @param classLoader sometimes null, the {@link ClassLoader} to use for loading all resources and {@link Class}es,
     *        null to use the default {@link ClassLoader}
     */
    public static PlannerBenchmarkFactory createFromSolverConfigXmlResource(String solverConfigResource,
            ClassLoader classLoader) {
        SolverConfig solverConfig = SolverConfig.createFromXmlResource(solverConfigResource, classLoader);
        PlannerBenchmarkConfig benchmarkConfig = PlannerBenchmarkConfig.createFromSolverConfig(solverConfig);
        return new DefaultPlannerBenchmarkFactory(benchmarkConfig);
    }

    /**
     * As defined by {@link #createFromSolverConfigXmlResource(String)}.
     *
     * @param solverConfigResource never null, a classpath resource
     *        as defined by {@link ClassLoader#getResource(String)}
     * @param benchmarkDirectory never null
     */
    public static PlannerBenchmarkFactory createFromSolverConfigXmlResource(String solverConfigResource,
            File benchmarkDirectory) {
        SolverConfig solverConfig = SolverConfig.createFromXmlResource(solverConfigResource);
        PlannerBenchmarkConfig benchmarkConfig = PlannerBenchmarkConfig.createFromSolverConfig(solverConfig,
                benchmarkDirectory);
        return new DefaultPlannerBenchmarkFactory(benchmarkConfig);
    }

    /**
     * As defined by {@link #createFromSolverConfigXmlResource(String)}.
     *
     * @param solverConfigResource never null, a classpath resource
     *        as defined by {@link ClassLoader#getResource(String)}
     * @param benchmarkDirectory never null
     * @param classLoader sometimes null, the {@link ClassLoader} to use for loading all resources and {@link Class}es,
     *        null to use the default {@link ClassLoader}
     */
    public static PlannerBenchmarkFactory createFromSolverConfigXmlResource(String solverConfigResource,
            File benchmarkDirectory, ClassLoader classLoader) {
        SolverConfig solverConfig = SolverConfig.createFromXmlResource(solverConfigResource, classLoader);
        PlannerBenchmarkConfig benchmarkConfig = PlannerBenchmarkConfig.createFromSolverConfig(solverConfig,
                benchmarkDirectory);
        return new DefaultPlannerBenchmarkFactory(benchmarkConfig);
    }

    // ************************************************************************
    // Static creation methods: XML
    // ************************************************************************

    /**
     * Reads an XML benchmark configuration from the classpath
     * and uses that {@link PlannerBenchmarkConfig} to build a {@link PlannerBenchmarkFactory}.
     * The XML root element must be {@code <plannerBenchmark>}.
     *

     * To read an XML solver configuration instead, use {@link #createFromSolverConfigXmlResource(String)}.
     *
     * @param benchmarkConfigResource never null, a classpath resource
     *        as defined by {@link ClassLoader#getResource(String)}
     * @return never null
     */
    public static PlannerBenchmarkFactory createFromXmlResource(String benchmarkConfigResource) {
        PlannerBenchmarkConfig benchmarkConfig = PlannerBenchmarkConfig.createFromXmlResource(benchmarkConfigResource);
        return new DefaultPlannerBenchmarkFactory(benchmarkConfig);
    }

    /**
     * As defined by {@link #createFromXmlResource(String)}.
     *
     * @param benchmarkConfigResource never null, a classpath resource
     *        as defined by {@link ClassLoader#getResource(String)}
     * @param classLoader sometimes null, the {@link ClassLoader} to use for loading all resources and {@link Class}es,
     *        null to use the default {@link ClassLoader}
     * @return never null
     */
    public static PlannerBenchmarkFactory createFromXmlResource(String benchmarkConfigResource, ClassLoader classLoader) {
        PlannerBenchmarkConfig benchmarkConfig = PlannerBenchmarkConfig.createFromXmlResource(benchmarkConfigResource,
                classLoader);
        return new DefaultPlannerBenchmarkFactory(benchmarkConfig);
    }

    /**
     * Reads an XML benchmark configuration from the file system
     * and uses that {@link PlannerBenchmarkConfig} to build a {@link PlannerBenchmarkFactory}.
     *

     * Warning: this leads to platform dependent code,
     * it's recommend to use {@link #createFromXmlResource(String)} instead.
     *
     * @param benchmarkConfigFile never null
     * @return never null
     */
    public static PlannerBenchmarkFactory createFromXmlFile(File benchmarkConfigFile) {
        PlannerBenchmarkConfig benchmarkConfig = PlannerBenchmarkConfig.createFromXmlFile(benchmarkConfigFile);
        return new DefaultPlannerBenchmarkFactory(benchmarkConfig);
    }

    /**
     * As defined by {@link #createFromXmlFile(File)}.
     *
     * @param benchmarkConfigFile never null
     * @param classLoader sometimes null, the {@link ClassLoader} to use for loading all resources and {@link Class}es,
     *        null to use the default {@link ClassLoader}
     * @return never null
     */
    public static PlannerBenchmarkFactory createFromXmlFile(File benchmarkConfigFile, ClassLoader classLoader) {
        PlannerBenchmarkConfig benchmarkConfig = PlannerBenchmarkConfig.createFromXmlFile(benchmarkConfigFile, classLoader);
        return new DefaultPlannerBenchmarkFactory(benchmarkConfig);
    }

    // ************************************************************************
    // Static creation methods: Freemarker XML
    // ************************************************************************

    /**
     * Reads an Freemarker template from the classpath that generates an XML benchmark configuration
     * and uses that {@link PlannerBenchmarkConfig} to build a {@link PlannerBenchmarkFactory}.
     * The generated XML root element must be {@code <plannerBenchmark>}.
     *
     * @param templateResource never null, a classpath resource as defined by {@link ClassLoader#getResource(String)}
     * @return never null
     * @see #createFromFreemarkerXmlResource(String)
     */
    public static PlannerBenchmarkFactory createFromFreemarkerXmlResource(String templateResource) {
        PlannerBenchmarkConfig benchmarkConfig = PlannerBenchmarkConfig.createFromFreemarkerXmlResource(templateResource);
        return new DefaultPlannerBenchmarkFactory(benchmarkConfig);
    }

    /**
     * As defined by {@link #createFromFreemarkerXmlResource(String)}.
     *
     * @param templateResource never null, a classpath resource as defined by {@link ClassLoader#getResource(String)}
     * @param classLoader sometimes null, the {@link ClassLoader} to use for loading all resources and {@link Class}es,
     *        null to use the default {@link ClassLoader}
     * @return never null
     */
    public static PlannerBenchmarkFactory createFromFreemarkerXmlResource(String templateResource, ClassLoader classLoader) {
        PlannerBenchmarkConfig benchmarkConfig = PlannerBenchmarkConfig.createFromFreemarkerXmlResource(templateResource,
                classLoader);
        return new DefaultPlannerBenchmarkFactory(benchmarkConfig);
    }

    /**
     * As defined by {@link #createFromFreemarkerXmlResource(String)}.
     *
     * @param templateResource never null, a classpath resource as defined by {@link ClassLoader#getResource(String)}
     * @param model sometimes null
     * @return never null
     */
    public static PlannerBenchmarkFactory createFromFreemarkerXmlResource(String templateResource, Object model) {
        PlannerBenchmarkConfig benchmarkConfig = PlannerBenchmarkConfig.createFromFreemarkerXmlResource(templateResource,
                model);
        return new DefaultPlannerBenchmarkFactory(benchmarkConfig);
    }

    /**
     * As defined by {@link #createFromFreemarkerXmlResource(String)}.
     *
     * @param templateResource never null, a classpath resource as defined by {@link ClassLoader#getResource(String)}
     * @param model sometimes null
     * @param classLoader sometimes null, the {@link ClassLoader} to use for loading all resources and {@link Class}es,
     *        null to use the default {@link ClassLoader}
     * @return never null
     */
    public static PlannerBenchmarkFactory createFromFreemarkerXmlResource(String templateResource, Object model,
            ClassLoader classLoader) {
        PlannerBenchmarkConfig benchmarkConfig = PlannerBenchmarkConfig.createFromFreemarkerXmlResource(templateResource, model,
                classLoader);
        return new DefaultPlannerBenchmarkFactory(benchmarkConfig);
    }

    /**
     * Reads an Freemarker template rom the file system that generates an XML benchmark configuration
     * and uses that {@link PlannerBenchmarkConfig} to build a {@link PlannerBenchmarkFactory}.
     * The generated XML root element must be {@code <plannerBenchmark>}.
     *

     * Warning: this leads to platform dependent code,
     * it's recommend to use {@link #createFromFreemarkerXmlResource(String)} instead.
     *
     * @param templateFile never null
     * @return never null
     */
    public static PlannerBenchmarkFactory createFromFreemarkerXmlFile(File templateFile) {
        PlannerBenchmarkConfig benchmarkConfig = PlannerBenchmarkConfig.createFromFreemarkerXmlFile(templateFile);
        return new DefaultPlannerBenchmarkFactory(benchmarkConfig);
    }

    /**
     * As defined by {@link #createFromFreemarkerXmlFile(File)}.
     *
     * @param templateFile never null
     * @param classLoader sometimes null, the {@link ClassLoader} to use for loading all resources and {@link Class}es,
     *        null to use the default {@link ClassLoader}
     * @return never null
     */
    public static PlannerBenchmarkFactory createFromFreemarkerXmlFile(File templateFile, ClassLoader classLoader) {
        PlannerBenchmarkConfig benchmarkConfig = PlannerBenchmarkConfig.createFromFreemarkerXmlFile(templateFile, classLoader);
        return new DefaultPlannerBenchmarkFactory(benchmarkConfig);
    }

    /**
     * As defined by {@link #createFromFreemarkerXmlFile(File)}.
     *
     * @param templateFile never null
     * @param model sometimes null
     * @return never null
     */
    public static PlannerBenchmarkFactory createFromFreemarkerXmlFile(File templateFile, Object model) {
        PlannerBenchmarkConfig benchmarkConfig = PlannerBenchmarkConfig.createFromFreemarkerXmlFile(templateFile, model);
        return new DefaultPlannerBenchmarkFactory(benchmarkConfig);
    }

    /**
     * As defined by {@link #createFromFreemarkerXmlFile(File)}.
     *
     * @param templateFile never null
     * @param model sometimes null
     * @param classLoader sometimes null, the {@link ClassLoader} to use for loading all resources and {@link Class}es,
     *        null to use the default {@link ClassLoader}
     * @return never null
     */
    public static PlannerBenchmarkFactory createFromFreemarkerXmlFile(File templateFile, Object model,
            ClassLoader classLoader) {
        PlannerBenchmarkConfig benchmarkConfig = PlannerBenchmarkConfig.createFromFreemarkerXmlFile(templateFile, model,
                classLoader);
        return new DefaultPlannerBenchmarkFactory(benchmarkConfig);
    }

    // ************************************************************************
    // Static creation methods: PlannerBenchmarkConfig
    // ************************************************************************

    /**
     * Uses a {@link PlannerBenchmarkConfig} to build a {@link PlannerBenchmarkFactory}.
     * If you don't need to manipulate the {@link PlannerBenchmarkConfig} programmatically,
     * use {@link #createFromXmlResource(String)} instead.
     *
     * @param benchmarkConfig never null
     * @return never null
     */
    public static PlannerBenchmarkFactory create(PlannerBenchmarkConfig benchmarkConfig) {
        return new DefaultPlannerBenchmarkFactory(benchmarkConfig);
    }

    // ************************************************************************
    // Interface methods
    // ************************************************************************

    /**
     * Creates a new {@link PlannerBenchmark} instance.
     *
     * @return never null
     */
    public abstract PlannerBenchmark buildPlannerBenchmark();

    /**
     * Creates a new {@link PlannerBenchmark} instance for datasets that are already in memory.
     *
     * @param problemList never null, can be empty
     * @param <Solution_> the solution type, the class with the {@link PlanningSolution} annotation
     * @return never null
     */
    public <Solution_> PlannerBenchmark buildPlannerBenchmark(List<Solution_> problemList) {
        return buildPlannerBenchmark(problemList.toArray());
    }

    /**
     * Creates a new {@link PlannerBenchmark} instance for datasets that are already in memory.
     *
     * @param problems never null, can be none
     * @param <Solution_> the solution type, the class with the {@link PlanningSolution} annotation
     * @return never null
     */
    public abstract <Solution_> PlannerBenchmark buildPlannerBenchmark(Solution_... problems);

}


text:
package org.springframework.data.neo4j.examples.galaxy.service;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Optional;

import org.neo4j.ogm.cypher.ComparisonOperator;
import org.neo4j.ogm.cypher.Filter;
import org.neo4j.ogm.cypher.query.Pagination;
import org.neo4j.ogm.session.Session;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.neo4j.examples.galaxy.domain.World;
import org.springframework.data.neo4j.examples.galaxy.repo.WorldRepository;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * @author Vince Bickers
 * @author Mark Angrish
 * @author Mark Paluch
 * @author Jens Schauder
 */
@Service
@Transactional
public class GalaxyService {

	@Autowired
	private WorldRepository worldRepository;

	@Autowired
	Session session;

	public long getNumberOfWorlds() {
		return worldRepository.count();
	}

	public World createWorld(String name, int moons) {
		return worldRepository.save(new World(name, moons));
	}

	public World create(World world) {
		return worldRepository.save(world);
	}

	public Iterable<World> getAllWorlds() {
		return worldRepository.findAll();
	}

	public Optional<World> findWorldById(Long id) {
		return worldRepository.findById(id);
	}

	public World findWorldByName(String name) {
		Iterable<World> worlds = findByProperty("name", name);
		if (worlds.iterator().hasNext()) {
			return worlds.iterator().next();
		} else {
			return null;
		}
	}

	public Iterable<World> findAllByNumberOfMoons(int numberOfMoons) {
		return findByProperty("moons", numberOfMoons);
	}

	public Collection<World> makeSomeWorlds() {

		Collection<World> worlds = new ArrayList<World>();

		// Solar worlds
		worlds.add(createWorld("Mercury", 0));
		worlds.add(createWorld("Venus", 0));

		World earth = createWorld("Earth", 1);
		World mars = createWorld("Mars", 2);

		mars.addRocketRouteTo(earth);

		// todo: handle bi-directional automatically
		//earth.addRocketRouteTo(mars);

		// this is a bit silly
		worldRepository.save(mars);

		// todo: handle-bidirectional automatically
		//worldRepository.save(earth);

		worlds.add(earth);
		worlds.add(mars);

		worlds.add(createWorld("Jupiter", 63));
		worlds.add(createWorld("Saturn", 62));
		worlds.add(createWorld("Uranus", 27));
		worlds.add(createWorld("Neptune", 13));

		// Norse worlds
		worlds.add(createWorld("Alfheimr", 0));
		worlds.add(createWorld("Midgard", 1));
		worlds.add(createWorld("Muspellheim", 2));
		worlds.add(createWorld("Asgard", 63));
		worlds.add(createWorld("Hel", 62));

		return worlds;
	}

	// not in original
	public Collection<World> makeAllWorldsAtOnce() {

		Collection<World> worlds = new ArrayList<World>();

		// Solar worlds

		worlds.add(new World("Mercury", 0));
		worlds.add(new World("Venus", 0));

		World earth = new World("Earth", 1);
		World mars = new World("Mars", 2);

		mars.addRocketRouteTo(earth);
		earth.addRocketRouteTo(mars);

		worlds.add(earth);
		worlds.add(mars);

		worlds.add(new World("Jupiter", 63));
		worlds.add(new World("Saturn", 62));
		worlds.add(new World("Uranus", 27));
		worlds.add(new World("Neptune", 13));

		// Norse worlds
		worlds.add(new World("Alfheimr", 0));
		worlds.add(new World("Midgard", 1));
		worlds.add(new World("Muspellheim", 2));
		worlds.add(new World("Asgard", 63));
		worlds.add(new World("Hel", 62));

		worldRepository.saveAll(worlds);

		return worlds;
	}

	public void deleteAll() {
		worldRepository.deleteAll();
	}

	private Iterable<World> findByProperty(String propertyName, Object propertyValue) {
		return session.loadAll(World.class, new Filter(propertyName, ComparisonOperator.EQUALS, propertyValue));
	}

	public Iterable<World> findByProperty(String propertyName, Object propertyValue, int depth) {
		return session.loadAll(World.class, new Filter(propertyName, ComparisonOperator.EQUALS, propertyValue), depth);
	}

	public Iterable<World> findAllWorlds(Pagination paging) {
		return session.loadAll(World.class, paging, 0);
	}

	public Iterable<World> findAllWorlds(Sort sort) {
		return worldRepository.findAll(sort, 0);
	}

	public Page<World> findAllWorlds(Pageable pageable) {
		return worldRepository.findAll(pageable, 0);
	}

	public Iterable<World> findAllWorlds(Sort sort, int depth) {
		return worldRepository.findAll(sort, depth);
	}

	public World findByName(String name) {
		return worldRepository.findByName(name);
	}
}


text:
[Java Development Kit](https://en.wikipedia.org/wiki/Java_Development_Kit)
----------------

The **Java Development Kit** (**JDK**) is an implementation of either one of the [Java Platform, Standard Edition](https://en.wikipedia.org/wiki/Java_Platform,_Standard_Edition); [Java Platform, Enterprise Edition](https://en.wikipedia.org/wiki/Java_Platform,_Enterprise_Edition) or [Java Platform, Micro Edition](https://en.wikipedia.org/wiki/Java_Platform,_Micro_Edition) platforms released by [Oracle Corporation](https://en.wikipedia.org/wiki/Oracle_Corporation) in the form of a binary product.

The JDK also comes with a complete [Java Runtime Environment](https://en.wikipedia.org/wiki/Java_Runtime_Environment), usually called a *private* runtime, due to the fact that it is separated from the "regular" JRE and has extra contents. It consists of a [Java Virtual Machine](https://en.wikipedia.org/wiki/Java_Virtual_Machine) and all of the class libraries present in the production environment, as well as additional libraries only useful to developers, such as the [internationalization](https://en.wikipedia.org/wiki/Internationalization_and_localization) libraries and the [IDL](https://en.wikipedia.org/wiki/Interface_description_language) libraries.

The JDK has as its primary components a collection of programming tools, including:

>- [**appletviewer**](https://en.wikipedia.org/wiki/AppletViewer) – this tool can be used to run and debug Java applets without a web browser
>
>- **apt** – the [annotation-processing tool](https://en.wikipedia.org/wiki/Metadata_facility_for_Java)
>
>- **extcheck** – a utility that detects JAR file conflicts
>
>- **idlj** – the IDL-to-Java compiler. This utility generates Java [bindings](https://en.wikipedia.org/wiki/Language_binding) from a given [Java IDL](https://en.wikipedia.org/wiki/Java_Interface_Definition_Language) file.
>
>- **jabswitch** – the [Java Access Bridge](https://en.wikipedia.org/wiki/Java_Access_Bridge). Exposes assistive technologies on Microsoft Windows systems
>
>- **java** – the [loader](https://en.wikipedia.org/wiki/Loader_(computing)) for Java applications. This tool is an interpreter and can interpret the class files generated by the [javac](https://en.wikipedia.org/wiki/Javac) compiler. Now a single launcher is used for both development and deployment. The old deployment launcher, jre, no longer comes with Sun JDK, and instead it has been replaced by this new java loader.
>
>- [**javac**](https://en.wikipedia.org/wiki/Javac) – the [Java compiler](https://en.wikipedia.org/wiki/Java_compiler), which converts source code into [Java bytecode](https://en.wikipedia.org/wiki/Java_bytecode)
>
>- [**javadoc**](https://en.wikipedia.org/wiki/Javadoc) – the documentation generator, which automatically generates documentation from [source code](https://en.wikipedia.org/wiki/Source_code) comments
>
>- **jar** – the archiver, which packages related class [libraries](https://en.wikipedia.org/wiki/Library_(computer_science)) into a single [JAR file](https://en.wikipedia.org/wiki/Jar_(file_format)). This tool also helps manage JAR files.
>
>- **javafxpackager** – tool to package and sign JavaFX applications
>
>- **jarsigner** – the jar signing and verification tool
>
>- **javah** – the C header and stub generator, used to write native methods
>
>- **javap** – the class file [disassembler](https://en.wikipedia.org/wiki/Disassembler)
>
>- **javaws** – the [Java Web Start](https://en.wikipedia.org/wiki/Java_Web_Start) launcher for JNLP applications
>
>- [**JConsole**](https://en.wikipedia.org/wiki/JConsole) – Java Monitoring and Management Console
>
>- **jdb** – the [debugger](https://en.wikipedia.org/wiki/Debugger)
>
>- **jhat** – Java Heap Analysis Tool (experimental)
>
>- **jinfo** – This utility gets configuration information from a running Java process or crash dump. (experimental)
>
>- **jmap** – This utility outputs the memory map for Java and can print shared object memory maps or heap memory details of a given process or core dump. (experimental)
>
>- **jmc** – Java Mission Control
>
>- **jps** – Java Virtual Machine Process Status Tool lists the instrumented HotSpot Java Virtual Machines (JVMs) on the target system. (experimental)
>
>- **jrunscript** – Java command-line [script](https://en.wikipedia.org/wiki/Shell_script) [shell](https://en.wikipedia.org/wiki/Shell_(computing)).
>
>- **jstack** – utility that prints Java [stack traces](https://en.wikipedia.org/wiki/Stack_trace) of Java threads (experimental)
>
>- **jstat** – [Java Virtual Machine](https://en.wikipedia.org/wiki/Java_Virtual_Machine) statistics monitoring tool (experimental)
>
>- **jstatd** – jstat daemon (experimental)
>
>- [**keytool**](https://en.wikipedia.org/wiki/Keystore) – tool for manipulating the [keystore](https://en.wikipedia.org/wiki/Keystore)
>
>- [**pack200**](https://en.wikipedia.org/wiki/Pack200) – JAR compression tool
>
>- **policytool** – the policy creation and management tool, which can determine policy for a Java runtime, specifying which permissions are available for code from various sources
>
>- [**VisualVM**](https://en.wikipedia.org/wiki/VisualVM) – visual tool integrating several [command-line](https://en.wikipedia.org/wiki/Command-line_interface) JDK tools and lightweight performance and memory [profiling](https://en.wikipedia.org/wiki/Profiling_(computer_programming)) capabilities
>
>- **wsimport** – generates portable [JAX-WS](https://en.wikipedia.org/wiki/JAX-WS) artifacts for invoking a web service.
>
>- **xjc** – Part of the Java API for XML Binding (JAXB) API. It accepts an XML schema and generates Java classes.


text:
// +build tools

// Package tools imports tool dependencies
package tools

import (
	_ "knative.dev/pkg/hack"
	_ "knative.dev/test-infra/scripts"

	// TODO add e2e test images needed
)


text:
<?xml version="1.0" encoding="UTF-8"?>
 <tileset name="Sinnoh Battle Frontier Set" firstgid="1" tilewidth="16" tileheight="16">
<image source="Sinnoh Battle Frontier Set.png" trans="000000"/>
</tileset>


text:
package org.apache.camel.dataformat.soap;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

import javax.xml.soap.MessageFactory;
import javax.xml.soap.SOAPMessage;

import org.apache.camel.Exchange;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.component.mock.MockEndpoint;
import org.apache.camel.dataformat.soap.name.TypeNameStrategy;
import org.apache.camel.test.junit4.CamelTestSupport;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;

public class SoapToSoapIgnoreTest extends CamelTestSupport {
    private static SoapJaxbDataFormat soapjaxbModel;
    private static SoapJaxbDataFormat soapjaxbModelIgnoreUnmarshalled;
    private static Map<String, String> namespacePrefixMap;

    @BeforeClass
    public static void setup() {
        namespacePrefixMap = new HashMap<>();
        namespacePrefixMap.put("http://schemas.xmlsoap.org/soap/envelope/", "soap");
        namespacePrefixMap.put("http://www.w3.org/2001/XMLSchema", "xsd");
        namespacePrefixMap.put("http://www.w3.org/2001/XMLSchema-instance", "xsi");
        namespacePrefixMap.put("http://www.example.com/contact", "cont");
        namespacePrefixMap.put("http://www.example.com/soapheaders", "custom");
        soapjaxbModel = new SoapJaxbDataFormat("com.example.contact:com.example.soapheaders");
        soapjaxbModel.setNamespacePrefix(namespacePrefixMap);
        soapjaxbModel.setPrettyPrint(true);
        soapjaxbModel.setIgnoreUnmarshalledHeaders(false);
        soapjaxbModel.setIgnoreJAXBElement(false);
        soapjaxbModel.setElementNameStrategy(new TypeNameStrategy());
        soapjaxbModelIgnoreUnmarshalled = new SoapJaxbDataFormat(
                                                                 "com.example.contact:com.example.soapheaders");
        soapjaxbModelIgnoreUnmarshalled.setNamespacePrefix(namespacePrefixMap);
        soapjaxbModelIgnoreUnmarshalled.setPrettyPrint(true);
        soapjaxbModelIgnoreUnmarshalled.setIgnoreUnmarshalledHeaders(true);
        soapjaxbModelIgnoreUnmarshalled.setElementNameStrategy(new TypeNameStrategy());
    }

    @AfterClass
    public static void teardown() {
        soapjaxbModel = null;
        namespacePrefixMap = null;
    }

    @Test
    public void testSoapMarshal() throws Exception {
        MockEndpoint endpoint = getMockEndpoint("mock:end");
        endpoint.setExpectedMessageCount(1);

        template.sendBody("direct:start", createRequest());

        assertMockEndpointsSatisfied();
        Exchange result = endpoint.assertExchangeReceived(0);

        byte[] body = (byte[])result.getIn().getBody();
        InputStream stream = new ByteArrayInputStream(body);
        SOAPMessage request = MessageFactory.newInstance().createMessage(null, stream);
        assertTrue("Expected no headers", null == request.getSOAPHeader()
                                          || !request.getSOAPHeader().extractAllHeaderElements().hasNext());
    }

    private InputStream createRequest() throws Exception {
        InputStream stream = this.getClass().getResourceAsStream("SoapMarshalHeadersTest.xml");
        return stream;
    }

    @Override
    protected RouteBuilder createRouteBuilder() {
        context.getGlobalOptions().put(Exchange.LOG_DEBUG_BODY_MAX_CHARS, "0");
        context.setTracing(true);

        return new RouteBuilder() {
            public void configure() {
                from("direct:start").unmarshal(soapjaxbModel).marshal(soapjaxbModelIgnoreUnmarshalled)
                    .to("mock:end");
            }
        };
    }
}


text:
<html>
    <head>
        <script type="text/javascript" src="../js/bower_components/jQuery/dist/jquery.min.js"></script>
        <script type="text/javascript" src="../js/simple-number-input.js"></script>
        <link rel="stylesheet" href="../css/simple-number-input.css">
    </head>

    <body>
        <input id="numberinput">
        <input id="numberinputStep">
    </body>
    <script>
        $('#numberinput').numberInput();
        $('#numberinputStep').numberInput({decimal: false, min: 0, max: 30, step: 2});
    </script>
</html>


text:
import { error as e } from '../utils/response-util';

export const jsonChecker = (req, res, next) => {
    if((req.method == 'POST' || req.method == 'PATCH') &&
        Object.keys(req.body).length < 1) {
        e.invalidInput(res, 'Invalid input');
    } else {
        next();
    }
};

export default jsonChecker;


text:
package kornell.core.entity.role;

public interface CourseClassObserverRole extends Role {
    String getCourseClassUUID();
    void setCourseClassUUID(String courseClassUUID);
}


text:
"use strict";

var interpreter = (function () {
    var _scopeStack = [];
    var _this;
    var _super;
    var _funcs = {LX_PLUS: function(c) { return (interpretExpr(c[0]) + interpretExpr(c[1])); },
		  LX_MINUS: function(c) { return (interpretExpr(c[0]) - interpretExpr(c[1])); },
		  LX_POW: function(c) { return (Math.pow(interpretExpr(c[0]), interpretExpr(c[1]))); },
		  LX_MULT: function(c) { return (interpretExpr(c[0]) * interpretExpr(c[1])); },
		  LX_DIV: function(c) { return (interpretExpr(c[0]) / interpretExpr(c[1])); },
		  LX_MODULO: function(c) { return (interpretExpr(c[0]) % interpretExpr(c[1])); },
		  LX_INC: function(c) { return (setValue(c[0].val, getValue(c[0].val) + 1)); },
		  LX_DEC: function(c) { return (setValue(c[0].val, getValue(c[0].val) - 1)); },

		  LX_OR: function(c) { return (interpretExpr(c[0]) | interpretExpr(c[1])); },
		  LX_XOR: function(c) { return (interpretExpr(c[0]) ^ interpretExpr(c[1])); },
		  LX_AND: function(c) { return (interpretExpr(c[0]) & interpretExpr(c[1])); },
		  LX_NOT: function(c) { return (~interpretExpr(c[0])); },
		  LX_LSHIFT: function(c) { return (interpretExpr(c[0]) << interpretExpr(c[1])); },
		  LX_RSHIFT: function(c) { return (interpretExpr(c[0]) >> interpretExpr(c[1])); },

		  LX_EQ: function(c) { return (interpretExpr(c[0]) == interpretExpr(c[1])); },
		  LX_NEQ: function(c) { return (interpretExpr(c[0]) != interpretExpr(c[1])); },
		  LX_LT: function(c) { return (interpretExpr(c[0]) < interpretExpr(c[1])); },
		  LX_LE: function(c) { return (interpretExpr(c[0]) <= interpretExpr(c[1])); },
		  LX_GT: function(c) { return (interpretExpr(c[0]) > interpretExpr(c[1])); },
		  LX_GE: function(c) { return (interpretExpr(c[0]) >= interpretExpr(c[1])); },

		  LX_ASSIGN: function(c) { return (setValue(c[0].val, interpretExpr(c[1]))); },
		  LX_PLUSSET: function(c) { return (setValue(c[0].val, getValue(c[0].val) + interpretExpr(c[1]))); },
		  LX_MINUSSET: function(c) { return (setValue(c[0].val, getValue(c[0].val) - interpretExpr(c[1]))); },
		  LX_MULTSET: function(c) { return (setValue(c[0].val, getValue(c[0].val) * interpretExpr(c[1]))); },
		  LX_DIVSET: function(c) { return (setValue(c[0].val, getValue(c[0].val) / interpretExpr(c[1]))); },
		  LX_MODULOSET: function(c) { return (setValue(c[0].val, getValue(c[0].val) % interpretExpr(c[1]))); },
		  LX_ANDSET: function(c) { return (setValue(c[0].val, getValue(c[0].val) & interpretExpr(c[1]))); },
		  LX_ORSET: function(c) { return (setValue(c[0].val, getValue(c[0].val) | interpretExpr(c[1]))); },
		  LX_XORSET: function(c) { return (setValue(c[0].val, getValue(c[0].val) ^ interpretExpr(c[1]))); },
		  LX_LSHIFTSET: function(c) { return (setValue(c[0].val, getValue(c[0].val) << interpretExpr(c[1]))); },
		  LX_RSHIFTSET: function(c) { return (setValue(c[0].val, getValue(c[0].val) >> interpretExpr(c[1]))); },

		  LX_LNOT: function(c) { return (0 + !interpretExpr(c[0])); },
		  LX_LOR: function(c) {
		      var val = interpretExpr(c[0]);
		      return (val ? val : interpretExpr(c[1]));
		  },
		  LX_LAND: function(c) {
		      var val = interpretExpr(c[0]);
		      return (!val ? val : interpretExpr(c[1]));
		  },

		  LX_BLOCK: function(c) {
		      var val;
		      pushScope();
		      for (var i in c)
			  val = interpretExpr(c[i]);
		      popScope();
		      return (val);
		  },
		  LX_FUNCALL: function(c) {
		      var f = getValue(c[0].val);
		      var val;

		      if (!f || typeof f != "function" && (typeof f != "object" || !f.name || f.name != "LX_FUNC")) {
			  console.error("Runtime warning: " + c[0].val + " is not a function");
			  return (null);
		      }

		      if (typeof f == "object") {
			  var args = f.children[0].children;
			  if (c.length - 1 < args.length)
			      console.warn("Runtime warning: too few arguments provided to function " + c[0].val);
			  else if (c.length - 1 > args.length)
			      console.warn("Runtime warning: too many arguments provided to function " + c[0].val);
			  pushScope();
			  for (var i = 0; i < args.length; i++)
			      _this[args[i].val] = i + 1 < c.length ? interpretExpr(c[i + 1]) : null;
			  val = interpretExpr(f.children[1]);
			  popScope();
		      } else {
			  var args = [];
			  if (c.length - 1 < f.length)
			      console.warn("Runtime warning: too few arguments provided to function " + c[0].val);
			  else if (c.length - 1 > f.length)
			      console.warn("Runtime warning: too many arguments provided to function " + c[0].val);
			  for (var i = 0; i < f.length; i++)
			      args.push(i + 1 < c.length ? interpretExpr(c[i + 1]) : null);
			  val = f.apply(null, args);
		      }
		      return (val);
		  },

		  LX_IF: function(c) {
		      if (interpretExpr(c[0]))
			  return (interpretExpr(c[1]));
		      return (c.length == 2 ? null : interpretExpr(c[2]));
		  },
		  LX_WHILE: function(c) {
		      var val = null;
		      pushScope();
		      while (interpretExpr(c[0]))
			  val = interpretExpr(c[1]);
		      popScope();
		      return (val);
		  },
		  LX_DO: function(c) {
		      var val = null;
		      pushScope();
		      do
			  val = interpretExpr(c[0]);
		      while (interpretExpr(c[1]));
		      popScope();
		      return (val);
		  },
		  LX_FOR: function(c) {
		      var val = null;
		      pushScope();
		      for (interpretExpr(c[0]); interpretExpr(c[1]); interpretExpr(c[2]))
			  val = interpretExpr(c[3]);
		      popScope();
		      return (val);
		  }
		 }

    function interpreter(ast) {
	if (!ast)
	    return (null);
	pushScope();
	defineBuiltins();
	return (interpretExpr(ast));
    }

    function defineBuiltins() {
	_this.cos = Math.cos;
	_this.acos = Math.acos;
	_this.sin = Math.sin;
	_this.asin = Math.asin;
	_this.tan = Math.tan;
	_this.atan = Math.atan;
	_this.atan2 = Math.atan2;
	_this.sqrt = Math.sqrt;
	_this.cbrt = Math.cbrt;
	_this.exp = Math.exp;
	_this.log = Math.log;
	_this.log10 = Math.log10;
	_this.log2 = Math.log2;
	_this.random = Math.random;
	_this.PI = Math.PI;
	_this.E = Math.E;
	_this.cout = function(x) {process.stdout.write(x);};
	_this.cerr = function(x) {process.stderr.write(x);};
    }

    function interpretExpr(ast) {
	if (["LX_NUMBER", "LX_STRING"].indexOf(ast.name) != -1)
	    return (ast.val);
	if (ast.name == "LX_ID")
	    return (getValue(ast.val));
	if (ast.name == "LX_FUNC")
	    return (ast);
	if (_funcs[ast.name])
	    return (_funcs[ast.name](ast.children));
	return (null);
    }

    function setValue(name, val) {
	for (var i = _scopeStack.length - 1; i >= 0; i--) {
	    if (_scopeStack[i][name] != undefined) {
		_scopeStack[i][name] = val;
		return (val);
	    }
	}
	_this[name] = val;
	return (val);
    }

    function getValue(name) {
	for (var i = _scopeStack.length - 1; i >= 0; i--) {
	    if (_scopeStack[i][name] != undefined)
		return (_scopeStack[i][name]);
	}
	return (undefined);
    }

    function pushScope() {
	_scopeStack.push({});
	_this = _scopeStack[_scopeStack.length - 1];
	_super = _scopeStack[_scopeStack.length - 2];
    }

    function popScope() {
	_scopeStack.pop();
	_this = _super;
	_super = _scopeStack[_scopeStack.length - 2];
    }

    return (interpreter);
} ());

module.exports = interpreter;


text:
/* global Validator:true */
/* global jQuery:true */
(function( Validator, $ ) {
	$.extend( Validator.prototype.copy, {
		"ccexpiration": {
			"placeholder": "YYYY MM"
		}
	});

}( Validator, jQuery ));


text:
(function() {
  var plugin;

  plugin = function(command) {
    return command.on('afterquery', function(event) {
      if (event.result.url.match(/\/\/\w+.hackpad.com/g)) {
        return event.result.title = event.result.title.replace(/&#(\d+);/g, function(a, b) {
          return String.fromCharCode(b);
        });
      }
    });
  };

  module.exports = plugin;

}).call(this);


text:
case node['platform_family']
when 'debian'
  default['nodejs']['install_repo'] = true
  default['nodejs']['repo']         = 'https://deb.nodesource.com/node_14.x'
  default['nodejs']['keyserver']    = 'keyserver.ubuntu.com'
  default['nodejs']['key']          = '1655a0ab68576280'
when 'rhel', 'fedora', 'amazon'
  default['nodejs']['install_repo'] = true
  release_ver = platform?('amazon') ? 7 : node['platform_version'].to_i
  default['nodejs']['repo']         = "https://rpm.nodesource.com/pub_14.x/el/#{release_ver}/$basearch"
  default['nodejs']['key']          = 'https://rpm.nodesource.com/pub/el/NODESOURCE-GPG-SIGNING-KEY-EL'
end


text:
import numpy as np
import imutils
import cv2

from var_dump import var_dump

from .point import *
from .utils import *
from .pair import *

#
#	Class Mask
#
#		Stores the original image, the boundaries,
#		the mask, the resulting grayscale image
#		and the contours and circles
#
#		Attributes:
#			ori 			: original image
# 			lower			: lower boundary for mask
# 			upper			: upper boundary for mask
# 			mask			: mask
# 			gray			: grayscale mask
# 			cnts			: set of contours
# 			points			: set of points within the contours
#
#		Methods:
#			mask			: distance to another Point
#			dilate_and_erode: make the contours bigger
#			gray_scale		: convert an image to grayscale
#			find_c_and_p_	: find all the contours in the thresholded image
#							  and all the points within the set of contours
#
#			show_original	: show original image
#			show_mask		: show mask
#
#
class Mask :

	# Constructor
	def __init__(self, img, lower=[130, 130, 190], upper=[255, 255, 255]) :

		# Save original and boundaries
		self.ori = img
		self.lower= np.array(lower, dtype = "uint8")
		self.upper = np.array(upper, dtype = "uint8")

		# Image size
		height, width = img.shape[:2]
		self.oriw = width
		self.orih = height

		# Find the colors within the specified boundaries and apply the mask
		self.mask = self.red_mask()

		# Conver image to grayscale
		# and keep only bright areas
		self.gray = self.gray_scale()

		# Find all contours in the thresholded image
		# and remove the small contours and the contours that can't be circles
		self.cnts, self.points = self.find_contours_and_points()

		# Dilate and erode the image
		#self.gray = self.dilate_and_erode(self.gray)

		# Find all the pairs within the set of circles
		self.pairs = self.find_pairs()

	# Create mask from boundary
	def mask(self) :
		mask = cv2.inRange(self.ori, self.lower, self.upper)
		return cv2.bitwise_and(self.ori, self.ori, mask = mask)

	# Red mask with boundary for red
	# and having red bigger than green and blue
	def red_mask(self) :
		mask = cv2.inRange(self.ori, self.lower, self.upper)
		red_mask = cv2.bitwise_and(self.ori, self.ori, mask = mask)
		redOverGreen = red_mask[:,:,2] > 1.12*red_mask[:,:,1]
		redOverBlue = red_mask[:,:,2] > 1.12*red_mask[:,:,0]
		red = np.logical_and(redOverGreen, redOverBlue)
		red = red.astype('uint8')
		end = cv2.bitwise_and(self.ori, self.ori, mask = red)
		return end

	def contour_is_valid(self, c) :
		# Area
		area = cv2.contourArea(c)
		if area > 2 and area < 200 :

			# Minimum enclosing rectangle
			rect = cv2.minAreaRect(c)
			(rWidth, rHeight) = rect[1]

			# Ratio between width and height
			ratio = rWidth / rHeight
			if ratio > 1 :
				ratio = 1 / ratio

			# If 0.5 < ratio < 1
			# then it has the appropriate shape
			if ratio > 0.5 :
				return True

		return False

	# Find all contours in the thresholded image
	# and remove the contours that don't look like circles
	#
	#	For that, calculate the minimum area rectangle
	#	that encloses the contour, and if both sides have a ratio
	#	bigger than 0.5 consider it valid.
	#
	#	Also, keep only contours with area bigger than 2 and smaller than 200
	#
	def find_contours_and_points(self) :
		# Create empty array
		cnts = []
		circles = []

		# Find the contours using openCV
		find = cv2.findContours(self.gray.copy(),
								cv2.RETR_EXTERNAL,
								cv2.CHAIN_APPROX_SIMPLE
							   )
		found = find[0] if imutils.is_cv2() else find[1]

		mask = np.ones(self.ori.shape[:2], dtype="uint8") * 255

		# Keep only contours with area
		# bigger than 9px and smaller than 200px
		# and that are like a square
		for c in found :

			cnts.append(c)

			if self.contour_is_valid(c) :
				circles.append(Point(c))
			else :
				cv2.drawContours(mask, [c], -1, 0, -1)

			self.gray = cv2.bitwise_and(self.gray, self.gray, mask=mask)

		return cnts, circles

	# Dilate and erode the contours
	def dilate_and_erode(self, ori) :
		out = cv2.dilate(ori, None, iterations=2)
		#out = cv2.erode(out, None, iterations=1)
		return out

	# Change img to gray_scale
	def gray_scale(self) :
		out = cv2.cvtColor(self.mask, cv2.COLOR_BGR2GRAY)

		maxval = out.max()
		bright = out[:,:] > 0.75*maxval
		bright = bright.astype('uint8')

		brightMask = cv2.bitwise_and(out, out, mask = bright)

		return brightMask

	# Find all the circles within the set of contours
	def find_circles(self) :
		circles = []
		for c in self.cnts :
			current = Point(c)
			if current.isCircle() :
				circles.append(current)

		return circles

	def find_pairs(self) :
		pairs = []
		for pt1 in self.points :
			for pt2 in self.points :
				if pt1 != pt2 :
					if pt1.cx > pt2.cx or (pt1.cx == pt2.cx and pt1.cy > pt2.cy) :
						if pt1.is_pair(pt2) :
							pairs.append(Pair(pt1, pt2, self.oriw, self.orih))

		return pairs

	# Show the original image
	def show_original(self) :
		cv2.imshow("Image", self.ori)
		cv2.waitKey(0)

	# Show the mask
	def show_mask(self) :
		cv2.imshow("Image", self.mask)
		cv2.waitKey(0)

	def __str__(self) :
		s = "Img: " + str(self.oriw) + "x" + str(self.orih) + "\n"
		s += " Contours: " + str(len(self.cnts)) + "\n"
		s += " Points  : " + str(len(self.points)) + "\n"
		s += " Pairs   : " + str(len(self.pairs)) + "\n"

		return s


text:
using System;
using System.Collections.Generic;
using System.Data.SQLite;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net;
using System.Reflection;
using System.Text;
using System.Web;
using Microsoft.Win32;

namespace Wox.Plugin.Doc
{
    public class Main : IPlugin
    {
        private List<Doc> docs = new List<Doc>();
        DocViewFrm frm = new DocViewFrm();
        private string docsetBasePath;

        public List<Result> Query(Query query)
        {
            List<Result> results = new List<Result>();
            if (query.ActionParameters.Count == 0)
            {
                results.Add(new Result()
                {
                    Title = "Current supported docs:"
                });
                results.AddRange(docs.Select(o => new Result()
                {
                    Title = o.Name.Replace(".docset", ""),
                    IcoPath = o.IconPath
                }).ToList());
                return results;
            }

            foreach (Doc doc in docs)
            {
                results.AddRange(QuerySqllite(doc, query.ActionParameters[0]));
            }

            return results;
        }

        public void Init(PluginInitContext context)
        {

            //todo:move to common place
            var otherCompanyDlls = new DirectoryInfo(context.PluginMetadata.PluginDirecotry).GetFiles("*.dll");
            AppDomain.CurrentDomain.AssemblyResolve += (sender, args) =>
                {
                    var dll = otherCompanyDlls.FirstOrDefault(fi =>
                        {
                            try
                            {
                                Assembly assembly = Assembly.LoadFile(fi.FullName);
                                return assembly.FullName == args.Name;
                            }
                            catch
                            {
                                return false;
                            }
                        });
                    if (dll == null)
                    {
                        return null;
                    }

                    return Assembly.LoadFile(dll.FullName);
                };

            docsetBasePath = context.PluginMetadata.PluginDirecotry + @"Docset";
            if (!Directory.Exists(docsetBasePath))
                Directory.CreateDirectory(docsetBasePath);

            foreach (string path in Directory.GetDirectories(docsetBasePath))
            {
                string name = path.Substring(path.LastIndexOf('\\') + 1);
                string dbPath = path + @"\Contents\Resources\docSet.dsidx";
                string dbType = CheckTableExists("searchIndex", dbPath) ? "DASH" : "ZDASH";
                docs.Add(new Doc
                {
                    Name = name,
                    DBPath = dbPath,
                    DBType = dbType,
                    IconPath = TryGetIcon(name, path)
                });
            }
        }

        private string TryGetIcon(string name, string path)
        {
            string url = "https://raw.github.com/jkozera/zeal/master/zeal/icons/" +
                         name.Replace(".docset", "").Replace(" ", "_") + ".png";
            string imagePath = path + "\\icon.png";
            if (!File.Exists(imagePath))
            {
                HttpWebRequest lxRequest = (HttpWebRequest)WebRequest.Create(url);
                // returned values are returned as a stream, then read into a string
                String lsResponse = string.Empty;
                using (HttpWebResponse lxResponse = (HttpWebResponse)lxRequest.GetResponse())
                {
                    using (BinaryReader reader = new BinaryReader(lxResponse.GetResponseStream()))
                    {
                        Byte[] lnByte = reader.ReadBytes(1 * 1024 * 1024 * 10);
                        using (FileStream lxFS = new FileStream(imagePath, FileMode.Create))
                        {
                            lxFS.Write(lnByte, 0, lnByte.Length);
                        }
                    }
                }

            }
            return imagePath;
        }

        private List<Result> QuerySqllite(Doc doc, string key)
        {
            string dbPath = "Data Source =" + doc.DBPath;
            SQLiteConnection conn = new SQLiteConnection(dbPath);
            conn.Open();
            string sql = GetSqlByDocDBType(doc.DBType).Replace("{0}", key);
            SQLiteCommand cmdQ = new SQLiteCommand(sql, conn);
            SQLiteDataReader reader = cmdQ.ExecuteReader();

            List<Result> results = new List<Result>();
            while (reader.Read())
            {
                string name = reader.GetString(reader.GetOrdinal("name"));
                string docPath = reader.GetString(reader.GetOrdinal("path"));

                results.Add(new Result
                    {
                        Title = name,
                        SubTitle = doc.Name.Replace(".docset", ""),
                        IcoPath = doc.IconPath,
                        Action = (c) =>
                        {
                            string url = string.Format(@"{0}\{1}\Contents\Resources\Documents\{2}#{3}", docsetBasePath,
                                doc.Name, docPath, name);

                            //frm.ShowDoc(url);
                            string browser = GetDefaultBrowserPath();
                            Process.Start(browser, String.Format("\"file:///{0}\"", url));
                        }
                    });
            }

            conn.Close();

            return results;
        }

        private static string GetDefaultBrowserPath()
        {
            string key = @"HTTP\shell\open\command";
            using (RegistryKey registrykey = Registry.ClassesRoot.OpenSubKey(key, false))
            {
                if (registrykey != null) return ((string)registrykey.GetValue(null, null)).Split('"')[1];
            }
            return null;
        }

        private string GetSqlByDocDBType(string type)
        {
            string sql = string.Empty;
            if (type == "DASH")
            {
                sql = "select * from searchIndex where name like '%{0}%' order by name asc, path asc limit 30";
            }
            if (type == "ZDASH")
            {
                sql = @"select ztokenname as name, zpath as path from ztoken
join ztokenmetainformation on ztoken.zmetainformation = ztokenmetainformation.z_pk
join zfilepath on ztokenmetainformation.zfile = zfilepath.z_pk
where (ztokenname like '%{0}%') order by lower(ztokenname) asc, zpath asc limit 30";
            }

            return sql;
        }

        private bool CheckTableExists(string table, string path)
        {
            string dbPath = "Data Source =" + path;
            SQLiteConnection conn = new SQLiteConnection(dbPath);
            conn.Open();
            string sql = "SELECT name FROM sqlite_master WHERE type='table' AND name='" + table + "';";
            SQLiteCommand cmdQ = new SQLiteCommand(sql, conn);
            object obj = cmdQ.ExecuteScalar();
            conn.Close();
            return obj != null;
        }
    }
}


text:
package org.ayo.robot;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.TextView;

import org.ayo.sample.menu.touch.TouchBoard;

/**
 * Created by Administrator on 2016/12/19.
 */

public abstract class DemoBase extends AyoActivityAttacher {

    TextView tv_title, tv_method, tv_comment, tv_notify, tv_comment_enter, tv_setting_enter;
    FrameLayout shapeViewContainer;
    BaseView baseView;
    TouchBoard touchBoard_left;
    TouchBoard touchBoard_right;

    private boolean isCommentShow = false;
    private boolean isSettingShow = false;

    @Override
    protected int getLayoutId() {
        return R.layout.demo_base;
    }

    @Override
    protected void onCreate2(View view, @Nullable Bundle bundle) {
        tv_title = id(R.id.tv_title);
        tv_method = id(R.id.tv_method);
        tv_comment = id(R.id.tv_comment);
        tv_notify = id(R.id.tv_notify);
        tv_comment_enter = id(R.id.tv_comment_enter);
        tv_setting_enter = id(R.id.tv_setting_enter);

        shapeViewContainer = id(R.id.shapeView_container);
        touchBoard_left = id(R.id.touchBoard_left);
        touchBoard_right = id(R.id.touchBoard_right);

        baseView = createTestView();
        FrameLayout.LayoutParams lp = new FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT);
        shapeViewContainer.addView(baseView, lp);

        baseView.setOnFingerTouchCallback(new BaseView.OnFingerTouchCallback() {
            @Override
            public void onFingerMove(int x, int y, int dx, int dy) {
                onViewTouchMove(x, y, dx, dy);
            }

            @Override
            public void onFingerDown(int x, int y) {
                onViewTouchDown(x, y);
            }

            @Override
            public void onFingerUp(int x, int y) {
                onViewTouchUp(x, y);
            }

            @Override
            public void onClick(int x, int y) {
                onViewClicked(x, y);
            }
        });

        setTitle(baseView.getTitle());
        setMethod(baseView.getMethod());
        setComment(baseView.getComment());

        touchBoard_left.setCallback(new TouchBoard.Callback() {
            @Override
            public void onDown(int x, int y) {

            }

            @Override
            public void onUp(int x, int y) {

            }

            @Override
            public void onClick() {
                onLeftTouchBoardClicked();
            }

            @Override
            public void onMove(int x, int y, int dx, int dy) {
                onLeftTouchBoardMove(x, y, dx, dy);
            }
        });

        touchBoard_right.setCallback(new TouchBoard.Callback() {
            @Override
            public void onDown(int x, int y) {

            }

            @Override
            public void onUp(int x, int y) {

            }

            @Override
            public void onClick() {
                onRightTouchBoardClicked();
            }

            @Override
            public void onMove(int x, int y, int dx, int dy) {
                onRightTouchBoardMove(x, y, dx, dy);
            }
        });

        ///-----设置
        final View root = findViewById(R.id.body);
        final PaintSettingView paintSettingView = DemoShapeMgmr.attach(getActivity(), root, getTestView());

        ///-----------笔记
        ///tv_comment.setVisibility(View.GONE);
        new android.os.Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                tv_comment.animate().translationY(-tv_comment.getHeight());
                paintSettingView.animate().translationY(-paintSettingView.getHeight());
            }
        }, 200);
        tv_comment_enter.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v) {
                tv_comment.animate().translationY(0);
                isCommentShow = true;
            }
        });
        tv_setting_enter.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v) {
                paintSettingView.animate().translationY(0);
                isSettingShow = true;
            }
        });

        root.findViewById(R.id.body).setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v) {
                if(isCommentShow){
                    tv_comment.animate().translationYBy(-tv_comment.getHeight());
                    isCommentShow = false;
                }
                if(isSettingShow){
                    paintSettingView.animate().translationYBy(-paintSettingView.getHeight());
                    isSettingShow = false;
                }
            }
        });

        setTestViewBackgroundStroke();
    }

    @Override
    protected void onDestroy2() {

    }

    @Override
    protected void onPageVisibleChanged(boolean b, boolean b1, @Nullable Bundle bundle) {

    }

    protected void onLeftTouchBoardMove(int x, int y, int dx, int dy){}
    protected void onRightTouchBoardMove(int x, int y, int dx, int dy){}
    protected void onLeftTouchBoardClicked(){}
    protected void onRightTouchBoardClicked(){}

    protected void onViewTouchDown(int x, int y){}
    protected void onViewTouchUp(int x, int y){}
    protected void onViewTouchMove(int x, int y, int dx, int dy){}
    protected void onViewClicked(int x, int y){}

    protected abstract BaseView createTestView();

    protected void enableLeftTouchBoard(boolean enable){
        touchBoard_left.setVisibility(enable ? View.VISIBLE : View.GONE);
    }

    protected void enableRightTouchBoard(boolean enable){
        touchBoard_right.setVisibility(enable ? View.VISIBLE : View.GONE);
    }

    protected void setTestViewBackgroundStroke(){
        shapeViewContainer.setBackgroundResource(R.drawable.round_rect);
    }

    protected void setTestViewBackgroundFill(int bgColor){
        shapeViewContainer.setBackgroundColor(bgColor);
    }

    protected <T extends BaseView> T getTestView(){
        return (T) baseView;
    }

    protected void setNotify(String s){
        tv_notify.setText(s);
    }

    private void setTitle(String s){
        tv_title.setText(s);
    }

    private void setMethod(String s){
        tv_method.setText(s);
    }

    private void setComment(String s){
        tv_comment.setText(s);
    }
}


text:
<?php

namespace Drupal\Core\Routing;

/**
 * Provides an interface for redirect destinations.
 */
interface RedirectDestinationInterface {

  /**
   * Prepares a 'destination' URL query parameter for use with \Drupal\Core\Url.
   *
   * Used to direct the user back to the referring page after completing a form.
   * By default the current URL is returned. If a destination exists in the
   * current request, that destination is returned. As such, a destination can
   * persist across multiple pages.
   *
   * @return array
   *   An associative array containing the key:
   *   - destination: The value of the current request's 'destination' query
   *     parameter, if present. This can be either a relative or absolute URL.
   *     However, for security, redirection to external URLs is not performed.
   *     If the query parameter isn't present, then the URL of the current
   *     request is returned.
   *
   * @see \Drupal\Core\EventSubscriber\RedirectResponseSubscriber::checkRedirectUrl()
   * @ingroup form_api
   */
  public function getAsArray();

  /**
   * Gets the destination as a path.
   *
   * To convert to a URL suitable for
   * \Symfony\Component\HttpFoundation\RedirectResponse::__construct() use
   * @code
   * \Drupal\Core\Url::fromUserInput(\Drupal::destination()->get())->setAbsolute()->toString()
   * @endcode
   *
   * @return string
   */
  public function get();

  /**
   * Sets the destination as URL.
   *
   * This method should be used really rarely, for example views uses it, in
   * order to override all destination calls in all of its rendering.
   *
   * @param string $new_destination
   *   The new destination.
   *
   * @return $this
   */
  public function set($new_destination);

}


text:
	<?php $this->load->view('_include') ?>

	<?php $this->load->view('_header') ?>

	<?php $this->load->view('_leftside') ?>

SALE ITEMS

                            No
                            Name
                            Type
                            Start Date
                            End Date
                            Status
                            Action

                            No
                            Name
                            Type
                            Start Date
                            End Date
                            Status
                            Action

                            Donna Snider
                            Customer Support
                            27

                            	<input type="checkbox" data-switchery data-switchery-color="#1e88e5" checked id="switch_demo_primary" />
			                    Active

                            	remove_red_eye
                            	edit
                            	delete

                            Donna Snider
                            Customer Support
                            27

                            	<input type="checkbox" data-switchery data-switchery-color="#1e88e5" checked id="switch_demo_primary" />
			                    Active

                            	remove_red_eye
                            	edit
                            	delete

                            Donna Snider
                            Customer Support
                            27

                            	<input type="checkbox" data-switchery data-switchery-color="#1e88e5" checked id="switch_demo_primary" />
			                    Active

                            	remove_red_eye
                            	edit
                            	delete

    <?php $this->load->view('_rightside') ?>


text:
using System;
using System.Collections.Generic;
using Bender.Collections;
using Bender.Configuration;
using Bender.Nodes;
using Bender.Nodes.Object;
using Bender.Reflection;
using Flexo.Extensions;
using NUnit.Framework;
using Should;
using NodeBase = Bender.Nodes.Object.ObjectNodeBase;

namespace Tests.Nodes.Object.NodeFactory.Serializable
{
    [TestFixture]
    public class RootNodeTests
    {
        private interface ISomeInterface { }
        private class SomeType<T> : ISomeInterface { }

        private static readonly object[] RootTypeCases = TestCases.Create()
            .AddType<IList<string>>(new List<string>(), "ArrayOfString", "ArrayOfString", NodeType.Array)
            .AddType<IDictionary<string, string>>(new Dictionary<string, string>(), "DictionaryOfString", "DictionaryOfString", NodeType.Object)
            .AddType<ISomeInterface>(new SomeType<string>(), "ISomeInterface", "SomeTypeOfString", NodeType.Object)
            .All;

        [Test]
        [TestCaseSource("RootTypeCases")]
        public void should_create_node_from_actual_type_overload(
            Type specifiedType, object value, string specifiedTypeName, string actualName, NodeType nodeType)
        {
            var node = Bender.Nodes.Object.NodeFactory.CreateSerializableRoot(
                value, value.ToCachedType(), Options.Create(), "xml").As<NodeBase>();

            node_should_be_in_valid_state(actualName, node, value, nodeType, value.GetType());
        }

        [Test]
        [TestCaseSource("RootTypeCases")]
        public void should_create_node_from_specified_type_overload(
            Type specifiedType, object value, string specifiedName, string actualName, NodeType nodeType)
        {
            var node = Bender.Nodes.Object.NodeFactory.CreateSerializableRoot(value, specifiedType.ToCachedType(),
                Options.Create(), "xml").As<NodeBase>();

            node_should_be_in_valid_state(specifiedName, node, value, nodeType, specifiedType);
        }

        private void node_should_be_in_valid_state(string name, NodeBase node,
            object value, NodeType nodeType, Type specifiedType)
        {
            node.HasParent.ShouldBeFalse();
            node.NodeType.ShouldEqual(nodeType);
            node.Mode.ShouldEqual(Mode.Serialize);
            node.Format.ShouldEqual(NodeBase.NodeFormat);
            node.Value.ShouldBeSameAs(value);
            node.ActualType.Type.ShouldEqual(value.GetType());
            node.SpecifiedType.Type.ShouldEqual(specifiedType);
            node.Name.ShouldEqual(name);
        }

        [Test]
        public void should_fail_to_create_simple_type_node_from_actual_type_overload()
        {
            Assert.Throws<TypeNotSupportedException>(() =>
                Bender.Nodes.Object.NodeFactory.CreateSerializableRoot("hai",
                    typeof(string).ToCachedType(), Options.Create(), "xml"))
                .Message.ShouldEqual("Simple type 'System.String' is not supported for " +
                                     "serialization. Only complex types can be serialized.");
        }

        [Test]
        public void should_fail_to_create_simple_type_node_from_specified_type_overload()
        {
            Assert.Throws<TypeNotSupportedException>(() =>
                Bender.Nodes.Object.NodeFactory.CreateSerializableRoot("hai",
                    typeof(string).ToCachedType(), Options.Create(), "xml"))
                .Message.ShouldEqual("Simple type 'System.String' is not supported for " +
                                     "serialization. Only complex types can be serialized.");
        }
    }
}


text:
#ifndef ALIITSONLINESPDPHYSANALYZER_H
#define ALIITSONLINESPDPHYSANALYZER_H

////////////////////////////////////////////////////////////
// Author: Henrik Tydesjo                                 //
// This class is used in the detector algorithm framework //
// to process the data stored in special container files  //
// (see AliITSOnlineSPDphys).                             //
////////////////////////////////////////////////////////////

#include <TString.h>

class AliITSOnlineSPDphys;
class AliITSOnlineCalibrationSPDhandler;
class TGraph;
class TH2F;

class AliITSOnlineSPDphysAnalyzer {

 public:
  AliITSOnlineSPDphysAnalyzer(const Char_t *fileName, AliITSOnlineCalibrationSPDhandler* handler, Bool_t readFromGridFile=kFALSE);
  AliITSOnlineSPDphysAnalyzer(AliITSOnlineSPDphys* physObj, AliITSOnlineCalibrationSPDhandler* handler);
  AliITSOnlineSPDphysAnalyzer(const AliITSOnlineSPDphysAnalyzer& handle);
  ~AliITSOnlineSPDphysAnalyzer();

  AliITSOnlineSPDphysAnalyzer& operator=(const AliITSOnlineSPDphysAnalyzer& handle);

  void       SetCalibHandler(AliITSOnlineCalibrationSPDhandler *handler) {fHandler=handler;}
  void       SetParam(const Char_t *pname, const Char_t *pval);
  void       ReadParamsFromLocation(const Char_t *dirName);

  UInt_t     ProcessDead();
  UInt_t     ProcessDeadPixels();
  UInt_t     ProcessNoisyPixels();
  UInt_t     ProcessNoisyPixelsFast();
  UInt_t     ProcessNoisyPixels(UInt_t eq, UInt_t nrEvts);

  UInt_t     GetNrEnoughStatChips();
  UInt_t     GetNrDeadChips();
  UInt_t     GetNrInefficientChips();
  UInt_t     GetNrNeedsMoreStatChips();

  AliITSOnlineSPDphys* GetOnlinePhys() {return fPhysObj;}
  UInt_t     GetEqNr() const;
  UInt_t     GetNrEvents() const;

  TH2F*      GetHitMapTot();
  TH2F*      GetPhysicalHitMapTot();
  TH2F*      GetHitMapChip(UInt_t hs, UInt_t chip);

 private:
  TString  fFileName; // container file name
  enum     calibvals{kMINTH,kMEANTH,kDAC,kUNIMA,kNOISE,kDELAY};  // calib types
  AliITSOnlineSPDphys               *fPhysObj; // container obj
  AliITSOnlineCalibrationSPDhandler *fHandler; // calib helper obj
  void     Init(Bool_t readFromGridFile=kFALSE);    // initialization
  void     Exponent(Double_t &val, Int_t &valExp) const;

  UInt_t   fNrEnoughStatChips;    // nr of enough stat chips
  UInt_t   fNrDeadChips;          // nr of dead chips
  UInt_t   fNrInefficientChips;   // nr of inefficient chips

  Double_t fNrEqHits;         // total nr of hits for associated eq
  Bool_t   fbDeadProcessed;   // flag to tell if ProcessDeadPixels has been called

  // dead noisy parameters:
  Double_t fThreshNoisy;       // at what confidence level do we search for noisy
  Double_t fThreshDead;        // at what confidence level do we search for dead
  UInt_t   fMinEventsForNoisy; // min nr of events required to try noisy algorithm
  UInt_t   fMinEventsForDead;  // min nr of events required to try dead algorithm
  Float_t  fDefinitelyNoisyRatio; // if a pixel fires more than this ratio of the events, it must be noisy
  Double_t fMinNrEqHitsForDeadChips; // minimum nr of hits for eq to assign dead chip
  Double_t fRatioToMeanForInefficientChip; // ratio to mean nr of hits per chip to assign ineff. chip

};

#endif