text:
<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" href="./testcase.xsl"?>
<test_definition>
  <suite name="wrt-integration-android-tests" category="Integration_with_Android_System">
    <set name="Integration" type="js">
      <testcase purpose="Validate if Crosswalk support HW accelerated HTML5 video" type="Functional" status="approved" component="Web Features" execution_type="manual" priority="P1" id="Crosswalk_WebApp_Video_HWAccelerate">
        <description>
          <test_script_entry>/opt/wrt-uxmanu-android-tests/uxmanu/Crosswalk_WebApp_Video_HWAccelerate.html</test_script_entry>
        </description>
      </testcase>
      <testcase purpose="Validate if enable the feature of HTML5 Notification in Crosswalk" type="Functional" status="approved" component="Web Features" execution_type="manual" priority="P1" id="Crosswalk_WebApp_HTML5_Notification">
        <description>
          <pre_condition>
            1.Make sure Crosswalk binary is installed
          </pre_condition>
          <test_script_entry>/opt/wrt-uxmanu-android-tests/uxmanu/Crosswalk_WebApp_HTML5_Notification.html</test_script_entry>
        </description>
      </testcase>
      <testcase purpose="Validate Crosswalk suppor lock and unlock screen when running Web Apps" type="Functional" status="approved" component="Integration with Android System" execution_type="manual" priority="P1" id="Crosswalk_Lock_And_Unlock_Screen">
        <description>
          <pre_condition>
            1.Make sure Crosswalk application is launched;
            2.Make sure there some webapps are available.
          </pre_condition>
          <test_script_entry>/opt/wrt-uxmanu-android-tests/uxmanu/Crosswalk_Lock_And_Unlock_Screen.html</test_script_entry>
        </description>
      </testcase>
      <testcase purpose="Validate if web app sound volume work fine on Crosswalk" type="Functional" status="approved" component="Integration with Android System" execution_type="manual" priority="P1" id="Crosswalk_WebApps_Volume">
        <description>
          <pre_condition>
            1.Make sure a webapp with sound is installed on Android OS.
          </pre_condition>
          <test_script_entry>/opt/wrt-uxmanu-android-tests/uxmanu/Crosswalk_WebApps_Volume.html</test_script_entry>
        </description>
       </testcase>
      <testcase purpose="Validate Crosswalk support Web App work normally that system interruption (popup, audio effect) when running Web Apps" type="Functional" status="approved" component="Integration with Android System" execution_type="manual" priority="P2" id="Crosswalk_System_Interruption">
        <description>
          <pre_condition>
            1. Make sure Crosswalk application is launched;
            2. Make sure there has one Web App is running.
          </pre_condition>
          <test_script_entry>/opt/wrt-uxmanu-android-tests/uxmanu/Crosswalk_System_Interruption.html </test_script_entry>
        </description>
      </testcase>
      <testcase purpose="Validate if Web App could be terminated in task manager" type="Functional" status="approved" component="Integration with Android System" execution_type="manual" priority="P1" id="Crosswalk_WebApp_Terminated_TaskManager">
        <description>
          <pre_condition>
            1. Make sure Crosswalk is installed
            2. Make sure there some webapps are available
          </pre_condition>
           <test_script_entry>/opt/wrt-uxmanu-android-tests/uxmanu/Crosswalk_WebApp_Integration_TaskManager.html </test_script_entry>
        </description>
      </testcase>
      <testcase purpose="Validate if Crosswalk support Web Apps could be switch successfully" type="Functional" status="approved" component="Integration with Android System" execution_type="manual" priority="P1" id="Crosswalk_WebApp_Integration_Switch">
        <description>
          <pre_condition>
            1. Make sure Crosswalk is installed
            2. Make sure there some webapps are available
          </pre_condition>
          <post_condition/>
          <test_script_entry>/opt/wrt-uxmanu-android-tests/uxmanu/Crosswalk_WebApp_Integration_Switch.html </test_script_entry>
        </description>
      </testcase>
      <testcase purpose="Validate if Crosswalk support Web Apps interface no cursors" type="Functional" status="approved" component="Integration with Android System" execution_type="manual" priority="P2" id="Crosswalk_WebApp_Integration_NoCursors">
        <description>
          <pre_condition>
            1. Make sure Crosswalk is installed
            2. Make sure there some webapps are available
          </pre_condition>
          <test_script_entry>/opt/wrt-uxmanu-android-tests/uxmanu/Crosswalk_WebApp_Integration_NoCursors.html </test_script_entry>
        </description>
      </testcase>
      <testcase purpose="Validate if the HW Key work well in Crosswalk App" type="Functional" status="approved" component="Integration with Android System" execution_type="manual" priority="P1" id="Crosswalk_WebApp_HW_KEY">
        <description>
          <pre_condition>
            1. Make sure Crosswalk is installed
            2. Make sure has some multimedia Web Apps
          </pre_condition>
          <test_script_entry>/opt/wrt-uxmanu-android-tests/uxmanu/Crosswalk_WebApp_HW_KEY.html </test_script_entry>
        </description>
      </testcase>
      <testcase purpose="Validate if the Virtual keyboard work fine in Crosswalk App" type="Functional" status="approved" component="Integration with Android System" execution_type="manual" priority="P2" id="Crosswalk_WebApp_VKB_Basic">
        <description>
          <pre_condition>
            1. Make sure Crosswalk is installed
            2. Make sure there some webapps are available,and webapps contains text input box
          </pre_condition>
          <test_script_entry>/opt/wrt-uxmanu-android-tests/uxmanu/Crosswalk_WebApp_VKB_Basic.html </test_script_entry>
        </description>
      </testcase>
      <testcase purpose="Validate if the Virtual keyboard ContentSwitch work fine in Crosswalk App" type="Functional" status="approved" component="Integration with Android System" execution_type="manual" priority="P2" id="Crosswalk_WebApp_VKB_ContentSwitch">
        <description>
          <pre_condition>
            1. Make sure Crosswalk is installed
            2. Make sure there some webapps are available,and webapps contains text input box
          </pre_condition>
          <post_condition/>
          <test_script_entry>/opt/wrt-uxmanu-android-tests/uxmanu/Crosswalk_WebApp_VKB_ContentSwitch.html </test_script_entry>
        </description>
      </testcase>
      <testcase purpose="Validate if the Virtual keyboard Rotation work fine in Crosswalk App" type="Functional" status="approved" component="Integration with Android System" execution_type="manual" priority="P2" id="Crosswalk_WebApp_VKB_Rotation">
        <description>
          <pre_condition>
            1. Make sure Crosswalk is installed
            2. Make sure there some webapps are available,and webapps contains text input box
          </pre_condition>
          <post_condition/>
          <test_script_entry>/opt/wrt-uxmanu-android-tests/uxmanu/Crosswalk_WebApp_VKB_Rotation.html </test_script_entry>
        </description>
      </testcase>
      <testcase purpose="Validate if Crosswalk support scroll gesture on Web Apps" type="Functional" status="approved" component="Integration with Android System" execution_type="manual" priority="P1" id="Crosswalk_WebApp_Touch_Gesture_Scroll">
        <description>
          <pre_condition>
            1. Make sure Crosswalk application is launched and the device connected to network
            *Package a Web App,it contains below web links:
            Open website link: http://www.hao123.com
            *Install this Web App
          </pre_condition>
          <test_script_entry>/opt/wrt-uxmanu-android-tests/uxmanu/Crosswalk_WebApp_Touch_Gesture_Scroll.html </test_script_entry>
        </description>
      </testcase>
      <testcase purpose="Validate if Crosswalk support swipe gesture on Web Apps" type="Functional" status="approved" component="Integration with Android System" execution_type="manual" priority="P1" id="Crosswalk_WebApp_Touch_Gesture_Swipe">
        <description>
          <pre_condition>
            1. Make sure Crosswalk application is launched and the device connected to network
            2. Package a Web App,it contains below web links:Open website link: http://www.hao123.com
            3. Install this Web App
          </pre_condition>
          <test_script_entry>/opt/wrt-uxmanu-android-tests/uxmanu/Crosswalk_WebApp_Touch_Gesture_Swipe.html </test_script_entry>
        </description>
      </testcase>
      <testcase purpose="Validate if Crosswalk support click gesture on Web Apps" type="Functional" status="approved" component="Integration with Android System" execution_type="manual" priority="P1" id="Crosswalk_WebApp_Touch_Gesture_Click">
        <description>
          <pre_condition>
            1. Make sure Crosswalk application is launched and the device connected to network
            2. Package a Web App,it contains below web links:Open website link: http://www.hao123.com
            3. Install this Web App
          </pre_condition>
          <test_script_entry>/opt/wrt-uxmanu-android-tests/uxmanu/Crosswalk_WebApp_Touch_Gesture_Click.html </test_script_entry>
        </description>
      </testcase>
      <testcase purpose="Validate Crosswalk support rotate between portrait orientation screen and landscape orientation screen" type="Functional" status="approved" component="Integration with Android System" execution_type="manual" priority="P1" id="Crosswalk_WebApp_Orientation">
        <description>
          <pre_condition>
            1. Make sure Crosswalk is installed
            2. Make sure there some webapps are available
          </pre_condition>
          <test_script_entry>/opt/wrt-uxmanu-android-tests/uxmanu/Crosswalk_WebApp_Orientation.html </test_script_entry>
        </description>
      </testcase>
      <testcase purpose="Validate if Crosswalk support stop activity by back key" type="Functional" status="approved" component="Integration with Android System" execution_type="manual" priority="P2" id="Crosswalk_WebApp_BackKey_Exit">
        <description>
          <pre_condition>
            1.Make sure Crosswalk application is installed and the device connected to network;
            2.Package a web app,it contains below web links:Open website link: http://www.hao123.com ;
            3.Install this web app
          </pre_condition>
          <test_script_entry>/opt/wrt-uxmanu-android-tests/uxmanu/Crosswalk_WebApp_BackKey_Exit.html </test_script_entry>
        </description>
      </testcase>
      <testcase purpose="Validate if Crosswalk support go back to previous page by back key" type="Functional" status="approved" component="Integration with Android System" execution_type="manual" priority="P1" id="Crosswalk_WebApp_BackKey_Back">
        <description>
          <pre_condition>
            1.Make sure Crosswalk application is installed and the device connected to network;
            2.Package a web app,it contains below web links:Open website link: http://www.hao123.com ;
            3.Install this web app
          </pre_condition>
          <test_script_entry>/opt/wrt-uxmanu-android-tests/uxmanu/Crosswalk_WebApp_BackKey_Back.html </test_script_entry>
        </description>
      </testcase>
      <testcase purpose="Validate if could copy hyperlink" type="Functional" status="approved" component="Integration with Android System" execution_type="manual" priority="P2" id="Crosswalk_CopyAndPaste_Copy_Hyperlink">
        <description>
          <pre_condition>
            1.Make sure Crosswalk binary is installed;
            2.Make sure at least one audio app is installed.
          </pre_condition>
          <test_script_entry>/opt/wrt-uxmanu-android-tests/uxmanu/Crosswalk_CopyAndPaste_Copy_Hyperlink.html </test_script_entry>
        </description>
      </testcase>
      <testcase purpose="Validate if could copy MailAddress" type="Functional" status="approved" component="Integration with Android System" execution_type="manual" priority="P2" id="Crosswalk_CopyAndPaste_Copy_MailAddress">
        <description>
          <pre_condition>
            1.Make sure Crosswalk binary is installed;
            2.Make sure at least one audio app is installed.
          </pre_condition>
          <test_script_entry>/opt/wrt-uxmanu-android-tests/uxmanu/Crosswalk_CopyAndPaste_Copy_MailAddress.html </test_script_entry>
        </description>
      </testcase>
      <testcase purpose="Validate if could copy Paragraph" type="Functional" status="approved" component="Integration with Android System" execution_type="manual" priority="P2" id="Crosswalk_CopyAndPaste_Copy_Paragraph">
        <description>
          <pre_condition>
            1.Make sure Crosswalk binary is installed;
            2.Make sure at least one audio app is installed.
          </pre_condition>
          <test_script_entry>/opt/wrt-uxmanu-android-tests/uxmanu/Crosswalk_CopyAndPaste_Copy_Paragraph.html </test_script_entry>
        </description>
      </testcase>
      <testcase purpose="Validate if could copy PhoneNumber" type="Functional" status="approved" component="Integration with Android System" execution_type="manual" priority="P2" id="Crosswalk_CopyAndPaste_Copy_PhoneNumber">
        <description>
          <pre_condition>
            1.Make sure Crosswalk binary is installed;
            2.Make sure at least one audio app is installed.
          </pre_condition>
          <test_script_entry>/opt/wrt-uxmanu-android-tests/uxmanu/Crosswalk_CopyAndPaste_Copy_PhoneNumber.html </test_script_entry>
        </description>
      </testcase>
      <testcase purpose="Validate if could copy Photo" type="Functional" status="approved" component="Integration with Android System" execution_type="manual" priority="P3" id="Crosswalk_CopyAndPaste_Copy_Photo">
        <description>
          <pre_condition>
            1.Make sure Crosswalk binary is installed;
            2.Make sure at least one audio app is installed.
          </pre_condition>
          <test_script_entry>/opt/wrt-uxmanu-android-tests/uxmanu/Crosswalk_CopyAndPaste_Copy_Photo.html </test_script_entry>
        </description>
      </testcase>
      <testcase purpose="Validate if could copy SeveralCopies" type="Functional" status="approved" component="Integration with Android System" execution_type="manual" priority="P2" id="Crosswalk_CopyAndPaste_Copy_SeveralCopies">
        <description>
          <pre_condition>
            1.Make sure Crosswalk binary is installed;
            2.Make sure at least one audio app is installed.
          </pre_condition>
          <test_script_entry>/opt/wrt-uxmanu-android-tests/uxmanu/Crosswalk_CopyAndPaste_Copy_SeveralCopies.html </test_script_entry>
        </description>
      </testcase>
      <testcase purpose="Validate if could copy ToNativeapp" type="Functional" status="approved" component="Integration with Android System" execution_type="manual" priority="P2" id="Crosswalk_CopyAndPaste_Copy_ToNativeapp">
        <description>
          <pre_condition>
            1.Make sure Crosswalk binary is installed;
            2.Make sure at least one audio app is installed.
          </pre_condition>
          <test_script_entry>/opt/wrt-uxmanu-android-tests/uxmanu/Crosswalk_CopyAndPaste_Copy_ToNativeapp.html </test_script_entry>
        </description>
      </testcase>
      <testcase purpose="Validate if could copy ToWebapp" type="Functional" status="approved" component="Integration with Android System" execution_type="manual" priority="P2" id="Crosswalk_CopyAndPaste_Copy_ToWebapp">
        <description>
          <pre_condition>
            1.Make sure Crosswalk binary is installed;
            2.Make sure at least one audio app is installed.
          </pre_condition>
          <test_script_entry>/opt/wrt-uxmanu-android-tests/uxmanu/Crosswalk_CopyAndPaste_Copy_ToWebapp.html </test_script_entry>
        </description>
      </testcase>
      <testcase purpose="Validate if could copy Select all" type="Functional" status="approved" component="Integration with Android System" execution_type="manual" priority="P1" id="Crosswalk_CopyAndPaste_SelectAll_Copy">
        <description>
          <pre_condition>
            1.Make sure Crosswalk binary is installed;
            2.Make sure at least one audio app is installed.
          </pre_condition>
          <test_script_entry>/opt/wrt-uxmanu-android-tests/uxmanu/Crosswalk_CopyAndPaste_SelectAll_Copy.html </test_script_entry>
        </description>
      </testcase>
      <testcase purpose="Validate if could copy Selected_Copy" type="Functional" status="approved" component="Integration with Android System" execution_type="manual" priority="P1" id="Crosswalk_CopyAndPaste_Selected_Copy">
        <description>
          <pre_condition>
            1.Make sure Crosswalk binary is installed;
            2.Make sure at least one audio app is installed.
          </pre_condition>
          <test_script_entry>/opt/wrt-uxmanu-android-tests/uxmanu/Crosswalk_CopyAndPaste_Selected_Copy.html </test_script_entry>
        </description>
      </testcase>
      <testcase purpose="Validate if could cut text" type="Functional" status="approved" component="Integration with Android System" execution_type="manual" priority="P1" id="Crosswalk_CopyAndPaste_Selected_Cut">
        <description>
          <pre_condition>
            1.Make sure Crosswalk binary is installed;
            2.Make sure at least one audio app is installed.
          </pre_condition>
          <test_script_entry>/opt/wrt-uxmanu-android-tests/uxmanu/Crosswalk_CopyAndPaste_Selected_Cut.html </test_script_entry>
        </description>
      </testcase>
      <testcase purpose="Validate if the UI display normal" type="Functional" status="approved" component="Integration with Android System" execution_type="manual" priority="P1" id="Crosswalk_CopyAndPaste_Selected_UI">
        <description>
          <pre_condition>
            1.Make sure Crosswalk binary is installed;
            2.Make sure at least one audio app is installed.
          </pre_condition>
          <test_script_entry>/opt/wrt-uxmanu-android-tests/uxmanu/Crosswalk_CopyAndPaste_Selected_UI.html </test_script_entry>
        </description>
      </testcase>
    <testcase purpose="Validate if could select on char and copy, paste" type="Functional" status="approved" component="Integration with Android System" execution_type="manual" priority="P2" id="Crosswalk_CopyAndPaste_SelectOneChar_Copy">
        <description>
          <pre_condition>
            1.Make sure Crosswalk binary is installed;
            2.Make sure at least one audio app is installed.
          </pre_condition>
          <test_script_entry>/opt/wrt-uxmanu-android-tests/uxmanu/Crosswalk_CopyAndPaste_SelectOneChar_Copy.html </test_script_entry>
        </description>
      </testcase>
      <testcase purpose="Validate if could select speci char and copy, paste" type="Functional" status="approved" component="Integration with Android System" execution_type="manual" priority="P2" id="Crosswalk_CopyAndPaste_SelectSpecialChar_Copy">
        <description>
          <pre_condition>
            1.Make sure Crosswalk binary is installed;
            2.Make sure at least one audio app is installed.
          </pre_condition>
          <test_script_entry>/opt/wrt-uxmanu-android-tests/uxmanu/Crosswalk_CopyAndPaste_SelectSpecialChar_Copy.html </test_script_entry>
        </description>
      </testcase>
      <testcase purpose="Validate crosswalk support copy and paste cross application" type="Functional" status="approved" component="Integration with Android System" execution_type="manual" priority="P1" id="Crosswalk_CopyAndPaste_Cross_Application">
        <description>
          <pre_condition>
            1.Make sure Crosswalk binary is installed
          </pre_condition>
          <test_script_entry>/opt/wrt-uxmanu-android-tests/uxmanu/Crosswalk_CopyAndPaste_Cross_Application.html</test_script_entry>
        </description>
      </testcase>
      <testcase purpose="Validate crosswalk support copy and paste from native to web application" type="Functional" status="approved" component="Integration with Android System" execution_type="manual" priority="P1" id="Crosswalk_CopyAndPaste_Copy_NativeToWeb">
        <description>
          <pre_condition>
            1.Make sure Crosswalk binary is installed
          </pre_condition>
          <test_script_entry>/opt/wrt-uxmanu-android-tests/uxmanu/Crosswalk_CopyAndPaste_Copy_NativeToWeb.html</test_script_entry>
        </description>
      </testcase>
    </set>
    <set name="Runtimelibrary" type="js">
      <testcase purpose="Validate if display normal when browser support WebGL on ARM" type="Functional" status="approved" component="Crosswalk Runtime Library" execution_type="manual" priority="P1" id="Crosswalk_UseChromeBlacklist_WebGLSupport_ARM" >
        <description>
          <pre_condition>
            1.Make sure Crosswalk binary is installed;
            2.Make sure at least one webapp is installed.
            3.Use the ARM device which WebGL is enable in it
          </pre_condition>
          <test_script_entry>/opt/wrt-uxmanu-android-tests/uxmanu/Crosswalk_UseChromeBlacklist_WebGLSupport_ARM.html </test_script_entry>
        </description>
       </testcase>
      <testcase purpose="Validate if display normal when browser not support WebGL on ARM" type="Functional" status="approved" component="Crosswalk Runtime Library" execution_type="manual" priority="P2" id="Crosswalk_UseChromeBlacklist_WebGLNotSupport_ARM">
        <description>
          <pre_condition>
            1.Make sure Crosswalk binary is installed;
            2.Make sure at least one webapp is installed.
            3.Use the ARM device which WebGL is unable in it
          </pre_condition>
          <test_script_entry>/opt/wrt-uxmanu-android-tests/uxmanu/Crosswalk_UseChromeBlacklist_WebGLNotSupport_ARM.html </test_script_entry>
        </description>
      </testcase>
      <testcase purpose="Validate if display normal when support WebGL on IA" type="Functional" status="approved" component="Crosswalk Runtime Library" execution_type="manual" priority="P2" id="Crosswalk_UseChromeBlacklist_WebGLSupport_IA">
        <description>
          <pre_condition>
            1.Make sure Crosswalk binary is installed;
            2.Make sure at least one webapp is installed.
            3.Use the IA device which WebGL is enable in it
          </pre_condition>
          <test_script_entry>/opt/wrt-uxmanu-android-tests/uxmanu/Crosswalk_UseChromeBlacklist_WebGLSupport_IA.html </test_script_entry>
        </description>
      </testcase>
    </set>
  </suite>
</test_definition>


text:
package org.terracotta.management.service.monitoring.buffer;

import com.tc.classloader.CommonComponent;

/**
 * @author Mathieu Carbou
 */
@CommonComponent
public interface ReadWriteBuffer<V> extends ReadOnlyBuffer<V> {

  /**
   * Put a value in the buffer, making some space by discarding some other values if necessary
   *
   * @return The value that has been removed, or null if none
   */
  V put(V value);

}

redpajama_set_name: RedPajamaGithub


text:
require 'lotus/model'
require 'lotus/mailer'
Dir["#{ __dir__ }/new_container/**/*.rb"].each { |file| require_relative file }

Lotus::Model.configure do
  ##
  # Database adapter
  #
  # Available options:
  #
  #  * Memory adapter
  #    adapter type: :memory, uri: 'memory://localhost/new_container_development'
  #
  #  * SQL adapter
  #    adapter type: :sql, uri: 'sqlite://db/new_container_development.sqlite3'
  #    adapter type: :sql, uri: 'postgres://localhost/new_container_development'
  #    adapter type: :sql, uri: 'mysql://localhost/new_container_development'
  #
  adapter type: :sql, uri: ENV['NEW_CONTAINER_DATABASE_URL']

  ##
  # Migrations
  #
  migrations 'db/migrations'
  schema     'db/schema.sql'

  ##
  # Database mapping
  #
  # Intended for specifying application wide mappings.
  #
  # You can specify mapping file to load with:
  #
  # mapping "#{__dir__}/config/mapping"
  #
  # Alternatively, you can use a block syntax like the following:
  #
  mapping do
    # collection :users do
    #   entity     User
    #   repository UserRepository
    #
    #   attribute :id,   Integer
    #   attribute :name, String
    # end
  end
end.load!

Lotus::Mailer.configure do
  root "#{ __dir__ }/new_container/mailers"

  # See http://lotusrb.org/guides/mailers/delivery
  delivery do
    development :test
    test        :test
    # production :stmp, address: ENV['SMTP_PORT'], port: 1025
  end
end.load!


text:
#include <Config/Templates/Animation.hpp>
#include <Config/Templates/Config.hpp>
#include <Config/Templates/GameObject.hpp>
#include <Config/Templates/Mount.hpp>
#include <Config/Templates/Scene.hpp>

#include <Bindings/Config.hpp>

namespace obe::Config::Templates::Bindings
{
    void LoadFunctionGetAnimationTemplates(sol::state_view state)
    {
        sol::table TemplatesNamespace
            = state["obe"]["Config"]["Templates"].get<sol::table>();
        TemplatesNamespace.set_function(
            "getAnimationTemplates", obe::Config::Templates::getAnimationTemplates);
    }
    void LoadFunctionGetConfigTemplates(sol::state_view state)
    {
        sol::table TemplatesNamespace
            = state["obe"]["Config"]["Templates"].get<sol::table>();
        TemplatesNamespace.set_function(
            "getConfigTemplates", obe::Config::Templates::getConfigTemplates);
    }
    void LoadFunctionGetGameObjectTemplates(sol::state_view state)
    {
        sol::table TemplatesNamespace
            = state["obe"]["Config"]["Templates"].get<sol::table>();
        TemplatesNamespace.set_function(
            "getGameObjectTemplates", obe::Config::Templates::getGameObjectTemplates);
    }
    void LoadFunctionGetMountTemplates(sol::state_view state)
    {
        sol::table TemplatesNamespace
            = state["obe"]["Config"]["Templates"].get<sol::table>();
        TemplatesNamespace.set_function(
            "getMountTemplates", obe::Config::Templates::getMountTemplates);
    }
    void LoadFunctionGetSceneTemplates(sol::state_view state)
    {
        sol::table TemplatesNamespace
            = state["obe"]["Config"]["Templates"].get<sol::table>();
        TemplatesNamespace.set_function(
            "getSceneTemplates", obe::Config::Templates::getSceneTemplates);
    }
    void LoadGlobalWaitCommand(sol::state_view state)
    {
        sol::table TemplatesNamespace
            = state["obe"]["Config"]["Templates"].get<sol::table>();
        TemplatesNamespace["wait_command"] = obe::Config::Templates::wait_command;
    }
    void LoadGlobalPlayGroupCommand(sol::state_view state)
    {
        sol::table TemplatesNamespace
            = state["obe"]["Config"]["Templates"].get<sol::table>();
        TemplatesNamespace["play_group_command"]
            = obe::Config::Templates::play_group_command;
    }
    void LoadGlobalSetAnimationCommand(sol::state_view state)
    {
        sol::table TemplatesNamespace
            = state["obe"]["Config"]["Templates"].get<sol::table>();
        TemplatesNamespace["set_animation_command"]
            = obe::Config::Templates::set_animation_command;
    }
};


text:
package org.apache.ibatis.annotations;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface CacheNamespaceRef {
  public abstract Class<?> value();
}


text:
<?php
namespace Dime\TimetrackerBundle\Entity;

use Gedmo\Mapping\Annotation as Gedmo;
use Doctrine\ORM\Mapping as ORM;
use FOS\UserBundle\Entity\User as BaseUser;
use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;
use Symfony\Component\Validator\Constraints as Assert;
use JMS\SerializerBundle\Annotation\SerializedName;

/**
 * Dime\TimetrackerBundle\Entity\Project
 *
 * @UniqueEntity(fields={"email"})
 * @ORM\Table(name="users")
 * @ORM\Entity(repositoryClass="Dime\TimetrackerBundle\Entity\UserRepository")
 */
class User extends BaseUser
{
    /**
     * @var integer $id
     *
     * @ORM\Id
     * @ORM\Column(name="id", type="integer")
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    protected $id;

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

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

    /**
     * @var datetime $createdAt
     *
     * @Gedmo\Timestampable(on="create")
     * @SerializedName("createdAt")
     * @ORM\Column(name="created_at", type="datetime")
     */
    protected $createdAt;

    /**
     * @var datetime $updatedAt
     *
     * @Gedmo\Timestampable(on="update")
     * @SerializedName("updatedAt")
     * @ORM\Column(name="updated_at", type="datetime")
     */
    protected $updatedAt;

    /**
     * Get id
     *
     * @return integer
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set firstname
     *
     * @param  string $firstname
     * @return User
     */
    public function setFirstname($firstname)
    {
        $this->firstname = $firstname;

        return $this;
    }

    /**
     * Get firstname
     *
     * @return string
     */
    public function getFirstname()
    {
        return $this->firstname;
    }

    /**
     * Set lastname
     *
     * @param  string $lastname
     * @return User
     */
    public function setLastname($lastname)
    {
        $this->lastname = $lastname;

        return $this;
    }

    /**
     * Get lastname
     *
     * @return string
     */
    public function getLastname()
    {
        return $this->lastname;
    }

    /**
     * Get created at datetime
     *
     * @return datetime
     */
    public function getCreatedAt()
    {
        return $this->createdAt;
    }

    /**
     * Get updated at datetime
     *
     * @return datetime
     */
    public function getUpdatedAt()
    {
        return $this->updatedAt;
    }

    /**
     * get user as string
     *
     * @return string
     */
    public function __toString()
    {
        $user = trim($this->getFirstname() . ' ' . $this->getLastname());
        if ($this->hasEmail()) {
            $user .= empty($user) ? $this->getEmail() : ' (' . $this->getEmail() . ')';
        }

        if (empty($user)) {
            $user = $this->getId();
        }

        return $user;
    }
}


text:
package com.amazonaws.services.ec2.model;

import java.io.Serializable;

import com.amazonaws.AmazonWebServiceRequest;
import com.amazonaws.Request;
import com.amazonaws.services.ec2.model.transform.BundleInstanceRequestMarshaller;

/**
 * Container for the parameters to the {@link com.amazonaws.services.ec2.AmazonEC2#bundleInstance(BundleInstanceRequest) BundleInstance operation}.
 *

 * Bundles an Amazon instance store-backed Windows instance.
 *

 *

 * During bundling, only the root device volume (C:\) is bundled. Data on
 * other instance store volumes is not preserved.
 *

 *

 * NOTE: This action is not applicable for Linux/Unix instances or
 * Windows instances that are backed by Amazon EBS.
 *

 *

 * For more information, see
 *  Creating an Instance Store-Backed Windows AMI
 * .
 *

 *
 * @see com.amazonaws.services.ec2.AmazonEC2#bundleInstance(BundleInstanceRequest)
 */
public class BundleInstanceRequest extends AmazonWebServiceRequest implements Serializable, Cloneable, DryRunSupportedRequest<BundleInstanceRequest> {

    /**
     * The ID of the instance to bundle.
Type: String
Default: None
     *
Required: Yes
     */
    private String instanceId;

    /**
     * The bucket in which to store the AMI. You can specify a bucket that
     * you already own or a new bucket that Amazon EC2 creates on your
     * behalf. If you specify a bucket that belongs to someone else, Amazon
     * EC2 returns an error.
     */
    private Storage storage;

    /**
     * Default constructor for a new BundleInstanceRequest object.  Callers should use the
     * setter or fluent setter (with...) methods to initialize this object after creating it.
     */
    public BundleInstanceRequest() {}

    /**
     * Constructs a new BundleInstanceRequest object.
     * Callers should use the setter or fluent setter (with...) methods to
     * initialize any additional object members.
     *
     * @param instanceId The ID of the instance to bundle.
Type: String
     *
Default: None
Required: Yes
     * @param storage The bucket in which to store the AMI. You can specify a
     * bucket that you already own or a new bucket that Amazon EC2 creates on
     * your behalf. If you specify a bucket that belongs to someone else,
     * Amazon EC2 returns an error.
     */
    public BundleInstanceRequest(String instanceId, Storage storage) {
        setInstanceId(instanceId);
        setStorage(storage);
    }

    /**
     * The ID of the instance to bundle.
Type: String
Default: None
     *
Required: Yes
     *
     * @return The ID of the instance to bundle.
Type: String
Default: None
     *
Required: Yes
     */
    public String getInstanceId() {
        return instanceId;
    }

    /**
     * The ID of the instance to bundle.
Type: String
Default: None
     *
Required: Yes
     *
     * @param instanceId The ID of the instance to bundle.
Type: String
Default: None
     *
Required: Yes
     */
    public void setInstanceId(String instanceId) {
        this.instanceId = instanceId;
    }

    /**
     * The ID of the instance to bundle.
Type: String
Default: None
     *
Required: Yes
     *

     * Returns a reference to this object so that method calls can be chained together.
     *
     * @param instanceId The ID of the instance to bundle.
Type: String
Default: None
     *
Required: Yes
     *
     * @return A reference to this updated object so that method calls can be chained
     *         together.
     */
    public BundleInstanceRequest withInstanceId(String instanceId) {
        this.instanceId = instanceId;
        return this;
    }

    /**
     * The bucket in which to store the AMI. You can specify a bucket that
     * you already own or a new bucket that Amazon EC2 creates on your
     * behalf. If you specify a bucket that belongs to someone else, Amazon
     * EC2 returns an error.
     *
     * @return The bucket in which to store the AMI. You can specify a bucket that
     *         you already own or a new bucket that Amazon EC2 creates on your
     *         behalf. If you specify a bucket that belongs to someone else, Amazon
     *         EC2 returns an error.
     */
    public Storage getStorage() {
        return storage;
    }

    /**
     * The bucket in which to store the AMI. You can specify a bucket that
     * you already own or a new bucket that Amazon EC2 creates on your
     * behalf. If you specify a bucket that belongs to someone else, Amazon
     * EC2 returns an error.
     *
     * @param storage The bucket in which to store the AMI. You can specify a bucket that
     *         you already own or a new bucket that Amazon EC2 creates on your
     *         behalf. If you specify a bucket that belongs to someone else, Amazon
     *         EC2 returns an error.
     */
    public void setStorage(Storage storage) {
        this.storage = storage;
    }

    /**
     * The bucket in which to store the AMI. You can specify a bucket that
     * you already own or a new bucket that Amazon EC2 creates on your
     * behalf. If you specify a bucket that belongs to someone else, Amazon
     * EC2 returns an error.
     *

     * Returns a reference to this object so that method calls can be chained together.
     *
     * @param storage The bucket in which to store the AMI. You can specify a bucket that
     *         you already own or a new bucket that Amazon EC2 creates on your
     *         behalf. If you specify a bucket that belongs to someone else, Amazon
     *         EC2 returns an error.
     *
     * @return A reference to this updated object so that method calls can be chained
     *         together.
     */
    public BundleInstanceRequest withStorage(Storage storage) {
        this.storage = storage;
        return this;
    }

    /**
     * This method is intended for internal use only.
     * Returns the marshaled request configured with additional parameters to
     * enable operation dry-run.
     */
    @Override
    public Request<BundleInstanceRequest> getDryRunRequest() {
        Request<BundleInstanceRequest> request = new BundleInstanceRequestMarshaller().marshall(this);
        request.addParameter("DryRun", Boolean.toString(true));
        return request;
    }

    /**
     * Returns a string representation of this object; useful for testing and
     * debugging.
     *
     * @return A string representation of this object.
     *
     * @see java.lang.Object#toString()
     */
    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("{");
        if (getInstanceId() != null) sb.append("InstanceId: " + getInstanceId() + ",");
        if (getStorage() != null) sb.append("Storage: " + getStorage() );
        sb.append("}");
        return sb.toString();
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int hashCode = 1;

        hashCode = prime * hashCode + ((getInstanceId() == null) ? 0 : getInstanceId().hashCode());
        hashCode = prime * hashCode + ((getStorage() == null) ? 0 : getStorage().hashCode());
        return hashCode;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj) return true;
        if (obj == null) return false;

        if (obj instanceof BundleInstanceRequest == false) return false;
        BundleInstanceRequest other = (BundleInstanceRequest)obj;

        if (other.getInstanceId() == null ^ this.getInstanceId() == null) return false;
        if (other.getInstanceId() != null && other.getInstanceId().equals(this.getInstanceId()) == false) return false;
        if (other.getStorage() == null ^ this.getStorage() == null) return false;
        if (other.getStorage() != null && other.getStorage().equals(this.getStorage()) == false) return false;
        return true;
    }

    @Override
    public BundleInstanceRequest clone() {

            return (BundleInstanceRequest) super.clone();
    }

}


text:
"""
Backend for browsing category parses.
"""

import collections
import cgi
import json
import os
import sling
import sling.flags as flags
import sling.log as log
import tempfile
import util

from http.server import BaseHTTPRequestHandler, HTTPServer
from collections import defaultdict
from fact_matcher import FactMatchType
from urllib.parse import urlparse, parse_qs

# Returns the list of fact match types.
def fact_match_type_names():
  return [t.name for t in FactMatchType]

# Scores a given parse using specified match-type weights.
class Metric:
  def __init__(self, metric_str):
    self.weights = {}  # string match-type -> weight
    for t in fact_match_type_names():
      self.weights[t] = 0.0

    d = dict([x.split(':') for x in metric_str.split(',')])
    for (k, v) in d.items():
      self.weights[k] = float(v)

  # Returns the score of 'match_counts' as per the weights.
  def score(self, match_counts):
    s = 0.0
    for match_type, count in match_counts.counts.items():
      s += self.weights[match_type] * count
    return s

# Stores a usable subset of spans in a signature.
class SpanSubset:
  def __init__(self, span_subset_str=None):
    self.allowed = None
    if span_subset_str is not None and span_subset_str != "-1":
      self.allowed = [int(x) for x in span_subset_str.split(',')]

  # Returns whether span numbered 'index' is allowed.
  def is_allowed(self, index):
    return self.allowed is None or index in self.allowed

# Wrapper around a parse.
class Parse:
  def __init__(self, unique_id, category, frame, parse):
    self.id = unique_id          # unique int id for the parse
    self.parse = parse           # the parse itself
    self.category = category     # QID for the category
    self.frame = frame           # frame of the category
    self.span_counts = []        # i -> match counts for ith span in parse

    # Score and counts as per a set of spans. Changes as the user tinkers
    # with various settings.
    self.score = 0.0
    self.counts = None

  # Computes and caches the match counts for each span from the parse frame.
  def compute_span_counts(self):
    if len(self.span_counts) == 0:
      for span in self.parse.spans:
        c = util.fact_matches_for_span(span)
        self.span_counts.append(c)

  # Computes aggregate match counts across all selected spans.
  def counts_for(self, span_subset=None, counts=None):
    if counts is None:
      counts = util.MatchCounts()
    for index, count in enumerate(self.span_counts):
      if span_subset is None or span_subset.is_allowed(index):
        counts.merge(count)
    return counts

  # Returns a list of (span signature, span match counts) for all selected spans
  # as per 'span_subset'.
  def selected_span_counts(self, span_subset=None):
    output = []
    for index, counts in enumerate(self.span_counts):
      if span_subset is None or span_subset.is_allowed(index):
        output.append((self.parse.spans[index].signature, counts.to_dict()))
    return output

  # Computes a list of name-parts for 'parse'.
  def name_parts(self, span_subset=None, use_span_signature=False):
    def _word(text, token):
      size = token.size if token.size is not None else 1
      return text[token.start:token.start + size]

    tokens = self.frame.document.tokens
    text = self.frame.document.text
    begin = 0
    parts = []
    for index, span in enumerate(self.parse.spans):
      if begin < span.begin:
        words = ' '.join([_word(text, t) for t in tokens[begin:span.begin]])
        parts.append((words, "", ""))

      words = ' '.join([_word(text, t) for t in tokens[span.begin:span.end]])
      if span_subset is None or span_subset.is_allowed(index):
        if use_span_signature:
          words = span.signature
        parts.append((words, '.'.join([x.id for x in span.pids]), span.qid.id))
      else:
        parts.append((words, "", ""))
      begin = span.end
    if begin < len(tokens):
      words = ' '.join([_word(text, t) for t in tokens[begin:]])
      parts.append((words, "", ""))

    return [{
        "text": p[0],
        "pqid": p[1] + "=" + p[2] if p[1] != "" else "",
      } for p in parts]

# Decides whether a parse should be selected for further processing.
class ParseSelector:
  def __init__(self, formula_str):
    typenames = fact_match_type_names()
    for symbol in ["NAME", "SCORE", "INTERESTING", "QID"]:
      assert symbol not in typenames, symbol

    if formula_str is None or formula_str == "":
      formula_str = "True"  # every parse is selected
    self.formula = formula_str

  # Returns whether 'parse' should be selected. Assumes that 'parse' has its
  # counts (for the relevent subset of spans) filled in.
  def select(self, parse):
    formula = self.formula
    if formula == "True":
      return True

    # Replace symbols by their values. This is just a regex replace.
    c = parse.counts.counts
    for t in fact_match_type_names():
      formula = formula.replace("$" + t, str(c.get(t, 0)))

    # Replace other special fields.
    formula = formula.replace("$SCORE", str(parse.score))
    formula = formula.replace("$INTERESTING", \
      str(c.get("NEW", 0) + c.get("ADDITIONAL", 0) + \
      c.get("SUBSUMED_BY_EXISTING", 0)))
    formula = formula.replace("$NAME", "parse.frame.name")
    formula = formula.replace("$QID", "parse.category")
    return eval(formula) is True

# Wraps a request from the front-end to the server.
#
# A request is comprised of a text 'query' (e.g. a signature or category),
# a set of weights (captured by 'metric'), a set of span indices
# (captured by 'span_subset'; relevant only for signature queries), and
# a parse-selection formula captured by 'parse_selector'.
class Request:
  def __init__(self, query, metric, span_subset=None, \
               parse_selector=None, topk=500):
    self.query = query
    self.metric = Metric(metric)
    self.span_subset = SpanSubset(span_subset)
    self.parse_selector = ParseSelector(parse_selector)
    self.topk = topk

# Response to a signature query.
class SignatureResponse:
  def __init__(self, request):
    self.request = request
    self.error_message = None
    self.span_signatures = util.parse_to_span_signatures(request.query)

    # All counts are after the parse selector has come into play.
    self.counts_across_spans = util.MatchCounts()
    self.counts_across_selected_spans = util.MatchCounts()
    self.counts_by_span = [util.MatchCounts() for _ in self.span_signatures]

    # Top selected parses shown.
    self.top_parses = []

    # Statistics of selected parses that aren't not shown.
    self.top_parses_not_shown = {"num": 0, "counts": util.MatchCounts()}

    # Statistics of unselected parses.
    self.unselected_parses = {"num": 0, "counts": util.MatchCounts()}

  # Adds 'parse' to the response.
  def add(self, parse):
    for index, span in enumerate(parse.parse.spans):
      counts = parse.span_counts[index]
      self.counts_across_spans.merge(counts)
      self.counts_by_span[index].merge(counts)
      if self.request.span_subset.is_allowed(index):
        self.counts_across_selected_spans.merge(counts)
    self.top_parses.append(parse)

  # Records 'parse' as been rejected from the response.
  def reject(self, parse):
    self.unselected_parses["num"] += 1
    self.unselected_parses["counts"].merge(parse.counts)

  # Trims the response to top-k as per user's metric.
  def trim(self):
    k = self.request.topk
    self.top_parses.sort(key=lambda parse: -parse.score);
    self.top_parses_not_shown["num"] = max(0, len(self.top_parses) - k)
    c = self.top_parses_not_shown["counts"]
    for parse in self.top_parses[k:]:
      parse.counts_for(self.request.span_subset, c)
    self.top_parses = self.top_parses[:k]

  # Sets error message.
  def error(self, message):
    self.error_message = message

  # Converts the response to JSON for communicating back to the front-end.
  def to_json(self):
    data = {}
    data["response_type"] = "signature"
    if self.error_message is not None:
      data["error"] = self.error_message
      return json.dumps(data)

    data["num_total_spans"] = len(self.counts_by_span)
    data["num_selected_spans"] = sum([
        self.request.span_subset.is_allowed(i) \
            for i in range(len(self.counts_by_span))])

    data["per_span"] = [
      {
        "selected" : self.request.span_subset.is_allowed(index),
        "signature" : self.span_signatures[index],
        "counts": self.counts_by_span[index].to_dict()
      } for index, count in enumerate(self.counts_by_span)
    ]
    data["total_spans"] = self.counts_across_spans.to_dict()
    data["selected_spans"] = self.counts_across_selected_spans.to_dict()

    data["parses"] = [{
      "parse_id": p.id,
      "category_qid": p.category,
      "name": p.frame.name,
      "name_parts": p.name_parts(self.request.span_subset),
      "score": round(p.score, 2),
      "counts": p.counts.to_dict(),
      "selected_span_counts": p.selected_span_counts(self.request.span_subset)
    } for p in self.top_parses]

    data["parses_not_shown"] = {
      "num": self.top_parses_not_shown["num"],
      "counts": self.top_parses_not_shown["counts"].to_dict()
    }
    data["parses_not_selected"] = {
      "num": self.unselected_parses["num"],
      "counts": self.unselected_parses["counts"].to_dict()
    }

    return json.dumps(data)

# Response to a category request.
class CategoryResponse:
  def __init__(self, request):
    self.request = request
    self.num_extra = 0
    self.rejected = 0
    self.parses = []

  # Adds 'parse' as a candidate parse for the category.
  def add(self, parse):
    self.parses.append(parse)

  # Rejects 'parse' as a candidate parse for the category.
  def reject(self, parse):
    self.rejected += 1

  # Trims the response to keep only top-k parses.
  def trim(self, topk):
    self.parses.sort(key=lambda p: -p.score)
    self.num_extra = max(0, len(self.parses) - topk)
    self.parses = self.parses[0:topk]

  # Converts the response to JSON for communicating back to the front-end.
  def to_json(self):
    d = {}
    d["response_type"] = "category"
    d["rejected"] = self.rejected
    d["extra"] = self.num_extra
    parses = []
    for parse in self.parses:
      entry = {
        "signature" : " ".join(parse.parse.signature),
        "name_parts" : parse.name_parts(span_subset=None, \
            use_span_signature=True),
        "parse_id" : parse.id,
        "score" : round(parse.score, 2),
        "counts" : parse.counts.to_dict()
      }
      parses.append(entry)
    d["parses"] = parses
    return json.dumps(d)

# Response for a recordio generation request.
class RecordioResponse:
  def __init__(self, request, store):
    self.request = request
    self.error_message = None
    self.num_facts = defaultdict(int)
    self.store = store

    # Recordio will be generated only for these match types.
    self.match_types = [
      FactMatchType.NEW.name,
      FactMatchType.ADDITIONAL.name,
      FactMatchType.SUBSUMED_BY_EXISTING.name
    ]
    self.frames = []
    self.output_file = ""

  # Records an error message during recordio generation.
  def error(self, message):
    self.error_message = message

  # Adds facts implied by 'parse' to the set of facts that will be written.
  def add(self, parse):
    for index, span in enumerate(parse.parse.spans):
      if not self.request.span_subset.is_allowed(index):
        continue

      pid = span.pids
      qid = span.qid
      if len(pid) > 1:  # skip multi-hop facts
        continue
      else:
        pid = pid[0]

      for bucket in span.fact_matches.buckets:
        if bucket.match_type in self.match_types:
          for item in bucket.source_items:
            frame = self.store.frame([("item", item)])
            frame.facts = self.store.frame([(pid, qid)])
            frame.provenance = self.store.frame([
                ("category", parse.category),
                ("method", "Member of Category:%s" % parse.frame.name)
            ])
            frame.comment = "%s : %s = %s" % (item, span.signature, qid)
            frame.match_type = bucket.match_type
            self.num_facts[(pid.id, bucket.match_type)] += 1
            self.frames.append(frame)

  # Writes the facts to 'filename'.
  def write(self, filename):
    self.output_file = filename
    writer = sling.RecordWriter(filename)
    for frame in self.frames:
      writer.write(frame.item.id, frame.data(binary=True))

  # Returns a JSON-formatted summary of recordio generation.
  def to_json(self):
    ls = []
    for (pid, match_type), count in self.num_facts.items():
      ls.append((pid, match_type, count))
    d = {}
    d["counts"] = ls
    d["output_file" ] = self.output_file
    return json.dumps(d)

# Aggregate statistics for a signature across all its parses allowed by
# the parse selection formula.
class SignatureStats:
  def __init__(self, signature):
    self.signature = signature
    self.score = 0.0                   # aggregate score as per user-weights
    self.counts = util.MatchCounts()   # aggregate match counts
    self.example_category = None       # exemplar category for the parse
    self.rejected = 0                  # no. of parses rejected by the formula
    self.selected = 0                  # no. of parses allowed by the formula

  # Records 'parse' as a rejected parse for the signature.
  def reject_parse(self, parse):
    self.rejected += 1

  # Records 'parse' as a selected parse for the signature.
  def add_parse(self, parse, request):
    self.selected += 1
    self.counts.merge(parse.counts)
    self.score += parse.score
    if self.example_category is None:
      self.example_category = parse.frame.name

  # Returns a dictionary form of the statistics.
  def to_dict(self):
    data = {}
    data["signature"] = self.signature
    data["example_category"] = self.example_category
    data["score"] = round(self.score, 2)
    data["rejected"] = self.rejected
    data["selected"] = self.selected
    data["counts"] = self.counts.to_dict()
    return data

# Container for parses, categories, and mappings that are read only once
# and persisted across various HTTP requests.
class ServerGlobals:
  # Initializes the globals from 'parses_filename'.
  def init(self, parses_filename, output_dir):
    self.output_dir = output_dir
    reader = sling.RecordReader(parses_filename)
    self.category_name_to_qid = {}                 # category name -> qid
    self.category_frame = {}                       # category qid -> frame
    self.category_parses = {}                      # category qid -> parses
    self.signature_to_parse = defaultdict(list)    # signature -> parse
    self.store = sling.Store()
    self.num_parses = 0
    for index, (qid, value) in enumerate(reader):
      if (index + 1) % 20000 == 0:
        log.info("%d categories read" % index)
      qid = qid.decode('utf-8')
      frame = self.store.parse(value)
      self.category_name_to_qid[frame.name] = qid
      self.category_frame[qid] = frame
      self.category_parses[qid] = []
      for parse in frame("parse"):
        element = Parse(self.num_parses, qid, frame, parse)
        signature = util.full_parse_signature(parse)
        self.signature_to_parse[signature].append(element)
        self.category_parses[qid].append(element)
        self.num_parses += 1
    self.store.lockgc()
    self.store.freeze()
    self.store.unlockgc()

  # Returns whether 'key' is a category QID or name.
  def is_category(self, key):
    return key in self.category_frame or key in self.category_name_to_qid

  # Returns a list of (parse, selected?) tuples for each parse matching
  # 'signature'. Selection and scoring is done as per 'request'.
  # parse.counts and parse.score are filled in for each parse.
  #
  # If multiple parses matching 'signature' belong to the same category, then
  # only the highest scoring one (as per 'request') is returned.
  def parses_for_signature(self, signature, request):
    parses = []
    for parse in self.signature_to_parse[signature]:
      parse.compute_span_counts()
      parse.counts = parse.counts_for(request.span_subset)
      parse.score = request.metric.score(parse.counts)
      parses.append((parse, request.parse_selector.select(parse)))
    parses.sort(key=lambda t: -t[0].score)

    output = []
    seen = set()
    for parse, selected in parses:
      if parse.category not in seen:
        output.append((parse, selected))
        seen.add(parse.category)
    return output

  # Returns the JSON response for a top signatures request.
  def handle_top(self, request):
    all_stats = []   # i -> SignatureStats for ith signature
    for signature in self.signature_to_parse:
      signature_stats = SignatureStats(signature)
      for parse, selected in self.parses_for_signature(signature, request):
        if selected:
          signature_stats.add_parse(parse, request)
        else:
          signature_stats.reject_parse(parse)
      if signature_stats.selected > 0:
        all_stats.append(signature_stats)
    all_stats.sort(key=lambda s: -s.score)

    if request.topk >= 0:
      all_stats = all_stats[:request.topk]
    all_stats = [s.to_dict() for s in all_stats]
    return json.dumps({"response_type":"top", "stats":all_stats})

  # Returns the JSON response for a signature query.
  def handle_signature(self, request):
    response = SignatureResponse(request)
    signature = request.query
    if signature in self.signature_to_parse:
      for parse, selected in self.parses_for_signature(signature, request):
        if selected:
          response.add(parse)
        else:
          response.reject(parse)
      response.trim()
    else:
      response.error("Unknown input:" + signature)
    return response

  # Returns the JSON response for a category query.
  def handle_category(self, request):
    response = CategoryResponse(request)
    qid = request.query
    if qid in self.category_name_to_qid:
      qid = self.category_name_to_qid[qid]

    parses = self.category_parses[qid]
    for parse in parses:
      parse.compute_span_counts()
      parse.counts = parse.counts_for(span_subset=None)
      parse.score = request.metric.score(parse.counts)
      if request.parse_selector.select(parse):
        response.add(parse)
      else:
        response.reject(parse)

    response.trim(request.topk)
    return response

  # Handles a recordio generation request and returns a summary.
  def handle_recordio(self, request):
    response = RecordioResponse(request, sling.Store(self.store))
    signature = request.query
    if signature in self.signature_to_parse:
      filename = ""
      first = True
      for parse, selected in self.parses_for_signature(signature, request):
        if first:
          # Make an appropriate filename from the PID(s) involved.
          first = False
          for index, span in enumerate(parse.parse.spans):
            if request.span_subset.is_allowed(index):
              filename = filename + ".".join([p.id for p in span.pids]) + "_"
        if selected:
          response.add(parse)

      # Generate the full filename for the recordio.
      (fd, filename) = tempfile.mkstemp(\
        suffix=".rec", prefix=filename, dir=self.output_dir)
      response.write(filename)
      os.close(fd)
    else:
      response.error("No such signature:" + signature)
    return response

# This will be visible inside the browser, which is a BaseHTTPRequestHandler.
server_globals = ServerGlobals()

# Main class for browsing category parses.
class BrowserService(BaseHTTPRequestHandler):
  MIME_TYPES = {
    ".jpg": "image/jpeg",
    ".jpeg": "image/jpeg",
    ".png": "image/png",
    ".ico": "image/x-icon",
    ".css": "text/css",
    ".js": "text/javascript",
    ".html": "text/html; charset=utf-8",
    ".txt": "text/plain; charset=utf-8",
  }

    # Writes 'obj', which could be bytes or a string, to the response.
  def write(self, obj):
    if type(obj) is bytes:
      self.wfile.write(obj)
    else:
      self.wfile.write(bytes(obj, 'utf-8'))

  # Sends default HTTP response headers.
  def _set_headers(self, mimetype="text/html"):
    self.send_response(200)
    self.send_header('Content-type', mimetype)
    self.end_headers()

  # Computes the returns the fact-matching score for the given parse. Weights
  # for each bucket-type are given in 'weights' (FactMatchType.name -> float).
  def parse_fact_score(self, parse, weights):
    score = 0.0
    match_counts = util.fact_matches_for_parse(parse, max_examples=0)
    for match_type, count in match_counts.counts.items():
      score += count * weights[match_type]
    return score

  # Returns the (mime type, whether content is static?) for 'path'.
  def get_mime_type(self, path):
    default_output = ("text/json; charset=utf-8", False)
    if path.startswith("/wikicat/query?") or \
      path.startswith("/wikicat/recordio?") or \
      path.startswith("/wikicat/basic") or \
      path.startswith("/wikicat/weights"):
      return default_output

    ext = path.rfind(".")
    if ext == -1:
      return default_output
    ext = path[ext:]
    if ext not in BrowserService.MIME_TYPES:
      return ("", False)
    return (BrowserService.MIME_TYPES[ext], True)

  # Returns default weights for all match types.
  def default_weights(self):
    wts = {
      "NEW": 0.1,
      "EXACT": 1.0,
      "SUBSUMES_EXISTING": 0.05,
      "SUBSUMED_BY_EXISTING": 0.5,
      "CONFLICT": -20,
      "ADDITIONAL": 0.05
    }
    result = []
    for t in fact_match_type_names():
      wt = wts.get(t, 0.0)
      result.append((t, wt))
    return json.dumps(result)

  # Returns very basic statistics about the parses.
  def basic_stats(self):
    data = {}
    data["num_categories"] = len(server_globals.category_parses)
    data["num_parses"] = server_globals.num_parses
    return json.dumps(data)

  # Converts 'params' into a Request object.
  def params_to_request(self, params):
    return Request(\
        params["query"][0], params["metric"][0], \
        span_subset=params["spans"][0],
        parse_selector=params["selector"][0])

  # Overridden method for generating the head of the response.
  def do_HEAD(self):
    self._set_headers()

  # Overridden GET request handler.
  def do_GET(self):
    print(self.client_address)
    # Accept only local requests.
    if self.client_address[0] not in ['127.0.0.1', 'localhost']:
      return

    params = parse_qs(urlparse(self.path).query)
    print(params, self.path)
    if self.path.startswith("/wikicat/"):
      (mime_type, static) = self.get_mime_type(self.path)
      if static and mime_type != "":
        # Static content is served by reading the specified file.
        # All static content is based off the sling/nlp/wikicat/app folder.
        self._set_headers(mime_type)
        path = os.getcwd() + "/sling/nlp/wikicat/app/" + self.path[9:]
        with open(path, "rb") as f:
          self.write(f.read())
      elif not static:
        self._set_headers(mime_type)
        if self.path.startswith("/wikicat/basic"):
          response = self.basic_stats()
        elif self.path.startswith("/wikicat/weights"):
          response = self.default_weights()
        elif self.path.startswith("/wikicat/query?"):
          request = self.params_to_request(params)
          if request.query.lower() == "top":
            response = server_globals.handle_top(request)
          elif server_globals.is_category(request.query):
            response = server_globals.handle_category(request).to_json()
          else:
            response = server_globals.handle_signature(request).to_json()
        elif self.path.startswith("/wikicat/recordio?"):
          request = self.params_to_request(params)
          response = server_globals.handle_recordio(request).to_json()
        self.write(response)

  # Overridden method for responding to POST requests.
  def do_POST(self):
    if self.client_address[0] not in ['127.0.0.1', 'localhost']:
      return
    raise ValueError("No POST handler! Use GET instead.")

if __name__ == "__main__":
  flags.define("--port",
               help="port number for the HTTP server",
               default=8001,
               type=int,
               metavar="PORT")
  flags.define("--parses",
               help="Recordio of category parses",
               default="local/data/e/wikicat/parses-with-match-statistics.rec",
               type=str,
               metavar="FILE")
  flags.define("--output",
               help="Output dir where Wikibot recordios will be generated.",
               default="local/data/e/wikicat/facts",
               type=str,
               metavar="DIR")
  flags.parse()
  log.info('Reading parses from %s' % flags.arg.parses)
  server_globals.init(flags.arg.parses, flags.arg.output)

  if not os.path.exists(flags.arg.output):
    os.makedirs(flags.arg.output)
  log.info("Output recordios will be dumped to %s" % flags.arg.output)

  server_address = ('', flags.arg.port)
  httpd = HTTPServer(server_address, BrowserService)
  log.info('Running: http://localhost:%d/wikicat/index.html' % flags.arg.port)
  httpd.serve_forever()


text:
package com.github.swissquote.carnotzet.core.maven;

import java.io.BufferedReader;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;

import org.apache.maven.model.Model;
import org.apache.maven.model.io.xpp3.MavenXpp3Reader;
import org.codehaus.plexus.util.xml.pull.XmlPullParserException;

import com.github.swissquote.carnotzet.core.CarnotzetDefinitionException;

import lombok.AllArgsConstructor;
import lombok.NonNull;
import lombok.Value;

/**
 * Utility class that can be used to describe the root maven artifact for creating a carnotzet
 */
@Value
@AllArgsConstructor
public class CarnotzetModuleCoordinates {

	@NonNull
	private final String groupId;
	@NonNull
	private final String artifactId;
	@NonNull
	private final String version;
	private final String classifier;

	public CarnotzetModuleCoordinates(String groupId, String artifactId, String version) {
		this(groupId, artifactId, version, null);
	}

	public static CarnotzetModuleCoordinates fromPom(@NonNull Path pom) {
		Model result;
		try {
			BufferedReader in = new BufferedReader(Files.newBufferedReader(pom, StandardCharsets.UTF_8));
			MavenXpp3Reader reader = new MavenXpp3Reader();
			result = reader.read(in);
		}
		catch (XmlPullParserException | IOException e) {
			throw new CarnotzetDefinitionException(e);
		}
		String groupId = result.getGroupId();
		String version = result.getVersion();
		if (groupId == null) {
			groupId = result.getParent().getGroupId();
		}
		if (version == null) {
			version = result.getParent().getVersion();
		}
		return new CarnotzetModuleCoordinates(groupId, result.getArtifactId(), version, null);
	}

}


text:
project_path: /web/tools/_project.yaml
book_path: /web/tools/_book.yaml
description: Reference documentation for the "Avoids Requesting The Notification Permission On Page Load" Lighthouse audit.

{# wf_updated_on: 2017-12-11 #}
{# wf_published_on: 2016-12-05 #}
{# wf_blink_components: N/A #}

# Avoids Requesting The Notification Permission On Page Load  {: .page-title }

## Overview {: #overview }

As explained in [What Makes a Good Notification][good], good notifications are
timely, relevant, and precise. If your page asks for permission to send
notifications on page load, those notifications may not be relevant to your
users or precise to their needs. A better user experience is to offer to send
users a specific type of notification, and to present the permissions request
after they opt-in.

[good]: /web/fundamentals/push-notifications/

## Recommendations {: #recommendations }

Under **URLs**, Lighthouse reports the line and column numbers where your
code is requesting permission to send notifications. Remove these calls,
and tie the requests to user gestures instead.

## More information {: #more-info }

If notification permissions was already granted or denied to a page before
Lighthouse's audit, Lighthouse cannot determine if the page requests
notification permissions on page load. Reset the permissions and run
Lighthouse again. See [Change website permissions][help] for more help.

Lighthouse collects the JavaScript that was executed on page load. If this
code contains calls to `notification.requestPermission()`, and notification
permission was not already granted, then notification permission was requested.

[help]: https://support.google.com/chrome/answer/6148059

{% include "web/tools/lighthouse/audits/_feedback/notifications-on-load.html" %}


text:
from django.utils import timezone
from django.utils.six import text_type
from django.conf import settings
from django.contrib.auth import get_user_model

from rest_framework import (
    views,
    response,
    authentication,
    exceptions,
    HTTP_HEADER_ENCODING,
)
import jwt

from onadata.apps.fieldsight.models import Site
from .models import RemoteApp, ConnectedDomain, ConnectedProject
from .serializers import SiteSerializer

AUTH_HEADER_TYPE_BYTES = 'Bearer'.encode(HTTP_HEADER_ENCODING)

class RemoteAppAuthentication(authentication.BaseAuthentication):
    def authenticate_header(self, request):
        """
        Value of www-authenticate header in 401 error
        """
        return 'Bearer realm=api'

    def authenticate(self, request):
        header = request.META.get('HTTP_AUTHORIZATION')
        if header is None:
            return None

        # Following two lines is needed for test client
        if isinstance(header, text_type):
            header = header.encode(HTTP_HEADER_ENCODING)

        parts = header.split()

        # No Bearer header at all
        if parts[0] != AUTH_HEADER_TYPE_BYTES:
            return None

        # Improper Bearer header
        if len(parts) != 2:
            raise exceptions.AuthenticationFailed(
                'Authorization header must be of format: Bearer <token>'
            )

        token = parts[1]
        payload = jwt.decode(
            token,
            settings.SECRET_KEY,
            algorithm='HS256',
        )

        user_id = payload.get('userId')
        if not user_id:
            raise exceptions.AuthenticationFailed(
                'User Id not present in token'
            )

        User = get_user_model()
        try:
            user = User.objects.get(id=user_id)
        except User.DoesNotExist:
            raise exceptions.AuthenticationFailed(
                'User not found'
            )

        try:
            remote_app = RemoteApp.objects.get(token=token)
        except RemoteApp.DoesNotExist:
            raise exceptions.AuthenticationFailed(
                'Application not found'
            )

        if remote_app.auth_user != user:
            raise exceptions.AuthenticationFailed(
                'Application not found'
            )

        domain = request.META.get('HTTP_ORIGIN') or \
            request.META.get('ORIGINAL_HTTP_REFERER') or \
            request.META.get('HTTP_REFERRER')
        if not domain or not ConnectedDomain.objects.filter(
            app=remote_app,
            domain=domain,
        ).exists():
            raise exceptions.AuthenticationFailed(
                'Domain not allowed'
            )

        return user, remote_app

class RemoteProjectView(views.APIView):
    authentication_classes = [RemoteAppAuthentication]

    def get(self, request, project_key):
        connected_project = ConnectedProject.objects.filter(
            app=request.auth,
            key=project_key,
        ).first()

        if not connected_project:
            raise exceptions.NotFound('Project not found')

        if connected_project.updated_at:
            last_timestamp = request.GET.get('last_timestamp')
            updated_timestamp = connected_project.updated_at.strftime('%s')
            if last_timestamp and \
                    updated_timestamp <= last_timestamp:
                return response.Response({
                    'updated': False,
                    'timestamp': timezone.now().strftime('%s'),
                })

        sites = Site.objects.filter(
            project=connected_project.project,
        )
        data = SiteSerializer(
            sites,
            many=True,
        ).data

        return response.Response({
            'updated': True,
            'data': data,
            'timestamp': timezone.now().strftime('%s'),
        })


text:
package org.motechproject.mtraining.domain;

import org.motechproject.mds.annotations.Access;
import org.motechproject.mds.annotations.Entity;
import org.motechproject.mds.annotations.Field;
import org.motechproject.mds.domain.MdsEntity;
import org.motechproject.mds.util.SecurityMode;
import org.motechproject.mtraining.util.Constants;

import java.util.List;
import java.util.Objects;

/**
 * Question object with resource identifiers for question and answer
 */
@Entity
@Access(value = SecurityMode.PERMISSIONS, members = {Constants.MANAGE_MTRAINING})
public class Question extends MdsEntity {

    /**
     * Question resource identifier in the external system
     */
    @Field
    private String question;

    /**
     * List of Answer objects that contain identifier in the external system
     */
    @Field
    private List<Answer> answers;

    public Question() {
        this (null, null);
    }

    public Question(String question, List<Answer> answers) {
        this.question = question;
        this.answers = answers;
    }

    public String getQuestion() {
        return question;
    }

    public void setQuestion(String question) {
        this.question = question;
    }

    public List<Answer> getAnswers() {
        return answers;
    }

    public void setAnswers(List<Answer> answers) {
        this.answers = answers;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj) {
            return true;
        }

        if (obj == null || getClass() != obj.getClass()) {
            return false;
        }

        final Question other = (Question) obj;

        return Objects.equals(this.getId(), other.getId())
                && Objects.equals(this.getQuestion(), other.getQuestion())
                && Objects.equals(this.getAnswers(), other.getAnswers());
    }

    @Override
    public int hashCode() {
        return Objects.hash(getQuestion(), getAnswers());
    }
}


text:
namespace te
{
	namespace api
	{
		class TE_EXPORT DepthTexture : public Texture
		{
		public:

			static DepthTexture* Create(uint32 width, uint32 height);
		};
	}
}


text:
from distutils.core import Extension, setup

mikktspace = Extension(
  '_mikktspace',
  sources=['mikktpy.i', 'mikktpy.cpp', 'mikktspace.c'],
  swig_opts=['-modern', '-c++'],
  extra_compile_args=['/EHsc'])

setup (name = 'MikkTSpace',
       version = '1.0',
       description = 'This is a demo package',
       ext_modules = [mikktspace])


text:
package nl.tno.idsa.library.actions;

import nl.tno.idsa.framework.semantics_impl.actions.Action;
import nl.tno.idsa.framework.semantics_impl.variables.GroupVariable;
import nl.tno.idsa.framework.world.GeometryType;
import nl.tno.idsa.library.models.ModelMoveToOffender;

/**
 * Created by jongsd on 4-8-15.
 */
@SuppressWarnings("unused")

// TODO Doesn't this action inherit from MoveToTarget?

public class MoveToOffender extends Action {

    public MoveToOffender() {
        super(new ModelMoveToOffender(),
                new GroupVariable(),
                new GroupVariable(),
                GeometryType.asSet(GeometryType.POINT),
                ProvidesAgents.NO, AllowsInsertMoveActionBefore.NO);
        setMovesActor(true);
    }

    @Override
    @SuppressWarnings("unchecked") // Generic array.
    protected Class<? extends Action>[] createSemanticSuperclassArray() {
        return null;
    }
}


text:
package com.mgaetan89.showsrage.databinding;

import android.content.Context;
import android.content.res.Resources;
import android.widget.TextView;

import com.mgaetan89.showsrage.R;

import org.junit.Test;

import static org.mockito.Matchers.anyInt;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;

public class Setters_SetTextColorResTest {
	@Test
	public void setTextColorRes() {
		Context context = mock(Context.class);
		when(context.getResources()).thenReturn(mock(Resources.class));

		TextView textView = mock(TextView.class);
		when(textView.getContext()).thenReturn(context);

		Setters.setTextColorRes(textView, R.color.primary);

		verify(textView).setTextColor(anyInt());
	}
}


text:
<?php

namespace WellCommerce\Bundle\AppBundle\Tests\Repository;

use WellCommerce\Bundle\CoreBundle\Test\Repository\AbstractRepositoryTestCase;

/**
 * Class CurrencyRepositoryTest
 *
 * @author  Adam Piotrowski <adam@wellcommerce.org>
 */
class CurrencyRepositoryTest extends AbstractRepositoryTestCase
{
    protected function getAlias()
    {
        return 'currency';
    }

    protected function get()
    {
        return $this->container->get('currency.repository');
    }
}


text:
Skarù·reʔ keyboard
======================

Copyright (C) 2015 First Peoples' Cultural Foundation

Version 9.0

Skarù·reʔ keyboard layout for Unicode

Links
-----

 * Home:     <http://www.fpcf.ca/>
 * Deployed: <http://s.keyman.com/keyboard/fv_skaru_re>
 * Help:     <http://help.keyman.com/keyboard/fv_skaru_re>

Supported Platforms
-------------------

 * Windows
 * Web
 * Mobile


text:
/* global jest, describe, it, expect, beforeEach */

'use strict';

jest.dontMock('../RepoBadgeList');

describe('RepoBadgeList', function() {

	var React, TestUtils, RepoBadgeList, Component;

	beforeEach(function() {
		React = require('react/addons');
	    TestUtils = React.addons.TestUtils;

	    RepoBadgeList = require('../RepoBadgeList');
	    Component = TestUtils.renderIntoDocument(React.createElement(RepoBadgeList, {
	    	gitHubRepo: require.requireActual('../../../models/__mocks__/fakeGitHubRepoList.js').repos[0]
	    }));
	});

	it('has class repo-badge-list', function() {
		var element = TestUtils.findRenderedDOMComponentWithClass(Component, 'repo-badge-list');
	    expect(element).toBeDefined();
	});

	it('can have an alternative style when "altStyle" property is true', function() {
		var AltComponent = TestUtils.renderIntoDocument(React.createElement(RepoBadgeList, {
	    	gitHubRepo: require.requireActual('../../../models/__mocks__/fakeGitHubRepoList.js').repos[0],
	    	altStyle: true
	    }));

		var notAltElement = TestUtils.scryRenderedDOMComponentsWithClass(Component, 'repo-badge-list-alt');
	    expect(notAltElement).toEqual([]);

	    var altElement = TestUtils.findRenderedDOMComponentWithClass(AltComponent, 'repo-badge-list-alt');
	    expect(altElement).toBeDefined();
	});

	it('contains repo-badge elements', function() {
		var elements = TestUtils.scryRenderedDOMComponentsWithClass(Component, 'repo-badge');
	    expect(elements.length).toBeGreaterThan(0);
	});

});


text:
/**
 * @fileoverview Handles a ThemeElements element in a theme document
 */

goog.provide('jsopenxml.theme.ThemeElements');
//----------------------------------------------------------------------------//
//--- Automatically generated to provide intellisense for visual studio, -----//
//--- please do not edit manually. -------------------------------------------//
//----------------------------------------------------------------------------//
window.jsopenxml = window.jsopenxml || {};
window.jsopenxml.theme = window.jsopenxml.theme || {};
//--- intellisense end -------------------------------------------------------//

goog.require('jsopenxml.theme.ClrScheme');
goog.require('jsopenxml.theme.FontScheme');
goog.require('jsopenxml.theme.FmtScheme');

/**
 * @constructor
 * @param {Element} themeElements
 */
jsopenxml.theme.ThemeElements = function (themeElements) {
    this.element = themeElements;

    goog.array.forEach(this.element.childNodes, function (childElement) {
        switch (childElement.nodeName) {
            case "a:clrScheme": this.clrScheme = new jsopenxml.theme.ClrScheme(childElement); break;
            case "a:fontScheme": this.fontScheme = new jsopenxml.theme.FontScheme(childElement); break;
            case "a:fmtScheme": this.fmtScheme = new jsopenxml.theme.FmtScheme(childElement); break;
        }
    }, this);
};

/**
 * Get the clrScheme instance
 * @return {jsopenxml.theme.ClrScheme}
 */
jsopenxml.theme.ThemeElements.prototype.getClrScheme = function () {
    return this.clrScheme;
};

/**
 * Get the fontScheme instance
 * @return {jsopenxml.theme.FontScheme}
 */
jsopenxml.theme.ThemeElements.prototype.getFontScheme = function () {
    return this.fontScheme;
};

/**
 * Get the fmtScheme instance
 * @return {jsopenxml.theme.FmtScheme}
 */
jsopenxml.theme.ThemeElements.prototype.getFmtScheme = function () {
    return this.fmtScheme;
};


text:
package ethanjones.cubes.core.util;

import com.badlogic.gdx.math.RandomXS128;

/**
 * thread random
 */
public class ThreadRandom extends RandomXS128 {

	private static ThreadLocal<ThreadRandom> local = new ThreadLocal<ThreadRandom>() {
		@Override
		protected ThreadRandom initialValue() {
			return new ThreadRandom();
		}
	};

	public static ThreadRandom get() {
		return local.get();
	}
}


text:
package io.github.binout.microjavaee.interfaces.rest;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

@Path("ping")
public class PingResource {

    @GET
    @Produces("image/png")
    public InputStream ping() throws IOException {
        Properties properties = new Properties();
        properties.load(resource("config.properties"));
        return resource(properties.getProperty("name") + ".png");
    }

    private InputStream resource(String name) {
        return Thread.currentThread().getContextClassLoader().getResourceAsStream(name);
    }
}


text:
import os

import properties_user_links_list

TEST_PROPERTY_ID = os.getenv("GA_TEST_PROPERTY_ID")

def test_properties_user_links_list(capsys):
    transports = ["grpc", "rest"]
    for transport in transports:
        properties_user_links_list.list_property_user_links(
            TEST_PROPERTY_ID, transport=transport
        )
        out, _ = capsys.readouterr()
        assert "Result" in out


text:
//>>built
define("dijit/_base/place", [
	"dojo/_base/array", // array.forEach
	"dojo/_base/lang", // lang.isArray
	"dojo/window", // windowUtils.getBox
	"../place",
	".."	// export to dijit namespace
], function(array, lang, windowUtils, place, dijit){

	// module:
	//		dijit/_base/place
	// summary:
	//		Back compatibility module, new code should use dijit/place directly instead of using this module.

	dijit.getViewport = function(){
		// summary:
		//		Deprecated method to return the dimensions and scroll position of the viewable area of a browser window.
		//		New code should use windowUtils.getBox()

		return windowUtils.getBox();
	};

	/*=====
	dijit.placeOnScreen = function(node, pos, corners, padding){
		// summary:
		//		Positions one of the node's corners at specified position
		//		such that node is fully visible in viewport.
		//		Deprecated, new code should use dijit.place.at() instead.
	};
	=====*/
	dijit.placeOnScreen = place.at;

	/*=====
	dijit.placeOnScreenAroundElement = function(node, aroundElement, aroundCorners, layoutNode){
		// summary:
		//		Like dijit.placeOnScreenAroundNode(), except it accepts an arbitrary object
		//		for the "around" argument and finds a proper processor to place a node.
		//		Deprecated, new code should use dijit.place.around() instead.
	};
	====*/
	dijit.placeOnScreenAroundElement = function(node, aroundNode, aroundCorners, layoutNode){
		// Convert old style {"BL": "TL", "BR": "TR"} type argument
		// to style needed by dijit.place code:
		//		[
		// 			{aroundCorner: "BL", corner: "TL" },
		//			{aroundCorner: "BR", corner: "TR" }
		//		]
		var positions;
		if(lang.isArray(aroundCorners)){
			positions = aroundCorners;
		}else{
			positions = [];
			for(var key in aroundCorners){
				positions.push({aroundCorner: key, corner: aroundCorners[key]});
			}
		}

		return place.around(node, aroundNode, positions, true, layoutNode);
	};

	/*=====
	dijit.placeOnScreenAroundNode = function(node, aroundNode, aroundCorners, layoutNode){
		// summary:
		//		Position node adjacent or kitty-corner to aroundNode
		//		such that it's fully visible in viewport.
		//		Deprecated, new code should use dijit.place.around() instead.
	};
	=====*/
	dijit.placeOnScreenAroundNode = dijit.placeOnScreenAroundElement;

	/*=====
	dijit.placeOnScreenAroundRectangle = function(node, aroundRect, aroundCorners, layoutNode){
		// summary:
		//		Like dijit.placeOnScreenAroundNode(), except that the "around"
		//		parameter is an arbitrary rectangle on the screen (x, y, width, height)
		//		instead of a dom node.
		//		Deprecated, new code should use dijit.place.around() instead.
	};
	=====*/
	dijit.placeOnScreenAroundRectangle = dijit.placeOnScreenAroundElement;

	dijit.getPopupAroundAlignment = function(/*Array*/ position, /*Boolean*/ leftToRight){
		// summary:
		//		Deprecated method, unneeded when using dijit/place directly.
		//		Transforms the passed array of preferred positions into a format suitable for
		//		passing as the aroundCorners argument to dijit.placeOnScreenAroundElement.
		//
		// position: String[]
		//		This variable controls the position of the drop down.
		//		It's an array of strings with the following values:
		//
		//			* before: places drop down to the left of the target node/widget, or to the right in
		//			  the case of RTL scripts like Hebrew and Arabic
		//			* after: places drop down to the right of the target node/widget, or to the left in
		//			  the case of RTL scripts like Hebrew and Arabic
		//			* above: drop down goes above target node
		//			* below: drop down goes below target node
		//
		//		The list is positions is tried, in order, until a position is found where the drop down fits
		//		within the viewport.
		//
		// leftToRight: Boolean
		//		Whether the popup will be displaying in leftToRight mode.
		//
		var align = {};
		array.forEach(position, function(pos){
			var ltr = leftToRight;
			switch(pos){
				case "after":
					align[leftToRight ? "BR" : "BL"] = leftToRight ? "BL" : "BR";
					break;
				case "before":
					align[leftToRight ? "BL" : "BR"] = leftToRight ? "BR" : "BL";
					break;
				case "below-alt":
					ltr = !ltr;
					// fall through
				case "below":
					// first try to align left borders, next try to align right borders (or reverse for RTL mode)
					align[ltr ? "BL" : "BR"] = ltr ? "TL" : "TR";
					align[ltr ? "BR" : "BL"] = ltr ? "TR" : "TL";
					break;
				case "above-alt":
					ltr = !ltr;
					// fall through
				case "above":
				default:
					// first try to align left borders, next try to align right borders (or reverse for RTL mode)
					align[ltr ? "TL" : "TR"] = ltr ? "BL" : "BR";
					align[ltr ? "TR" : "TL"] = ltr ? "BR" : "BL";
					break;
			}
		});
		return align;
	};

	return dijit;
});


text:
@class ELLSqlPowerLogAnalyser;

@interface ELLReportSectionModel : NSObject

@property (nonatomic, readonly, strong) ELLSqlPowerLogAnalyser *logAnalyser;
@property (nonatomic, readonly, strong) NSDate *startDate;
@property (nonatomic, readonly, strong) NSDate *endDate;
@property (nonatomic, readonly, assign) BOOL readyToReport;
@property (nonatomic, readonly, strong) NSArray *results;
@property (nonatomic, readonly, strong) NSArray *filteredResults;

- (instancetype)initWithLogAnalyser:(ELLSqlPowerLogAnalyser *)logAnalyser startDate:(NSDate *)startDate endDate:(NSDate *)endDate;
- (void)load;

- (void)filterResults:(NSString *)filterTerm;
- (void)clearFilter;

@end


text:
<?php

namespace Magento\Cms\Test\Unit\Ui\Component\Listing\Column\Cms;

class OptionsTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @var \Magento\Cms\Ui\Component\Listing\Column\Cms\Options
     */
    protected $options;

    /**
     * @var \Magento\Store\Model\System\Store|\PHPUnit_Framework_MockObject_MockObject
     */
    protected $systemStoreMock;

    /**
     * @var \Magento\Store\Model\Website|\PHPUnit_Framework_MockObject_MockObject
     */
    protected $websiteMock;

    /**
     * @var \Magento\Store\Model\Group|\PHPUnit_Framework_MockObject_MockObject
     */
    protected $groupMock;

    /**
     * @var \Magento\Store\Model\Store|\PHPUnit_Framework_MockObject_MockObject
     */
    protected $storeMock;

    /**
     * @var \Magento\Framework\Escaper|\PHPUnit_Framework_MockObject_MockObject
     */
    protected $escaperMock;

    protected function setUp()
    {
        $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this);

        $this->systemStoreMock = $this->getMockBuilder('Magento\Store\Model\System\Store')
            ->disableOriginalConstructor()
            ->getMock();

        $this->websiteMock = $this->getMock(
            'Magento\Store\Model\Website',
            ['getId', 'getName'],
            [],
            '',
            false
        );

        $this->groupMock = $this->getMock('Magento\Store\Model\Group', [], [], '', false);

        $this->storeMock = $this->getMock('Magento\Store\Model\Store', [], [], '', false);

        $this->escaperMock = $this->getMock('Magento\Framework\Escaper', [], [], '', false);

        $this->options = $objectManager->getObject(
            'Magento\Cms\Ui\Component\Listing\Column\Cms\Options',
            [
                'systemStore' => $this->systemStoreMock,
                'escaper' => $this->escaperMock
            ]
        );
    }

    public function testToOptionArray()
    {
        $websiteCollection = [$this->websiteMock];
        $groupCollection = [$this->groupMock];
        $storeCollection = [$this->storeMock];

        $expectedOptions = [
            [
                'label' => __('All Store Views'),
                'value' => '0'
            ],
            [
                'label' => 'Main Website',
                'value' => [
                    [
                        'label' => '    Main Website Store',
                        'value' => [
                            [
                                'label' => '        Default Store View',
                                'value' => '1'
                            ]
                        ]
                    ]
                ]
            ]
        ];

        $this->systemStoreMock->expects($this->once())->method('getWebsiteCollection')->willReturn($websiteCollection);
        $this->systemStoreMock->expects($this->once())->method('getGroupCollection')->willReturn($groupCollection);
        $this->systemStoreMock->expects($this->once())->method('getStoreCollection')->willReturn($storeCollection);

        $this->websiteMock->expects($this->atLeastOnce())->method('getId')->willReturn('1');
        $this->websiteMock->expects($this->any())->method('getName')->willReturn('Main Website');

        $this->groupMock->expects($this->atLeastOnce())->method('getWebsiteId')->willReturn('1');
        $this->groupMock->expects($this->atLeastOnce())->method('getId')->willReturn('1');
        $this->groupMock->expects($this->atLeastOnce())->method('getName')->willReturn('Main Website Store');

        $this->storeMock->expects($this->atLeastOnce())->method('getGroupId')->willReturn('1');
        $this->storeMock->expects($this->atLeastOnce())->method('getName')->willReturn('Default Store View');
        $this->storeMock->expects($this->atLeastOnce())->method('getId')->willReturn('1');

        $this->escaperMock->expects($this->atLeastOnce())->method('escapeHtml')->willReturnMap(
            [
                ['Default Store View', null, 'Default Store View'],
                ['Main Website Store', null, 'Main Website Store'],
                ['Main Website', null, 'Main Website']
            ]
        );

        $this->assertEquals($expectedOptions, $this->options->toOptionArray());
    }
}


text:
function initialize_domTest()
{

InspectorTest.trackGetChildNodesEvents = function(nodeInfo, callback)
{
    InspectorTest.eventHandler["DOM.setChildNodes"] = setChildNodes;

    function setChildNodes(message)
    {
        var nodes = message.params.nodes;
        for (var i = 0; i < nodes.length; ++i)
            InspectorTest.addNode(nodeInfo, nodes[i]);
        if (callback)
            callback();
    }
}

InspectorTest.addNode = function(nodeInfo, node)
{
    nodeInfo[node.nodeId] = node;
    delete node.nodeId;
    var children = node.children || [];
    for (var i = 0; i < children.length; ++i)
        InspectorTest.addNode(nodeInfo, children[i]);
    var shadowRoots = node.shadowRoots || [];
    for (var i = 0; i < shadowRoots.length; ++i)
        InspectorTest.addNode(nodeInfo, shadowRoots[i]);
}

InspectorTest.requestDocumentNodeId = function(callback)
{
    InspectorTest.sendCommandOrDie("DOM.getDocument", {}, onGotDocument);

    function onGotDocument(result)
    {
        callback(result.root.nodeId);
    }
};

InspectorTest.requestNodeId = function(documentNodeId, selector, callback)
{
    InspectorTest.sendCommandOrDie("DOM.querySelector", { "nodeId": documentNodeId , "selector": selector }, onGotNode);

    function onGotNode(result)
    {
        callback(result.nodeId);
    }
};

}


text:
const test = require('ava')
const chalk = require('chalk')
const tester = require('../modules/tester')
const helper = require('../modules/helper')

const name = 'start'
const quiet = true ? '--quiet' : ''

test.serial('local', start(name, quiet, true))
test.serial('remote', start(name, quiet, false))

function start(name, quiet, local) {
  return async t => {

    helper.verboseLogging(!quiet)
    const options = { quiet, local }
    let exitcode = await tester.setupTest(options, name)
    t.is(exitcode, 0) // success

    helper.newline()

    exitcode = await tester.muStart(options, '', '(when mu repo exists already)')
    t.is(exitcode, 126) //cannot execute

    exitcode = await tester.mu([quiet, 'gibberish'])
    t.is(exitcode, 127) //argument not found

    await tester.cleanupTest(local, name)
  }
}


text:
<h3 align="center">

```javascript
            .__                            *
   ____  ____ |  |   _____   ____   ____ _____ @
_/ ___\/  _ \|  |  /     \_/ __ \ /    \\__  \
  \  \__(  <_> )  |_|  Y Y  \  ___/|   |  \/ __ \_
   \___  >____/|____/__|_|  /\___  >___|  (____  /
      \/    GENERATOR    \/     \/     \/     \/
                      @colmena/colmena-generator
```

</h3>

> Proof of Concept: Code Generator for Colmena

## Links

-   [Plop](https://plopjs.com/documentation/) | Generator tool that connects Inquirer prompts and Handlebars templates to support rapid generator development
-   [Inquirer](https://github.com/SBoudrias/Inquirer.js/#objects) | A collection of common interactive command line user interfaces
-   [Handlebars](https://github.com/wycats/handlebars.js/) | Provides the power necessary to let you build semantic templates effectively with no frustration


text:
<?php
namespace Core2\Classes\Table;

use Core2\Classes\Table;

require_once __DIR__ . '/../Table.php';
require_once 'Data/Filter.php';

/**
 *
 */
class Data extends Table {

    /**
     * @return array
     */
    public function fetchData(): array {

        if ( ! $this->is_fetched && ! empty($this->data) && is_array($this->data)) {
            $this->is_fetched = true;

            $filter = new Data\Filter();

            $this->records_total = count($this->data);

            if ( ! empty($this->search_controls) && ! empty($this->session->table->search)) {
                $this->data = $filter->searchData($this->data, $this->search_controls, $this->session->table->search);
            }

            if (isset($this->session->table->order) &&
                $this->session->table->order &&
                isset($this->columns[$this->session->table->order - 1])
            ) {
                $column = $this->columns[$this->session->table->order - 1];

                if ($column instanceof Column && $column->isSorting()) {
                    $order_field = $column->getField();

                    $first_row = current($this->data);

                    if (isset($first_row[$order_field])) {
                        $this->data = $filter->orderData($this->data, $order_field, $this->session->table->order_type);
                    }
                }
            }

            $this->records_total = count($this->data);

            if ($this->records_total > (($this->current_page - 1) * $this->records_per_page) - $this->records_per_page) {
                $data_result = $filter->pageData($this->data, $this->records_per_page, $this->current_page);

                if ( ! empty($data_result)) {
                    foreach ($data_result as $key => $row) {
                        $this->data_rows[] = new Row($row);
                    }
                }

            } else {
                $this->data_rows = [];
            }
        }

        return $this->data_rows;
    }
}