text:
import sys
import unittest
from nose.tools import assert_true, assert_false, assert_is_not_none, \
    assert_equals, assert_is_none

from robotide.robotapi import (
    TestCaseFile, Resource, VariableTable, TestDataDirectory)
from robotide.context import IS_WINDOWS
from robotide.namespace.namespace import _VariableStash
from robotide.controller.filecontrollers import DataController
from robotide.spec.iteminfo import ArgumentInfo, VariableInfo
from robotide.spec.librarymanager import LibraryManager
from robotide.utils import normpath

from datafilereader import *
from resources.mocks import FakeSettings

RESOURCES_DIR = 'resources'

sys.path.append(os.path.join(os.path.dirname(__file__), '..', RESOURCES_DIR,
                             'robotdata', 'libs'))
sys.path.append(os.path.join(os.path.dirname(__file__), '..', RESOURCES_DIR,
                             'robotdata', 'put_into_python_path'))

OS_LIB = 'OperatingSystem'
COLLECTIONS_LIB = 'Collections'
STRING_LIB = 'String'
TELNET_LIB = 'Telnet'
TELNET_LIB_ALIAS = 'telikka'
RES_NAME_VARIABLE = '${resname}'
LIB_NAME_VARIABLE = '${libname}'
UNRESOLVABLE_VARIABLE = '${unresolvable}'
UNKNOWN_VARIABLE = '${this var does not exist}'
EXTENSION_VAR = '${extension}'
EXTENSION = 'txt'
INVALID_FILE_PATH = '/this/is/invalid.py'
EXISTING_USER_KEYWORD = 'Should be in keywords Uk'
COLLIDING_ARGUMENT = '${colliding argument}'
COLLIDING_CONSTANT = COLLIDING_ARGUMENT.upper()

def _build_test_case_file():
    tcf = TestCaseFile()
    tcf.source = 'tmp.txt'
    tcf.directory = '/tmp/'
    _add_settings_table(tcf)
    _add_variable_table(tcf)
    _add_keyword_table(tcf)
    return tcf

def _add_settings_table(tcf):
    tcf.setting_table.add_library(OS_LIB)
    tcf.setting_table.add_resource(RESOURCE_PATH)
    tcf.setting_table.add_resource(RESOURCE_LIB_PATH)
    tcf.setting_table.add_resource(RES_NAME_VARIABLE)
    tcf.setting_table.add_library(LIB_NAME_VARIABLE)
    tcf.setting_table.add_library(UNRESOLVABLE_VARIABLE)
    tcf.setting_table.add_library(LIBRARY_WITH_SPACES_IN_PATH)
    tcf.setting_table.add_library(TELNET_LIB, ['WITH NAME', TELNET_LIB_ALIAS])
    tcf.setting_table.add_resource(RESOURCE_WITH_VARIABLE_IN_PATH)
    tcf.setting_table.add_variables(INVALID_FILE_PATH)

def _add_variable_table(tcf):
    tcf.variable_table.add(LIB_NAME_VARIABLE, COLLECTIONS_LIB)
    tcf.variable_table.add(RES_NAME_VARIABLE, RESOURCE_WITH_VARS)
    tcf.variable_table.add(EXTENSION_VAR, EXTENSION)
    tcf.variable_table.add(UNRESOLVABLE_VARIABLE, UNKNOWN_VARIABLE)
    tcf.variable_table.add(COLLIDING_CONSTANT, 'collision')
    tcf.variable_table.add('&{dict var}', {'key': 'value'})
    tcf.variable_table.add(u'${I <3 Unicode and \xe4iti}', u'123 \xe7')

def _add_keyword_table(tcf):
    uk_table = tcf.keyword_table
    uk_table.add(EXISTING_USER_KEYWORD)
    uk_table.keywords[0].args.value = [
        '${keyword argument}', '${colliding argument}',
        '${keyword argument with default} = default']

class ParentMock(object):
    source = '/tmp/example/parentmock'
    directory = '/tmp/exmaple'
    report_invalid_syntax = lambda *args: None

class _DataFileTest(unittest.TestCase):

    @classmethod
    def setUpClass(cls):
        cls.tcf = _build_test_case_file()
        cls.tcf_ctrl = DataController(cls.tcf, None)
        cls.kw = cls.tcf_ctrl.keywords[0]
        cls.ns = Namespace(FakeSettings())
        cls.library_manager = LibraryManager(':memory:')
        cls.library_manager.start()
        cls.library_manager.create_database()
        cls.ns.set_library_manager(cls.library_manager)

    @classmethod
    def tearDownClass(cls):
        cls.library_manager.stop()
        cls.library_manager = None

class TestKeywordSuggestions(_DataFileTest):

    def test_getting_suggestions_for_empty_datafile(self):
        start = 'shOulD'
        sugs = self.ns.get_suggestions_for(self.kw, start)
        assert_true(len(sugs) > 0)
        for s in sugs:
            assert_true(s.name.lower().startswith(start.lower()))

    def test_getting_suggestions_in_order(self):
        sugs = self.ns.get_suggestions_for(self.kw, 'sHoUlD')
        assert_true(len(sugs) > 2)
        assert_equals(sugs, sorted(sugs))

    def test_user_keywords(self):
        sugs = self.ns.get_suggestions_for(self.kw, 'sHoUlD')
        assert_true(EXISTING_USER_KEYWORD in [s.name for s in sugs])

    def test_imported_lib_keywords(self):
        sugs = self.ns.get_suggestions_for(self.kw, 'create file')
        self._assert_import_kws(sugs, OS_LIB)

    def test_lib_from_resource_file(self):
        sugs = self.ns.get_suggestions_for(self.kw, 'generate random')
        self._assert_import_kws(sugs, STRING_LIB)

    def test_lib_import_from_var(self):
        sugs = self.ns.get_suggestions_for(self.kw, 'Copy List')
        self._assert_import_kws(sugs, COLLECTIONS_LIB)

    def test_lib_import_with_spaces(self):
        sugs = self.ns.get_suggestions_for(self.kw, 'space')
        # remove variable suggestions
        sugs = [s for s in sugs if not isinstance(s, VariableInfo)]
        self._assert_import_kws(sugs, 'spacelib')

    def test_resource_file_keywords(self):
        sugs = self.ns.get_suggestions_for(self.kw, 'Resource Uk')
        self._assert_import_kws(sugs, RESOURCES_HTML)

    def test_resource_file_keyword_with_longname(self):
        sugs = self.ns.get_suggestions_for(
            self.kw, RESOURCES_HTML.replace('.html', '') + '.Resource Uk')
        self._assert_import_kws(sugs, RESOURCES_HTML)

    def test_keywords_normalization(self):
        sugs = self.ns.get_suggestions_for(self.kw, 'Reso   Urceuk')
        self._assert_import_kws(sugs, RESOURCES_HTML)

    def test_uk_from_resource_files_resource_file(self):
        sugs = self.ns.get_suggestions_for(self.kw, 'UK From Text Resource')
        self._assert_import_kws(sugs, 'resource.txt')

    def test_resource_file_from_variable(self):
        sugs = self.ns.get_suggestions_for(
            self.kw, 'UK From Variable Resource')
        self._assert_import_kws(sugs, 'resource_with_variables.txt')

    def test_resource_file_from_resource_file_with_variable(self):
        sugs = self.ns.get_suggestions_for(
            self.kw, 'UK From Resource from Resource with Variable')
        self._assert_import_kws(
            sugs, 'resource_from_resource_with_variable.txt')

    def test_library_from_resourcefile_variable(self):
        sugs = self.ns.get_suggestions_for(self.kw, 'Execute Manual')
        self._assert_import_kws(sugs, 'Dialogs')

    def test_xml_library(self):
        sugs = self.ns.get_suggestions_for(self._get_controller(
            TESTCASEFILE_WITH_EVERYTHING).keywords[0], 'Attributeless Keyword')
        self._assert_import_kws(sugs, 'LibSpecLibrary')

    def test_xml_library_is_library_keyword(self):
        everything_tcf = TestCaseFile(
            source=TESTCASEFILE_WITH_EVERYTHING).populate()
        assert_true(self.ns.is_library_keyword(
            everything_tcf, 'Attributeless Keyword'))

    def test_variable_path_separator(self):
        sugs = self.ns.get_suggestions_for(
            self._get_controller(TESTCASEFILE_WITH_EVERYTHING).keywords[0], 'foo')
        self._assert_import_kws(sugs, 'even_more_resources.txt')

    def test_keywords_only_once_per_source(self):
        sugs = self.ns.get_suggestions_for(self.kw, '')
        kw_set = []
        for kw in sugs:
            if self._not_variable(kw):
                key = 'kw: %s %s' % (kw.name, kw.source)
                assert_false(key in kw_set, key)
                kw_set.append(key)

    def _not_variable(self, item):
        return not (item.name.startswith('$') or item.name.startswith('@'))

    def test_global_variable_list_suggestions(self):
        global_vars = [name for name in _VariableStash.global_variables]
        self._test_global_variable(global_vars[0])
        self._test_global_variable(global_vars[5])
        self._test_global_variable(global_vars[-1])

    def _test_global_variable(self, variable, expected=None):
        assert_equals(
            expected or variable, self.ns.get_suggestions_for(self.kw, variable)[0].name)

    def test_resource_with_variable_in_path(self):
        sugs = self.ns.get_suggestions_for(self.kw, 'Resu UK')
        self._assert_import_kws(sugs, 'resu.txt')

    def test_scalar_variable_suggestion(self):
        scalar_vars = self.ns.get_suggestions_for(self.kw, '$')
        assert_true(len(scalar_vars) > 0)
        assert_true(
            len(self.ns.get_suggestions_for(self.kw, '${')) == len(scalar_vars))
        sug = self.ns.get_suggestions_for(self.kw, '${lib')
        assert_true(sug[0].name == LIB_NAME_VARIABLE)

    def test_list_variable_suggestion(self):
        list_vars = self.ns.get_suggestions_for(self.kw, '@')
        assert_true(len(list_vars) > 0)
        assert_true(
            len(self.ns.get_suggestions_for(self.kw, '@{')) == len(list_vars))

    def test_dict_variable_suggestion(self):
        dict_vars = self.ns.get_suggestions_for(self.kw, '&')
        assert_true(len(dict_vars) > 0)
        assert_true(
            len(self.ns.get_suggestions_for(self.kw, '&{')) == len(dict_vars))

    def test_variable_suggestions_without_varwrapping(self):
        self._test_global_variable('space', '${SPACE}')
        self._test_global_variable('EMP', '${EMPTY}')

    def test_vars_from_file(self):
        sugs = self.ns.get_suggestions_for(self._get_controller(TESTCASEFILE_WITH_EVERYTHING).keywords[0],
                                           '${var_from_file')
        assert_true(len(sugs) > 0)

    def _get_controller(self, source):
        return DataController(TestCaseFile(source=source).populate(), None)

    def test_library_arguments_are_resolved(self):
        sugs = self.ns.get_suggestions_for(self._get_controller(TESTCASEFILE_WITH_EVERYTHING).keywords[0],
                                           'Get ')
        assert_true(len(sugs) > 0)
        for item in sugs:
            if item.name == 'Get Mandatory':
                return
        raise AssertionError('Get mandatory not found')

    def test_vars_from_path_resource_file(self):
        sugs = self.ns.get_suggestions_for(self._get_controller(TESTCASEFILE_WITH_EVERYTHING).keywords[0],
                                           '${Path RESOURCE var')
        assert_true(len(sugs) > 0)

    def test_variable_file_arguments_are_resolved(self):
        sugs = self.ns.get_suggestions_for(self._get_controller(TESTCASEFILE_WITH_EVERYTHING).keywords[0],
                                           '${dyn ')
        assert_true(len(sugs) > 0)

    def test_variable_file_variables_are_available_in_resource_imports(self):
        sugs = self.ns.get_suggestions_for(self._get_controller(TESTCASEFILE_WITH_RESOURCES_WITH_VARIABLES_FROM_VARIABLE_FILE).tests[0],
                                           'from resource with variable in pa')
        self._assert_import_kws(sugs, 'res.txt')

    def test_vars_from_keyword_arguments(self):
        sugs = self.ns.get_suggestions_for(self.kw, '${keyword argu')
        assert_equals(len(sugs), 2)
        sugs = self.ns.get_suggestions_for(
            self.kw, '${keyword argument with defau')
        assert_equals(len(sugs), 1)
        self._check_source(
            self.kw, '${keyword argument with defau', ArgumentInfo.SOURCE)

    def test_argument_is_superior_to_variable_from_variable_table(self):
        sugs = self.ns.get_suggestions_for(self.kw, COLLIDING_ARGUMENT[0:4])
        assert_true(any(True for s in sugs if s.source == ArgumentInfo.SOURCE))

    def test_keyword_arguments_are_suggested_first(self):
        sugs = self.ns.get_suggestions_for(self.kw, '')
        self._assert_import_kws(sugs[:2], ArgumentInfo.SOURCE)

    def test_suggestions_for_datafile(self):
        sugs = self.ns.get_suggestions_for(self.tcf_ctrl, 'Execute Manual')
        self._assert_import_kws(sugs, 'Dialogs')
        sugs = self.ns.get_suggestions_for(self.tcf_ctrl, '${libna')
        assert_true(len(sugs) == 1)

    def test_variable_sources(self):
        everything_tcf = self._get_controller(TESTCASEFILE_WITH_EVERYTHING)
        self._check_source(everything_tcf, '${arg}', 'everything.html')
        self._check_source(everything_tcf, '@{list}', 'everything.html')
        self._check_source(everything_tcf, '${dynamic var}', 'dynamic_varz.py')
        self._check_source(
            everything_tcf, '${OPERATING SYSTEM}', 'another_resource.html')

    def test_relative_imports(self):
        relative_tcf = self._get_controller(RELATIVE_IMPORTS)
        self._check_source(relative_tcf, 'local', 'local')

    def _check_source(self, controller, name, source):
        sugs = self.ns.get_suggestions_for(controller, name)
        assert_equals(len(sugs), 1)
        assert_equals(sugs[0].source, source)

    def _assert_import_kws(self, sugs, source):
        assert_true(len(sugs) > 0)
        for s in sugs:
            assert_true(s.source.endswith(source),
                        '%s does not end with %s' % (s.source, source))

    def test_reset(self):
        sugs = self.ns.get_suggestions_for(self.kw, 'generate random')
        sugs2 = self.ns.get_suggestions_for(self.kw, 'generate random')
        assert_true(sugs[0] is sugs2[0])
        self.ns.reset_resource_and_library_cache()
        sugs3 = self.ns.get_suggestions_for(self.kw, 'generate random')
        assert_false(sugs[0] is sugs3[0])

class TestKeywordSearch(_DataFileTest):

    def test_is_library_keyword(self):
        assert_true(self.ns.is_library_keyword(self.tcf, 'Should Be Equal'))
        assert_false(self.ns.is_library_keyword(self.tcf, 'kameli'))
        assert_false(self.ns.is_library_keyword(
            self.tcf, 'UK From Resource from Resource with Variable'))

    def test_is_library_keyword_longname(self):
        assert_true(
            self.ns.is_library_keyword(self.tcf, 'Builtin.Should Be Equal'))

    def test_is_library_keyword_longname_with_alias(self):
        assert_true(
            self.ns.is_library_keyword(self.tcf, TELNET_LIB_ALIAS+'.LOGIN'))

    def test_find_default_keywords(self):
        all_kws = self.ns.get_all_keywords([])
        assert_is_not_none(all_kws)
        self.assert_in_keywords(all_kws, 'Should Be Equal')

    def test_find_suite_keywords(self):
        everything_tcf = TestCaseFile(
            source=TESTCASEFILE_WITH_EVERYTHING).populate()
        all_kws = self.ns.get_all_keywords([self.tcf, everything_tcf])
        self.assert_in_keywords(all_kws, 'Should be in keywords Uk',
                                         'Copy List',
                                         'Uk From Variable Resource')
        self.assert_in_keywords(all_kws, 'My Test Setup',
                                         'My Suite Teardown')

    def test_resource_kws_only_once(self):
        directory = TestDataDirectory(source=SIMPLE_TEST_SUITE_PATH).populate()
        all_kws = self.ns.get_all_keywords(directory.children)
        self._check_resource_keyword_only_once(all_kws)

    def test_resource_kws_only_once_through_project(self):
        project = construct_project(SIMPLE_TEST_SUITE_PATH)
        all_kws = project.get_all_keywords()
        project.close()
        self._check_resource_keyword_only_once(all_kws)

    def _check_resource_keyword_only_once(self, all_kws):
        results = [(kw.name, kw.source)
                   for kw in all_kws if kw.name == "Only From Resource"]
        assert_equals(len(results), 1)
        assert_equals(
            results[0], (u'Only From Resource', u'testdata_resource.txt'))

    def test_find_user_keyword_name_normalized(self):
        assert_is_not_none(self.ns.find_user_keyword(
            self.tcf, 'UK Fromresource from rESOURCE with variaBLE'))
        assert_is_none(self.ns.find_user_keyword(self.tcf, 'Copy List'))

    def test_is_user_keyword(self):
        assert_true(self.ns.is_user_keyword(
            self.tcf, 'UKFromResource from ResourcewithVariable'))
        assert_false(self.ns.is_user_keyword(self.tcf, 'hevoinen'))
        assert_false(self.ns.is_user_keyword(self.tcf, 'Should Be Equal'))

    def test_is_user_keyword_in_resource_file(self):
        everything_tcf = TestCaseFile(
            source=TESTCASEFILE_WITH_EVERYTHING).populate()
        assert_is_not_none(
            self.ns.find_user_keyword(everything_tcf, 'Duplicate UK'))
        assert_true(self.ns.is_user_keyword(everything_tcf, 'Duplicate UK'))
        assert_is_not_none(
            self.ns.find_user_keyword(everything_tcf, 'Another Resource UK'))
        assert_true(
            self.ns.is_user_keyword(everything_tcf, 'Another Resource UK'))

    def test_given_when_then_and_aliases(self):
        assert_is_not_none(self.ns.find_user_keyword(
            self.tcf, '  Given   UK Fromresource from rESOURCE with variaBLE'))
        assert_is_not_none(self.ns.find_user_keyword(
            self.tcf, 'when  UK Fromresource from rESOURCE with variaBLE'))
        assert_is_not_none(self.ns.find_user_keyword(
            self.tcf, '  then UK Fromresource from rESOURCE with variaBLE'))
        assert_is_not_none(self.ns.find_user_keyword(
            self.tcf, 'AND UK Fromresource from rESOURCE with variaBLE'))
        assert_is_none(self.ns.find_user_keyword(
            self.tcf, 'given and UK Fromresource from rESOURCE with variaBLE'))

    def assert_in_keywords(self, keywords, *kw_names):
        for kw_name in kw_names:
            if not self._in_keywords(keywords, kw_name):
                raise AssertionError(kw_name)

    def _in_keywords(self, keywords, kw_name):
        return any([kw_name.lower() == kw.name.lower() for kw in keywords])

class TestVariableStash(unittest.TestCase):

    def _variable_stash_contains(self, name, vars):
        assert_true('${{{0}}}'.format(name) in [v.name for v in vars])

    def test_variable_resolving(self):
        vars = _VariableStash()
        var_table = VariableTable(ParentMock())
        var_table.add('${var1}', 'foo')
        var_table.add('${var2}', 'bar')
        vars.set_from_variable_table(var_table)
        result = vars.replace_variables('hoo${var1}hii${var2}huu')
        assert_equals('hoofoohiibarhuu', result)

    def test_list_variable_index_resolving(self):
        vars = _VariableStash()
        var_table = VariableTable(ParentMock())
        var_table.add('@{var}', ['foo', 'bar'])
        vars.set_from_variable_table(var_table)
        assert_equals('Hi, foo!', vars.replace_variables('Hi, @{var}[0]!'))

    def test_dict_variable_key_resolving(self):
        vars = _VariableStash()
        var_table = VariableTable(ParentMock())
        var_table.add('&{var}', ['foo=bar'])
        vars.set_from_variable_table(var_table)
        assert_equals('Hi, bar!', vars.replace_variables('Hi, &{var}[foo]!'))

    def test_variable_resolving_with_unresolvable_value(self):
        vars = _VariableStash()
        var_table = VariableTable(ParentMock())
        var_table.add('${var1}', '${unresolvable variable}')
        var_table.add('${var2}', 'bar')
        vars.set_from_variable_table(var_table)
        self._variable_stash_contains('var1', vars)
        self._variable_stash_contains('var2', vars)

    def test_has_default_values(self):
        vars = _VariableStash()
        self._variable_stash_contains('SPACE', vars)
        self._variable_stash_contains('PREV_TEST_MESSAGE', vars)

    def test_global_variable_trues_value_is_replaced_with_true(self):
        assert_equals(_VariableStash().replace_variables('${True}'), True)

    def test_global_variable_falses_value_is_replaced_with_false(self):
        assert_equals(_VariableStash().replace_variables('${False}'), False)

    def test_global_variable_nones_value_is_replaced_with_none(self):
        assert_equals(_VariableStash().replace_variables('${None}'), None)

    def test_global_variable_nulls_value_is_replaced_with_none(self):
        assert_equals(_VariableStash().replace_variables('${null}'), None)

class TestResourceGetter(_DataFileTest):

    def test_resource_getter(self):
        resources = self.ns.get_resources(self.tcf)
        assert_equals(len(resources), 8)
        paths = []
        for res in resources:
            normalized = normpath(res.source)
            assert_false(normalized in paths)
            paths.append(normalized)

class TestResourceCache(_DataFileTest):

    def setUp(self):
        self._res_cache = self.ns._resource_factory

    def test_file_read_only_once(self):
        imp = Resource(None, RESOURCE_PATH)
        first = self._res_cache.get_resource(imp.directory, imp.name)
        second = self._res_cache.get_resource(imp.directory, imp.name)
        assert_true(first is second)

    def test_file_with_absolute_path(self):
        imp = Resource(ParentMock(), RESOURCE_PATH)
        assert_true(self._res_cache.get_resource(imp.directory, imp.name))

    def test_file_with_invalid_path(self):
        imp = Resource(ParentMock(), '${kumikameli}')
        assert_is_none(self._res_cache.get_resource(imp.directory, imp.name))

    if IS_WINDOWS:
        def test_case_sensetive_filenames(self):
            imp = Resource(None, RESOURCE_PATH)
            first = self._res_cache.get_resource(
                imp.directory, imp.name.lower())
            second = self._res_cache.get_resource(
                imp.directory, imp.name.upper())
            assert_true(first is second)

if __name__ == "__main__":
    unittest.main()


text:
param (
  $BuildStatusFile,
  $BuildDataFile,
  $ResFileTemplate,
  $OutputFile
)

$BuildStatus = Get-Content $BuildStatusFile
$BuildData = Get-Content $BuildDataFile
$ResFile = Get-Content $ResFileTemplate
$ClNumber = (((-split ($BuildData -match 'CL_NUMBER'))[-1]) -split '=')[-1].Trim("`";")
$TensorflowCommit = (-split ($BuildStatus -match 'BUILD_EMBED_LABEL'))[-1]
$ResFile = $ResFile.Replace('CL_NUMBER_TEMPLATE', $ClNumber)
$ResFile = $ResFile.Replace('TENSORFLOW_COMMIT_TEMPLATE', $TensorflowCommit)
Out-File -FilePath $OutputFile -InputObject $ResFile -Encoding unicode

redpajama_set_name: RedPajamaGithub


text:
<!--

    Copyright 2005-2014 The Kuali Foundation

    Licensed under the Educational Community License, Version 2.0 (the "License");
    you may not use this file except in compliance with the License.
    You may obtain a copy of the License at

    http://www.opensource.org/licenses/ecl2.php

    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.

-->
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
                    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

  <!-- LightTable demo -->
  <bean id="Demo-LightTable-View" parent="ComponentLibraryView">
    <property name="xmlFilePath" value="/org/kuali/rice/krad/demo/uif/library/DemoLightTable.xml"/>
    <property name="javaFullClassPath" value="org.kuali.rice.krad.uif.container.LightTable"/>
    <property name="docBookAnchor" value="d6813e6638"/>
    <property name="demoGroups">
      <list>
        <ref bean="Demo-LightTable-Example1"/>
        <ref bean="Demo-LightTable-Example2"/>
        <ref bean="Demo-LightTable-Example3"/>
        <ref bean="Demo-LightTable-Example4"/>
      </list>
    </property>
  </bean>

  <bean id="Demo-LightTable-Example1" parent="Uif-VerticalBoxSection">
    <property name="items">
      <list>
        <bean parent="Uif-Link" p:linkText="Basic DataFields LightTable"
              p:href="@{#ConfigProperties['krad.url']}/uicomponents?viewId=Demo-LightTable-View1&methodToCall=start"
              p:target="_blank"/>
      </list>
    </property>
  </bean>

  <bean id="Demo-LightTable-Example2" parent="Uif-VerticalBoxSection">
    <property name="items">
      <list>
        <bean parent="Uif-Link" p:linkText="Inquiry, Links, and Actions"
              p:href="@{#ConfigProperties['krad.url']}/uicomponents?viewId=Demo-LightTable-View2&methodToCall=start"
              p:target="_blank"/>
      </list>
    </property>
  </bean>

  <bean id="Demo-LightTable-Example3" parent="Uif-VerticalBoxSection">
    <property name="items">
      <list>
        <bean parent="Uif-Link" p:linkText="Conditional Render"
              p:href="@{#ConfigProperties['krad.url']}/uicomponents?viewId=Demo-LightTable-View3&methodToCall=start"
              p:target="_blank"/>
      </list>
    </property>
  </bean>

  <bean id="Demo-LightTable-Example4" parent="Uif-VerticalBoxSection">
    <property name="items">
      <list>
        <bean parent="Uif-Link" p:linkText="Basic Inputs"
              p:href="@{#ConfigProperties['krad.url']}/uicomponents?viewId=Demo-LightTable-View4&methodToCall=start"
              p:target="_blank"/>
      </list>
    </property>
  </bean>

  <bean id="Demo-LightTable-View1" parent="Uif-FormView">
    <property name="headerText" value="Light Table test"/>
    <property name="items">
      <list>
        <bean parent="Uif-Page">
          <property name="items">
            <list>
              <bean parent="Uif-PrimaryActionButton" p:actionLabel="Refresh Table" p:refreshId="Demo-LightTableGroup1"
                    p:methodToCall="refresh"/>
              <ref bean="Demo-LightTableGroup1"/>
            </list>
          </property>
        </bean>
      </list>
    </property>
    <property name="formClass" value="org.kuali.rice.krad.labs.kitchensink.UifComponentsTestForm"/>
  </bean>

  <bean id="Demo-LightTable-View2" parent="Uif-FormView">
    <property name="headerText" value="Light Table test"/>
    <property name="items">
      <list>
        <bean parent="Uif-Page">
          <property name="items">
            <list>
              <bean parent="Uif-PrimaryActionButton" p:actionLabel="Refresh Table" p:refreshId="Demo-LightTableGroup2"
                    p:methodToCall="refresh"/>
              <ref bean="Demo-LightTableGroup2"/>
            </list>
          </property>
        </bean>
      </list>
    </property>
    <property name="formClass" value="org.kuali.rice.krad.labs.kitchensink.UifComponentsTestForm"/>
  </bean>

  <bean id="Demo-LightTable-View3" parent="Uif-FormView">
    <property name="headerText" value="Light Table test"/>
    <property name="items">
      <list>
        <bean parent="Uif-Page">
          <property name="items">
            <list>
              <bean parent="Uif-PrimaryActionButton" p:actionLabel="Refresh Table" p:refreshId="Demo-LightTableGroup3"
                    p:methodToCall="refresh"/>
              <ref bean="Demo-LightTableGroup3"/>
            </list>
          </property>
        </bean>
      </list>
    </property>
    <property name="formClass" value="org.kuali.rice.krad.labs.kitchensink.UifComponentsTestForm"/>
  </bean>

  <bean id="Demo-LightTable-View4" parent="Uif-FormView">
    <property name="headerText" value="Light Table test"/>
    <property name="items">
      <list>
        <bean parent="Uif-Page">
          <property name="items">
            <list>
              <bean parent="Uif-PrimaryActionButton" p:actionLabel="Refresh Table" p:refreshId="Demo-LightTableGroup4"
                    p:methodToCall="refresh"/>
              <ref bean="Demo-LightTableGroup4"/>
            </list>
          </property>
        </bean>
      </list>
    </property>
    <property name="formClass" value="org.kuali.rice.krad.labs.kitchensink.UifComponentsTestForm"/>
  </bean>

  <!-- ex:Demo-LightTable-Example1 start-->
  <bean id="Demo-LightTableGroup1" parent="Uif-LightTableGroup">
    <property name="propertyName" value="list6"/>
    <property name="items">
      <list>
        <bean parent="Uif-DataField" p:label="Field 1" p:propertyName="field1"/>
        <bean parent="Uif-DataField" p:label="Field 2" p:propertyName="field2"/>
        <bean parent="Uif-DataField" p:label="Field 3" p:propertyName="field3"/>
        <bean parent="Uif-DataField" p:label="Field 4" p:propertyName="field4"/>
      </list>
    </property>
  </bean>
  <!-- ex:Demo-LightTable-Example1 end-->

  <!-- ex:Demo-LightTable-Example2 start-->
  <bean id="Demo-LightTableGroup2" parent="Uif-LightTableGroup">
    <property name="propertyName" value="list6"/>
    <property name="items">
      <list>
        <bean parent="Uif-DataField" p:label="Inquiry" p:propertyName="field3">
          <property name="inquiry">
            <bean parent="Uif-Inquiry" p:dataObjectClassName="org.kuali.rice.krad.demo.travel.account.TravelAccount"
                  p:inquiryParameters="field3:number"/>
          </property>
        </bean>
        <bean parent="Uif-DataField" p:label="Field 1" p:propertyName="field1"/>
        <bean parent="Uif-DataField" p:label="Field 2" p:propertyName="field2"/>
        <bean parent="Uif-LinkField" p:label="Field 4" p:link.linkText="@{#lp.field4}"
              p:link.href="@{#ConfigProperties['krad.url']}/uicomponents?methodToCall=start&viewId=UifCompView&field1=@{#lp.field2}"/>
        <bean parent="Uif-HorizontalFieldGroup" p:label="Field Group" p:group.validationMessages.render="false">
          <property name="items">
            <list>
              <bean parent="Uif-Action" p:actionLabel="edit"
                    p:actionScript="alert('You clicked edit for line with index @{#index}');"/>
              <bean parent="Uif-Action" p:actionLabel="delete"
                    p:actionScript="alert('You tried to delete for line with index @{#index}');"/>
            </list>
          </property>
        </bean>
      </list>
    </property>
  </bean>
  <!-- ex:Demo-LightTable-Example2 end-->

  <!-- ex:Demo-LightTable-Example3 start-->
  <bean id="Demo-LightTableGroup3" parent="Uif-LightTableGroup">
    <property name="propertyName" value="list6"/>
    <property name="items">
      <list>
        <bean parent="Uif-DataField" p:label="Field 1" p:propertyName="field1"/>
        <bean parent="Uif-DataField" p:label="Field 2" p:propertyName="field2"/>
        <bean parent="Uif-DataField" p:label="Field 3" p:propertyName="field3"
              p:render="@{new Integer(#lp.field4) gt 5}"/>
        <bean parent="Uif-DataField" p:label="Field 4" p:propertyName="field4"/>
      </list>
    </property>
  </bean>
  <!-- ex:Demo-LightTable-Example3 end-->

  <!-- ex:Demo-LightTable-Example4 start-->
  <bean id="Demo-LightTableGroup4" parent="Uif-LightTableGroup">
    <property name="propertyName" value="list6"/>
    <property name="items">
      <list>
        <bean parent="Uif-InputField" p:label="Field 1" p:propertyName="field1" p:required="true">
          <property name="validCharactersConstraint">
            <bean parent="AlphaNumericPatternConstraint"/>
          </property>
        </bean>
        <bean parent="Uif-DataField" p:label="Field 2" p:propertyName="field2"/>
        <bean parent="Uif-InputField" p:label="Field 3" p:propertyName="bfield">
          <property name="control">
            <bean parent="Uif-CheckboxControl"/>
          </property>
        </bean>
        <bean parent="Uif-InputField" p:label="Field 4" p:propertyName="field4">
          <property name="control">
            <bean parent="Uif-DropdownControl" p:options-ref="test-options"/>
          </property>
        </bean>
      </list>
    </property>
  </bean>
  <!-- ex:Demo-LightTable-Example4 start-->

</beans>


text:
<#
/********************************************************
*                                                        *
*   © Microsoft. All rights reserved.                    *
*                                                        *
*********************************************************/

.SYNOPSIS
    Sends sample split and merge requests to the Split-Merge service
    and writes the request status to the console output.

.NOTES
    Author: Microsoft SQL Elastic Scale team
    Last Updated: 8/22/2014

.EXAMPLES
    .\ExecuteSampleSplitMerge.ps1 `
        -UserName 'mysqluser' `
        -Password 'MySqlPassw0rd' `
        -ShardMapManagerServerName 'abcdefghij.database.windows.net' `
        -ShardKeyType 'Int32' `
        -SplitMergeServiceEndpoint 'https://mysplitmergeservice.cloudapp.net' `
        -CertificateThumbprint '0123456789abcdef0123456789abcdef01234567'

    .\ExecuteSampleSplitMerge.ps1 `
        -UserName 'mysqluser' `
        -Password 'MySqlPassw0rd' `
        -ShardMapManagerServerName 'abcdefghij.database.windows.net' `
        -ShardKeyType 'Int64' `
        -SplitMergeServiceEndpoint 'https://mysplitmergeservice.cloudapp.net' `
        -CertificateThumbprint '0123456789abcdef0123456789abcdef01234567'

    .\ExecuteSampleSplitMerge.ps1 `
        -UserName 'mysqluser' `
        -Password 'MySqlPassw0rd' `
        -ShardMapManagerServerName 'abcdefghij.database.windows.net' `
        -ShardKeyType 'Guid' `
        -SplitRangeLow '00000000-0000-0000-0000-000000000000' `
        -SplitValue '10000000-0000-0000-0000-000000000000' `
        -SplitRangeHigh '20000000-0000-0000-0000-000000000000' `
        -SplitMergeServiceEndpoint 'https://mysplitmergeservice.cloudapp.net' `
        -CertificateThumbprint '0123456789abcdef0123456789abcdef01234567'

    .\ExecuteSampleSplitMerge.ps1 `
        -UserName 'mysqluser' `
        -Password 'MySqlPassw0rd' `
        -ShardMapManagerServerName 'abcdefghij.database.windows.net' `
        -ShardKeyType 'Binary' `
        -SplitRangeLow '0x00' `
        -SplitValue '0x64' `
        -SplitRangeHigh '0xc8' `
        -SplitMergeServiceEndpoint 'https://mysplitmergeservice.cloudapp.net' `
        -CertificateThumbprint '0123456789abcdef0123456789abcdef01234567'

    .\ExecuteSampleSplitMerge.ps1 `
        -UserName 'mysqluser' `
        -Password 'MySqlPassw0rd' `
        -ShardMapManagerServerName 'abcdefghij.database.windows.net' `
        -ShardKeyType 'Datetime' `
        -SplitRangeLow '2010-3-21 12:00:00' `
        -SplitValue '2015-7-1 12:00:00' `
        -SplitRangeHigh '2018-9-24 12:00:00' `
        -SplitMergeServiceEndpoint 'https://mysplitmergeservice.cloudapp.net' `
        -CertificateThumbprint '0123456789abcdef0123456789abcdef01234567'
#>

[CmdletBinding()]
param (
    [parameter(Mandatory=$true)][string]$UserName,
    [parameter(Mandatory=$true)][string]$Password,
    [parameter(Mandatory=$true)][string]$ShardMapManagerServerName,
    [parameter(Mandatory=$true)][string]$SplitMergeServiceEndpoint,

    [string]$ShardMapManagerDatabaseName = 'SplitMergeShardManagement',
    [string]$ShardServerName1 = $ShardMapManagerServerName,
    [string]$ShardDatabaseName1 = 'ShardDb1',
    [string]$ShardServerName2 = $ShardMapManagerServerName,
    [string]$ShardDatabaseName2 = 'ShardDb2',

    [string]$ShardMapName = "MyTestShardMap",

    $ShardKeyType = 'Int32', # Other accepted values are 'Int64', 'Guid', 'Binary', or 'Datetime'

    # Below values must be convertible to ShardKeyType
    $SplitRangeLow = 0,
    $SplitValue = 100,
    $SplitRangeHigh = 200,

    # The thumbprint of the client certificate to be used for authentication.
    # Do not specify if client certificate authentication is not enabled in the service.
    [string]$CertificateThumbprint = $null
)

Set-StrictMode -Version Latest
$ErrorActionPreference = "Stop"

# Import SplitMerge module
$ScriptDir = Split-Path -parent $MyInvocation.MyCommand.Path
Import-Module $ScriptDir\SplitMerge -Force

# Send split request - split the high end of the range to the second shard
Write-Output 'Sending split request'
$splitOperationId = Submit-SplitRequest `
    -SplitMergeServiceEndpoint $SplitMergeServiceEndpoint `
    -ShardMapManagerServerName $ShardMapManagerServerName `
    -ShardMapManagerDatabaseName $ShardMapManagerDatabaseName `
    -TargetServerName $ShardServerName2 `
    -TargetDatabaseName $ShardDatabaseName2 `
    -UserName $UserName `
    -Password $Password `
    -ShardMapName $ShardMapName `
    -ShardKeyType $ShardKeyType `
    -SplitRangeLowKey $SplitRangeLow `
    -SplitValue $SplitValue `
    -SplitRangeHighKey $SplitRangeHigh `
    -CertificateThumbprint $CertificateThumbprint

Write-Output "Began split operation with id $splitOperationId"

# Get split request output
Wait-SplitMergeRequest -SplitMergeServiceEndpoint $SplitMergeServiceEndpoint -OperationId $splitOperationId -CertificateThumbprint $CertificateThumbprint

# Send merge request - merge the high end of the range back where the low end of the range is (i.e. the first shard)
Write-Output 'Sending merge request'
$mergeOperationId = Submit-MergeRequest `
    -SplitMergeServiceEndpoint $SplitMergeServiceEndpoint `
    -ShardMapManagerServerName $ShardMapManagerServerName `
    -ShardMapManagerDatabaseName $ShardMapManagerDatabaseName `
    -UserName $UserName `
    -Password $Password `
    -ShardMapName $ShardMapName `
    -ShardKeyType $ShardKeyType `
    -SourceRangeLowKey $SplitValue `
    -SourceRangeHighKey $SplitRangeHigh `
    -TargetRangeLowKey $SplitRangeLow `
    -TargetRangeHighKey $SplitValue `
    -CertificateThumbprint $CertificateThumbprint

Write-Output "Began merge operation with id $mergeOperationId"

# Get merge request output
Wait-SplitMergeRequest -SplitMergeServiceEndpoint $SplitMergeServiceEndpoint -OperationId $mergeOperationId -CertificateThumbprint $CertificateThumbprint


text:
module Khaleesi
  class Generator

    # The constructor accepts all settings then keep them as fields, lively in whole processing job.
    def initialize(opts={})
      # source directory path (must absolutely).
      @src_dir = opts[:src_dir].to_s

      # destination directory path (must absolutely).
      @dest_dir = opts[:dest_dir].to_s

      # setting to tell syntax highlighter output line numbers.
      $line_numbers = opts[:line_numbers].to_s.eql?('true')

      # a css class name which developer wants to customizable.
      $css_class = opts[:css_class] || 'highlight'

      # a full time pattern used to including date and time like '2014-08-22 16:45'.
      # see http://www.ruby-doc.org/core-2.1.2/Time.html#strftime-method for pattern details.
      @time_pattern = opts[:time_pattern] || '%a %e %b %H:%M %Y'

      # a short time pattern used to display only date like '2014-08-22'.
      @date_pattern = opts[:date_pattern] || '%F'

      # we just pick on those pages who changed but haven't commit
      # to git repository to generate, ignore the unchanged pages.
      # this action could be a huge benefit when you were creating
      # a new page and you want just to focusing that page at all.
      @diff_plus = opts[:diff_plus].to_s.eql?('true')

      # indicating which syntax highlighter would be used, default is Rouge.
      $use_pygments = opts[:highlighter].to_s.eql?('pygments')

      # specify which headers will generate a "Table of Contents" id, leave empty means disable TOC generation.
      $toc_selection = opts[:toc_selection].to_s

      @decrt_regexp = produce_variable_regex('decorator')
      @title_regexp = produce_variable_regex('title')
      @var_regexp = /(\p{Word}+):(\p{Word}+)/
      @doc_regexp = /^‡{6,}$/

      @page_dir = "#{@src_dir}/_pages/"

      # a cascaded variable stack that storing a set of page's variable while generating,
      # able for each handling page to grab it parent's variable and parent's variable.
      @variable_stack = Array.new

      # a queue that storing valid pages, use to avoid invalid page(decorator file)
      # influence the page link, page times generation.
      @page_stack = Array.new
    end

    # Main entry of Generator that generates all the pages of the site,
    # it scan the source directory files that obey the rule of page,
    # evaluates and applies all predefine logical, writes the final
    # content into destination directory cascaded.
    def generate
      start_time = Time.now

      Dir.glob("#{@page_dir}/**/*") do |page_file|
        next unless File.readable? page_file
        next unless is_valid_file page_file

        $toc_index = 0
        @page_stack.clear
        @page_stack.push File.expand_path(page_file)
        single_start_time = Time.now

        if @diff_plus
          file_status = nil
          base_name = File.basename(page_file)
          Dir.chdir(File.expand_path('..', page_file)) do
            file_status = %x[git status -s #{base_name} 2>&1]
          end
          file_status = file_status.to_s.strip

          # only haven't commit pages available, Git will return nothing if page committed.
          next if file_status.empty?

          # a correct message from Git should included the file name, may occur errors
          # in command running such as Git didn't install if not include.
          unless file_status.include? base_name
            puts file_status
            next
          end
        end

        extract_page_structure(page_file)

        variables = @variable_stack.pop
        # page can't stand without decorator
        next unless variables and variables[@decrt_regexp, 3]

        # isn't legal page if title missing
        next unless variables[@title_regexp, 3]

        content = is_html_file(page_file) ? parse_html_file(page_file) : parse_markdown_file(page_file)

        page_path = File.expand_path(@dest_dir + gen_link(page_file, variables))
        page_dir_path = File.dirname(page_path)
        unless File.directory?(page_dir_path)
          FileUtils.mkdir_p(page_dir_path)
        end

        bytes = IO.write(page_path, content)
        puts "Done (#{Generator.humanize(Time.now - single_start_time)}) => '#{page_path}' bytes[#{bytes}]."
      end

      puts "Generator time elapsed : #{Generator.humanize(Time.now - start_time)}."
    end

    def parse_markdown_file(file_path)
      content = extract_page_structure(file_path)
      content = parse_decorator_file(handle_markdown(content))
      @variable_stack.pop
      content
    end

    def parse_decorator_file(bore_content)
      variables = @variable_stack.last
      decorator = variables ? variables[@decrt_regexp, 3] : nil
      decorator ? parse_html_file("#{@src_dir}/_decorators/#{decorator.strip}.html", bore_content) : bore_content
    end

    def parse_html_file(file_path, bore_content=nil)
      content = extract_page_structure(file_path)

      content = parse_html_content(content.to_s, bore_content)
      content = parse_decorator_file(content) # recurse parse

      @variable_stack.pop
      content
    end

    def parse_html_content(html_content, bore_content)
      # http://www.ruby-doc.org/core-2.1.0/Regexp.html#class-Regexp-label-Repetition use '.+?' to disable greedy match.
      regexp = /(#foreach\p{Blank}?\(\$(\p{Graph}+)\p{Blank}?:\p{Blank}?\$(\p{Graph}+)\p{Blank}?(asc|desc)?\p{Blank}?(\d*)\)(.+?)#end)/m
      while (foreach_snippet = html_content.match(regexp))
        foreach_snippet = handle_foreach_snippet(foreach_snippet)

        # because the Regexp cannot skip a unhandled foreach snippet, so we claim every
        # snippet must done successfully, and if not, we shall use blank instead.
        html_content.sub!(regexp, foreach_snippet.to_s)
      end

      regexp = /(#if\p{Blank}chain:(prev|next)\(\$(\p{Graph}+)\)(.+?)#end)/m
      while (chain_snippet = html_content.match(regexp))
        chain_snippet = handle_chain_snippet(chain_snippet)
        html_content.sub!(regexp, chain_snippet.to_s)
      end

      # handle the html content after foreach and chain logical, to avoid that
      # logical included after this handle, such as including markdown files.
      html_content = handle_html_content(html_content)

      # we deal with decorator's content at final because it may slow down
      # the process even cause errors for the "foreach" and "chain" scripts.
      html_content.sub!(/\$\{decorator:content}/, bore_content) if bore_content

      html_content
    end

    def handle_html_content(html_content, added_scope=nil)
      page_file = @page_stack.last
      parsed_text = ''
      sub_script = ''

      # char by char to evaluate html content.
      html_content.each_char do |char|
        is_valid = sub_script.start_with?('${')
        case char
          when '$'
            # if met the variable expression beginner, we'll append precede characters to parsed_text
            # so the invalid part of expression still output as usual text rather than erase them.
            parsed_text << sub_script unless sub_script.empty?
            sub_script.clear << char

          when '{', ':'
            is_valid = sub_script.eql? '$' if char == '{'
            is_valid = is_valid && sub_script.length > 3 if char == ':'
            if is_valid
              sub_script << char
            else
              parsed_text << sub_script << char
              sub_script.clear
            end

          when '}'
            is_valid = is_valid && sub_script.length > 4
            sub_script << char
            if is_valid

              # parsing variable expressions such as :
              # ${variable:title}, ${variable:description}, ${custom_scope:custom_value} etc.
              form_scope = sub_script[@var_regexp, 1]
              form_value = sub_script[@var_regexp, 2]

              case form_scope
                when 'variable', added_scope

                  case form_value
                    when 'createtime'
                      create_time = Generator.fetch_create_time(page_file)
                      parsed_text << (create_time ? create_time.strftime(@time_pattern) : sub_script)

                    when 'createdate'
                      create_time = Generator.fetch_create_time(page_file)
                      parsed_text << (create_time ? create_time.strftime(@date_pattern) : sub_script)

                    when 'modifytime'
                      modify_time = Generator.fetch_modify_time(page_file)
                      parsed_text << (modify_time ? modify_time.strftime(@time_pattern) : sub_script)

                    when 'modifydate'
                      modify_time = Generator.fetch_modify_time(page_file)
                      parsed_text << (modify_time ? modify_time.strftime(@date_pattern) : sub_script)

                    when 'link'
                      page_link = gen_link(page_file, @variable_stack.last)
                      parsed_text << (page_link ? page_link : sub_script)

                    else
                      text = nil
                      if form_value.eql?('content') and form_scope.eql?(added_scope)
                        text = parse_html_file(page_file) if is_html_file(page_file)
                        text = parse_markdown_file(page_file) if is_markdown_file(page_file)

                      else
                        regexp = /^#{form_value}(\p{Blank}?):(.+)$/
                        @variable_stack.reverse_each do |var|
                          text = var[regexp, 2] if var
                          break if text
                        end

                      end

                      parsed_text << (text ? text.strip : sub_script)

                  end

                when 'page'
                  match_page = nil
                  Dir.glob("#{@page_dir}/**/#{form_value}.*") do |inner_page|
                    match_page = inner_page
                    break
                  end

                  if is_html_file(match_page)
                    @page_stack.push match_page
                    inc_content = parse_html_file(match_page)
                    @page_stack.pop
                  end
                  inc_content = parse_markdown_file(match_page) if is_markdown_file(match_page)

                  parsed_text << (inc_content ? inc_content : sub_script)

                else
                  parsed_text << sub_script
              end

            else
              parsed_text << sub_script
            end

            sub_script.clear

          else
            is_valid = is_valid && char.index(/\p{Graph}/)
            if is_valid
              sub_script << char
            else
              parsed_text << sub_script << char
              sub_script.clear
            end
        end
      end

      parsed_text
    end

    # Foreach loop was design for traversal all files of directory which inside the "_pages" directory,
    # each time through the loop, the segment who planning to repeat would be evaluate and output as parsed text.
    # at the beginning, we'll gather all files and sort by sequence or create time finally produce an ordered list.
    # NOTE: sub-directory writing was acceptable, also apply order-by-limit mode like SQL to manipulate that list.
    #
    # examples :
    #
    # loop the whole list :
    #

    #   #foreach ($theme : $themes)
    #
${theme:name}

    #
${theme:description}

    #   #end
    #

    #
    # loop the whole list but sortby descending and limit 5 items.
    #

    #   #foreach ($theme : $themes desc 5)
    #
${theme:name}

    #
${theme:description}

    #   #end
    #

    def handle_foreach_snippet(foreach_snippet)
      dir_path = foreach_snippet[3].prepend(@page_dir)
      return unless Dir.exists? dir_path

      loop_body = foreach_snippet[6]
      var_name = foreach_snippet[2]
      order_by = foreach_snippet[4]
      limit = foreach_snippet[5].to_i
      limit = -1 if limit == 0

      page_ary = take_page_array(dir_path)
      # if sub-term enable descending order, we'll reversing the page stack.
      page_ary.reverse! if order_by.eql?('desc')

      parsed_body = ''
      page_ary.each_with_index do |page, index|
        # abort loop if has limitation.
        break if index == limit
        parsed_body << handle_snippet_page(page, loop_body, var_name)
      end
      parsed_body
    end

    # Chain, just as its name meaning, we take the previous or next page from the ordered list
    # which same of foreach snippet, of course that list contained current page we just
    # generating on, so we took the near item for it, just make it like a chain.
    #
    # examples :
    #
    # #if chain:prev($theme)
    #
Prev Theme : ${theme:title}

    # #end
    #
    # #if chain:next($theme)
    #
Next Theme : ${theme:title}

    # #end
    def handle_chain_snippet(chain_snippet)
      cmd = chain_snippet[2]
      var_name = chain_snippet[3]
      loop_body = chain_snippet[4]

      page_ary = take_page_array(File.expand_path('..', @page_stack.first))
      page_ary.each_with_index do |page, index|
        next unless page.to_s.eql? @page_stack.first

        page = cmd.eql?('prev') ? page_ary.prev(index) : page_ary.next(index)
        return page ? handle_snippet_page(page, loop_body, var_name) : nil
      end
      nil
    end

    def handle_snippet_page(page, loop_body, var_name)
      # make current page properties occupy atop for two stacks while processing such sub-level files.
      @variable_stack.push(page.instance_variable_get(:@page_variables))
      @page_stack.push page.to_s

      parsed_body = handle_html_content(loop_body, var_name)

      # abandon that properties immediately.
      @variable_stack.pop
      @page_stack.pop

      parsed_body
    end

    # Search that directory and it's sub-directories, collecting all valid files,
    # then sorting by sequence or create time before return.
    def take_page_array(dir_path)
      page_ary = Array.new
      Dir.glob("#{dir_path}/**/*") do |page_file|
        next unless is_valid_file(page_file)

        extract_page_structure(page_file)
        page_ary.push Page.new(page_file, @variable_stack.pop)
      end

      page_ary.sort! do |left, right|
        right <=> left
      end
    end

    # Split by separators, extract page's variables and content.
    def extract_page_structure(page_file)
      begin
        document = IO.read(page_file)
      rescue Exception => e
        puts e.message
        document = ''
      end

      index = document.index(@doc_regexp).to_i
      if index > 0
        @variable_stack.push(document[0, index])
        document[index..-1].sub(@doc_regexp, '').strip
      else
        # we must hold the variable stack.
        @variable_stack.push(nil)
        document
      end
    end

    def gen_link(page_path, variables)
      # only generate link for title-present page.
      title = variables[@title_regexp, 3] if variables
      return unless title

      relative_path = File.dirname(page_path[/(\p{Graph}+)\/_pages(\p{Graph}+)/, 2])
      relative_path << '/' unless relative_path.end_with? '/'

      # fetch and use the pre-define page name if legal.
      page_name = variables[produce_variable_regex('slug'), 3]
      return File.expand_path(relative_path << page_name) unless page_name.strip.empty? if page_name

      # we shall use the page title to generating a link.
      Generator.format_as_legal_link(title)

      # may hunting down all title's characters, use file name as safe way.
      title = File.basename(page_path, '.*') if title.empty?

      File.expand_path(relative_path << title << '.html')
    end

    def self.format_as_legal_link(text)
      text.strip!
      # delete else of characters if not [alpha, number, whitespace, dashes, underscore].
      text.gsub!(/[^0-9a-z \-_]/i, '')
      # replace whitespace to dashes.
      text.gsub!(' ', '-')
      text.squeeze!('-')
      text.downcase!
    end

    def self.fetch_create_time(page_file)
      # fetch the first Git versioned time as create time.
      fetch_git_time(page_file, 'tail')
    end

    def self.fetch_modify_time(page_file)
      # fetch the last Git versioned time as modify time.
      fetch_git_time(page_file, 'head')
    end

    # Enter into the file container and take the Git time,
    # if something wrong with executing(Git didn't install?),
    # we'll use current time as replacement.
    def self.fetch_git_time(page_file, cmd)
      Dir.chdir(File.expand_path('..', page_file)) do
        commit_time = %x[git log --date=iso --pretty='%cd' #{File.basename(page_file)} 2>&1 | #{cmd} -1]
        begin
          # the rightful time looks like this : "2014-08-18 18:44:41 +0800"
          Time.parse(commit_time)
        rescue
          Time.now
        end
      end
    end

    # intercept the Redcarpet processing, do the syntax highlighter with Rouge or Pygments.
    class HTML < Redcarpet::Render::HTML
      def block_code(code, language)
        language = 'text' if language.to_s.strip.empty?
        css_class = $css_class + ' ' + language
        return pygments_colorize(css_class, code, language) if $use_pygments
        rouge_colorize(css_class, code, language)
      end

      def pygments_colorize(css_class, code, language)
        opts = {:cssclass => css_class, :linenos => $line_numbers}
        begin
          colored_html = Pygments.highlight(code, :lexer => language, :options => opts)
        rescue MentosError
          colored_html = Pygments.highlight(code, :lexer => 'text', :options => opts)
        end
        return colored_html unless $line_numbers

        # we'll have the html structure consistent whatever line numbers present or not.
        colored_html.sub!(" class=\"#{css_class}table\"", '')
        colored_html.sub!('
', '')
        colored_html.gsub!('
', '')
        colored_html.sub!(' class="code"', '')
        root_elements = "
"
        colored_html.sub!(root_elements, '')
        colored_html.prepend(root_elements).concat('
')
        colored_html
      end

      def rouge_colorize(css_class, code, language)
        formatter = Rouge::Formatters::HTML.new(:css_class => css_class, :line_numbers => $line_numbers)
        lexer = Rouge::Lexer.find_fancy(language, code) || Rouge::Lexers::PlainText
        colored_html = formatter.format(lexer.lex(code))

        if $line_numbers
          colored_html.sub!('class="gutter gl" style="text-align: right"', 'class="linenos"')
          colored_html.sub!(' style="border-spacing: 0"', '')
          colored_html.sub!(' class="lineno"', '')
          colored_html.sub!(' class="code"', '')
          colored_html.sub!('
', '')
          colored_html.sub!('
', '')
        else
          colored_html.sub!("", '')
          colored_html.sub!('', '')
          colored_html.prepend("
").concat('
')
        end

        colored_html
      end

      # intercept header generation, decide which need to output id by settings.
      def header(title, level)
        is_unique = $toc_selection.include?('unique')
        "\n<h%s%s>%s</h%s>\n" % [
            level, if $toc_selection.include?(level.to_s)
                     " id=\"#{is_unique ? unique_id : header_anchor(title)}\""
                   else
                     ''
                   end, title, level]
      end

      # This method origin from redcarpet-3.1.2/ext/redcarpet/html.c:268.
      def header_anchor(text)
        # We must unescape HTML entities because
        # Redcarpet escape them before.
        text = CGI.unescapeHTML(text)

        # delete markup entities.
        text = text.gsub(/<\/?[^>]*>/, '')

        Generator.format_as_legal_link(text)
        text.length < 3 ? unique_id : text
      end

      def unique_id
        "header-#{$toc_index = $toc_index + 1}"
      end

      def initialize(opts={})
        opts.store(:with_toc_data, true)
        # opts.store(:prettify, true)
        opts.store(:xhtml, true)
        super
      end
    end

    def handle_markdown(text)
      return '' if text.to_s.empty?
      markdown = Redcarpet::Markdown.new(HTML, fenced_code_blocks: true, autolink: true, no_intra_emphasis: true, strikethrough: true, tables: true)
      markdown.render(text)
    end

    def produce_variable_regex(var_name)
      /^#{var_name}(\p{Blank}?):(\p{Blank}?)(.+)$/
    end

    def is_valid_file(file_path)
      is_markdown_file(file_path) or is_html_file(file_path)
    end

    def is_markdown_file(file_path)
      file_path and file_path.end_with? '.md'
    end

    def is_html_file(file_path)
      file_path and file_path.end_with? '.html'
    end

    def self.humanize(secs) # http://stackoverflow.com/a/4136485/1294681
      secs = secs * 1000
      [[1000, :milliseconds], [60, :seconds], [60, :minutes]].map { |count, name|
        if secs > 0
          secs, n = secs.divmod(count)
          n.to_i > 0 ? "#{n.to_i} #{name}" : ''
        end
      }.compact.reverse.join(' ').squeeze(' ').strip
    end
  end

  class Page
    @page_file
    @page_variables

    def initialize(page_file, page_variables)
      @page_file = File.expand_path(page_file)
      @page_variables = page_variables
    end

    def <=> (other)
      regexp = /^sequence(\p{Blank}?):(\p{Blank}?)(\d+)$/

      self_sequence = @page_variables[regexp, 3] if @page_variables
      o_variables = other.instance_variable_get(:@page_variables)
      other_sequence = o_variables[regexp, 3] if o_variables

      # if which one specify sequence, we shall force comparing by sequence.
      if self_sequence || other_sequence
        self_sequence = self_sequence.to_i
        other_sequence = other_sequence.to_i

        return 1 if self_sequence < other_sequence
        return 0 if self_sequence == other_sequence
        return -1 if self_sequence > other_sequence
      end

      other_create_time = other.take_create_time
      self_create_time = take_create_time
      other_create_time <=> self_create_time
    end

    @create_time
    def take_create_time
      # cache the create time to improve performance while sorting by.
      return @create_time if @create_time
      @create_time = Generator.fetch_create_time(@page_file)
    end

    def to_s
      @page_file
    end
  end

  class Array < Array
    def next(index)
      index += 1
      index < size ? at(index) : nil
    end
    def prev(index)
      index > 0 ? at(index - 1) : nil
    end
  end
end


text:
//
//  TKAppDelegate.m
//  Created by Devin Ross on 1/31/11.
//

#import "TKAppDelegate.h"
#import "TKWindow.h"

@implementation TKAppDelegate

- (BOOL) application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

	if(self.window==nil){
		self.window = [[TKWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
		self.window.backgroundColor = [UIColor blackColor];
		[self.window makeKeyAndVisible];
	}

    [self applicationDidStartup:application];

	return YES;
}
- (void) applicationWillEnterForeground:(UIApplication *)application {
	[self applicationDidStartup:application];
}
- (void) applicationDidStartup:(UIApplication *)application{
	// Default Implementaion Does Nothing
}

@end


text:
//
//  Use this file to import your target's public headers that you would like to expose to Swift.
//

//-----------------------------------------------------------
//SlideMenu
#import "SWRevealViewController.h"

//-----------------------------------------------------------
//Crypto (MD5)
#import <CommonCrypto/CommonCrypto.h>

//-----------------------------------------------------------
//Kuasars
#import <BDSClientSDK/BDSClientSDK.h>
#import <Kuasars/Kuasars.h>

//-----------------------------------------------------------
//Kurento toolbox
#import <KurentoToolbox/KurentoToolbox.h>

/*#import <libjingle_peerconnection/RTCICECandidate.h>
#import <libjingle_peerconnection/RTCSessionDescription.h>
#import <libjingle_peerconnection/RTCMediaStream.h>
#import <libjingle_peerconnection/RTCVideoTrack.h>
#import <libjingle_peerconnection/RTCAudioTrack.h>
*/

#import <WebRTC/RTCICECandidate.h>
#import <WebRTC/RTCPeerConnection.h>
#import <WebRTC/RTCSessionDescription.h>
#import <WebRTC/RTCMediaStream.h>
#import <WebRTC/RTCVideoTrack.h>
#import <WebRTC/RTCAudioTrack.h>
#import <WebRTC/RTCDataChannel.h>
#import "ReachabilityUtil.h"


text:
class HomeworkPolicy
  attr_reader :user, :homework

  def initialize(user, homework)
    @user = user
    @homework = homework
  end

  def create?
  end

end


text:
<!DOCTYPE html>

        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">

		<title>{% if page.title %} {{ page.title }} {% else %} {{ site.name }} {% endif %}</title>
	    <meta http-equiv="X-UA-Compatible" content="IE=edge">
	    <meta name="viewport" content="width=device-width, initial-scale=1">

        <link rel="stylesheet" href="{{ site.baseurl }}/css/syntax.css">

    	<link href="{{ site.baseurl }}/css/bootstrap.min.css" rel="stylesheet">

        <link rel="stylesheet" href="{{ site.baseurl }}/css/main.css">

				{% if site.about %}

					about

					{{ site.about }}

				{% endif %}

				navigation

				home

				{% for i in site.urls %}
					{{ i.text }}

				{% endfor %}

				{{ content }}

					© {{ site.name }}
					{% if site.github %}
						- {{ site.github }}
					{% endif %}


text:
'use strict';

/**
 * Module dependencies.
 */
var should = require('should'),
	mongoose = require('mongoose'),
	User = mongoose.model('User'),
	Interest = mongoose.model('Interest');

/**
 * Globals
 */
var user;

/**
 * Unit tests
 */
describe('User Model Unit Tests:', function() {
	before(function(done) {
		user = new User({
			name: 'Justin Chiang',
			email: 'jc4127@columbia.edu',
			interests: [ mongoose.Types.ObjectId((new Interest({name: 'hockey'}))._id) ]
		});

		done();
	});

	describe('Method Save', function() {
		it('should begin with no users', function(done) {
			User.find({}, function(err, users) {
				users.should.have.length(0);
				done();
			});
		});

		it('should be able to save without problems', function(done) {
			this.timeout(10000);
			user.save(done);
		});

	});

	after(function(done) {
		User.remove().exec();
		done();
	});
});


text:
//
//  RCTRealtimeMessaging.m
//  RCTRealtimeMessaging
//
//  Created by Joao Caixinha on 02/04/15.
//  Copyright (c) 2015 Realtime. All rights reserved.
//

#import "RCTRealtimeMessaging.h"
#import <RCTConvert.h>

@implementation RCTRealtimeMessaging
@synthesize bridge = _bridge;

- (void)connect:(NSDictionary*)connectionSettings id:(NSString*)pId{
    RCT_EXPORT();

    NSString *appKey = [RCTConvert NSString:connectionSettings[@"appKey"]];
    NSString *clientConnMeta = [RCTConvert NSString:connectionSettings[@"connectionMetadata"]];
    NSString *url = [RCTConvert NSString:connectionSettings[@"url"]];
    NSString *clusterUrl = [RCTConvert NSString:connectionSettings[@"clusterUrl"]];
    NSString *token = [RCTConvert NSString:connectionSettings[@"token"]];

    if (!_queue) {
        _queue = [[NSMutableDictionary alloc] init];
    }

    OrtcClient *ortcClient = [_queue objectForKey:pId];

    if (!ortcClient) {
        ortcClient = [OrtcClient ortcClientWithConfig:self];
        [_queue setObject:ortcClient forKey:pId];
    }

    // Set connection properties
    [ortcClient setConnectionMetadata:clientConnMeta];

    if (url) {
        [ortcClient setUrl:url];
    }else if (clusterUrl)
    {
        [ortcClient setClusterUrl:clusterUrl];
    }
    // Connect
    [ortcClient connect:appKey authenticationToken:token];

}

-(void)sendMessage:(NSString*)message toChannel:(NSString*)channel usingClient:(NSString*)clientID
{
    RCT_EXPORT();
    OrtcClient *ortcClient = [_queue objectForKey:clientID];
    [ortcClient send:channel message:message];
}

/**
 * Occurs when the client connects.
 *
 * @param ortc The ORTC object.
 */
- (void)onConnected:(OrtcClient*) ortc
{
    RCT_EXPORT();
    NSString *clientID = [[_queue allKeysForObject:ortc] objectAtIndex:0];
    [self.bridge.eventDispatcher sendDeviceEventWithName:[NSString stringWithFormat:@"%@-onConnected", clientID]
                                                    body:@{}];
}

- (void)subscribe:(NSString*)channel subscribeOnReconnected:(BOOL)aSubscribeOnReconnected usingClient:(NSString*)clientID
{
    RCT_EXPORT();
    OrtcClient *ortcClient = [_queue objectForKey:clientID];
    [ortcClient subscribe:channel subscribeOnReconnected:aSubscribeOnReconnected onMessage:^(OrtcClient *ortc, NSString *channel, NSString *message)
     {

             NSString *clientID = [[_queue allKeysForObject:ortc] objectAtIndex:0];
             [self.bridge.eventDispatcher sendDeviceEventWithName:[NSString stringWithFormat:@"%@-onMessage", clientID]
                                                             body:@{@"message": message,
                                                                    @"channel": channel
                                                                    }];
     }];
}

- (void)subscribeWithNotifications:(NSString*) channel subscribeOnReconnected:(BOOL) aSubscribeOnReconnected usingClient:(NSString*)clientID
{
    RCT_EXPORT();
    OrtcClient *ortcClient = [_queue objectForKey:clientID];
    [ortcClient subscribeWithNotifications:channel subscribeOnReconnected:aSubscribeOnReconnected onMessage:^(OrtcClient *ortc, NSString *channel, NSString *message) {

            NSString *clientID = [[_queue allKeysForObject:ortc] objectAtIndex:0];
            [self.bridge.eventDispatcher sendDeviceEventWithName:[NSString stringWithFormat:@"%@-onMessage", clientID]
                                                            body:@{@"message": message,
                                                                   @"channel": channel,
                                                                   }];
    }];
}

/** Enables presence for the specified channel with first 100 unique metadata if true.

 @warning This function will send your private key over the internet. Make sure to use secure connection.
 @param url Server containing the presence service.
 @param isCluster Specifies if url is cluster.
 @param applicationKey Application key with access to presence service.
 @param privateKey The private key provided when the ORTC service is purchased.
 @param channel Channel with presence data active.
 @param metadata Defines if to collect first 100 unique metadata.
 @param callback Callback with error (NSError) and result (NSString) parameters
 */
- (void)enablePresence:(NSString*) aUrl isCLuster:(BOOL) aIsCluster applicationKey:(NSString*) aApplicationKey privateKey:(NSString*) aPrivateKey channel:(NSString*) channel metadata:(BOOL) aMetadata usingClient:(NSString*)clientID
{
    RCT_EXPORT();
    OrtcClient *ortcClient = [_queue objectForKey:clientID];
    [ortcClient enablePresence:aUrl isCLuster:aIsCluster applicationKey:aApplicationKey privateKey:aPrivateKey channel:channel metadata:aMetadata callback:^(NSError *error, NSString *result) {
        if (error) {
            [self.bridge.eventDispatcher sendDeviceEventWithName:[NSString stringWithFormat:@"%@-onEnablePresence", clientID]
                                                            body:@{@"error": error.localizedDescription,
                                                                   }];
        }else{
            [self.bridge.eventDispatcher sendDeviceEventWithName:[NSString stringWithFormat:@"%@-onEnablePresence", clientID]
                                                            body:@{@"result": result,
                                                                   }];
        }
    }];
}

/** Disables presence for the specified channel.

 @warning This function will send your private key over the internet. Make sure to use secure connection.
 @param url Server containing the presence service.
 @param isCluster Specifies if url is cluster.
 @param applicationKey Application key with access to presence service.
 @param privateKey The private key provided when the ORTC service is purchased.
 @param channel Channel with presence data active.
 @param callback Callback with error (NSError) and result (NSString) parameters
 */
- (void)disablePresence:(NSString*) aUrl isCLuster:(BOOL) aIsCluster applicationKey:(NSString*) aApplicationKey privateKey:(NSString*) aPrivateKey channel:(NSString*)channel usingClient:(NSString*)clientID
{
    RCT_EXPORT();
    OrtcClient *ortcClient = [_queue objectForKey:clientID];
    [ortcClient disablePresence:aUrl isCLuster:aIsCluster applicationKey:aApplicationKey privateKey:aPrivateKey channel:channel callback:^(NSError *error, NSString *result) {
        if (error) {
            [self.bridge.eventDispatcher sendDeviceEventWithName:[NSString stringWithFormat:@"%@-onDisablePresence", clientID]
                                                            body:@{@"error": error.localizedDescription,
                                                                   }];
        }else{
            [self.bridge.eventDispatcher sendDeviceEventWithName:[NSString stringWithFormat:@"%@-onDisablePresence", clientID]
                                                            body:@{@"result": result,
                                                                   }];
        }
    }];
}

/**
 * Gets a NSDictionary indicating the subscriptions in the specified channel and if active the first 100 unique metadata.
 *
 * @param url Server containing the presence service.
 * @param isCluster Specifies if url is cluster.
 * @param applicationKey Application key with access to presence service.
 * @param authenticationToken Authentication token with access to presence service.
 * @param channel Channel with presence data active.
 * @param callback Callback with error (NSError) and result (NSDictionary) parameters
 */
- (void)presence:(NSString*) aUrl isCLuster:(BOOL) aIsCluster applicationKey:(NSString*) aApplicationKey authenticationToken:(NSString*) aAuthenticationToken channel:(NSString*) channel usingClient:(NSString*)clientID
{
    RCT_EXPORT();
    OrtcClient *ortcClient = [_queue objectForKey:clientID];
    [ortcClient presence:aUrl isCLuster:aIsCluster applicationKey:aApplicationKey authenticationToken:aAuthenticationToken channel:channel callback:^(NSError *error, NSDictionary *result) {

        if (error) {
            [self.bridge.eventDispatcher sendDeviceEventWithName:[NSString stringWithFormat:@"%@-onPresence", clientID]
                                                            body:@{@"error": error.localizedDescription,
                                                                   }];
        }else{
            [self.bridge.eventDispatcher sendDeviceEventWithName:[NSString stringWithFormat:@"%@-onPresence", clientID]
                                                            body:@{@"result": result,
                                                                   }];
        }
    }];
}

/**
 * Occurs when the client disconnects.
 *
 * @param ortc The ORTC object.
 */
- (void)onDisconnected:(OrtcClient*) ortc
{
    RCT_EXPORT();
    NSString *clientID = [[_queue allKeysForObject:ortc] objectAtIndex:0];
    [self.bridge.eventDispatcher sendDeviceEventWithName:[NSString stringWithFormat:@"%@-onDisconnected", clientID]
                                                    body:@{}];
}
/**
 * Occurs when the client subscribes to a channel.
 *
 * @param ortc The ORTC object.
 * @param channel The channel name.
 */
- (void)onSubscribed:(OrtcClient*) ortc channel:(NSString*) channel
{
    RCT_EXPORT();
    NSString *clientID = [[_queue allKeysForObject:ortc] objectAtIndex:0];
    [self.bridge.eventDispatcher sendDeviceEventWithName:[NSString stringWithFormat:@"%@-onSubscribed", clientID]
                                                    body:@{@"channel":channel,
                                                           }];
}
/**
 * Occurs when the client unsubscribes from a channel.
 *
 * @param ortc The ORTC object.
 * @param channel The channel name.
 */
- (void)onUnsubscribed:(OrtcClient*) ortc channel:(NSString*) channel
{
    RCT_EXPORT();
    NSString *clientID = [[_queue allKeysForObject:ortc] objectAtIndex:0];
    [self.bridge.eventDispatcher sendDeviceEventWithName:[NSString stringWithFormat:@"%@-onUnSubscribed", clientID]
                                                    body:@{@"channel":channel,
                                                           }];
}

/**
 * Occurs when there is an exception.
 *
 * @param ortc The ORTC object.
 * @param error The occurred exception.
 */
- (void)onException:(OrtcClient*) ortc error:(NSError*) error
{
    RCT_EXPORT();
    NSString *clientID = [[_queue allKeysForObject:ortc] objectAtIndex:0];
    [self.bridge.eventDispatcher sendDeviceEventWithName:[NSString stringWithFormat:@"%@-onException", clientID]
                                                    body:@{@"error":error.localizedDescription,
                                                           }];
}

/**
 * Occurs when the client attempts to reconnect.
 *
 * @param ortc The ORTC object.
 */
- (void)onReconnecting:(OrtcClient*) ortc
{
    RCT_EXPORT();
    NSString *clientID = [[_queue allKeysForObject:ortc] objectAtIndex:0];
    [self.bridge.eventDispatcher sendDeviceEventWithName:[NSString stringWithFormat:@"%@-onReconnecting", clientID]
                                                    body:@{}];
}
/**
 * Occurs when the client reconnects.
 *
 * @param ortc The ORTC object.
 */
- (void)onReconnected:(OrtcClient*) ortc
{
    RCT_EXPORT();
    NSString *clientID = [[_queue allKeysForObject:ortc] objectAtIndex:0];
    [self.bridge.eventDispatcher sendDeviceEventWithName:[NSString stringWithFormat:@"%@-onReconnected", clientID]
                                                    body:@{}];
}

/**
 * Unsubscribes from a channel to stop receiving messages sent to it.
 *
 * @param channel The channel name.
 */
- (void)unsubscribe:(NSString*) channel usingClient:(NSString*)clientID
{
    RCT_EXPORT();
    OrtcClient *ortcClient = [_queue objectForKey:clientID];
    [ortcClient unsubscribe:channel];
}
/**
 * Disconnects.
 */
- (void)disconnect:(NSString*)clientID
{
    RCT_EXPORT();
    OrtcClient *ortcClient = [_queue objectForKey:clientID];
    [ortcClient disconnect];
}
/**
 * Indicates whether is subscribed to a channel or not.
 *
 * @param channel The channel name.
 *
 * @return TRUE if subscribed to the channel or FALSE if not.
 */
- (NSNumber*)isSubscribed:(NSString*) channel usingClient:(NSString*)clientID callback:(RCTResponseSenderBlock)callback
{
    RCT_EXPORT();
    OrtcClient *ortcClient = [_queue objectForKey:clientID];
    NSNumber* result = [ortcClient isSubscribed:channel];
    callback(@[result]);

    return result;
}

/** Saves the channels and its permissions for the authentication token in the ORTC server.
 @warning This function will send your private key over the internet. Make sure to use secure connection.
 @param url ORTC server URL.
 @param isCluster Indicates whether the ORTC server is in a cluster.
 @param authenticationToken The authentication token generated by an application server (for instance: a unique session ID).
 @param authenticationTokenIsPrivate Indicates whether the authentication token is private (1) or not (0).
 @param applicationKey The application key provided together with the ORTC service purchasing.
 @param timeToLive The authentication token time to live (TTL), in other words, the allowed activity time (in seconds).
 @param privateKey The private key provided together with the ORTC service purchasing.
 @param permissions The channels and their permissions (w: write, r: read, p: presence, case sensitive).
 @return TRUE if the authentication was successful or FALSE if it was not.
 */
- (BOOL)saveAuthentication:(NSString*) url isCLuster:(BOOL) isCluster authenticationToken:(NSString*) authenticationToken authenticationTokenIsPrivate:(BOOL) authenticationTokenIsPrivate applicationKey:(NSString*) applicationKey timeToLive:(int) timeToLive privateKey:(NSString*) privateKey permissions:(NSMutableDictionary*) permissions usingClient:(NSString*)clientID callback:(RCTResponseSenderBlock)callback
{
    RCT_EXPORT();
    OrtcClient *ortcClient = [_queue objectForKey:clientID];
    BOOL result =  [ortcClient saveAuthentication:url isCLuster:isCluster authenticationToken:authenticationToken authenticationTokenIsPrivate:authenticationTokenIsPrivate applicationKey:applicationKey timeToLive:timeToLive privateKey:privateKey permissions:permissions];
    callback(@[[NSNumber numberWithBool:result]]);

    return result;
}

/**
 * Get heartbeat interval.
 */
- (int) getHeartbeatTime:(NSString*)clientID callback:(RCTResponseSenderBlock)callback
{
    RCT_EXPORT();
    OrtcClient *ortcClient = [_queue objectForKey:clientID];
    int result = ortcClient.getHeartbeatTime;
    callback(@[[NSNumber numberWithInt:result]]);

    return result;
}
/**
 * Set heartbeat interval.
 */
- (void) setHeartbeatTime:(int)newHeartbeatTime usingClient:(NSString*)clientID{
    RCT_EXPORT();
    OrtcClient *ortcClient = [_queue objectForKey:clientID];
    [ortcClient setHeartbeatTime:newHeartbeatTime];
}
/**
 * Get how many times can the client fail the heartbeat.
 */
- (int) getHeartbeatFails:(NSString*)clientID callback:(RCTResponseSenderBlock)callback
{
    RCT_EXPORT();
    OrtcClient *ortcClient = [_queue objectForKey:clientID];
    int result = [ortcClient getHeartbeatFails];
    callback(@[[NSNumber numberWithInt:result]]);

    return result;
}
/**
 * Set heartbeat fails. Defines how many times can the client fail the heartbeat.
 */
- (void) setHeartbeatFails:(int) newHeartbeatFails usingClient:(NSString*)clientID
{
    RCT_EXPORT();
    OrtcClient *ortcClient = [_queue objectForKey:clientID];
    [ortcClient setHeartbeatFails:newHeartbeatFails];
}
/**
 * Indicates whether heartbeat is active or not.
 */
- (BOOL) isHeartbeatActive:(NSString*)clientID callback:(RCTResponseSenderBlock)callback
{
    RCT_EXPORT();
    OrtcClient *ortcClient = [_queue objectForKey:clientID];
    BOOL result = [ortcClient isHeartbeatActive];
    callback(@[[NSNumber numberWithInt:result]]);

    return result;
}
/**
 * Enables the client heartbeat
 */
- (void) enableHeartbeat:(NSString*)clientID
{
    RCT_EXPORT();
    OrtcClient *ortcClient = [_queue objectForKey:clientID];
    [ortcClient enableHeartbeat];
}
/**
 * Disables the client heartbeat
 */
- (void) disableHeartbeat:(NSString*)clientID
{
    RCT_EXPORT();
    OrtcClient *ortcClient = [_queue objectForKey:clientID];
    [ortcClient disableHeartbeat];
}

+ (void) setDEVICE_TOKEN:(NSString *) deviceToken
{
    RCT_EXPORT();
    [OrtcClient setDEVICE_TOKEN:deviceToken];
}

@end


text:
<link href='https://fonts.googleapis.com/css?family=Bitter' rel='stylesheet' type='text/css'>

				Quizart

{{data.name}},
			{{data.age}}

{{data.badge}}

{{data.country}}

Games
{{data.totalGames}}

Wins
{{data.wins}}

Win%
{{data.wins/data.totalGames*100 | number : 2}}%

Favourite Topics

 0">
			You have not followed any topics as yet. How about picking some topics from below.

 0">

					{{topic.level}}

{{topic.topicId.topicName}}

					{{topic.gamesWon}} / {{topic.gamesPlayed}}

11">

						<button ng-if="topicsFollowed.length>=8" ng-click="seeHide(topicsFollowed.length)"></button>

					<button class="play-now-button btn btn-success" ng-click="play()">More Topics</button>


text:
require 'spec_helper_acceptance'

describe 'concat ensure_newline parameter' do
  basedir = default.tmpdir('concat')
  context '=> false' do
    before(:all) do
      pp = <<-EOS
        file { '#{basedir}':
          ensure => directory
        }
      EOS

      apply_manifest(pp)
    end
    pp = <<-EOS
      concat { '#{basedir}/file':
        ensure_newline => false,
      }
      concat::fragment { '1':
        target  => '#{basedir}/file',
        content => '1',
      }
      concat::fragment { '2':
        target  => '#{basedir}/file',
        content => '2',
      }
    EOS

    it 'applies the manifest twice with no stderr' do
      apply_manifest(pp, catch_failures: true)
      apply_manifest(pp, catch_changes: true)
    end

    describe file("#{basedir}/file") do
      it { is_expected.to be_file }
      its(:content) { is_expected.to match '12' }
    end
  end

  context '=> true' do
    pp = <<-EOS
      concat { '#{basedir}/file':
        ensure_newline => true,
      }
      concat::fragment { '1':
        target  => '#{basedir}/file',
        content => '1',
      }
      concat::fragment { '2':
        target  => '#{basedir}/file',
        content => '2',
      }
    EOS

    it 'applies the manifest twice with no stderr' do
      apply_manifest(pp, catch_failures: true)
      apply_manifest(pp, catch_changes: true)
    end

    describe file("#{basedir}/file") do
      it { is_expected.to be_file }
      its(:content) do
        is_expected.to match %r{1\n2\n}
      end
    end
  end
end


text:
/**
 * Description : This is a test suite that tests an LRS endpoint based on the testing requirements document
 * found at https://github.com/adlnet/xapi-lrs-conformance-requirements
 */

(function (module, fs, extend, moment, request, requestPromise, chai, liburl, Joi, helper, multipartParser, redirect, templatingSelection) {
    // "use strict";

    var expect = chai.expect;
    if(global.OAUTH)
        request = helper.OAuthRequest(request);

describe('Version Property Requirements (Data 2.4.10)', () => {

/**  Matchup with Conformance Requirements Document
 * XAPI-00101 - in version.js
 * Unnumbered test - came from XAPI-00332
 */

    templatingSelection.createTemplate('version.js');

/**  XAPI-00332, Communication 3.3 Versioning which should be moved to Data 2.4.10 Version Property
 * Statements returned by an LRS MUST retain the version property they are accepted with.
 */
    it ('Statements returned by an LRS MUST retain the version property they are accepted with (Format, Data 2.4.10, XAPI-00332)', function (done){
        this.timeout(0);
        var stmtTime = Date.now();

        var statementTemplates = [
            {statement: '{{statements.default}}'}
        ];

        var version = '1.0.3';
        var id = helper.generateUUID();

        var statement = helper.createFromTemplate(statementTemplates);
        statement = statement.statement;
        statement.id = id;
        statement.version = version;

        var query = helper.getUrlEncoding({statementId: id});

        request(helper.getEndpointAndAuth())
        .post(helper.getEndpointStatements())
        .headers(helper.addAllHeaders({}))
        .json(statement)
        .expect(200)
        .end(function (err, res) {
            if (err) {
                done(err);
            } else {
                request(helper.getEndpointAndAuth())
                .get(helper.getEndpointStatements() + '?' + query)
                .wait(helper.genDelay(stmtTime, '?' + query, id))
                .headers(helper.addAllHeaders({}))
                .expect(200)
                .end(function(err,res){
                     if (err){
                        done(err);
                     }
                     else{
                        var results = helper.parse(res.body);
                        expect(results.version).to.equal(version);
                        done();
                     }
                });
            }
        });
    });

});

}(module, require('fs'), require('extend'), require('moment'), require('super-request'), require('supertest-as-promised'), require('chai'), require('url'), require('joi'), require('./../helper'), require('./../multipartParser'), require('./../redirect.js'), require('./../templatingSelection')));


text:
#ifndef CORE_DATA_RENDER_VNODE_VNODE_RENDER_MANAGER_
#define CORE_DATA_RENDER_VNODE_VNODE_RENDER_MANAGER_

#include <map>
#include <string>

#include "core/data_render/vm.h"
#include "core/data_render/vnode/vnode.h"
#include "core/data_render/vnode/vcomponent.h"
#include "core/data_render/vnode/vnode_exec_env.h"
#include "core/render/manager/render_manager.h"
#include "core/render/node/render_object.h"

namespace weex {
namespace core {
namespace data_render {

class HttpModule;
class VNodeRenderManager {
 friend class VNode;
 private:
  VNodeRenderManager() {}

  ~VNodeRenderManager() {}

 public:
  void CreatePage(const std::string &input, const std::string &page_id, const std::string &options, const std::string &init_data, std::function<void(const char*)> exec_js);

  void CreatePage(const char *contents, size_t length, const std::string& page_id, const std::string& options, const std::string& init_data, std::function<void(const char*)> exec_js);

  bool RefreshPage(const std::string &page_id, const std::string &init_data);
  bool ClosePage(const std::string &page_id);
  void FireEvent(const std::string &page_id, const std::string &ref, const std::string &event,const std::string &args,const std::string &dom_changes);
  void ExecuteRegisterModules(ExecState *exec_state, std::vector<std::string>& registers);
  void RegisterModules(const std::string &modules) { modules_.push_back(modules); }
  bool RequireModule(ExecState *exec_state, std::string &name, std::string &result);
  void PatchVNode(ExecState *exec_state, VNode *v_node, VNode *new_node);
  void CallNativeModule(ExecState *exec_state, const std::string &module, const std::string &method, const std::string &args, int argc = 0);
  void UpdateComponentData(const std::string& page_id, const char* cid, const std::string& json_data);
  void WXLogNative(ExecState *exec_state, const std::string &info);
  static VNodeRenderManager *GetInstance() {
    if (!g_instance) {
      g_instance = new VNodeRenderManager();
    }
    return g_instance;
  }

  inline ExecState *GetExecState(const std::string &instance_id) {
    auto it = exec_states_.find(instance_id);
    return it != exec_states_.end() ? it->second : nullptr;
  }

  inline VNode *GetRootVNode(const std::string &instance_id) {
    auto it = vnode_trees_.find(instance_id);
    return it != vnode_trees_.end() ? it->second : nullptr;
  }

 private:
  void InitVM();
  bool CreatePageInternal(const std::string &page_id, VNode *v_node);
  bool RefreshPageInternal(const std::string &page_id, VNode *new_node);
  bool ClosePageInternal(const std::string &page_id);
  void DownloadAndExecScript(ExecState *exec_state, const std::string &page_id,
                             std::function<void(const char *)> exec_js);

  std::string CreatePageWithContent(const uint8_t *contents, size_t length,
                                    const std::string &page_id,
                                    const std::string &options,
                                    const std::string &init_data,
                                    std::function<void(const char*)> exec_js);
  std::string CreatePageWithContent(const std::string &input,
                                    const std::string &page_id,
                                    const std::string &options,
                                    const std::string &init_data,
                                    std::function<void(const char *)> exec_js);

  static VM *g_vm;
  static VNodeRenderManager *g_instance;

  std::map<std::string, VNode *> vnode_trees_;
  std::map<std::string, ExecState *> exec_states_;
  std::vector<std::string> modules_;
};
}  // namespace data_render
}  // namespace core
}  // namespace weex
#endif  // CORE_DATA_RENDER_VNODE_VNODE_RENDER_MANAGER_


text:
 Improve this Doc

   View Source

$sceDelegate

    - $sceDelegateProvider

      - service in module ng

$sceDelegate is a service that is used by the $sce service to provide Strict
Contextual Escaping (SCE) services to AngularJS.

For an overview of this service and the functionnality it provides in AngularJS, see the main
page for SCE. The current page is targeted for developers who need to alter how
SCE works in their application, which shouldn't be needed in most cases.

AngularJS strongly relies on contextual escaping for the security of bindings: disabling or
modifying this might cause cross site scripting (XSS) vulnerabilities. For libraries owners,
changes to this service will also influence users, so be extra careful and document your changes.

Typically, you would configure or override the $sceDelegate instead of
the $sce service to customize the way Strict Contextual Escaping works in AngularJS.  This is
because, while the $sce provides numerous shorthand methods, etc., you really only need to
override 3 core functions (trustAs, getTrusted and valueOf) to replace the way things
work because $sce delegates to $sceDelegate for these operations.

Refer $sceDelegateProvider to configure this service.

The default instance of $sceDelegate should work out of the box with little pain.  While you
can override it completely to change the behavior of $sce, the common case would
involve configuring the $sceDelegateProvider instead by setting
your own whitelists and blacklists for trusting URLs used for loading AngularJS resources such as
templates.  Refer $sceDelegateProvider.resourceUrlWhitelist and $sceDelegateProvider.resourceUrlBlacklist

Usage

$sceDelegate();

Methods

trustAs(type, value);

Returns a trusted representation of the parameter for the specified context. This trusted
object will later on be used as-is, without any security check, by bindings or directives
that require this security context.
For instance, marking a string as trusted for the $sce.HTML context will entirely bypass
the potential $sanitize call in corresponding $sce.HTML bindings or directives, such as
ng-bind-html. Note that in most cases you won't need to call this function: if you have the
sanitizer loaded, passing the value itself will render all the HTML that does not pose a
security risk.

See getTrusted for the function that will consume those
trusted values, and $sce for general documentation about strict contextual
escaping.

Parameters

      Param
      Type
      Details

        type

        string

The context in which this value is safe for use, e.g. $sce.URL,
    $sce.RESOURCE_URL, $sce.HTML, $sce.JS or $sce.CSS.

        value

        *

The value that should be considered trusted.

Returns

    *

A trusted representation of value, that can be used in the given context.

valueOf(value);

If the passed parameter had been returned by a prior call to $sceDelegate.trustAs, returns the value that had been passed to $sceDelegate.trustAs.

If the passed parameter is not a value that had been returned by $sceDelegate.trustAs, it must be returned as-is.

Parameters

      Param
      Type
      Details

        value

        *

The result of a prior $sceDelegate.trustAs
    call or anything else.

Returns

    *

The value that was originally provided to $sceDelegate.trustAs if value is the result of such a call.  Otherwise, returns
    value unchanged.

getTrusted(type, maybeTrusted);

Takes any input, and either returns a value that's safe to use in the specified context, or
throws an exception.

In practice, there are several cases. When given a string, this function runs checks
and sanitization to make it safe without prior assumptions. When given the result of a $sceDelegate.trustAs call, it returns the originally supplied
value if that value's context is valid for this call's context. Finally, this function can
also throw when there is no way to turn maybeTrusted in a safe value (e.g., no sanitization
is available or possible.)

Parameters

      Param
      Type
      Details

        type

        string

The context in which this value is to be used (such as $sce.HTML).

        maybeTrusted

        *

The result of a prior $sceDelegate.trustAs call, or anything else (which will not be considered trusted.)

Returns

    *

A version of the value that's safe to use in the given context, or throws an
    exception if this is impossible.


text:
-	[`0.9`, `0.9.2`, `latest` (*0.9/Dockerfile*)](https://github.com/ahawkins/docker-thrift/blob/61c3478ab828d3e610f192b442ac2a7221749c47/0.9/Dockerfile)

For more information about this image and its history, please see the [relevant manifest file (`library/thrift`)](https://github.com/docker-library/official-images/blob/master/library/thrift) in the [`docker-library/official-images` GitHub repo](https://github.com/docker-library/official-images).

# What Is Thrift

> The Apache Thrift software framework, for scalable cross-language services development, combines a software stack with a code generation engine to build services that work efficiently and seamlessly between C++, Java, Python, PHP, Ruby, Erlang, Perl, Haskell, C#, Cocoa, JavaScript, Node.js, Smalltalk, OCaml and Delphi and other languages.

Read more about [Thrift](https://thrift.apache.org).

# How To Use This Image

This is image is intended to run as an executable. Files are provided by mounting a directory. Here's an example of compiling `service.thrift` to ruby to the current directory.

	docker run -v "$PWD:/data" thrift thrift -o /data --gen rb /data/service.thrift

Note, that you may want to include `-u $(id -u)` to set the UID on generated files. The thrift process runs as root by default which will generate root owned files depending on your docker setup.

# License

View [license information](http://www.apache.org/licenses/) for the software contained in this image.

# Supported Docker versions

This image is officially supported on Docker version 1.6.2.

Support for older versions (down to 1.0) is provided on a best-effort basis.

# User Feedback

## Documentation

Documentation for this image is stored in the [`thrift/` directory](https://github.com/docker-library/docs/tree/master/thrift) of the [`docker-library/docs` GitHub repo](https://github.com/docker-library/docs). Be sure to familiarize yourself with the [repository's `README.md` file](https://github.com/docker-library/docs/blob/master/README.md) before attempting a pull request.

## Issues

If you have any problems with or questions about this image, please contact us through a [GitHub issue](https://github.com/ahawkins/docker-thrift/issues).

You can also reach many of the official image maintainers via the `#docker-library` IRC channel on [Freenode](https://freenode.net).

## Contributing

You are invited to contribute new features, fixes, or updates, large or small; we are always thrilled to receive pull requests, and do our best to process them as fast as we can.

Before you start to code, we recommend discussing your plans through a [GitHub issue](https://github.com/ahawkins/docker-thrift/issues), especially for more ambitious contributions. This gives other contributors a chance to point you in the right direction, give you feedback on your design, and help you find out if someone else is working on the same thing.


text:
package com.google.zxing.client.android.camera.open;

import android.hardware.Camera;

/**
 * Provides an abstracted means to open a {@link Camera}. The API changes over Android API versions and
 * this allows the app to use newer API methods while retaining backwards-compatible behavior.
 */
public interface OpenCameraInterface {

    Camera open();

}


text:
var args = arguments [0] || {};

function _init (_args) {

	Alloy.Globals.GoogleAnalytics.trackScreen({
		screenName: "Home Screen"
	});

	Alloy.Globals.pageFlow = $.pageflow;

	if (OS_IOS) {
		var leftMenuView = Alloy.createController("menu").getView();

		leftMenuView.hide();
		Alloy.Globals.sidemenu = $.tisidemenu;
	}
	else
	if (OS_ANDROID) {

		Alloy.Globals.sidemenu = $.homewin;

	}

	Alloy.Globals.pageFlow.addChild({
		controller: 'contentView' ,
		navBarHidden: true ,
		direction: {
			top: 0 ,
			left: 1
		}
	});

}

exports.init = _init;

_init();


text:
/*
 * PLUGIN THROTTLE
 *
 * German language file.
 *
 * Author:
 */

 theUILang.throttles		= "Channels";
 theUILang.throttle		= "Channel";
 theUILang.mnuThrottle		= "Set Channel";
 theUILang.mnuUnlimited 	= "No Channel";
 theUILang.channelName		= "Name";
 theUILang.channelDefault	= "Default channel";

thePlugins.get("throttle").langLoaded();


text:
#ifndef __CSD_HPP
#define __CSD_HPP

#include <set>
#include <string>
#include <vector>

using namespace std;

/**
 * Downloaded file
 */
class File {
    public:
    /**
     * Source url
     */
    const string url;
    /**
     * Data received from url
     */
    const string data;
    /**
     * Adler 32 hash of `data` in hex format
     */
    const string adler32hex;

    /**
     * File name
     */
    const string name;

    /**
     * Downloads and hashes the file from `url`
     */
    File(const string url);

    /**
     * \returns true if data of x < data of y
     */
    bool static size_cmp(File x, File y);

    private:
    string download_url(const string url) const;
    string mk_hash() const;
    string mk_fname() const;
};

class OriginUrl : public File {
    public:
    const set<string> urls;

    OriginUrl(const string url);

    /**
     * \returns Files found in this file/url. fetches the files in
     *    parallel, blocks until are files are received.
     */
    vector<File> fetch_files();

    private:
    set<string> parse_urls() const;
};

#endif


text:
require 'rails_helper'

RSpec.describe LedgerAccount, type: :model do
  pending "add some examples to (or delete) #{__FILE__}"
end