text:
namespace google {
namespace protobuf {

using internal::WireFormat;
using internal::ReflectionOps;

Message::~Message() {}

void Message::MergeFrom(const Message& from) {
  const Descriptor* descriptor = GetDescriptor();
  GOOGLE_CHECK_EQ(from.GetDescriptor(), descriptor)
    << ": Tried to merge from a message with a different type.  "
       "to: " << descriptor->full_name() << ", "
       "from:" << from.GetDescriptor()->full_name();
  ReflectionOps::Merge(from, this);
}

void Message::CheckTypeAndMergeFrom(const MessageLite& other) {
  MergeFrom(*down_cast<const Message*>(&other));
}

void Message::CopyFrom(const Message& from) {
  const Descriptor* descriptor = GetDescriptor();
  GOOGLE_CHECK_EQ(from.GetDescriptor(), descriptor)
    << ": Tried to copy from a message with a different type."
       "to: " << descriptor->full_name() << ", "
       "from:" << from.GetDescriptor()->full_name();
  ReflectionOps::Copy(from, this);
}

int Message::Compare(const Message& other) const {
  const Descriptor* descriptor = GetDescriptor();
  GOOGLE_CHECK_EQ(other.GetDescriptor(), descriptor)
    << ": Tried to compare a message with a different type.  "
       "a: " << descriptor->full_name() << ", "
       "b:" << other.GetDescriptor()->full_name();
  return ReflectionOps::Compare(*this, other);
}

int Message::CheckTypeAndCompare(const MessageLite& other) const {
  return Compare(*down_cast<const Message*>(&other));
}

void Message::SortFields() {
  ReflectionOps::SortFields(this);
}

string Message::GetTypeName() const {
  return GetDescriptor()->full_name();
}

void Message::Clear() {
  ReflectionOps::Clear(this);
}

bool Message::IsInitialized() const {
  return ReflectionOps::IsInitialized(*this);
}

void Message::FindInitializationErrors(vector<string>* errors) const {
  return ReflectionOps::FindInitializationErrors(*this, "", errors);
}

string Message::InitializationErrorString() const {
  vector<string> errors;
  FindInitializationErrors(&errors);
  return JoinStrings(errors, ", ");
}

void Message::CheckInitialized() const {
  GOOGLE_CHECK(IsInitialized())
    << "Message of type \"" << GetDescriptor()->full_name()
    << "\" is missing required fields: " << InitializationErrorString();
}

void Message::DiscardUnknownFields() {
  return ReflectionOps::DiscardUnknownFields(this);
}

bool Message::MergePartialFromCodedStream(io::CodedInputStream* input) {
  return WireFormat::ParseAndMergePartial(input, this);
}

bool Message::ParseFromFileDescriptor(int file_descriptor) {
  io::FileInputStream input(file_descriptor);
  return ParseFromZeroCopyStream(&input) && input.GetErrno() == 0;
}

bool Message::ParsePartialFromFileDescriptor(int file_descriptor) {
  io::FileInputStream input(file_descriptor);
  return ParsePartialFromZeroCopyStream(&input) && input.GetErrno() == 0;
}

bool Message::ParseFromIstream(istream* input) {
  io::IstreamInputStream zero_copy_input(input);
  return ParseFromZeroCopyStream(&zero_copy_input) && input->eof();
}

bool Message::ParsePartialFromIstream(istream* input) {
  io::IstreamInputStream zero_copy_input(input);
  return ParsePartialFromZeroCopyStream(&zero_copy_input) && input->eof();
}

void Message::SerializeWithCachedSizes(
    io::CodedOutputStream* output) const {
  WireFormat::SerializeWithCachedSizes(*this, GetCachedSize(), output);
}

int Message::ByteSize() const {
  int size = WireFormat::ByteSize(*this);
  SetCachedSize(size);
  return size;
}

void Message::SetCachedSize(int size) const {
  GOOGLE_LOG(FATAL) << "Message class \"" << GetDescriptor()->full_name()
             << "\" implements neither SetCachedSize() nor ByteSize().  "
                "Must implement one or the other.";
}

int Message::SpaceUsed() const {
  return GetReflection()->SpaceUsed(*this);
}

bool Message::SerializeToFileDescriptor(int file_descriptor) const {
  io::FileOutputStream output(file_descriptor);
  return SerializeToZeroCopyStream(&output);
}

bool Message::SerializePartialToFileDescriptor(int file_descriptor) const {
  io::FileOutputStream output(file_descriptor);
  return SerializePartialToZeroCopyStream(&output);
}

bool Message::SerializeToOstream(ostream* output) const {
  {
    io::OstreamOutputStream zero_copy_output(output);
    if (!SerializeToZeroCopyStream(&zero_copy_output)) return false;
  }
  return output->good();
}

bool Message::SerializePartialToOstream(ostream* output) const {
  io::OstreamOutputStream zero_copy_output(output);
  return SerializePartialToZeroCopyStream(&zero_copy_output);
}

// =============================================================================
// Reflection and associated Template Specializations

Reflection::~Reflection() {}

#define HANDLE_TYPE(TYPE, CPPTYPE, CTYPE)                             \
template<>                                                            \
const RepeatedField<TYPE>& Reflection::GetRepeatedField<TYPE>(        \
    const Message& message, const FieldDescriptor* field) const {     \
  return *static_cast<RepeatedField<TYPE>* >(                         \
      MutableRawRepeatedField(const_cast<Message*>(&message),         \
                          field, CPPTYPE, CTYPE, NULL));              \
}                                                                     \
                                                                      \
template<>                                                            \
RepeatedField<TYPE>* Reflection::MutableRepeatedField<TYPE>(          \
    Message* message, const FieldDescriptor* field) const {           \
  return static_cast<RepeatedField<TYPE>* >(                          \
      MutableRawRepeatedField(message, field, CPPTYPE, CTYPE, NULL)); \
}

HANDLE_TYPE(int32,  FieldDescriptor::CPPTYPE_INT32,  -1);
HANDLE_TYPE(int64,  FieldDescriptor::CPPTYPE_INT64,  -1);
HANDLE_TYPE(uint32, FieldDescriptor::CPPTYPE_UINT32, -1);
HANDLE_TYPE(uint64, FieldDescriptor::CPPTYPE_UINT64, -1);
HANDLE_TYPE(float,  FieldDescriptor::CPPTYPE_FLOAT,  -1);
HANDLE_TYPE(double, FieldDescriptor::CPPTYPE_DOUBLE, -1);
HANDLE_TYPE(bool,   FieldDescriptor::CPPTYPE_BOOL,   -1);

#undef HANDLE_TYPE

void* Reflection::MutableRawRepeatedString(
    Message* message, const FieldDescriptor* field, bool is_string) const {
  return MutableRawRepeatedField(message, field,
      FieldDescriptor::CPPTYPE_STRING, FieldOptions::STRING, NULL);
}

// =============================================================================
// MessageFactory

MessageFactory::~MessageFactory() {}

namespace {

class GeneratedMessageFactory : public MessageFactory {
 public:
  GeneratedMessageFactory();
  ~GeneratedMessageFactory();

  static GeneratedMessageFactory* singleton();

  typedef void RegistrationFunc(const string&);
  void RegisterFile(const char* file, RegistrationFunc* registration_func);
  void RegisterType(const Descriptor* descriptor, const Message* prototype);

  // implements MessageFactory ---------------------------------------
  const Message* GetPrototype(const Descriptor* type);

 private:
  // Only written at static init time, so does not require locking.
  hash_map<const char*, RegistrationFunc*,
           hash<const char*>, streq> file_map_;

  // Initialized lazily, so requires locking.
  Mutex mutex_;
  hash_map<const Descriptor*, const Message*> type_map_;
};

GeneratedMessageFactory* generated_message_factory_ = NULL;
GOOGLE_PROTOBUF_DECLARE_ONCE(generated_message_factory_once_init_);

void ShutdownGeneratedMessageFactory() {
  delete generated_message_factory_;
}

void InitGeneratedMessageFactory() {
  generated_message_factory_ = new GeneratedMessageFactory;
  internal::OnShutdown(&ShutdownGeneratedMessageFactory);
}

GeneratedMessageFactory::GeneratedMessageFactory() {}
GeneratedMessageFactory::~GeneratedMessageFactory() {}

GeneratedMessageFactory* GeneratedMessageFactory::singleton() {
  ::google::protobuf::GoogleOnceInit(&generated_message_factory_once_init_,
                 &InitGeneratedMessageFactory);
  return generated_message_factory_;
}

void GeneratedMessageFactory::RegisterFile(
    const char* file, RegistrationFunc* registration_func) {
  if (!InsertIfNotPresent(&file_map_, file, registration_func)) {
    GOOGLE_LOG(FATAL) << "File is already registered: " << file;
  }
}

void GeneratedMessageFactory::RegisterType(const Descriptor* descriptor,
                                           const Message* prototype) {
  GOOGLE_DCHECK_EQ(descriptor->file()->pool(), DescriptorPool::generated_pool())
    << "Tried to register a non-generated type with the generated "
       "type registry.";

  // This should only be called as a result of calling a file registration
  // function during GetPrototype(), in which case we already have locked
  // the mutex.
  mutex_.AssertHeld();
  if (!InsertIfNotPresent(&type_map_, descriptor, prototype)) {
    GOOGLE_LOG(DFATAL) << "Type is already registered: " << descriptor->full_name();
  }
}

const Message* GeneratedMessageFactory::GetPrototype(const Descriptor* type) {
  {
    ReaderMutexLock lock(&mutex_);
    const Message* result = FindPtrOrNull(type_map_, type);
    if (result != NULL) return result;
  }

  // If the type is not in the generated pool, then we can't possibly handle
  // it.
  if (type->file()->pool() != DescriptorPool::generated_pool()) return NULL;

  // Apparently the file hasn't been registered yet.  Let's do that now.
  RegistrationFunc* registration_func =
      FindPtrOrNull(file_map_, type->file()->name().c_str());
  if (registration_func == NULL) {
    GOOGLE_LOG(DFATAL) << "File appears to be in generated pool but wasn't "
                   "registered: " << type->file()->name();
    return NULL;
  }

  WriterMutexLock lock(&mutex_);

  // Check if another thread preempted us.
  const Message* result = FindPtrOrNull(type_map_, type);
  if (result == NULL) {
    // Nope.  OK, register everything.
    registration_func(type->file()->name());
    // Should be here now.
    result = FindPtrOrNull(type_map_, type);
  }

  if (result == NULL) {
    GOOGLE_LOG(DFATAL) << "Type appears to be in generated pool but wasn't "
                << "registered: " << type->full_name();
  }

  return result;
}

}  // namespace

MessageFactory* MessageFactory::generated_factory() {
  return GeneratedMessageFactory::singleton();
}

void MessageFactory::InternalRegisterGeneratedFile(
    const char* filename, void (*register_messages)(const string&)) {
  GeneratedMessageFactory::singleton()->RegisterFile(filename,
                                                     register_messages);
}

void MessageFactory::InternalRegisterGeneratedMessage(
    const Descriptor* descriptor, const Message* prototype) {
  GeneratedMessageFactory::singleton()->RegisterType(descriptor, prototype);
}

}  // namespace protobuf
}  // namespace google


text:
//  Page-level vars
var by;
var is_licensed_under;
var derivative_text;
var commaproject;
var commaOrganization;

function unHighlight() {
    titleOutput.removeAttribute("class");
    authorOutput.removeAttribute("class");
    lincenseOutput.removeAttribute("class");
    derivativeOutput.removeAttribute("class");
    organizationOutput.removeAttribute("class");
    projectOutput.removeAttribute("class");
}

function SelectAll(id) {
    var output_html = document.getElementById(id);
    output_html.focus();
    output_html.select();
}

function SelectText(element) {
    var doc = document;
    var text = doc.getElementById(element);
    if (doc.body.createTextRange) { // ms
        var range = doc.body.createTextRange();
        range.moveToElementText(text);
        range.select();
    } else if (window.getSelection) {
        var selection = window.getSelection();
        var range = doc.createRange();
        range.selectNodeContents(text);
        selection.removeAllRanges();
        selection.addRange(range);
    }
}

function isValidURL(id) {
    // Check for scheme and that no spaces or dbl quotes are present
    // Add "http://" if no prefix supplied at all
    // Allow scheme-independent URLs
    var re = /^((ftp:|http:|https:)?\/\/)?[^ "]+$/;
    if (re.test(id.value))
    {
        re = /^(ftp:|http:|https:)?\/\//;
        if(!re.test(id.value)) {
            id.value = "http://" + id.value;
        }
        return true;
     }
     else
         return false
}

function onloadform()
                    {
    var AtributionForm = document.getElementById("AtributionForm");
    AtributionForm.reset();
    titleOutput = document.createElement('a');
    authorOutput = document.createElement('a');
    lincenseOutput = document.createElement('a');
    derivativeOutput = document.createElement('a');
    organizationOutput = document.createElement('a');
    projectOutput = document.createElement('a');
    by = document.createTextNode("");
    commaproject = document.createTextNode("");
    commaOrganization = document.createTextNode("");
    is_licensed_under = document.createTextNode("");
    derivative_text = document.createTextNode("");

    output.innerHTML = "";
    output.appendChild(titleOutput);
    output.appendChild(by);
    output.appendChild(authorOutput);
    output.appendChild(commaproject);
    output.appendChild(projectOutput);
    output.appendChild(commaOrganization);
    output.appendChild(organizationOutput);
    output.appendChild(is_licensed_under);
    output.appendChild(lincenseOutput);
    output.appendChild(derivative_text);
    output.appendChild(derivativeOutput);
    output.style.display = 'none';
}

function onchangevalue(item) {
    unHighlight();
    $('#output').show();

    if (titleOutput.innerHTML == "")
        titleOutput.innerHTML = '"' + "This work" + '"'; // INNER_TEXT
    if (item.id == "titleTextBox") {
        titleOutput.setAttribute("class", "highlight");
        titleOutput.innerHTML = '"' + item.value + '"'; // INNER_TEXT
    }
    if (item.id == "authornameTextBox") {

        if (organizationOutput.innerHTML != "")
            commaOrganization.nodeValue = ", ";
        if (projectOutput.innerHTML != "")
            commaproject.nodeValue = ", ";
        by.nodeValue = " by ";
        authorOutput.setAttribute("class", "highlight");
        authorOutput.innerHTML = item.value; // INNER_TEXT
    }
    if (item.id == "OrganizationTextBox") {
        if (authorOutput.innerHTML != "" || projectOutput.innerHTML != "")
            commaOrganization.nodeValue = ", ";
        else
            commaOrganization.nodeValue = "";
        by.nodeValue = " by ";
        organizationOutput.setAttribute("class", "highlight");
        organizationOutput.innerHTML = item.value; // INNER_TEXT
    }
    if (item.id == "ProjectTextBox") {

        if (authorOutput.innerHTML != "")
            commaproject.nodeValue = ", ";
        else
            commaproject.nodeValue = "";

        if (organizationOutput.innerHTML != "")
            commaOrganization.nodeValue = ", ";
        else
            commaOrganization.nodeValue = "";

        by.nodeValue = " by ";
        projectOutput.setAttribute("class", "highlight");
        projectOutput.innerHTML = item.value; // INNER_TEXT
    }

}

function changeTitle()
{
    unHighlight();
    var title = document.getElementById("titleTextBox");
    var titleURL = document.getElementById("titleURLTextBox");
    //  titleOutput = document.createElement('a');
    if (title.value.length > 0)
    {
        titleOutput.innerHTML = '"' + title.value + '"'; // INNER_TEXT
    }
    else
        titleOutput.innerHTML = '"' + "This work" + '"';
    if (isValidURL(titleURL) && titleURL.value.length > 0) {
            $('#ItemUrlPrompt').hide();
            titleOutput.href = titleURL.value; // Instead of calling setAttribute
            titleOutput.target = '_blank';
        }
        else {
            if(titleURL.value.length > 0) $('#ItemUrlPrompt').show();
            titleOutput.removeAttribute("href");
            titleOutput.removeAttribute("target");
            titleURL.focus();
            titleURL.select();
        }
}

function changeAuthor()
{
    unHighlight();
    var authorName = document.getElementById("authornameTextBox");
    var authorURL = document.getElementById("authorURLTextBox");
    if (authorName.value.length > 0)
    {
        authorOutput.innerHTML = authorName.value; // INNER_TEXT
        if (organizationOutput.innerHTML != "")
                commaOrganization.nodeValue = ", ";
        if (projectOutput.innerHTML != "")
            commaproject.nodeValue = ", ";
        // INNER_TEXT
        if (isValidURL(authorURL) && authorURL.value.length > 0) {
            $('#AuthorUrlPrompt').hide();
            authorOutput.href = authorURL.value; // Insted of calling setAttribute
            authorOutput.target = '_blank';
        }
        else {
            if(authorURL.value.length > 0) $('#AuthorUrlPrompt').show();
            authorOutput.removeAttribute("href");
            authorOutput.removeAttribute("target");
            authorURL.focus();
            authorURL.select();
        }
        by.nodeValue = " by ";
    }
    else {
        by.nodeValue = "";
        authorOutput.innerHTML = "";
        authorOutput.removeAttribute("href");
        authorOutput.removeAttribute("target");
    }
}

function changeLicense()
{
    unHighlight();
    window.getSelection().removeAllRanges();  // clear any text selection on page - usually text attribution

    var license = document.getElementById("LicenseListBox");
    var version = document.getElementById("VersionDropDown");
    LicenceIndex = license.options[license.selectedIndex].index;
     var versionValue = version.options[version.selectedIndex].value;
    if (LicenceIndex < 7 && LicenceIndex != 0)
        version.disabled = false;
    else {
        version.disabled = true;
        version.selectedIndex = 0;
    }

    var LicenseSelected = license.options[license.selectedIndex].value;
    if (LicenceIndex != 0)
    {
        if (version.disabled == true)
            versionValue = "";
        is_licensed_under.nodeValue = " is licensed under "
        var addURL = LicenseSelected.substring(3, LicenseSelected.length) + "/" + versionValue;
        var LicenseURL = "http://creativecommons.org/licenses/" + addURL.toLocaleLowerCase();
        if (LicenceIndex == 7)
        {
            is_licensed_under.nodeValue = " is in the "
            LicenseURL = "https://wiki.creativecommons.org/Public_domain";
        }
        if (LicenceIndex == 8)
        {
            is_licensed_under.nodeValue = " is in the "
            LicenseURL = "http://creativecommons.org/publicdomain/zero/1.0/";
        }

        lincenseOutput.href = LicenseURL; // Insted of calling setAttribute
        lincenseOutput.target = '_blank';
        lincenseOutput.innerHTML = (license.options[license.selectedIndex].value + " " + versionValue).trim();

    }
    else
    {
        lincenseOutput.removeAttribute("href");
        lincenseOutput.removeAttribute("target");// Insted of calling setAttribute
        lincenseOutput.innerHTML = "";
    }
}

function changeDerivative()
{
    unHighlight();
    var derivative = document.getElementById("DerivativeCheckBox");
    var derivativeURL = document.getElementById("DerivativeTextBox");
    if (derivative.checked)
        derivativeURL.disabled = false;
    else {
        derivativeURL.value = "";
        derivativeURL.disabled = true;
    }

    if (derivative.checked)
    {
                if (derivativeURL.value.length > 0 && isValidURL(derivativeURL)) {
                    $('#DerivUrlPrompt').hide();
                    derivativeOutput.href = derivativeURL.value; // Insted of calling setAttribute
                    derivativeOutput.target = '_blank';
                    derivativeOutput.innerHTML = "original work"; // INNER_TEXT
                    derivative_text.nodeValue = " / A derivative from the ";
                }
        else {
                    $('#DerivUrlPrompt').show();
                    derivativeOutput.removeAttribute("href");
                    derivativeOutput.removeAttribute("target");
                    derivativeOutput.innerHTML = "";
                    derivative_text.nodeValue = "";
                    derivativeURL.focus();
                    derivativeURL.select();
                }
    }
    else
    {
        derivativeOutput.removeAttribute("href");
        derivativeOutput.removeAttribute("target");
        derivativeOutput.innerHTML = "";
        derivative_text.nodeValue = "";
    }
}

function changeProject()
{
    unHighlight();
    var ProjectName = document.getElementById("ProjectTextBox");
    var ProjectURL = document.getElementById("ProjectURLTextBox");
    if (ProjectName.value.length > 0) {
        if (authorOutput.innerHTML != "")
            commaproject.nodeValue = ", ";
        else
            commaproject.nodeValue = "";

        if (organizationOutput.innerHTML != "")
            commaOrganization.nodeValue = ", ";
        else
            commaOrganization.nodeValue = "";

        projectOutput.innerHTML = ProjectName.value; // INNER_TEXT
        // INNER_TEXT
        if (isValidURL(ProjectURL) && ProjectURL.value.length > 0) {
            $('#ProjectUrlPrompt').hide();
            projectOutput.href = ProjectURL.value; // Insted of calling setAttribute
            projectOutput.target = '_blank';
        }
        else {
            if (ProjectURL.value.length > 0) $('#ProjectUrlPrompt').show();
            projectOutput.removeAttribute("href");
            projectOutput.removeAttribute("target");
            ProjectURL.focus();
            ProjectURL.select();
        }
    }
    else {
        commaproject.nodeValue = "";
        projectOutput.innerHTML = "";
        projectOutput.removeAttribute("href");
        projectOutput.removeAttribute("target");
    }
}

function changeOrganization() {
    unHighlight();
    var OrganizationName = document.getElementById("OrganizationTextBox");
    var OrganizationURL = document.getElementById("OrganizationURLTextBox");
    if (OrganizationName.value.length > 0) {
        if (authorOutput.innerHTML != "" || projectOutput.innerHTML != "")
            commaOrganization.nodeValue = ", ";
        else
            commaOrganization.nodeValue = "";
        organizationOutput.innerHTML = OrganizationName.value; // INNER_TEXT
        // INNER_TEXT
        if (isValidURL(OrganizationURL) && OrganizationURL.value.length > 0) {
            $('#OrgUrlPrompt').hide();
            organizationOutput.href = OrganizationURL.value; // Insted of calling setAttribute
            organizationOutput.target = '_blank';
        }
        else {
            if (OrganizationURL.value.length > 0) $('#OrgUrlPrompt').show();
            organizationOutput.removeAttribute("href");
            organizationOutput.removeAttribute("target");
            OrganizationURL.focus();
            OrganizationURL.select();
        }
    }
    else {
        commaOrganization.nodeValue = "";
        organizationOutput.innerHTML = "";
        organizationOutput.removeAttribute("href");
        organizationOutput.removeAttribute("target");
    }
}

function checkInput(form)
{
    handleLicensePrompt();

    var title = document.getElementById("titleTextBox");
    if (title.value.length == 0)
    {
        titleOutput.innerHTML = '"' + "This work" + '"'; // INNER_TEXT
    }
    var output_html = document.getElementById("output-html");
    var outputappend = output.innerHTML.replace(" class=" + '"' + "highlight" + '"', "");
    var find = "";
    var re = new RegExp(find, 'g');
    outputappend = outputappend.replace(re, '');
    output_html.value = outputappend;
}

function handleLicensePrompt() {
    if ($("#LicenseListBox")[0].selectedIndex == 0) {
        // No license selected
        $('#LicensePrompt').show();
    }
    else {
        // hide prompt
        $('#LicensePrompt').hide();
    }
}

// initial page setup
$(document).ready(function () {
    // hide all hide class containers
    $('#collapsible-panels .hide').hide();
    $('.popup').hide();

    // append click event to the a element
    $('#collapsible-panels .collapsecontent').on('click', function (e) {
        // slide down the corresponding div if hidden, or slide up if shown
        //  alert($(this).parent().attr('id'));

        // TODO: Need to base this on IDs - currently depends on a specific level of divs
        $(this).parent().closest('div').next('#collapsible-panels .hide').slideToggle('slow');
        // set the current item as active
        $(this).toggleClass('active');
        e.preventDefault();
    });

    var counter = 0;
    var temp_id=null;
    $('.tooltip_display').click(function () {
        var $this = $(this);
        var id_value = $(this).attr('id');
        if (temp_id != id_value)
            $('.closeButton').click();
        temp_id = id_value;
        $.ajax({
            type: "GET",
            url: "helpdata.xml",
            dataType: "xml",
            success: function (xml) {
                $(xml).find('Header').each(function () {
                    var id = $(this).attr('id');
                    var title = $(this).find('content').text();
                    if (id == id_value) {
                        counter = counter + 1;
                        $('#' + id_value + '_popup').html(title);
                    }
                });
            }
        });
        if (counter % 2 == 0)
        $('#popup_' + id_value).html(function ()
            {
            $('#popup_' + id_value).css({
                    left: $this.position() + '20px',
                    top: $this.position() + '20px'
                }).show(500)
            }).fadeIn("slow");
        else {
            var container = $('.popup');
            container.hide(500);
            container.fadeOut("slow");
        }
    });

    $('.closeButton').click(function () {
        var container = $('.popup');
        counter = 0;
        container.hide(500);
        container.fadeOut("slow");
    });

});

redpajama_set_name: RedPajamaGithub


text:
import { CreditCardIcon, Flex, Text } from "@artsy/palette"

interface Props {
  brand: string
  lastDigits: string
  expirationMonth: number
  expirationYear: number
  textColor?: string
}

export const CreditCardDetails = (props: Props) => {
  const {
    lastDigits,
    expirationMonth,
    expirationYear,
    brand,
    textColor = "black100",
  } = props

  return (
    <Flex alignItems="center">
      <CreditCardIcon mr={1} type={brand} width="25px" />
      <Text
        variant="sm-display"
        color={textColor}
        style={{ position: "relative", top: "1px" }}
      >
        •••• {lastDigits}
           Exp {expirationMonth.toString().padStart(2, "0")}/
        {expirationYear.toString().slice(-2)}
      </Text>
    </Flex>
  )
}


text:
SYNONYM

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Grevillea 14(no. 69): 11 (1885)

#### Original name
Fomes pyrrhocreas Cooke, 1885

### Remarks
null


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace TelegramBot.Models
{
    public class MessageEntity
    {
        public string type { get; set; }
        public long offset { get; set; }
        public long lenght { get; set; }
        public string url { get; set; }
        public User user { get; set; }
    }
}


text:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
×Ö·û±àÂë ---
<script>
	document.write((document.charset || document.characterSet).toUpperCase());
</script>
</body>
</html>


text:
package com.ch.exception;

import javax.ws.rs.WebApplicationException;

/**
 * Created by Aaron.Witter on 02/08/2016.
 */
public class PresenterAuthenticationException extends WebApplicationException {

  private final String id;
  private final String auth;

  public PresenterAuthenticationException(String id, String auth) {
    this.id = id;
    this.auth = auth;
  }

  @Override
  public String getMessage() {
    return String.format("Error authenticating the presenter using the given credentials: id: %s, auth: %s",
        id, auth);
  }
}


text:
package com.vaadin.tests.server.component.absolutelayout;

import static org.junit.Assert.assertEquals;

import org.junit.Test;

import com.vaadin.ui.AbsoluteLayout;
import com.vaadin.ui.Button;

/**
 * Tests adding of components to {@link AbsoluteLayout}
 *
 * @since
 * @author Vaadin Ltd
 */
public class AddComponentsTest {

    @Test
    public void testAddExistingWithDifferentPosition() {
        AbsoluteLayout layout = new AbsoluteLayout();
        Button b1 = new Button("OK");
        layout.addComponent(b1, "top: 100px; left: 0px;");
        assertEquals(1, layout.getComponentCount());
        layout.addComponent(b1, "bottom: 0px; right: 0px;");
        assertEquals(1, layout.getComponentCount());
    }

}


text:
package com.google.devtools.j2objc.translate;

import com.google.devtools.j2objc.GenerationTest;
import com.google.devtools.j2objc.ast.Statement;

import java.io.IOException;
import java.util.List;

/**
 * Unit tests for {@link JavaToIOSMethodTranslatorTest}.
 *
 * @author Tom Ball
 */
public class JavaToIOSMethodTranslatorTest extends GenerationTest {

  public void testCopyCloneRenaming() throws IOException {
    String translation = translateSourceFile(
        "public class Example implements Cloneable { "
        + "int i;"
        + "public Example copy() { return (Example) clone(); }"
        + "public Object clone() { "
        + "  try { Example e = (Example) super.clone(); e.i = i; return e; } "
        + "  catch (CloneNotSupportedException e) { return null; }}}",
        "Example", "Example.h");
    assertTranslation(translation, "- (Example *)copy__ OBJC_METHOD_FAMILY_NONE;");
    translation = getTranslatedFile("Example.m");
    assertTranslation(translation,
        "return (Example *) check_class_cast([self clone], [Example class]);");
    assertTranslation(translation, "- (id)copyWithZone:(NSZone *)zone {");
    assertTranslation(translation,
        "Example *e = (Example *) check_class_cast([super clone], [Example class]);");
    assertTranslation(translation, "((Example *) nil_chk(e))->i_ = i_");
  }

  public void testStringValueOfBoolean() throws IOException {
    String source =
        "String trueString = String.valueOf(true); String falseString = String.valueOf(false);";
    List<Statement> stmts = translateStatements(source);
    assertEquals(2, stmts.size());
    String result = generateStatement(stmts.get(0));
    assertEquals("NSString *trueString = [NSString valueOfBool:YES];", result);
    result = generateStatement(stmts.get(1));
    assertEquals("NSString *falseString = [NSString valueOfBool:NO];", result);
  }

  /**
   * Verify that statements within a translated method get translated, too.
   */
  public void testMethodAndStatementTranslation() throws IOException {
    String translation = translateSourceFile(
        "class Test { public String toString(boolean value) { return String.valueOf(value); } }",
        "Test", "Test.m");
    assertTranslatedLines(translation,
        "- (NSString *)toStringWithBoolean:(jboolean)value {",
        "return [NSString valueOfBool:value];");
  }

  public void testStringDefaultConstructor() throws IOException {
    String source = "String s = new String();";
    List<Statement> stmts = translateStatements(source);
    assertEquals(1, stmts.size());
    String result = generateStatement(stmts.get(0));
    assertEquals("NSString *s = [NSString string];", result);
  }

  public void testStringConstructorWithString() throws IOException {
    String source = "String s = new String(\"test\");";
    List<Statement> stmts = translateStatements(source);
    assertEquals(1, stmts.size());
    String result = generateStatement(stmts.get(0));
    assertEquals("NSString *s = @\"test\";", result);
  }

  public void testStringHashCode() throws IOException {
    String source = "int test = \"foo\".hashCode();";
    List<Statement> stmts = translateStatements(source);
    assertEquals(1, stmts.size());
    String result = generateStatement(stmts.get(0));
    assertEquals("jint test = ((jint) [@\"foo\" hash]);", result);
  }

  public void testClassGetSuperclass() throws IOException {
    String source = "Class cls = getClass(); Class superClass = cls.getSuperclass();";
    List<Statement> stmts = translateStatements(source);
    assertEquals(2, stmts.size());
    String result = generateStatement(stmts.get(0));
    assertEquals("IOSClass *cls = [self getClass];", result);
    result = generateStatement(stmts.get(1));
    assertEquals("IOSClass *superClass = [cls getSuperclass];", result);
  }

  /**
   * Verify that Class.getName() and Class.getSimpleName() return the
   * Obj-C class name.  They are the same because Obj-C has a flat class
   * namespace.
   */
  public void testClassGetName() throws IOException {
    String source = "Class cls = getClass(); String s1 = cls.getName();"
        + "String s2 = cls.getSimpleName(); String s3 = cls.getCanonicalName();";
    List<Statement> stmts = translateStatements(source);
    assertEquals(4, stmts.size());
    String result = generateStatement(stmts.get(1));
    assertEquals("NSString *s1 = [cls getName];", result);
    result = generateStatement(stmts.get(2));
    assertEquals("NSString *s2 = [cls getSimpleName];", result);
    result = generateStatement(stmts.get(3));
    assertEquals("NSString *s3 = [cls getCanonicalName];", result);
  }

  public void testStringSubstring() throws IOException {
    String source = "String s1 = \"123456\"; String s2 = s1.substring(2); "
        + "String s3 = s1.substring(2, 4);";
    List<Statement> stmts = translateStatements(source);
    assertEquals(3, stmts.size());
    String result = generateStatement(stmts.get(1));
    assertEquals("NSString *s2 = [s1 substring:2];", result);
    result = generateStatement(stmts.get(2));
    assertEquals("NSString *s3 = [s1 substring:2 endIndex:4];", result);
  }

  public void testStringIndexOf() throws IOException {
    String source = "String s = \"'twas brillig, and the slithy toves\";"
        + "int idx = s.indexOf('g'); idx = s.indexOf(\"brillig\");"
        + "idx = s.lastIndexOf('v'); idx = s.lastIndexOf(\"the\");"
        + "idx = s.indexOf('g', 1); idx = s.indexOf(\"brillig\", 2);"
        + "idx = s.lastIndexOf('v', 3); idx = s.lastIndexOf(\"the\", 4);";
    List<Statement> stmts = translateStatements(source);
    assertEquals(9, stmts.size());
    String result = generateStatement(stmts.get(1));
    assertEquals("jint idx = [s indexOf:'g'];", result);
    result = generateStatement(stmts.get(2));
    assertEquals("idx = [s indexOfString:@\"brillig\"];", result);
    result = generateStatement(stmts.get(3));
    assertEquals("idx = [s lastIndexOf:'v'];", result);
    result = generateStatement(stmts.get(4));
    assertEquals("idx = [s lastIndexOfString:@\"the\"];", result);
    result = generateStatement(stmts.get(5));
    assertEquals("idx = [s indexOf:'g' fromIndex:1];", result);
    result = generateStatement(stmts.get(6));
    assertEquals("idx = [s indexOfString:@\"brillig\" fromIndex:2];", result);
    result = generateStatement(stmts.get(7));
    assertEquals("idx = [s lastIndexOf:'v' fromIndex:3];", result);
    result = generateStatement(stmts.get(8));
    assertEquals("idx = [s lastIndexOfString:@\"the\" fromIndex:4];", result);
  }

  public void testStringToCharArray() throws IOException {
    String source = "String s = \"123456\"; char[] array = s.toCharArray();";
    List<Statement> stmts = translateStatements(source);
    assertEquals(2, stmts.size());
    String result = generateStatement(stmts.get(1));
    assertEquals("IOSCharArray *array = [s toCharArray];", result);
  }

  public void testNewInstanceMapping() throws IOException {
    String source = "try { Class<?> clazz = Object.class; "
        + "Object o = clazz.newInstance(); } catch (Exception e) {}";
    List<Statement> stmts = translateStatements(source);
    assertEquals(1, stmts.size());
    String result = generateStatement(stmts.get(0));
    assertTranslation(result, "[clazz newInstance]");
  }

  // Verify that a method named cloned in a class that doesn't
  // implement Cloneable is unchanged.
  public void testNonCloneableClone() throws IOException {
    String translation = translateSourceFile(
        "public class Example { "
        + "String s; "
        + "public Object clone() { "
        + "  Example e = new Example();"
        + "  e.s = s;"
        + "  return e;"
        + "}}",
        "Example", "Example.h");
    assertTranslation(translation, "- (id)clone;");
    translation = getTranslatedFile("Example.m");
    assertTranslation(translation, "- (id)clone {");
  }

  // Verify that if a Cloneable class doesn't have a clone method,
  public void testCloneMethodAddedToCloneable() throws IOException {
    String translation = translateSourceFile(
        "public class Example implements Cloneable { int i; }",
        "Example", "Example.m");
    assertTranslation(translation, "- (id)copyWithZone:(NSZone *)zone {");
    assertTranslation(translation, "return [[self clone] retain];");
  }

  public void testCloneRenamingWithSuperClone() throws IOException {
    String translation = translateSourceFile(
        "public class Example implements Cloneable { "
        + "class Inner extends Example {"
        + "  int i;"
        + "  public Example copy() { return (Example) clone(); }"
        + "  public Object clone() { "
        + "    try { Inner inner = (Inner) super.clone(); inner.i = i; return inner; } "
        + "    catch (CloneNotSupportedException e) { return null; }}}}",
        "Example", "Example.h");
    assertTranslation(translation, "- (Example *)copy__ OBJC_METHOD_FAMILY_NONE;");
    translation = getTranslatedFile("Example.m");
    assertTranslation(translation,
        "return (Example *) check_class_cast([self clone], [Example class]);");
    assertTranslation(translation, "- (id)copyWithZone:(NSZone *)zone {");
    assertTranslation(translation, "Example_Inner *inner = "
        + "(Example_Inner *) check_class_cast([super clone], [Example_Inner class]);");
    assertTranslation(translation, "((Example_Inner *) nil_chk(inner))->i_ = i_;");
  }

  // Ensure using the builder pattern does not invoke O(2^N) running time.
  // The test below would have taken about 100 days to run before this was fixed.
  public void testHugeBuilderExpression() throws IOException {
    translateSourceFile(
        "public class Example { "
        + "  static class Builder { "
        + "    Example build() { return new Example(); } "
        + "    Builder add(int i) { return this; } "
        + "  } "
        + "  static Example create() { "
        + "    return new Builder()"
        + "      .add(10).add(11).add(12).add(13).add(14).add(15).add(16).add(17).add(18).add(19)"
        + "      .add(20).add(21).add(22).add(23).add(24).add(25).add(26).add(27).add(28).add(29)"
        + "      .add(30).add(31).add(32).add(33).add(34).add(35).add(36).add(37).add(38).add(39)"
        + "      .add(40).add(41).add(42).add(43).add(44).add(45).add(46).add(47).add(48).add(49)"
        + "      .build(); "
        + "} }",
        "Example", "Example.m");
  }
}


text:
using Acquaintance;
using CrossStitch.Core.MessageBus;
using System;
using System.Threading;

namespace CrossStitch.Core.Modules.Timer
{
    public class MessageTimerModule : IModule
    {
        public const int TimerIntervalSeconds = 10;

        private readonly IMessageBus _messageBus;
        private readonly int _intervalSeconds;
        private readonly ModuleLog _log;

        private RegisteredWaitHandle _waitHandle;
        private ManualResetEvent _stop;
        private long _sequence;

        public MessageTimerModule(IMessageBus messageBus)
            : this(messageBus, TimerIntervalSeconds)
        {
        }

        public MessageTimerModule(IMessageBus messageBus, int intervalSeconds)
        {
            if (intervalSeconds < 1)
                throw new ArgumentOutOfRangeException(nameof(intervalSeconds), "intervalSeconds must be 1 or higher");

            _intervalSeconds = intervalSeconds;
            //_timer = new Acquaintance.Timers.MessageTimer(delayMs: 5000, intervalMs: intervalSeconds * 1000);
            _messageBus = messageBus;
            _sequence = 0;
            _log = new ModuleLog(messageBus, Name);
        }

        public string Name => ModuleNames.Timer;

        public void Start()
        {
            _stop = new ManualResetEvent(false);
            _waitHandle = ThreadPool.RegisterWaitForSingleObject(_stop, TimerTick, null, 1000 * _intervalSeconds, false);
        }

        public void Stop()
        {
            _stop.Set();
        }

        public System.Collections.Generic.IReadOnlyDictionary<string, string> GetStatusDetails()
        {
            long sequenceId = Interlocked.Read(ref _sequence);
            return new System.Collections.Generic.Dictionary<string, string>
            {
                { "SequenceNumber", sequenceId.ToString() }
            };
        }

        public void Dispose()
        {
            Stop();
            _waitHandle = null;
        }

        private void TimerTick(object state, bool timedOut)
        {
            if (!timedOut)
                return;

            try
            {
                long sequence = Interlocked.Increment(ref _sequence);
                _messageBus.Publish("tick", new Acquaintance.Timers.MessageTimerEvent(null, sequence));
            }
            catch (Exception e)
            {
                _log.LogError(e, "Error publishing tick");
            }
        }
    }
}


text:
var Phase = require('./phase').Phase;
var inBody = require('./in_body_phase').Phase;

var start_tag_handlers = {
	html: 'startTagHtml',
	noframes: 'startTagNoframes',
	'-default': 'startTagOther',
}

var end_tag_handlers = {
	html: 'endTagHtml',
	'-default': 'endTagOther',
}

var p = exports.Phase = function AfterFramesetPhase(parser, tree) {
	Phase.call(this, parser, tree);
	this.start_tag_handlers = start_tag_handlers;
	this.end_tag_handlers = end_tag_handlers;
}

p.prototype = new Phase;

p.prototype.processCharacters = function(data) {
	this.parse_error("unexpected-char-after-frameset");
}

p.prototype.startTagNoframes = function(name, attributes) {
	new inBody(this.parser, this.tree).processStartTag(name, attributes);
}

p.prototype.startTagOther = function(name, attributes) {
	this.parse_error("unexpected-start-tag-after-frameset", {name: name});
}

p.prototype.endTagHtml = function(name) {
	this.parser.last_phase = this.parser.phase;
	this.parser.newPhase('trailingEnd');
}

p.prototype.endTagOther = function(name) {
	this.parse_error("unexpected-end-tag-after-frameset", {name: name});
}


text:
<?php
namespace App\Http\Controllers\Admin;

use App\Models\Equipment;
use App\Models\Site;
use Illuminate\Http\Request;
use App\Http\Controllers\Admin\BaseController;
use App\Models\EquipmentMaintain;

class EquipmentMaintainController extends BaseController
{
    public function newEntity(array $attributes = [])
    {
        // TODO: Implement newEntity() method.
        return new EquipmentMaintain($attributes);
    }

    /**
     * Display a listing of the resource.
     *
     * @return  \Illuminate\Http\Response
     */
    public function index()
    {
        //
        return view('admin.equipment-maintain.index');
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return  \Illuminate\Http\Response
     */
    public function create()
    {
        $equipments = Equipment::all();
        return view('admin.equipment-maintain.create', compact('equipments'));
    }

    /**
     * Display the specified resource.
     *
     * @param    int $id
     * @return  \Illuminate\Http\Response
     */
    public function edit($id)
    {
        $entity = EquipmentMaintain::find($id);
        $equipments = Equipment::all();
        return view('admin.equipment-maintain.edit', ['entity' => $entity, 'equipments' => $equipments]);
    }

    /**
     * Display the specified resource.
     *
     * @param    int $id
     * @return  \Illuminate\Http\Response
     */
    public function show($id)
    {
        $entity = EquipmentMaintain::find($id);
        return view('admin.equipment-maintain.show', ['entity' => $entity]);
    }

    /**
     * @param  Request $request
     * @param  array $searchCols
     * @param  array $with
     * @param  null $conditionCall
     * @param  bool $all_columns
     * @return  \Illuminate\Http\JsonResponse
     */
    public function pagination(Request $request, $searchCols = [], $with = [], $conditionCall = null, $dataHandleCall = null, $all_columns = false)
    {
        $searchCols = ["engineer", "maintain_content"];
        return parent::pagination($request, $searchCols, $with, $conditionCall, $dataHandleCall, true);
    }

    public function entityQuery()
    {
        $query = EquipmentMaintain::query();

        $query->select(
            'equipment_maintains.id as id',
            'equipment_maintains.equipment_id',
            'equipment_maintains.site_id',
            'equipment_maintains.engineer',
            'equipment_maintains.maintain_content',
            'equipment_maintains.created_at',
            'equipments.sn as equipments_sn',
            'sites.name as site_name'
        );
        $query->leftJoin('equipments', function ($join) {
            $join->on('equipments.id', '=', 'equipment_maintains.equipment_id');
        });

        $query->leftJoin('sites', function ($join) {
            $join->on('sites.id', '=', 'equipment_maintains.site_id');
        });
        return $query; // TODO: Change the autogenerated stub
    }

    public function store(Request $request, $only = [], $extraFields = [], $redirect_url = null)
    {
        $ep_id = $request->input('equipment_id', 0);
        $equipment = Equipment::find($ep_id);

        $extraFields = [
            'site_id' => $equipment->site_id
        ];
        return parent::store($request, $only, $extraFields, $redirect_url); // TODO: Change the autogenerated stub
    }

    public function update(Request $request, $id, $only = [], $extraFields = [], $redirect_url = null)
    {
        $ep_id = $request->input('equipment_id', 0);
        $equipment = Equipment::find($ep_id);

        $extraFields = [
            'site_id' => $equipment->site_id
        ];
        return parent::update($request, $id, $only, $extraFields, $redirect_url); // TODO: Change the autogenerated stub
    }

}


text:
using System;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using Frapid.Configuration;
using Frapid.Configuration.Models;
using Frapid.Framework.Extensions;

namespace Frapid.i18n.ResourceBuilder
{
    public sealed class ResourceWriter
    {
        public ResourceWriter(string tenant, Installable app)
        {
            this.Tenant = tenant;
            this.App = app;
        }

        public Installable App { get; }
        public string Tenant { get; }

        private static string GetILocalizeTemplate(string resourceClassName)
        {
            var builder = new StringBuilder();
            builder.Append("\tpublic sealed class Localize : ILocalize");
            builder.Append(Environment.NewLine);
            builder.Append("\t{");
            builder.Append(Environment.NewLine);
            builder.Append("\t\tpublic Dictionary<string, string> GetResources(CultureInfo culture)");
            builder.Append(Environment.NewLine);
            builder.Append("\t\t{");
            builder.Append(Environment.NewLine);
            builder.Append("\t\t\tstring resourceDirectory = " + resourceClassName + ".ResourceDirectory;");
            builder.Append(Environment.NewLine);
            builder.Append("\t\t\treturn I18NResource.GetResources(resourceDirectory, culture);");
            builder.Append(Environment.NewLine);
            builder.Append("\t\t}");
            builder.Append(Environment.NewLine);
            builder.Append("\t}");
            builder.Append(Environment.NewLine);
            builder.Append(Environment.NewLine);

            return builder.ToString();
        }

        public async Task WriteAsync()
        {
            if (string.IsNullOrWhiteSpace(this.App.I18NSource))
            {
                this.App.I18NSource = this.App.DirectoryPath.Replace(PathMapper.PathToRootDirectory, string.Empty);
            }

            string pathToResource = Path.Combine(this.App.I18NSource, "i18n").Replace("\\", "/");
            string resourceFile = I18NResource.GetResourceFile(PathMapper.MapPath(pathToResource), string.Empty);

            if (string.IsNullOrWhiteSpace(resourceFile))
            {
                return;
            }

            string className = this.App.I18NClassName.Or("I18N");

            var builder = new StringBuilder();
            builder.Append("using System.Collections.Generic;");
            builder.Append(Environment.NewLine);
            builder.Append("using System.Globalization;");
            builder.Append(Environment.NewLine);
            builder.Append("using Frapid.Configuration;");
            builder.Append(Environment.NewLine);
            builder.Append("using Frapid.i18n;");
            builder.Append(Environment.NewLine);
            builder.Append(Environment.NewLine);
            builder.Append("namespace " + this.App.AssemblyName);
            builder.Append(Environment.NewLine);
            builder.Append("{");
            builder.Append(Environment.NewLine);
            builder.Append(GetILocalizeTemplate(className));
            builder.Append("\tpublic static class "  + className);
            builder.Append(Environment.NewLine);
            builder.Append("\t{");
            builder.Append(Environment.NewLine);
            builder.Append("\t\tpublic static string ResourceDirectory { get; }");
            builder.Append(Environment.NewLine);
            builder.Append(Environment.NewLine);

            builder.Append("\t\tstatic " + className + "()");
            builder.Append(Environment.NewLine);
            builder.Append("\t\t{");
            builder.Append(Environment.NewLine);
            builder.Append($"\t\t\tResourceDirectory = PathMapper.MapPath(\"{pathToResource}\");");
            builder.Append(Environment.NewLine);
            builder.Append("\t\t}");
            builder.Append(Environment.NewLine);
            builder.Append(Environment.NewLine);

            var resources = await ResourceReader.GetResourcesAsync(this.Tenant, this.App, resourceFile).ConfigureAwait(false);
            //Save up-to-date resource on disk

            YamlSerializer.SaveToDisk(resourceFile, resources);
            foreach (var resource in resources)
            {
                builder.Append("\t\t/// <summary>");
                builder.Append(Environment.NewLine);
                builder.Append("\t\t///");
                builder.Append(Regex.Replace(resource.Value, @"\r\n?|\n", string.Empty));
                builder.Append(Environment.NewLine);
                builder.Append("\t\t/// </summary>");
                builder.Append(Environment.NewLine);
                string format = "\t\tpublic static string {0} => I18NResource.GetString(ResourceDirectory, \"{0}\");";
                builder.Append(string.Format(format, resource.Key));
                builder.Append(Environment.NewLine);
                builder.Append(Environment.NewLine);
            }

            builder.Append("\t}");
            builder.Append(Environment.NewLine);
            builder.Append("}");
            builder.Append(Environment.NewLine);

            string target = Path.Combine(this.App.DirectoryPath, className + ".cs");

            if (!string.IsNullOrWhiteSpace(this.App.I18NTarget))
            {
                target = Path.Combine(this.App.DirectoryPath, this.App.I18NTarget, className + ".cs");
            }

            Console.WriteLine($"Writing resource on " + target);
            Console.WriteLine(builder.ToString());
            File.WriteAllText(target, builder.ToString(), Encoding.UTF8);
        }
    }
}


text:
<?php

/**
 * Entity attribute option collection
 *
 * @category    Mage
 * @package     Mage_Eav
 * @author      Magento Core Team <core@magentocommerce.com>
 */
class Mage_Eav_Model_Mysql4_Entity_Attribute_Option_Collection
    extends Mage_Eav_Model_Resource_Entity_Attribute_Option_Collection
{
}


text:
#include <aws/waf/model/GetRateBasedRuleRequest.h>
#include <aws/core/utils/json/JsonSerializer.h>

#include <utility>

using namespace Aws::WAF::Model;
using namespace Aws::Utils::Json;
using namespace Aws::Utils;

GetRateBasedRuleRequest::GetRateBasedRuleRequest() :
    m_ruleIdHasBeenSet(false)
{
}

Aws::String GetRateBasedRuleRequest::SerializePayload() const
{
  JsonValue payload;

  if(m_ruleIdHasBeenSet)
  {
   payload.WithString("RuleId", m_ruleId);

  }

  return payload.View().WriteReadable();
}

Aws::Http::HeaderValueCollection GetRateBasedRuleRequest::GetRequestSpecificHeaders() const
{
  Aws::Http::HeaderValueCollection headers;
  headers.insert(Aws::Http::HeaderValuePair("X-Amz-Target", "AWSWAF_20150824.GetRateBasedRule"));
  return headers;

}


text:
namespace net_instaweb {

class ThreadSystem;

namespace {

const char kModPagespeedStatisticsHandlerPath[] = "/mod_pagespeed_statistics";

}  // namespace

RewriteOptions::Properties* ApacheConfig::apache_properties_ = NULL;

void ApacheConfig::Initialize() {
  if (Properties::Initialize(&apache_properties_)) {
    SystemRewriteOptions::Initialize();
    AddProperties();
  }
}

void ApacheConfig::Terminate() {
  if (Properties::Terminate(&apache_properties_)) {
    SystemRewriteOptions::Terminate();
  }
}

ApacheConfig::ApacheConfig(const StringPiece& description,
                           ThreadSystem* thread_system)
    : SystemRewriteOptions(description, thread_system) {
  Init();
}

ApacheConfig::ApacheConfig(ThreadSystem* thread_system)
    : SystemRewriteOptions(thread_system) {
  Init();
}

ApacheConfig::~ApacheConfig() {
}

void ApacheConfig::Init() {
  DCHECK(apache_properties_ != NULL)
      << "Call ApacheConfig::Initialize() before construction";
  InitializeOptions(apache_properties_);
}

void ApacheConfig::AddProperties() {
  AddApacheProperty(
      false, &ApacheConfig::fetch_from_mod_spdy_, "ffms",
      RewriteOptions::kFetchFromModSpdy,
      "Fetch SSL resources with help of recent mod_spdy", true);

  MergeSubclassProperties(apache_properties_);

  // Default properties are global but to set them the current API requires
  // an ApacheConfig instance and we're in a static method.
  //
  // TODO(jmarantz): Perform these operations on the Properties directly and
  // get rid of this hack.
  //
  // Instantiation of the options with a null thread system wouldn't usually be
  // safe but it's ok here because we're only updating the static properties on
  // process startup.  We won't have a thread-system yet or multiple threads.
  ApacheConfig config("dummy_options", NULL);
  config.set_default_x_header_value(kModPagespeedVersion);
}

ApacheConfig* ApacheConfig::Clone() const {
  ApacheConfig* options =
      new ApacheConfig(StrCat("cloned from ", description()), thread_system());
  options->Merge(*this);
  return options;
}

ApacheConfig* ApacheConfig::NewOptions() const {
  return new ApacheConfig(StrCat("derived from ", description()),
                          thread_system());
}

const ApacheConfig* ApacheConfig::DynamicCast(const RewriteOptions* instance) {
  const ApacheConfig* config = dynamic_cast<const ApacheConfig*>(instance);
  DCHECK(config != NULL);
  return config;
}

ApacheConfig* ApacheConfig::DynamicCast(RewriteOptions* instance) {
  ApacheConfig* config = dynamic_cast<ApacheConfig*>(instance);
  DCHECK(config != NULL);
  return config;
}

}  // namespace net_instaweb


text:
//Copyright © 2014 Sony Computer Entertainment America LLC. See License.txt.

using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Windows.Data;
using Sce.Atf.Applications;
using Sce.Atf.Wpf.Controls;
using Sce.Atf.Wpf.Models;

namespace Sce.Atf.Wpf.Applications.VersionControl
{
    /// <summary>
    /// Interaction logic for CheckInDialog.xaml
    /// </summary>
    public partial class CheckInDialog : CommonDialog
    {
        public CheckInDialog()
        {
            InitializeComponent();
        }
    }

    internal class CheckInItem : NotifyPropertyChangedBase
    {
        private readonly CheckInViewModel m_parent;

        public CheckInItem(CheckInViewModel parent, IResource resource)
        {
            m_parent = parent;
            Resource = resource;
        }

        public IResource Resource { get; private set; }
        public string LocalPath { get { return Resource.Uri.LocalPath; } }

        public bool IsChecked
        {
            get { return m_isChecked; }
            set
            {
                if (m_isChecked != value)
                {
                    m_isChecked = value;
                    OnPropertyChanged(IsCheckedArgs);
                    m_parent.CheckAllSelected(value);
                }
            }
        }

        private bool m_isChecked = true;
        private static readonly PropertyChangedEventArgs IsCheckedArgs
            = ObservableUtil.CreateArgs<CheckInItem>(x => x.IsChecked);

        public bool IsSelected
        {
            get { return m_isSelected; }
            set
            {
                if (m_isSelected != value)
                {
                    m_isSelected = value;
                    OnPropertyChanged(IsSelectedArgs);
                }
            }
        }

        private bool m_isSelected;
        private static readonly PropertyChangedEventArgs IsSelectedArgs
            = ObservableUtil.CreateArgs<CheckInItem>(x => x.IsSelected);
    }

    internal class CheckInViewModel : DialogViewModelBase
    {
        public CheckInViewModel(SourceControlService sourceControlService, IEnumerable<IResource> toCheckIn)
        {
            Title = "Check In Files".Localize();

            m_sourceControlService = sourceControlService;
            m_checkInItems = toCheckIn.Select(x => new CheckInItem(this, x)).ToList();

            Items = new ListCollectionView(m_checkInItems);
        }

        public ICollectionView Items { get; private set; }
        public string Description { get; set; }

        protected override void OnCloseDialog(CloseDialogEventArgs args)
        {
            base.OnCloseDialog(args);
            if (args.DialogResult == true)
            {
                var uris = (from item in m_checkInItems
                            where item.IsChecked
                            select item.Resource.Uri);

                m_sourceControlService.CheckIn(uris, Description);
            }
        }

        public void CheckAllSelected(bool check)
        {
            m_checkInItems
                .Where(x => x.IsSelected)
                .ForEach(x => x.IsChecked = check);
        }

        private readonly ISourceControlService m_sourceControlService;
        private readonly List<CheckInItem> m_checkInItems;
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <include
        android:id="@+id/header"
        layout="@layout/header_outline" />

    <LinearLayout
        android:id="@+id/outline_body"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_below="@id/header"
        android:orientation="vertical" />
</RelativeLayout>


text:
package flags

import (
	"flag"
	"fmt"
	"os"
	"sync"

	"github.com/vmware/govmomi/find"
	"github.com/vmware/govmomi/object"
	"golang.org/x/net/context"
)

type DatacenterFlag struct {
	*ClientFlag
	*OutputFlag

	register sync.Once
	path     string
	dc       *object.Datacenter
	finder   *find.Finder
	err      error
}

func (flag *DatacenterFlag) Register(f *flag.FlagSet) {
	flag.register.Do(func() {
		env := "GOVC_DATACENTER"
		value := os.Getenv(env)
		usage := fmt.Sprintf("Datacenter [%s]", env)
		f.StringVar(&flag.path, "dc", value, usage)
	})
}

func (flag *DatacenterFlag) Process() error { return nil }

func (flag *DatacenterFlag) Finder() (*find.Finder, error) {
	if flag.finder != nil {
		return flag.finder, nil
	}

	c, err := flag.Client()
	if err != nil {
		return nil, err
	}

	finder := find.NewFinder(c, flag.JSON)

	// Datacenter is not required (ls command for example).
	// Set for relative func if dc flag is given or
	// if there is a single (default) Datacenter
	if flag.path == "" {
		flag.dc, flag.err = finder.DefaultDatacenter(context.TODO())
	} else {
		if flag.dc, err = finder.Datacenter(context.TODO(), flag.path); err != nil {
			return nil, err
		}
	}

	finder.SetDatacenter(flag.dc)

	flag.finder = finder

	return flag.finder, nil
}

func (flag *DatacenterFlag) Datacenter() (*object.Datacenter, error) {
	if flag.dc != nil {
		return flag.dc, nil
	}

	_, err := flag.Finder()
	if err != nil {
		return nil, err
	}

	if flag.err != nil {
		// Should only happen if no dc is specified and len(dcs) > 1
		return nil, flag.err
	}

	return flag.dc, err
}


text:
<?php

namespace Aviator\Helpdesk\Middleware;

use Closure;
use Illuminate\Http\Request;

class TicketsRedirector
{
    /**
     * Handle an incoming request.
     * @param Request $request
     * @param Closure  $next
     * @return mixed
     */
    public function handle(Request $request, Closure $next)
    {
        /*
         * Guests may not access this route.
         */
        if (!$request->user()) {
            return redirect(
                route('login')
            );
        }

        /*
         * All agents (including supers) are redirected to the same page.
         */
        if ($request->user()->agent) {
            return redirect(
                route('helpdesk.agents.tickets.index')
            );
        }

        return $next($request);
    }
}


text:
jQuery.noConflict();

jQuery('ul.nav').superfish({
	delay:       200,                            // one second delay on mouseout
	animation:   {opacity:'show',height:'show'},  // fade-in and slide-down animation
	speed:       'fast',                          // faster animation speed
	autoArrows:  true,                           // disable generation of arrow mark-up
	dropShadows: false                            // disable drop shadows
});

jQuery('ul.nav > li > a.sf-with-ul').parent('li').addClass('sf-ul');

var $featured_slider = jQuery('#featured'),
	$featured_slides = $featured_slider.find('.slide'),
	slides_pos = [],
	slides_zindex = [],
	et_animation_running = false,
	et_disable_toptier = jQuery("meta[name=et_disable_toptier]").attr('content'),
	et_featured_slider_auto = jQuery("meta[name=et_featured_slider_auto]").attr('content'),
	et_featured_auto_speed = jQuery("meta[name=et_featured_auto_speed]").attr('content'),
	pause_scroll = false,
	featured_animation = 'easeInOutQuad'; //'easeInOutQuad','easeInOutQuint', 'easeInOutQuart'
if ($featured_slider.length) {
	$featured_slides.each(function(index, domEle){
		var $this_slide = jQuery(domEle);

		if ( index === 0 ) {
			$this_slide.find('a.main img').attr({
				width: '462',
				height: '306'
			});
			$this_slide.find('img.bottom-shadow').attr('width','462');
		} else {
			$this_slide.find('a.main img').attr({
				width: '354',
				height: '234'
			});
			$this_slide.find('img.bottom-shadow').attr('width','354');
		}

		slides_pos[index] = {
			width: $this_slide.width(),
			top: parseInt($this_slide.css('top')),
			left: parseInt($this_slide.css('left')),
			opacity: $this_slide.css('opacity')
		};
		slides_zindex[index] = $this_slide.css('zIndex');
		$this_slide.animate(slides_pos[index],100);

		jQuery(domEle).data('slide_pos',index);
	});

	jQuery('.next-block a').live('click',function(event){
		event.preventDefault();
		if (!et_animation_running) rotate_slide('next');
		if ( typeof(et_auto_animation) !== 'undefined' ) clearInterval(et_auto_animation);
	});

	jQuery('.prev-block a').live('click',function(event){
		event.preventDefault();
		if (!et_animation_running) rotate_slide('prev');
		if ( typeof(et_auto_animation) !== 'undefined' ) clearInterval(et_auto_animation);
	});

	$featured_slides.hover(function(){
		if ( !et_animation_running ) {
			if ( jQuery(this).hasClass('active-block') )
				jQuery(this).find('.featured-link').stop(true, true).animate({'opacity':'show'},300);
			else {
				jQuery(this).find('.gotoslide').stop(true, true).animate({'opacity':'show'},300);
			}
		}
		pause_scroll = true;
	},function(){
		if ( !et_animation_running ) {
			if ( jQuery(this).hasClass('active-block') )
				jQuery(this).find('.featured-link').stop(true, true).animate({'opacity':'hide'},300);
			else {
				jQuery(this).find('.gotoslide').stop(true, true).animate({'opacity':'hide'},300);
			}
		}
		pause_scroll = false;
	});

	jQuery('.active-block').live('click',function(event){
		window.location = jQuery(this).find('a.main').attr('href');
	});

	function rotate_slide(direction){
		et_animation_running = true;

		jQuery('.gotoslide').css('display','none');

		$featured_slides.removeClass('active-block');
		$featured_slides.removeClass('next-block');
		$featured_slides.removeClass('prev-block');

		$featured_slides.each(function(index, domEle){
			var $this_slide = jQuery(domEle),
				next_slide_num = $this_slide.data('slide_pos');

			if ( direction === 'next' ){
				if ( next_slide_num === 0 ) next_slide_num = $featured_slides.length-1;
				else next_slide_num = next_slide_num - 1;
			} else {
				next_slide_num = next_slide_num + 1;
				if ( next_slide_num === $featured_slides.length ) next_slide_num = 0;
			}

			$this_slide.animate(slides_pos[next_slide_num],600,featured_animation);
			if ( next_slide_num != 0 ) {
				$this_slide.find('a.main img').animate({'width':'354px','height':'234px'},600,featured_animation);
				$this_slide.find('img.bottom-shadow').animate({'width':'354px'},600,featured_animation);
			}
			else {
				$this_slide.addClass('active-block');
				$this_slide.find('a.main img').animate({'width':'462px','height':'306px'},600,featured_animation);
				$this_slide.find('img.bottom-shadow').animate({'width':'462px'},600,featured_animation);
			}

			if ( next_slide_num === 1 ) $this_slide.addClass('next-block');
			if ( next_slide_num === ($featured_slides.length-1) ) $this_slide.addClass('prev-block');

			setTimeout(function(){
				$this_slide.css({zIndex: slides_zindex[next_slide_num]});
			},300);

			$this_slide.data('slide_pos',next_slide_num);
		});

		et_animation_running = false;
	}

	if ( et_featured_slider_auto == 1 ) {
		et_auto_animation = setInterval(function(){
			if ( !pause_scroll ) rotate_slide('next');
		}, et_featured_auto_speed);
	}
}

var $footer_widget = jQuery(".footer-widget");
if (!($footer_widget.length == 0)) {
	$footer_widget.each(function (index, domEle) {
		// domEle == this
		if ((index+1)%3 == 0) jQuery(domEle).addClass("last").after("

");
	});
}

var $et_blurb_thumb = jQuery('#blurbs .thumb');
$et_blurb_thumb.find('a.fancybox').hover(function(){
	jQuery(this).find('img').fadeTo('fast', 0.8);
	jQuery(this).find('.zoom-icon').fadeTo('fast', 1);
}, function(){
	jQuery(this).find('img').fadeTo('fast', 1);
	jQuery(this).find('.zoom-icon').fadeTo('fast', 0);
});

var $et_left_area = jQuery('#left-area'),
	$et_sidebar = jQuery('#sidebar');

if ( $et_left_area.innerHeight() < $et_sidebar.innerHeight() ) $et_left_area.css( 'height', ( $et_sidebar.innerHeight()+15 ) );
if ( et_disable_toptier == 1 ) jQuery("ul.nav > li > ul").prev("a").attr("href","#");


text:
#import <Foundation/Foundation.h>

#ifndef _MMSERVICEIOTYPE_
    #define _MMSERVICEIOTYPE_

typedef NS_ENUM(NSInteger, MMServiceIOType){
    MMServiceIOTypeVoid = 0,
    MMServiceIOTypeString,
    MMServiceIOTypeEnum,
    MMServiceIOTypeBoolean,
    MMServiceIOTypeChar, // byte in Java
    MMServiceIOTypeUnichar, // char in Java
    MMServiceIOTypeShort,
    MMServiceIOTypeInteger,
    MMServiceIOTypeLongLong, // long in Java
    MMServiceIOTypeFloat,
    MMServiceIOTypeDouble,
    MMServiceIOTypeBigDecimal, // TBD
    MMServiceIOTypeBigInteger, // TBD
    MMServiceIOTypeDate,
    MMServiceIOTypeUri, // TBD
    MMServiceIOTypeArray,
    MMServiceIOTypeDictionary,
    MMServiceIOTypeData, // TBD
    MMServiceIOTypeBytes, // TBD
    MMServiceIOTypeMagnetNode,
};

#endif /* _MMSERVICEIOTYPE_ */


text:
@interface SNAccessTokenParam : NSObject

// 申请应用时分批的AppKey
@property (copy, nonatomic) NSString *client_id;

// 申请应用时分配的AppSecret
@property (copy, nonatomic) NSString *client_secret;

// 请求的类型,填写authorization_code
@property (copy, nonatomic) NSString *grant_type;

// 调用authorize获得code值
@property (copy, nonatomic) NSString *code;

// 回调地址,需要与注册应用里的回调地址一致
@property (copy, nonatomic) NSString *redirect_uri;

@end


text:
import { Component, ComponentClass, HTMLProps, StatelessComponent, ReactElement } from "react";

// fake intermediate interface to remove typing on size, as the typing
// is overrided by react-fa
interface SizeOverrideHTMLProps<T> extends HTMLProps<T> {
    size?: any;
}

export type IconSize = "lg" | "2x" | "3x" | "4x" | "5x";
export type IconRotation = "45" | "90" | "135" | "180" | "225" | "270" | "315";
export type IconFlip = "horizontal" | "vertical";
export type IconStackSize = "1x" | "2x";

type CustomComponent = string | ComponentClass<any> | StatelessComponent<any>;

export interface IconProps extends SizeOverrideHTMLProps<Icon> {
    name: string;
    size?: IconSize | undefined;
    spin?: boolean | undefined;
    rotate?: IconRotation | undefined;
    flip?: IconFlip | undefined;
    fixedWidth?: boolean | undefined;
    pulse?: boolean | undefined;
    stack?: IconStackSize | undefined;
    inverse?: boolean | undefined;
    Component?: CustomComponent | undefined;
}

export type Icon = Component<IconProps>;
export const Icon: ComponentClass<IconProps>;

export interface IconStackProps extends SizeOverrideHTMLProps<IconStack> {
    size?: IconSize | undefined;
    children?: ReactElement<IconProps> | Array<ReactElement<IconProps>> | undefined;
}

export type IconStack = Component<IconStackProps>;
export const IconStack: ComponentClass<IconStackProps>;

export default Icon;


text:
package live

//Licensed under the Apache License, Version 2.0 (the "License");
//you may not use this file except in compliance with the License.
//You may obtain a copy of the License at
//
//http://www.apache.org/licenses/LICENSE-2.0
//
//Unless required by applicable law or agreed to in writing, software
//distributed under the License is distributed on an "AS IS" BASIS,
//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//See the License for the specific language governing permissions and
//limitations under the License.
//
// Code generated by Alibaba Cloud SDK Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.

// LogInfos is a nested struct in live response
type LogInfos struct {
	LogInfoDetail []LogInfoDetail `json:"LogInfoDetail" xml:"LogInfoDetail"`
}


text:
char *get_preset(char[4]);
char *safe_genre(char *);

void get_audio_info(char *, struct audio *);
void get_mpeg_audio_info(char *, struct audio *);
#ifdef HAVE_FLAC_HEADERS
void get_flac_audio_info(char *, struct audio *);
#endif

const unsigned char *fourcc(FOURCC);
void avierror(const char *);
DWORD get32(FILE *);
WORD get16(FILE *);
int avinfo(char *, struct VIDEO *);

#endif


text: Optionally specify the 'excludes' pattern, such as "foo/bar/**/*". A file that matches this mask will not be imported even if it matches the mask specified in 'File(s) to import' section.


text:
// Copyright Jim Bosch 2010-2012.
// Copyright Stefan Seefeld 2016.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)

#ifndef boost_python_numpy_numpy_object_mgr_traits_hpp_
#define boost_python_numpy_numpy_object_mgr_traits_hpp_

#include <boost/python/numpy/config.hpp>

/**
 *  @brief Macro that specializes object_manager_traits by requiring a
 *         source-file implementation of get_pytype().
 */

#define NUMPY_OBJECT_MANAGER_TRAITS(manager)                            \
template <>								\
struct BOOST_NUMPY_DECL object_manager_traits<manager>			\
{									\
  BOOST_STATIC_CONSTANT(bool, is_specialized = true);			\
  static inline python::detail::new_reference adopt(PyObject* x)	\
  {									\
    return python::detail::new_reference(python::pytype_check((PyTypeObject*)get_pytype(), x)); \
  }									\
  static bool check(PyObject* x)					\
  {									\
    return ::PyObject_IsInstance(x, (PyObject*)get_pytype());		\
  }									\
  static manager* checked_downcast(PyObject* x)				\
  {									\
    return python::downcast<manager>((checked_downcast_impl)(x, (PyTypeObject*)get_pytype())); \
  }									\
  static PyTypeObject const * get_pytype();				\
}

#endif


text:
namespace MultiMiner.Engine.Data
{
    public class AvailableMiner
    {
        public string Name { get; set; }
        public string Version { get; set; }
        public string Url { get; set; }
    }
}


text:
"""This plugin generates tab completions for Beets commands for the Fish shell
<https://fishshell.com/>, including completions for Beets commands, plugin
commands, and option flags. Also generated are completions for all the album
and track fields, suggesting for example `genre:` or `album:` when querying the
Beets database. Completions for the *values* of those fields are not generated
by default but can be added via the `-e` / `--extravalues` flag. For example:
`beet fish -e genre -e albumartist`
"""

from __future__ import division, absolute_import, print_function

from beets.plugins import BeetsPlugin
from beets import library, ui
from beets.ui import commands
from operator import attrgetter
import os
BL_NEED2 = """complete -c beet -n '__fish_beet_needs_command' {} {}\n"""
BL_USE3 = """complete -c beet -n '__fish_beet_using_command {}' {} {}\n"""
BL_SUBS = """complete -c beet -n '__fish_at_level {} ""' {}  {}\n"""
BL_EXTRA3 = """complete -c beet -n '__fish_beet_use_extra {}' {} {}\n"""

HEAD = '''
function __fish_beet_needs_command
    set cmd (commandline -opc)
    if test (count $cmd) -eq 1
        return 0
    end
    return 1
end

function __fish_beet_using_command
    set cmd (commandline -opc)
    set needle (count $cmd)
    if test $needle -gt 1
        if begin test $argv[1] = $cmd[2];
            and not contains -- $cmd[$needle] $FIELDS; end
                return 0
        end
    end
    return 1
end

function __fish_beet_use_extra
    set cmd (commandline -opc)
    set needle (count $cmd)
    if test $argv[2]  = $cmd[$needle]
        return 0
    end
    return 1
end
'''

class FishPlugin(BeetsPlugin):

    def commands(self):
        cmd = ui.Subcommand('fish', help='generate Fish shell tab completions')
        cmd.func = self.run
        cmd.parser.add_option('-f', '--noFields', action='store_true',
                              default=False,
                              help='omit album/track field completions')
        cmd.parser.add_option(
            '-e',
            '--extravalues',
            action='append',
            type='choice',
            choices=library.Item.all_keys() +
            library.Album.all_keys(),
            help='include specified field *values* in completions')
        return [cmd]

    def run(self, lib, opts, args):
        # Gather the commands from Beets core and its plugins.
        # Collect the album and track fields.
        # If specified, also collect the values for these fields.
        # Make a giant string of all the above, formatted in a way that
        # allows Fish to do tab completion for the `beet` command.
        home_dir = os.path.expanduser("~")
        completion_dir = os.path.join(home_dir, '.config/fish/completions')
        try:
            os.makedirs(completion_dir)
        except OSError:
            if not os.path.isdir(completion_dir):
                raise
        completion_file_path = os.path.join(completion_dir, 'beet.fish')
        nobasicfields = opts.noFields  # Do not complete for album/track fields
        extravalues = opts.extravalues  # e.g., Also complete artists names
        beetcmds = sorted(
            (commands.default_commands +
             commands.plugins.commands()),
            key=attrgetter('name'))
        fields = sorted(set(
            library.Album.all_keys() + library.Item.all_keys()))
        # Collect commands, their aliases, and their help text
        cmd_names_help = []
        for cmd in beetcmds:
            names = [alias for alias in cmd.aliases]
            names.append(cmd.name)
            for name in names:
                cmd_names_help.append((name, cmd.help))
        # Concatenate the string
        totstring = HEAD + "\n"
        totstring += get_cmds_list([name[0] for name in cmd_names_help])
        totstring += '' if nobasicfields else get_standard_fields(fields)
        totstring += get_extravalues(lib, extravalues) if extravalues else ''
        totstring += "\n" + "# ====== {} =====".format(
            "setup basic beet completion") + "\n" * 2
        totstring += get_basic_beet_options()
        totstring += "\n" + "# ====== {} =====".format(
            "setup field completion for subcommands") + "\n"
        totstring += get_subcommands(
            cmd_names_help, nobasicfields, extravalues)
        # Set up completion for all the command options
        totstring += get_all_commands(beetcmds)

        with open(completion_file_path, 'w') as fish_file:
            fish_file.write(totstring)

def _escape(name):
    # Escape ? in fish
    if name == "?":
        name = "\\" + name
    return name

def get_cmds_list(cmds_names):
    # Make a list of all Beets core & plugin commands
    substr = ''
    substr += (
        "set CMDS " + " ".join(cmds_names) + ("\n" * 2)
    )
    return substr

def get_standard_fields(fields):
    # Make a list of album/track fields and append with ':'
    fields = (field + ":" for field in fields)
    substr = ''
    substr += (
        "set FIELDS " + " ".join(fields) + ("\n" * 2)
    )
    return substr

def get_extravalues(lib, extravalues):
    # Make a list of all values from an album/track field.
    # 'beet ls albumartist: <TAB>' yields completions for ABBA, Beatles, etc.
    word = ''
    values_set = get_set_of_values_for_field(lib, extravalues)
    for fld in extravalues:
        extraname = fld.upper() + 'S'
        word += (
            "set  " + extraname + " " + " ".join(sorted(values_set[fld]))
            + ("\n" * 2)
        )
    return word

def get_set_of_values_for_field(lib, fields):
    # Get unique values from a specified album/track field
    fields_dict = {}
    for each in fields:
        fields_dict[each] = set()
    for item in lib.items():
        for field in fields:
            fields_dict[field].add(wrap(item[field]))
    return fields_dict

def get_basic_beet_options():
    word = (
        BL_NEED2.format("-l format-item",
                        "-f -d 'print with custom format'") +
        BL_NEED2.format("-l format-album",
                        "-f -d 'print with custom format'") +
        BL_NEED2.format("-s  l  -l library",
                        "-f -r -d 'library database file to use'") +
        BL_NEED2.format("-s  d  -l directory",
                        "-f -r -d 'destination music directory'") +
        BL_NEED2.format("-s  v  -l verbose",
                        "-f -d 'print debugging information'") +

        BL_NEED2.format("-s  c  -l config",
                        "-f -r -d 'path to configuration file'") +
        BL_NEED2.format("-s  h  -l help",
                        "-f -d 'print this help message and exit'"))
    return word

def get_subcommands(cmd_name_and_help, nobasicfields, extravalues):
    # Formatting for Fish to complete our fields/values
    word = ""
    for cmdname, cmdhelp in cmd_name_and_help:
        cmdname = _escape(cmdname)

        word += "\n" + "# ------ {} -------".format(
            "fieldsetups for  " + cmdname) + "\n"
        word += (
            BL_NEED2.format(
                ("-a " + cmdname),
                ("-f " + "-d " + wrap(clean_whitespace(cmdhelp)))))

        if nobasicfields is False:
            word += (
                BL_USE3.format(
                    cmdname,
                    ("-a " + wrap("$FIELDS")),
                    ("-f " + "-d " + wrap("fieldname"))))

        if extravalues:
            for f in extravalues:
                setvar = wrap("$" + f.upper() + "S")
                word += " ".join(BL_EXTRA3.format(
                    (cmdname + " " + f + ":"),
                    ('-f ' + '-A ' + '-a ' + setvar),
                    ('-d ' + wrap(f))).split()) + "\n"
    return word

def get_all_commands(beetcmds):
    # Formatting for Fish to complete command options
    word = ""
    for cmd in beetcmds:
        names = [alias for alias in cmd.aliases]
        names.append(cmd.name)
        for name in names:
            name = _escape(name)

            word += "\n"
            word += ("\n" * 2) + "# ====== {} =====".format(
                "completions for  " + name) + "\n"

            for option in cmd.parser._get_all_options()[1:]:
                cmd_l = (" -l " + option._long_opts[0].replace('--', '')
                         )if option._long_opts else ''
                cmd_s = (" -s " + option._short_opts[0].replace('-', '')
                         ) if option._short_opts else ''
                cmd_need_arg = ' -r ' if option.nargs in [1] else ''
                cmd_helpstr = (" -d " + wrap(' '.join(option.help.split()))
                               ) if option.help else ''
                cmd_arglist = (' -a ' + wrap(" ".join(option.choices))
                               ) if option.choices else ''

                word += " ".join(BL_USE3.format(
                    name,
                    (cmd_need_arg + cmd_s + cmd_l + " -f " + cmd_arglist),
                    cmd_helpstr).split()) + "\n"

            word = (word + " ".join(BL_USE3.format(
                name,
                ("-s " + "h " + "-l " + "help" + " -f "),
                ('-d ' + wrap("print help") + "\n")
            ).split()))
    return word

def clean_whitespace(word):
    # Remove excess whitespace and tabs in a string
    return " ".join(word.split())

def wrap(word):
    # Need " or ' around strings but watch out if they're in the string
    sptoken = '\"'
    if ('"') in word and ("'") in word:
        word.replace('"', sptoken)
        return '"' + word + '"'

    tok = '"' if "'" in word else "'"
    return tok + word + tok


text: Rails.application.config.session_store :cookie_store, key: '_CarePax_session'


text:
$(document).ready(function() {
  $('.tag-explorer-topics-level-2 a').on('click', function(e) {
    e.preventDefault();

    var $this = $(this);
    var $subtopic = $($this.attr('href'));

    if ($this.hasClass('active')) {
      $this.removeClass('active');
      $this.siblings('.list-group-item').show();

      $subtopic.hide();
      $('.js-topic-filter').trigger('keyup');
    } else {
      // hide other subtopics
      $this.parents('.panel').find('.tag-explorer-topics-level-2').hide();

      // show selected subtopic & hide other topics
      $subtopic.show();
      $this.siblings('.list-group-item').removeClass('active').hide();
      $this.addClass('active');

      // scroll to top
      $this.parents('.tag-container').scrollTop(0);
    }
  });

  $('.tag-explorer-topics-level-1 input').on('change', function(e) {
    var $this = $(this);
    var $div = $this.parents('.list-group-item');
    var $target = $('#selected-topics').find('.tag-container');
    var val = $this.val();
    var $selected = $('#'+val+'_selected-item');
    var $suggested = $('#'+val+'-suggested');
    var topicName = $div.text().trim();

    var pos = val.lastIndexOf('_');
    var $topic = $('#'+val.substring(0, pos)+'_parent');
    var curated = $div.data('curated');

    if ($this.is(':checked') && $selected.length == 0) {
      $selected = $div.clone();

      $selected.attr('id', val+'_selected-item');
      $selected.appendTo($target);
      $selected.removeClass('no-search-match matched-search');
      $topic.addClass('list-group-item-info');

      // Curated topic warning
      if (curated) {
        var $curatedTopics = $('.curated-topics');
        if ($curatedTopics.is(':hidden')) {
          $curatedTopics.show();
        }

        $('.curated-topics-list').append('
'+topicName+'
');
      }

      // email subscribers warning
      if (Math.random() <= (1/5)) {
        var numSubs = Math.floor(Math.random() * (200 - 1000) + 1000);

        var $topicSubscribers = $('#topic-area-subscribers');

        if ($topicSubscribers.length == 0) {
          var $warningTarget = $('#tag-explorer').parents('.row').first();

          $('
0 users will be emailed about this document.
')
            .insertAfter($warningTarget);
          $topicSubscribers = $('#topic-area-subscribers');
        }

        $topicSubscribers.text(numSubs + Number($topicSubscribers.text()));
      }

      // Preview topic
      if (!curated) {
        var $previewTopics = $('.preview-topics');
        if ($previewTopics.is(':hidden')) {
          $previewTopics.show();
        }

        var documentTitle = "School capital funding allocations: 2015 to 2018";
        var previewURL = '/preview?url=https://www.gov.uk'+val.replace(/_/g, "/")+'&title='+documentTitle;
        var previewLink = '
'+topicName+'
';

        $('.preview-topics-list').append($(previewLink));
      }

      $('#no-topics').hide();

    } else if (!$this.is(':checked')) {
      var $selected = $('#'+val+'_selected-item');

      if ($selected.siblings().length == 0) {
        $('#no-topics').show();
      }

      $selected.remove();

      if ($div.siblings().find('input:checked').length == 0) {
        $topic.removeClass('list-group-item-info');
      }

      var $previewTopics = $('.preview-topics');
      $('#preview-topics-'+val).remove();
      if ($previewTopics.find('li').length == 0) {
        $previewTopics.hide();
      }

      var $topicCuratedItem = $('#topic-curated-warning-'+val);

      var $topicCuratedWarning = $('.curated-topics');
      if ($topicCuratedItem.siblings().length == 0) {
        $topicCuratedWarning.hide();
      }

      $topicCuratedItem.remove();
    }

    $suggested.prop('checked', $this.prop('checked'));
  });

  $('#selected-topics').on('change', 'input', function(e) {
    var $this = $(this);
    var $div = $this.parents('.list-group-item');
    var $master = $('#'+$this.val()+'-item');
    var $suggested = $('#'+$this.val()+'-suggested');

    if ($this.is(':checked') == false) {
      $master.find('input').click();
    }

    $suggested.prop('checked', $this.prop('checked'));
  });

  $('#policy-area-ids').chosen().change(function(e, p) {
    if (p.selected != null) {
      var numSubs = Math.floor(Math.random() * (200 - 1000) + 1000);

      var $policySubscribers = $('#policy-area-subscribers');

      if ($policySubscribers.length == 0) {
        $('
0 users will be emailed about this document.
')
          .insertAfter('#policy_area_ids_chosen');
        $policySubscribers = $('#policy-area-subscribers');
      }

      $policySubscribers.text(numSubs + Number($policySubscribers.text()));
    }
  });

  $('.suggested-topics-list').on('change', 'input', function(e) {
    var $this = $(this);
    var id = $this.val();

    $(id).find('input').prop('checked', $this.prop('checked')).trigger('change');
  });

  $('#suggested-topics-select').on('click', function(e) {
    e.preventDefault();

    $('.suggested-topics-list').find('input').prop('checked', true).trigger('change');
  });

  $('.preview-topics').hide() // hide preview box on load
  $('.curated-topics').hide() // hide curated topics box on load

  $('.nav-tabs').on('click', 'a', function(e) {
    unloadWarning = true;
  });

  $(window).on('beforeunload', function(e) {
    if (unloadWarning) {
      unloadWarning = false;
      return "You have unsaved changes that will be lost if you leave this page."
    }
  });
});


text:
package ru.stqa.pft.addressbook.tests;

import com.google.common.reflect.TypeToken;
import com.google.gson.Gson;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import ru.stqa.pft.addressbook.model.GroupData;
import ru.stqa.pft.addressbook.model.Groups;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;
import java.util.stream.Collectors;

import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.MatcherAssert.assertThat;

public class GroupCreationTests extends TestBase {

    @DataProvider
    public Iterator<Object[]> validGroupsFromJson() throws IOException {
        try (BufferedReader reader = new BufferedReader(new FileReader(new File("src/test/resources/groups.json")))) {
            String json = "";
            String line = reader.readLine();
            while (line != null) {
                System.out.println(line);
                json += line;
                line = reader.readLine();
            }
            Gson gson = new Gson();
            List<GroupData> groups = gson.fromJson(json, new TypeToken<List<GroupData>>(){}.getType());
            return groups.stream().map((g) -> new Object[]{g}).collect(Collectors.toList()).iterator();
        }
    }

    @Test(dataProvider = "validGroupsFromJson")
    public void testGroupCreation(GroupData group) {
        app.goTo().groupPage();
        Groups before = app.db().groups();
        app.group().create(group);
        Groups after = app.db().groups();
        assertThat(after.size(),equalTo(before.size() + 1));
        assertThat(after, equalTo(
                before.withAdded(group.withId(after.stream().mapToInt((g) -> g.getId()).max().getAsInt()))));
        verifyGroupListInUI();
    }
}


text:
#include "Test.h"
#include "Pattern.h"

#include "dsp/matrix_functions.h"

class BinaryTestsQ31:public Client::Suite
    {
        public:
            BinaryTestsQ31(Testing::testID_t id);
            virtual void setUp(Testing::testID_t,std::vector<Testing::param_t>& params,Client::PatternMgr *mgr);
            virtual void tearDown(Testing::testID_t,Client::PatternMgr *mgr);
        private:
            #include "BinaryTestsQ31_decl.h"
            Client::Pattern<q31_t> input1;
            Client::Pattern<q31_t> input2;
            Client::Pattern<q31_t> ref;
            Client::Pattern<int16_t> dims;
            Client::LocalPattern<q31_t> output;
            Client::LocalPattern<q31_t> tmp;

            /* Local copies of inputs since matrix instance in CMSIS-DSP are not using
               pointers to const.
            */
            Client::LocalPattern<q31_t> a;
            Client::LocalPattern<q31_t> b;

            int nbr;
            int nbc;

            arm_matrix_instance_q31 in1;
            arm_matrix_instance_q31 in2;
            arm_matrix_instance_q31 out;
    };


text:
package com.hjhrq1991.commonview.widget;

import android.content.Context;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.widget.ListView;

import com.hjhrq1991.commonview.View.CommonFooterView;

/**
 * @author hjhrq1991 created at 4/24/16 09 33.
 * @Package com.hjhrq1991.car.View
 * @Description:通用底部加载更多listivew
 */
public class CommonFooterListView extends ListView {

    private CommonFooterView mLoadingFooter;

    public CommonFooterListView(Context context) {
        super(context);
        addLoadMoreFooter();
    }

    public CommonFooterListView(Context context, AttributeSet attrs) {
        super(context, attrs);
        addLoadMoreFooter();
    }

    public CommonFooterListView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        addLoadMoreFooter();
    }

    public void setState(CommonFooterView.State state) {
        if (mLoadingFooter != null) {
            mLoadingFooter.setState(state);
        }
    }

    /**
     * 添加加载更多底部
     */
    public void addLoadMoreFooter() {
        if (mLoadingFooter == null) {
            mLoadingFooter = new CommonFooterView(getContext());
            addFooterView(mLoadingFooter);
            mLoadingFooter.setState(CommonFooterView.State.RESET);
        }
    }

    /**
     * 设置footer view的点击事件
     */
    public void setOnFooterClickListener(@Nullable CommonFooterView.OnFooterClickListener onFooterClickListener) {
        if (mLoadingFooter != null)
            mLoadingFooter.setOnFooterClickListener(onFooterClickListener);
    }

    public ListView getListView() {
        return this;
    }

}


text:
"use strict";

/* global describe,it */
var assert = require("assert");
var nooocl = require("../");
var CLHost = nooocl.CLHost;
var CLCommandQueue = nooocl.CLCommandQueue;
var fastcall = require("fastcall");
var ref = fastcall.ref;
var testHelpers = require("./testHelpers");
var path = require("path");
var Bluebird = require("bluebird");
var fs = Bluebird.promisifyAll(require("fs"));
var cd = __dirname;
var jpeg = require("jpeg-js");
var CLImage2D = nooocl.CLImage2D;
var NDRange = nooocl.NDRange;
var scope = nooocl.scope;

describe("CLImage2D", function () {
    beforeEach(function () {
        scope.begin();
    });

    afterEach(function () {
        scope.end();
    });

    it("should convert an image to grayscale", function (done) {
        testHelpers.doTest(function (env) {
            var host = env.host;
            var context = env.context;
            var device = env.device;
            return fs.readFileAsync(path.join(cd, "elefant.jpg")).then(function (data) {
                var inputImage = jpeg.decode(data);
                var queue = new CLCommandQueue(context, device);
                var format = new (host.cl.types.ImageFormat)({
                    imageChannelOrder: host.cl.defs.CL_RGBA,
                    imageChannelDataType: host.cl.defs.CL_UNSIGNED_INT8
                });
                var src = CLImage2D.wrapReadOnly(context, format, inputImage.width, inputImage.height, inputImage.data);
                var outputData = new Buffer(inputImage.data.length);
                var dst = CLImage2D.wrapWriteOnly(context, format, inputImage.width, inputImage.height, outputData);
                return fs.readFileAsync(path.join(cd, "toGray.cl"), "utf8").then(
                    function (source) {
                        var program = context.createProgram(source);
                        return program.build().then(function () {
                            var buildStatus = program.getBuildStatus(device);
                            if (buildStatus < 0) {
                                assert.fail("Build failed.\n" + program.getBuildLog(device));
                            }
                            var kernel = program.createKernel("toGray");
                            kernel.setArgs(src, dst);
                            queue.enqueueNDRangeKernel(kernel, new NDRange(inputImage.width, inputImage.height), null, null);
                            var out = {};
                            var origin = new NDRange(0, 0, 0);
                            var region = new NDRange(inputImage.width, inputImage.height, 1);
                            return queue.waitable().enqueueMapImage(dst, host.cl.defs.CL_MAP_READ, origin, region, out).promise
                                .then(function () {
                                    assert(out.ptr ? true : false);
                                    assert.equal(out.rowPitch, inputImage.width * 4);
                                    assert.equal(ref.address(out.ptr), ref.address(outputData));

                                    var outputImage = {
                                        width: inputImage.width,
                                        height: inputImage.height,
                                        data: outputData
                                    };

                                    var jpegData = jpeg.encode(outputImage, 85);

                                    return fs.writeFileAsync(path.join(cd, "out.jpg"), jpegData.data, "binary").finally(
                                        function () {
                                            return queue.waitable().enqueueUnmapMemory(dst, out.ptr).promise;
                                        });
                                });
                        });
                    });
            });
        }).nodeify(done);
    });
});


text:
//------------------------------------------------------------------------------
// <auto-generated>
//     This code was generated by a tool.
//
//     Changes to this file may cause incorrect behavior and will be lost if
//     the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------

namespace Hotcakes.Modules.Top10Products {

    public partial class Top10ProductsView {
    }
}


text:
package sample.async_native

import skinny.test.SkinnyFunSpec

class MinimumAppSpec extends SkinnyFunSpec {
  addFilter(classOf[MinimumApp], "/*")

  describe("Async native MinimumApp") {

    it("accepts GET requests") {
      get("/hello") {
        status should equal(200)
        body should equal("Hello, World!")
        header("Content-Type") should equal("text/plain; charset=UTF-8")
      }
    }

    it("accepts POST requests") {
      post("/hello", "name" -> "Martin") {
        status should equal(200)
        body should equal("Hello, Martin!")
        header("Content-Type") should equal("text/plain; charset=UTF-8")
      }
    }

    it("returns response headers") {
      get("/hello-with-cookie-1") {
        status should equal(200)
        body should equal("Hello, World!")
        header("Content-Type") should equal("text/plain; charset=UTF-8")
        header("Set-Cookie") should equal("theme=light;Path=/")
      }

      get("/hello-with-cookie-2") {
        status should equal(200)
        body should equal("Hello, World!")
        header("Content-Type") should equal("text/plain; charset=UTF-8")
        header("Set-Cookie") should equal("theme=light")
      }
    }

  }

}


text:
.icon-down-open:before { content: '\e75c'; } /* down open arrow */
.icon-left-open:before { content: '\e75d'; } /* left open arrow */
.icon-right-open:before { content: '\e75e'; } /* right open arrow */
.icon-up-open:before { content: '\e75f'; } /* up open arrow */


text: a bit about yourself