text:
"""
Attribute List Extension for Python-Markdown
============================================

Adds attribute list syntax. Inspired by
[maruku](http://maruku.rubyforge.org/proposal.html#attribute_lists)'s
feature of the same name.

Copyright 2011 [Waylan Limberg](http://achinghead.com/).

Contact: markdown@freewisdom.org

License: BSD (see ../LICENSE.md for details)

Dependencies:
* [Python 2.4+](http://python.org)
* [Markdown 2.1+](http://packages.python.org/Markdown/)

"""

from __future__ import absolute_import
from __future__ import unicode_literals
from . import Extension
from ..treeprocessors import Treeprocessor
from ..util import isBlockLevel
import re

try:
    Scanner = re.Scanner
except AttributeError:
    # must be on Python 2.4
    from sre import Scanner

def _handle_double_quote(s, t):
    k, v = t.split('=')
    return k, v.strip('"')

def _handle_single_quote(s, t):
    k, v = t.split('=')
    return k, v.strip("'")

def _handle_key_value(s, t):
    return t.split('=')

def _handle_word(s, t):
    if t.startswith('.'):
        return '.', t[1:]
    if t.startswith('#'):
        return 'id', t[1:]
    return t, t

_scanner = Scanner([
    (r'[^ ]+=".*?"', _handle_double_quote),
    (r"[^ ]+='.*?'", _handle_single_quote),
    (r'[^ ]+=[^ ]*', _handle_key_value),
    (r'[^ ]+', _handle_word),
    (r' ', None)
])

def get_attrs(str):
    """ Parse attribute list and return a list of attribute tuples. """
    return _scanner.scan(str)[0]

def isheader(elem):
    return elem.tag in ['h1', 'h2', 'h3', 'h4', 'h5', 'h6']

class AttrListTreeprocessor(Treeprocessor):

    BASE_RE = r'\{\:?([^\}]*)\}'
    HEADER_RE = re.compile(r'[ ]+%s[ ]*$' % BASE_RE)
    BLOCK_RE = re.compile(r'\n[ ]*%s[ ]*$' % BASE_RE)
    INLINE_RE = re.compile(r'^%s' % BASE_RE)
    NAME_RE = re.compile(r'[^A-Z_a-z\u00c0-\u00d6\u00d8-\u00f6\u00f8-\u02ff\u0370-\u037d'
                         r'\u037f-\u1fff\u200c-\u200d\u2070-\u218f\u2c00-\u2fef'
                         r'\u3001-\ud7ff\uf900-\ufdcf\ufdf0-\ufffd'
                         r'\:\-\.0-9\u00b7\u0300-\u036f\u203f-\u2040]+')

    def run(self, doc):
        for elem in doc.getiterator():
            if isBlockLevel(elem.tag):
                # Block level: check for attrs on last line of text
                RE = self.BLOCK_RE
                if isheader(elem) or elem.tag == 'dt':
                    # header or def-term: check for attrs at end of line
                    RE = self.HEADER_RE
                if len(elem) and elem.tag == 'li':
                    # special case list items. children may include a ul or ol.
                    pos = None
                    # find the ul or ol position
                    for i, child in enumerate(elem):
                        if child.tag in ['ul', 'ol']:
                            pos = i
                            break
                    if pos is None and elem[-1].tail:
                        # use tail of last child. no ul or ol.
                        m = RE.search(elem[-1].tail)
                        if m:
                            self.assign_attrs(elem, m.group(1))
                            elem[-1].tail = elem[-1].tail[:m.start()]
                    elif pos is not None and pos > 0 and elem[pos-1].tail:
                        # use tail of last child before ul or ol
                        m = RE.search(elem[pos-1].tail)
                        if m:
                            self.assign_attrs(elem, m.group(1))
                            elem[pos-1].tail = elem[pos-1].tail[:m.start()]
                    elif elem.text:
                        # use text. ul is first child.
                        m = RE.search(elem.text)
                        if m:
                            self.assign_attrs(elem, m.group(1))
                            elem.text = elem.text[:m.start()]
                elif len(elem) and elem[-1].tail:
                    # has children. Get from tail of last child
                    m = RE.search(elem[-1].tail)
                    if m:
                        self.assign_attrs(elem, m.group(1))
                        elem[-1].tail = elem[-1].tail[:m.start()]
                        if isheader(elem):
                            # clean up trailing #s
                            elem[-1].tail = elem[-1].tail.rstrip('#').rstrip()
                elif elem.text:
                    # no children. Get from text.
                    m = RE.search(elem.text)
                    if not m and elem.tag == 'td':
                        m = re.search(self.BASE_RE, elem.text)
                    if m:
                        self.assign_attrs(elem, m.group(1))
                        elem.text = elem.text[:m.start()]
                        if isheader(elem):
                            # clean up trailing #s
                            elem.text = elem.text.rstrip('#').rstrip()
            else:
                # inline: check for attrs at start of tail
                if elem.tail:
                    m = self.INLINE_RE.match(elem.tail)
                    if m:
                        self.assign_attrs(elem, m.group(1))
                        elem.tail = elem.tail[m.end():]

    def assign_attrs(self, elem, attrs):
        """ Assign attrs to element. """
        for k, v in get_attrs(attrs):
            if k == '.':
                # add to class
                cls = elem.get('class')
                if cls:
                    elem.set('class', '%s %s' % (cls, v))
                else:
                    elem.set('class', v)
            else:
                # assign attr k with v
                elem.set(self.sanitize_name(k), v)

    def sanitize_name(self, name):
        """
        Sanitize name as 'an XML Name, minus the ":"'.
        See http://www.w3.org/TR/REC-xml-names/#NT-NCName
        """
        return self.NAME_RE.sub('_', name)

class AttrListExtension(Extension):
    def extendMarkdown(self, md, md_globals):
        md.treeprocessors.add('attr_list', AttrListTreeprocessor(md), '>prettify')

def makeExtension(configs={}):
    return AttrListExtension(configs=configs)


text:
declare interface WebPushParams {
  TTL?: number;
  vapidDetails: {
    subject: string;
    publicKey: string;
    privateKey: string;
  };
}

declare interface WebPush {
  sendNotification(subscription: any, message: any, options: WebPushParams): Promise<any>;
}

let push: WebPush = require('web-push');

export function sendPush(subscription: any, payload?: Object): Promise<any> {
  return push.sendNotification(subscription, JSON.stringify(payload), {
    vapidDetails: {
      subject: 'mailto:test@angular.io',
      publicKey: 'BLRl_fG1TCTc1D2JwzOpdZjaRcJucXtG8TAd5g9vuYjl6KUUDxgoRjQPCgjZfY-_Rusd_qtjNvanHXeFvOFlxH4',
      privateKey: 't3JtFOflouvPUxFKeSSmZdjuVidnD_0dNGFM1v-N4PI',
    },
  });
}

redpajama_set_name: RedPajamaGithub


text:
import { buildProgram, buildComponent, buildElement, buildComment, buildText } from "./builders";
import {
  appendChild,
  parseComponentBlockParams
} from "./utils";
import voidMap from '../htmlbars-util/void-tag-names';

// Except for `mustache`, all tokens are only allowed outside of
// a start or end tag.
var tokenHandlers = {
  Comment: function(token) {
    var current = this.currentElement();
    var comment = buildComment(token.chars);
    appendChild(current, comment);
  },

  Chars: function(token) {
    var current = this.currentElement();
    var text = buildText(token.chars);
    appendChild(current, text);
  },

  StartTag: function(tag) {
    var element = buildElement(tag.tagName, tag.attributes, tag.modifiers || [], []);
    element.loc = {
      start: { line: tag.firstLine, column: tag.firstColumn},
      end: { line: null, column: null}
    };

    this.elementStack.push(element);
    if (voidMap.hasOwnProperty(tag.tagName) || tag.selfClosing) {
      tokenHandlers.EndTag.call(this, tag, true);
    }
  },

  BlockStatement: function(/*block*/) {
    if (this.tokenizer.state === 'comment') {
      return;
    } else if (this.tokenizer.state !== 'data') {
      throw new Error("A block may only be used inside an HTML element or another block.");
    }
  },

  MustacheStatement: function(mustache) {
    var tokenizer = this.tokenizer;

    switch(tokenizer.state) {
      // Tag helpers
      case "tagName":
        tokenizer.addElementModifier(mustache);
        tokenizer.state = "beforeAttributeName";
        return;
      case "beforeAttributeName":
        tokenizer.addElementModifier(mustache);
        return;
      case "attributeName":
      case "afterAttributeName":
        tokenizer.finalizeAttributeValue();
        tokenizer.addElementModifier(mustache);
        tokenizer.state = "beforeAttributeName";
        return;
      case "afterAttributeValueQuoted":
        tokenizer.addElementModifier(mustache);
        tokenizer.state = "beforeAttributeName";
        return;

      // Attribute values
      case "beforeAttributeValue":
        tokenizer.markAttributeQuoted(false);
        tokenizer.addToAttributeValue(mustache);
        tokenizer.state = 'attributeValueUnquoted';
        return;
      case "attributeValueDoubleQuoted":
      case "attributeValueSingleQuoted":
      case "attributeValueUnquoted":
        tokenizer.addToAttributeValue(mustache);
        return;

      // TODO: Only append child when the tokenizer state makes
      // sense to do so, otherwise throw an error.
      default:
        appendChild(this.currentElement(), mustache);
    }
  },

  EndTag: function(tag, selfClosing) {
    var element = this.elementStack.pop();
    var parent = this.currentElement();
    var disableComponentGeneration = this.options.disableComponentGeneration === true;

    validateEndTag(tag, element, selfClosing);

    if (disableComponentGeneration || element.tag.indexOf("-") === -1) {
      appendChild(parent, element);
    } else {
      var program = buildProgram(element.children);
      parseComponentBlockParams(element, program);
      var component = buildComponent(element.tag, element.attributes, program);
      appendChild(parent, component);
    }

  }

};

function validateEndTag(tag, element, selfClosing) {
  var error;

  if (voidMap[tag.tagName] && !selfClosing) {
    // EngTag is also called by StartTag for void and self-closing tags (i.e.
    // <input> or <br />, so we need to check for that here. Otherwise, we would
    // throw an error for those cases.
    error = "Invalid end tag " + formatEndTagInfo(tag) + " (void elements cannot have end tags).";
  } else if (element.tag === undefined) {
    error = "Closing tag " + formatEndTagInfo(tag) + " without an open tag.";
  } else if (element.tag !== tag.tagName) {
    error = "Closing tag " + formatEndTagInfo(tag) + " did not match last open tag `" + element.tag + "` (on line " +
            element.loc.start.line + ").";
  }

  if (error) { throw new Error(error); }
}

function formatEndTagInfo(tag) {
  return "`" + tag.tagName + "` (on line " + tag.lastLine + ")";
}

export default tokenHandlers;


text:
using System;

namespace SharpChatUIClientVS
{
    public static class ConnectionData
    {
        public static String serverIPString { get; set; }
        public static String serverPortString { get; set; }
    }
}


text:
module Microframe
  module ORM
    class Errors
      def initialize
        @errors = []
      end

      def add(error)
        @errors << error
      end

      def fetch_errors
        @errors
      end

      def clear_errors
        @errors = []
      end
    end
  end
end


text:
require 'test_helper'

class ReceiptsControllerTest < ActionController::TestCase

  def test_領収書のダウンロード
    sign_in user
    get :show, :params => {:id => receipt.id}
    assert_response :success
    assert_equal Digest::MD5.file(receipt.file.path), Digest::MD5.hexdigest(@response.body)
  end

end


text:
package main

import(
	"time"
	"strconv"
)

func GetLogValue(log_number string)(string,int64){
	timestamp := time.Now().Unix()
        logvalue = strconv.FormatInt(timestamp, 10) + log_number
	return logvalue,timestamp
}

func AddLogValue(log_number,logvalue string)(string,int64){
	timestamp := time.Now().Unix()
	logvalue = logvalue + "|" + strconv.FormatInt(timestamp, 10) + log_number
	return logvalue,timestamp
}

func GetLogKey(servicename,hostname string,timestamp int64)string{
	logkey = "cmha/service/" + servicename + "/log/" + hostname + "/mha-handlers/" + strconv.FormatInt(timestamp, 10)
	return logkey
}


text:
"use strict";
define([

	'underscore', 'pattern/Mammal'

], function(_, Mammal){

	describe('Mammal', function(){
		it('exports an Mammal constructor', function(){
			expect(typeof Mammal).toBe('function');
		});
		describe('constructor', function(){
			beforeEach(function(){
				this.mammal = new Mammal({name: 'example'});
			});
			it('sets optional properties', function(){
				expect(typeof this.mammal.name).toBe('string');
				expect(this.mammal.name).toBe('example');
			});
			it('returns {Mammal} new instance', function(){
				expect(typeof this.mammal).toBe('object');
				expect(this.mammal instanceof Mammal).toEqual(true);
			});
		});
		describe('member', function(){
			beforeEach(function(){
				this.mammal = new Mammal();
			});
			describe('age', function(){
				it('has a {number} length of existence', function(){
					expect(_.isNumber(this.mammal.age)).toEqual(true);
				});
			});
			describe('genus', function(){
				it('has a {string} genus name', function(){
					expect(_.isString(this.mammal.genus)).toEqual(true);
				});
			});
			describe('species', function(){
				it('has a {string} species name', function(){
					expect(_.isString(this.mammal.species)).toEqual(true);
				});
			});
			describe('weight', function(){
				it('has a {number} relative mass', function(){
					expect(_.isNumber(this.mammal.weight)).toEqual(true);
				});
			});
		});
		describe('method', function(){
			beforeEach(function(){
				this.mammal = new Mammal();
			});
			describe('drink', function(){
				it('returns {boolean} success indicator', function(){
					expect(typeof this.mammal.drink()).toBe('boolean');
				});
			});
			describe('feed', function(){
				it('returns {boolean} success indicator', function(){
					expect(typeof this.mammal.feed()).toBe('boolean');
				});
			});
		});
	});
});


text:
package io.getquill.codegen

import io.getquill.codegen.integration.CodegenTestCases._
import io.getquill.codegen.util.ConfigPrefix.TestSqlServerDB
import io.getquill.codegen.util._
import org.scalatest.matchers.should.Matchers._

class SqlServerCodegenTestCases extends CodegenSpec {
  import io.getquill.codegen.generated.postgres._

  type Prefix = TestSqlServerDB
  val prefix = TestSqlServerDB

  "trivial generator tests" - {
    "use trivial snake case schema" in WithContext[Prefix, `1-simple-snake`].run { ctx =>
      import `1-simple-snake-lib`.public._
      import ctx._

      val results = ctx.run(query[Person].filter(_.age > 11)).toSeq
      results should contain theSameElementsAs
        (List(Person(1, "Joe", "Bloggs", 22), Person(2, "Jack", "Ripper", 33)))
    }
    "use trivial literal schema" in WithContext[Prefix, `2-simple-literal`].run { ctx =>
      import `2-simple-literal-lib`.public._
      import ctx._

      val results = ctx.run(query[Person].filter(_.age > 11)).toSeq
      results should contain theSameElementsAs
        (List(Person(1, "Joe", "Bloggs", 22), Person(2, "Jack", "Ripper", 33)))
    }
  }

  "composable generator" - {

    "1-comp-sanity" in WithContext[Prefix, `1-comp-sanity`].run { ctx =>
      import `1-comp-sanity-lib`.public._
      import ctx._
      ctx.run(query[Person].filter(_.age > 11)) should contain theSameElementsAs List(
        Person(1, "Joe", "Bloggs", 22),
        Person(2, "Jack", "Ripper", 33)
      )
    }

    "2-comp-stereo-single" in WithContext[Prefix, `2-comp-stereo-single`].run { ctx =>
      import `2-comp-stereo-single-lib`.public._
      import ctx._
      (ctx.run(PersonDao.query.filter(_.age > 11))) should contain theSameElementsAs
        (List(
          Person(1, "Joe", "Bloggs", 22),
          Person(2, "Jack", "Ripper", 33)
        ))
    }

    "3-comp-stereo-oneschema" in WithContext[Prefix, `3-comp-stereo-oneschema`].run { ctx =>
      import `3-comp-stereo-oneschema-lib`.public._
      import ctx._

      (ctx.run(PublicSchema.PersonDao.alphaPerson.filter(_.age > 11))) should contain theSameElementsAs (
        List(
          Person(1, "Joe", "Bloggs", 22, 55L, "Wonkles"),
          Person(2, "Jack", "Ripper", 33, 66L, "Ginkles")
        )
      )
      (ctx.run(PublicSchema.AddressDao.publicAddress.filter(_.personFk == 1))) should contain theSameElementsAs (
        List(
          Address(1, "123 Someplace", 1001),
          Address(1, "678 Blah", 2002)
        )
      )
    }

    "4-comp-stereo-twoschema" in WithContext[Prefix, `4-comp-stereo-twoschema`].run { ctx =>
      import `4-comp-stereo-twoschema-lib`.common._
      import `4-comp-stereo-twoschema-lib`.public._
      import ctx._

      (ctx.run(PersonDao.alphaPerson.filter(_.age > 11))) should contain theSameElementsAs (
        List(
          Person(1, "Joe", "Bloggs", 22, 55L, "Wonkles"),
          Person(2, "Jack", "Ripper", 33, 66L, "Ginkles")
        )
      )
      (ctx.run(AddressDao.publicAddress.filter(_.personFk == 1))) should contain theSameElementsAs (
        List(
          Address(1, "123 Someplace", 1001),
          Address(1, "678 Blah", 2002)
        )
      )
    }

    "5 - non-stereotyped multiple schemas" in WithContext[Prefix, `5-comp-non-stereo-allschema`].run { ctx =>
      import `5-comp-non-stereo-allschema-lib`.alpha._
      import `5-comp-non-stereo-allschema-lib`.public._
      import ctx._

      (ctx.run(ctx.AlphaSchema.PersonDao.query.filter(_.age > 11))) should contain theSameElementsAs (
        List(
          Person(1, "Joe", "Bloggs", 22, "blah", 55, "Wonkles"),
          Person(2, "Jack", "Ripper", 33, "blah", 66, "Ginkles")
        )
      )
      (ctx.run(ctx.PublicSchema.AddressDao.query.filter(_.personFk == 1))) should contain theSameElementsAs (
        List(
          Address(1, "123 Someplace", 1001),
          Address(1, "678 Blah", 2002)
        )
      )
    }
  }
}


text:
@echo off
echo Building Thirdparty
mkdir thirdparty
cd thirdparty
echo Getting LLRPLTK....
git clone https://github.com/mbuckaway/LLRPToolkit LLRPToolkit
cd LLRPToolkit
mkdir build
cd build
cmake -G "Unix Makefiles" ..
make
make install


text:
'''import unittest

class Test_gold_room(unittest.TestCase):

    def test test_greedy(self):
        self.

def gold_room():
    print "You enter a room full of gold, how much gold do you take?"
    amount = raw_input('> ')
    if "0" in amount or "1" in amount:
        how_much = int(amount)
    else:
        dead("Man, learn to type a number.")

    if how_much < 50:
        print "Nice, you're not greedy, you win!"
        exit(0)
    else:
        dead("You greedy bastard!")

def dead(str):
    print str, "Good job!"

gold_room()'''

import os
def say_hello(input_func):
    name = input_func()
    return "Hello " + name

def prompt_for_name():
    return raw_input("What is your name? ")

print say_hello(prompt_for_name)
# Normally would pass in methods, but lambdas can be used for brevity
print say_hello(lambda: open("a.txt").readline())
print say_hello(lambda: os.environ.get("USER"))


text:
<?php

namespace Backend\Modules\FormBuilder\Ajax;

use Backend\Core\Engine\Base\AjaxAction as BackendBaseAJAXAction;
use Backend\Modules\FormBuilder\Engine\Model as BackendFormBuilderModel;

/**
 * Delete a field via ajax.
 */
class DeleteField extends BackendBaseAJAXAction
{
    /**
     * Execute the action
     */
    public function execute()
    {
        parent::execute();

        // get parameters
        $formId = trim(\SpoonFilter::getPostValue('form_id', null, '', 'int'));
        $fieldId = trim(\SpoonFilter::getPostValue('field_id', null, '', 'int'));

        // invalid form id
        if (!BackendFormBuilderModel::exists($formId)) {
            $this->output(self::BAD_REQUEST, null, 'form does not exist');
        } else {
            // invalid fieldId
            if (!BackendFormBuilderModel::existsField($fieldId, $formId)) {
                $this->output(self::BAD_REQUEST, null, 'field does not exist');
            } else {
                // get field
                $field = BackendFormBuilderModel::getField($fieldId);

                // submit button cannot be deleted
                if ($field['type'] == 'submit') {
                    $this->output(self::BAD_REQUEST, null, 'submit button cannot be deleted');
                } else {
                    // delete field
                    BackendFormBuilderModel::deleteField($fieldId);

                    // success output
                    $this->output(self::OK, null, 'field deleted');
                }
            }
        }
    }
}


text:
{% extends "layout.html" %}

{% block content %}

{% if form.has_errors %}

Your username and password didn't match. Please try again.

{% endif %}

Log in to your account

<form method="post" action="/login">
  {% csrf_token %}

	Username:
	<input type="text" name="username" value="{{ form.username }}">

	Password:
	<input type="password" name="password">

	<input type="submit" value="Login" /><input type="hidden" name="next" value="{{ next }}" />

</form>

{% endblock %}


text:
package com.amazonaws.services.glue.model.transform;

import java.util.List;
import javax.annotation.Generated;

import com.amazonaws.SdkClientException;
import com.amazonaws.services.glue.model.*;

import com.amazonaws.protocol.*;
import com.amazonaws.annotation.SdkInternalApi;

/**
 * AuditContextMarshaller
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
@SdkInternalApi
public class AuditContextMarshaller {

    private static final MarshallingInfo<String> ADDITIONALAUDITCONTEXT_BINDING = MarshallingInfo.builder(MarshallingType.STRING)
            .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("AdditionalAuditContext").build();
    private static final MarshallingInfo<List> REQUESTEDCOLUMNS_BINDING = MarshallingInfo.builder(MarshallingType.LIST)
            .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("RequestedColumns").build();
    private static final MarshallingInfo<Boolean> ALLCOLUMNSREQUESTED_BINDING = MarshallingInfo.builder(MarshallingType.BOOLEAN)
            .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("AllColumnsRequested").build();

    private static final AuditContextMarshaller instance = new AuditContextMarshaller();

    public static AuditContextMarshaller getInstance() {
        return instance;
    }

    /**
     * Marshall the given parameter object.
     */
    public void marshall(AuditContext auditContext, ProtocolMarshaller protocolMarshaller) {

        if (auditContext == null) {
            throw new SdkClientException("Invalid argument passed to marshall(...)");
        }

        try {
            protocolMarshaller.marshall(auditContext.getAdditionalAuditContext(), ADDITIONALAUDITCONTEXT_BINDING);
            protocolMarshaller.marshall(auditContext.getRequestedColumns(), REQUESTEDCOLUMNS_BINDING);
            protocolMarshaller.marshall(auditContext.getAllColumnsRequested(), ALLCOLUMNSREQUESTED_BINDING);
        } catch (Exception e) {
            throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
        }
    }

}


text:
package doodle
package core

sealed trait Gradient extends Product with Serializable
object Gradient {
  final case class Linear(
      start: Point,
      end: Point,
      stops: Seq[(Color, Double)],
      cycleMethod: CycleMethod
  ) extends Gradient
  final case class Radial(
      outer: Point,
      inner: Point,
      radius: Double,
      stops: Seq[(Color, Double)],
      cycleMethod: CycleMethod
  ) extends Gradient

  def linear(
      start: Point,
      end: Point,
      stops: Seq[(Color, Double)],
      cycleMethod: CycleMethod
  ): Gradient =
    Linear(start, end, stops, cycleMethod)

  def radial(
      outer: Point,
      inner: Point,
      radius: Double,
      stops: Seq[(Color, Double)],
      cycleMethod: CycleMethod
  ): Gradient =
    Radial(outer, inner, radius, stops, cycleMethod)

  def dichromaticVertical(color1: Color, color2: Color, length: Double) =
    Linear(
      Point.zero,
      Point.Cartesian(0, length),
      List((color1, 0.0), (color2, 1.0)),
      CycleMethod.repeat
    )

  def dichromaticHorizontal(color1: Color, color2: Color, length: Double) =
    Linear(
      Point.zero,
      Point.Cartesian(length, 0),
      List((color1, 0.0), (color2, 1.0)),
      CycleMethod.repeat
    )

  def dichromaticRadial(color1: Color, color2: Color, radius: Double) =
    Radial(
      Point.zero,
      Point.zero,
      radius,
      List((color1, 0.0), (color2, 1.0)),
      CycleMethod.repeat
    )

  sealed trait CycleMethod extends Product with Serializable {}
  object CycleMethod {
    case object NoCycle extends CycleMethod
    case object Reflect extends CycleMethod
    case object Repeat extends CycleMethod

    val noCycle: CycleMethod = NoCycle
    val reflect: CycleMethod = Reflect
    val repeat: CycleMethod = Repeat
  }
}


text:
(function () {
  "use strict";

  angular.module('mnXDCR').controller('mnXDCRDeleteReferenceDialogController', mnXDCRDeleteReferenceDialogController);

  function mnXDCRDeleteReferenceDialogController($scope, $uibModalInstance, mnPromiseHelper, mnXDCRService, name) {
    var vm = this;

    vm.name = name;
    vm.deleteClusterReference = deleteClusterReference;

    function deleteClusterReference() {
      var promise = mnXDCRService.deleteClusterReference(name);
      mnPromiseHelper(vm, promise, $uibModalInstance)
        .showGlobalSpinner()
        .closeFinally()
        .catchGlobalErrors()
        .broadcast("reloadXdcrPoller")
        .showGlobalSuccess("Cluster reference deleted successfully!");
    }
  }
})();


text:
/*
  DO NOT EDIT THIS FILE - the content was created using a source code generator
*/

#ifndef QVIRTUALKEYBOARDINPUTCONTEXTSLOTS_H
#define QVIRTUALKEYBOARDINPUTCONTEXTSLOTS_H

#include <QtCore/QObject>
#include <QtCore/QCoreApplication>
#include <QtCore/QString>

#include <QtVirtualKeyboard/QVirtualKeyboardInputContext>

#include "qt5xhb_common.h"
#include "qt5xhb_macros.h"
#include "qt5xhb_utils.h"
#include "qt5xhb_signals.h"

class QVirtualKeyboardInputContextSlots: public QObject
{
  Q_OBJECT
  public:
  QVirtualKeyboardInputContextSlots( QObject *parent = 0 );
  ~QVirtualKeyboardInputContextSlots();
  public slots:
  void preeditTextChanged();
  void inputMethodHintsChanged();
  void surroundingTextChanged();
  void selectedTextChanged();
  void anchorPositionChanged();
  void cursorPositionChanged();
  void anchorRectangleChanged();
  void cursorRectangleChanged();
  void shiftActiveChanged();
  void capsLockActiveChanged();
  void uppercaseChanged();
  void animatingChanged();
  void localeChanged();
  void selectionControlVisibleChanged();
  void anchorRectIntersectsClipRectChanged();
  void cursorRectIntersectsClipRectChanged();
};

#endif /* QVIRTUALKEYBOARDINPUTCONTEXTSLOTS_H */


text:
package net.schmizz.sshj.connection.channel.direct;

import net.schmizz.sshj.common.Buffer;
import net.schmizz.sshj.common.Message;
import net.schmizz.sshj.common.SSHPacket;
import net.schmizz.sshj.connection.Connection;
import net.schmizz.sshj.connection.ConnectionException;
import net.schmizz.sshj.connection.channel.AbstractChannel;
import net.schmizz.sshj.connection.channel.Channel;
import net.schmizz.sshj.connection.channel.OpenFailException;
import net.schmizz.sshj.transport.TransportException;

import java.nio.charset.Charset;
import java.util.concurrent.TimeUnit;

/** Base class for direct channels whose open is initiated by the client. */
public abstract class AbstractDirectChannel
        extends AbstractChannel
        implements Channel.Direct {

    protected AbstractDirectChannel(Connection conn, String type) {
        super(conn, type);

        /*
        * We expect to receive channel open confirmation/rejection and want to be able to next this packet.
        */
        conn.attach(this);
    }

    protected AbstractDirectChannel(Connection conn, String type, Charset remoteCharset) {
        super(conn, type, remoteCharset);

        /*
         * We expect to receive channel open confirmation/rejection and want to be able to next this packet.
         */
        conn.attach(this);
    }

    @Override
    public void open()
            throws ConnectionException, TransportException {
        trans.write(buildOpenReq());
        openEvent.await(conn.getTimeoutMs(), TimeUnit.MILLISECONDS);
    }

    private void gotOpenConfirmation(SSHPacket buf)
            throws ConnectionException {
        try {
            init(buf.readUInt32AsInt(), buf.readUInt32(), buf.readUInt32());
        } catch (Buffer.BufferException be) {
            throw new ConnectionException(be);
        }
        openEvent.set();
    }

    private void gotOpenFailure(SSHPacket buf)
            throws ConnectionException {
        try {
            openEvent.deliverError(new OpenFailException(getType(), buf.readUInt32AsInt(), buf.readString()));
        } catch (Buffer.BufferException be) {
            throw new ConnectionException(be);
        }
        finishOff();
    }

    protected SSHPacket buildOpenReq() {
        return new SSHPacket(Message.CHANNEL_OPEN)
                .putString(getType())
                .putUInt32(getID())
                .putUInt32(getLocalWinSize())
                .putUInt32(getLocalMaxPacketSize());
    }

    @Override
    protected void gotUnknown(Message cmd, SSHPacket buf)
            throws ConnectionException, TransportException {
        switch (cmd) {

            case CHANNEL_OPEN_CONFIRMATION:
                gotOpenConfirmation(buf);
                break;

            case CHANNEL_OPEN_FAILURE:
                gotOpenFailure(buf);
                break;

            default:
                super.gotUnknown(cmd, buf);
        }
    }

}


text:
package com.sardinha.mars.explorer.domain;

import static com.sardinha.mars.explorer.domain.CardinalPoint.EAST;
import static com.sardinha.mars.explorer.domain.CardinalPoint.NORTH;
import static com.sardinha.mars.explorer.domain.Command.L;
import static com.sardinha.mars.explorer.domain.Command.M;
import static com.sardinha.mars.explorer.domain.Command.R;
import static org.junit.Assert.assertEquals;

import org.junit.Test;

import com.sardinha.mars.explorer.MarsExplorerUnitTest;
import com.sardinha.mars.explorer.exceptions.ExplorerOutOfMapException;
import com.sardinha.mars.explorer.exceptions.MarsExplorerException;
import com.sardinha.mars.explorer.template.MarsMapTemplate;

import br.com.six2six.fixturefactory.Fixture;

public class ExplorerTest extends MarsExplorerUnitTest {

	private static final MarsMap DEFAULT_MAP = Fixture.from(MarsMap.class).gimme(MarsMapTemplate.VALID);

	@Test
	public void start_12N_execute_LMLMLMLMM_result_X_equals_1() throws MarsExplorerException {
		Command[] commands = { L, M, L, M, L, M, L, M, M };
		Explorer explorer = new Explorer("explorer1", 1, 2, NORTH, DEFAULT_MAP);
		explorer.execute(commands);
		assertEquals(1, explorer.getX());
	}

	@Test
	public void start_12N_execute_LMLMLMLMM_result_Y_equals_3() throws MarsExplorerException {
		Command[] commands = { L, M, L, M, L, M, L, M, M };
		Explorer explorer = new Explorer("explorer1", 1, 2, NORTH, DEFAULT_MAP);
		explorer.execute(commands);
		assertEquals(3, explorer.getY());
	}

	@Test
	public void start_12N_execute_LMLMLMLMM_result_direction_equals_N() throws MarsExplorerException {
		Command[] commands = { L, M, L, M, L, M, L, M, M };
		Explorer explorer = new Explorer("explorer1", 1, 2, NORTH, DEFAULT_MAP);
		explorer.execute(commands);
		assertEquals(NORTH, explorer.getDirection());
	}

	@Test
	public void start_33E_execute_MMRMMRMRRM_result_X_equals_5() throws MarsExplorerException {
		Command[] commands = { M, M, R, M, M, R, M, R, R, M };
		Explorer explorer = new Explorer("explorer2", 3, 3, EAST, DEFAULT_MAP);
		explorer.execute(commands);
		assertEquals(5, explorer.getX());
	}

	@Test
	public void start_33E_execute_MMRMMRMRRM_result_Y_equals_1() throws MarsExplorerException {
		Command[] commands = { M, M, R, M, M, R, M, R, R, M };
		Explorer explorer = new Explorer("explorer2", 3, 3, EAST, DEFAULT_MAP);
		explorer.execute(commands);
		assertEquals(1, explorer.getY());
	}

	@Test
	public void start_33E_execute_MMRMMRMRRM_result_direction_equals_E() throws MarsExplorerException {
		Command[] commands = { M, M, R, M, M, R, M, R, R, M };
		Explorer explorer = new Explorer("explorer2", 3, 3, EAST, DEFAULT_MAP);
		explorer.execute(commands);
		assertEquals(EAST, explorer.getDirection());
	}

	@Test(expected = ExplorerOutOfMapException.class)
	public void create_explorer_out_of_max_X_must_throw_exception() throws MarsExplorerException {
		MarsMap map = Fixture.from(MarsMap.class).gimme(MarsMapTemplate.LIMIT_3);
		new Explorer("explorer2", 4, 3, EAST, map);
	}

	@Test(expected = ExplorerOutOfMapException.class)
	public void create_explorer_out_of__min_X_must_throw_exception() throws MarsExplorerException {
		MarsMap map = Fixture.from(MarsMap.class).gimme(MarsMapTemplate.LIMIT_3);
		new Explorer("explorer2", -1, 3, EAST, map);
	}

	@Test(expected = ExplorerOutOfMapException.class)
	public void create_explorer_out_of_max_Y_must_throw_exception() throws MarsExplorerException {
		MarsMap map = Fixture.from(MarsMap.class).gimme(MarsMapTemplate.LIMIT_3);
		new Explorer("explorer2", 3, 4, EAST, map);
	}

	@Test(expected = ExplorerOutOfMapException.class)
	public void create_explorer_out_of__min_y_must_throw_exception() throws MarsExplorerException {
		MarsMap map = Fixture.from(MarsMap.class).gimme(MarsMapTemplate.LIMIT_3);
		new Explorer("explorer2", 3, -1, EAST, map);
	}

	@Test
	public void create_explorer_in_limit_is_valid() throws MarsExplorerException {
		MarsMap map = Fixture.from(MarsMap.class).gimme(MarsMapTemplate.LIMIT_3);
		new Explorer("explorer2", 3, 3, EAST, map);
	}

}


text:
using UnityEngine;

namespace Pear.InteractionEngine.Converters
{
	/// <summary>
	/// Converts a bool to a vector 3
	/// </summary>
	public class BoolToVector3 : MonoBehaviour, IPropertyConverter<bool, Vector3>
	{
		[Tooltip("Set Field Value on vector.X?")]
		public bool SetX = true;

		[Tooltip("Set Field Value on vector.Y?")]
		public bool SetY = true;

		[Tooltip("Set Field Value on vector.Z?")]
		public bool SetZ = true;

		[Tooltip("Value to set on the new vector's fields")]
		public float FieldValue = 1f;

		/// <summary>
		/// Creates a vector based on the FieldValue
		/// and whether or not that value should be set on each field
		/// </summary>
		/// <param name="convertFrom">bool to convert from</param>
		/// <returns>Vector3 based on user settings</returns>
		public Vector3 Convert(bool convertFrom)
		{
			if (!convertFrom)
				return Vector3.zero;

			return new Vector3(SetX ? FieldValue : 0,
				SetY ? FieldValue : 0,
				SetZ ? FieldValue : 0);
		}
	}
}


text:
namespace fileutils {

const char kNativePathSepChar = '/';
const char *kNativePathSepString = "/";

const char kNativePathListSepChar = ':';
const char *kNativePathListSepString = ":";

void GetDirectoryFiles(const std::string &directory, const std::string &pattern,
                       std::vector<std::string> &files)
{
  DIR *dp;
  if ((dp = opendir(directory.c_str())) != nullptr) {
    struct dirent *dirp;
    while ((dirp = readdir(dp)) != nullptr) {
      if (!fnmatch(pattern.c_str(), dirp->d_name, FNM_CASEFOLD | FNM_NOESCAPE | FNM_PERIOD)) {
        files.push_back(dirp->d_name);
      }
    }
    closedir(dp);
  }
}

std::string GetCurrentWorkingtDirectory() {
  std::vector<char> buffer(256);
  while (getcwd(&buffer[0], buffer.size()) == 0 &&
         errno == ERANGE) {
    buffer.resize(buffer.size() * 2);
  }
  return std::string(&buffer[0]);
}

} // namespace fileutils


text:
package com.mcleodmoores.starling.client.marketdata;

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

import org.testng.Assert;
import org.testng.annotations.Test;

import com.opengamma.id.ExternalId;
import com.opengamma.id.ExternalIdBundle;
import com.opengamma.util.test.TestGroup;
import com.opengamma.util.tuple.ObjectsPair;

/**
 * Unit tests for {@link MarketDataSet}.
 */
@Test(groups = TestGroup.UNIT)
public class MarketDataSetTest {

  /**
   * Tests the behaviour when a null map is supplied.
   */
  @Test(expectedExceptions = IllegalArgumentException.class)
  public void testNull() {
    MarketDataSet.of(null);
  }

  /**
   * Tests the creation of an empty set.
   */
  @Test
  public void testEmpty() {
    final MarketDataSet empty = MarketDataSet.empty();
    Assert.assertEquals(empty.size(), 0);
  }

  /**
   * Tests creation of the set.
   */
  @Test
  public void testOf() {
    final Map<MarketDataKey, Object> map = new HashMap<>();
    final MarketDataSet empty = MarketDataSet.of(map);
    Assert.assertEquals(empty.size(), 0);
    map.put(MarketDataKey.of(ExternalIdBundle.EMPTY), 1.2d);
    final MarketDataSet nonEmpty = MarketDataSet.of(map);
    Assert.assertEquals(nonEmpty.size(), 1);
    map.put(MarketDataKey.of(ExternalIdBundle.of(ExternalId.of("A", "B"))), 0d);
    final MarketDataSet two = MarketDataSet.of(map);
    Assert.assertEquals(two.size(), 2);
  }

  /**
   * Tests that keys can be found.
   */
  @Test
  public void testContainsKey() {
    final Map<MarketDataKey, Object> map = new HashMap<>();
    map.put(MarketDataKey.of(ExternalIdBundle.EMPTY), 1.2d);
    map.put(MarketDataKey.of(ExternalIdBundle.of(ExternalId.of("A", "B"))), 0d);
    final MarketDataSet two = MarketDataSet.of(map);
    Assert.assertTrue(two.containsKey(MarketDataKey.of(ExternalIdBundle.EMPTY)));
    Assert.assertTrue(two.containsKey(MarketDataKey.of(ExternalIdBundle.of(ExternalId.of("A", "B")))));
    Assert.assertFalse(two.containsKey(MarketDataKey.of(ExternalIdBundle.of(ExternalId.of("A", "B"), ExternalId.of("B", "C")))));
  }

  /**
   * Tests data insertion.
   */
  @Test
  public void testPut() {
    final MarketDataSet set = MarketDataSet.empty();
    set.put(MarketDataKey.of(ExternalIdBundle.EMPTY), 1.2d);
    set.put(MarketDataKey.of(ExternalIdBundle.of(ExternalId.of("A", "B"))), 0d);
    Assert.assertTrue(set.containsKey(MarketDataKey.of(ExternalIdBundle.EMPTY)));
    Assert.assertTrue(set.containsKey(MarketDataKey.of(ExternalIdBundle.of(ExternalId.of("A", "B")))));
    Assert.assertFalse(set.containsKey(MarketDataKey.of(ExternalIdBundle.of(ExternalId.of("A", "B"), ExternalId.of("B", "C")))));
    set.putAll(set);
    Assert.assertEquals(set.size(), 2);
    final MarketDataSet other = MarketDataSet.empty();
    other.put(MarketDataKey.of(ExternalId.of("C", "D").toBundle()), 3.4);
    set.putAll(other);
    Assert.assertEquals(set.size(), 3);
    Assert.assertTrue(set.containsKey(MarketDataKey.of(ExternalIdBundle.EMPTY)));
    Assert.assertTrue(set.containsKey(MarketDataKey.of(ExternalIdBundle.of(ExternalId.of("A", "B")))));
    Assert.assertTrue(set.containsKey(MarketDataKey.of(ExternalIdBundle.of(ExternalId.of("C", "D")))));
  }

  /**
   * Tests data retrieval.
   */
  @Test
  public void testGet() {
    final MarketDataSet set = MarketDataSet.empty();
    set.put(MarketDataKey.of(ExternalIdBundle.EMPTY), 1.2d);
    set.put(MarketDataKey.of(ExternalIdBundle.of(ExternalId.of("A", "B"))), 0d);
    Assert.assertEquals(1.2d, set.get(MarketDataKey.of(ExternalIdBundle.EMPTY)));
    Assert.assertEquals(0d, set.get(MarketDataKey.of(ExternalIdBundle.of(ExternalId.of("A", "B")))));
    Assert.assertNull(set.get(MarketDataKey.of(ExternalIdBundle.of(ExternalId.of("A", "B"), ExternalId.of("B", "C")))));
  }

  /**
   * Tests data removal.
   */
  @Test
  public void testRemove() {
    final MarketDataSet set = MarketDataSet.empty();
    set.put(MarketDataKey.of(ExternalIdBundle.EMPTY), 1.2d);
    set.put(MarketDataKey.of(ExternalIdBundle.of(ExternalId.of("A", "B"))), 0d);
    set.remove(MarketDataKey.of(ExternalIdBundle.EMPTY));
    Assert.assertNull(set.get(MarketDataKey.of(ExternalIdBundle.EMPTY)));
    Assert.assertEquals(0d, set.get(MarketDataKey.of(ExternalIdBundle.of(ExternalId.of("A", "B")))));
  }

  /**
   * Tests the key set.
   */
  @Test
  public void testKeySet() {
    final MarketDataSet set = MarketDataSet.empty();
    set.put(MarketDataKey.of(ExternalIdBundle.EMPTY), 1.2d);
    set.put(MarketDataKey.of(ExternalIdBundle.of(ExternalId.of("A", "B"))), 0d);
    final Set<MarketDataKey> keys = set.keySet();
    Assert.assertTrue(keys.contains(MarketDataKey.of(ExternalIdBundle.EMPTY)));
    Assert.assertTrue(keys.contains(MarketDataKey.of(ExternalIdBundle.of(ExternalId.of("A", "B")))));
    Assert.assertFalse(keys.contains(MarketDataKey.of(ExternalIdBundle.of(ExternalId.of("A", "B"), ExternalId.of("B", "C")))));
    Assert.assertEquals(keys.size(), 2);
  }

  /**
   * Tests the entry set.
   */
  @Test
  public void testEntrySet() {
    final MarketDataSet set = MarketDataSet.empty();
    set.put(MarketDataKey.of(ExternalIdBundle.EMPTY), 1.2d);
    set.put(MarketDataKey.of(ExternalIdBundle.of(ExternalId.of("A", "B"))), 0d);
    final Set<Map.Entry<MarketDataKey, Object>> entries = set.entrySet();
    Assert.assertTrue(entries.contains(ObjectsPair.of(MarketDataKey.of(ExternalIdBundle.EMPTY), 1.2d)));
    Assert.assertTrue(entries.contains(ObjectsPair.of(MarketDataKey.of(ExternalIdBundle.of(ExternalId.of("A", "B"))), 0d)));
    Assert.assertFalse(entries.contains(ObjectsPair.of(MarketDataKey.of(ExternalIdBundle.of(ExternalId.of("A", "B"), ExternalId.of("B", "C"))), 0d)));
    Assert.assertEquals(entries.size(), 2);
  }

  /**
   * Tests the size.
   */
  @Test
  public void testSize() {
    final MarketDataSet set = MarketDataSet.empty();
    Assert.assertEquals(set.size(), 0);
    set.put(MarketDataKey.of(ExternalIdBundle.EMPTY), 1.2d);
    Assert.assertEquals(set.size(), 1);
    set.put(MarketDataKey.of(ExternalIdBundle.of(ExternalId.of("A", "B"))), 0d);
    Assert.assertEquals(set.size(), 2);
    set.remove(MarketDataKey.of(ExternalIdBundle.EMPTY));
    Assert.assertEquals(set.size(), 1);
    set.remove(MarketDataKey.of(ExternalIdBundle.of(ExternalId.of("A", "B"))));
    Assert.assertEquals(set.size(), 0);
  }

  /**
   * Tests the object.
   */
  @Test
  public void testObject() {
    final MarketDataSet set = MarketDataSet.empty();
    set.put(MarketDataKey.of(ExternalIdBundle.of(ExternalId.of("A", "B"))), 0d);
    Assert.assertNotEquals(null, set);
    Assert.assertNotEquals(new Object(), set);
    Assert.assertEquals(set, set);
    Assert.assertEquals(set.hashCode(), set.hashCode());
    Assert.assertEquals(set.toString(), "MarketDataSet[{MarketDataKey{externalIdBundle=Bundle[A~B], field=Market_Value, "
        + "source=DEFAULT, provider=DEFAULT, normalizer=UnitNormalizer}=0.0}]");
    final MarketDataSet other = MarketDataSet.empty();
    other.put(MarketDataKey.of(ExternalIdBundle.EMPTY), 1.2d);
    Assert.assertNotEquals(set, other);
  }
}


text:
"""
kombu.compression
=================

Compression utilities.

:copyright: (c) 2009 - 2011 by Ask Solem.
:license: BSD, see LICENSE for more details.

"""
import zlib

_aliases = {}
_encoders = {}
_decoders = {}

def register(encoder, decoder, content_type, aliases=[]):
    """Register new compression method.

    :param encoder: Function used to compress text.
    :param decoder: Function used to decompress previously compressed text.
    :param content_type: The mime type this compression method identifies as.
    :param aliases: A list of names to associate with this compression method.

    """
    _encoders[content_type] = encoder
    _decoders[content_type] = decoder
    _aliases.update((alias, content_type) for alias in aliases)

def encoders():
    """Returns a list of available compression methods."""
    return _encoders.keys()

def get_encoder(t):
    """Get encoder by alias name."""
    t = _aliases.get(t, t)
    return _encoders[t], t

def get_decoder(t):
    """Get decoder by alias name."""
    return _decoders[_aliases.get(t, t)]

def compress(body, content_type):
    """Compress text.

    :param body: The text to compress.
    :param content_type: mime-type of compression method to use.

    """
    encoder, content_type = get_encoder(content_type)
    return encoder(body.encode("utf-8")), content_type

def decompress(body, content_type):
    """Decompress compressed text.

    :param body: Previously compressed text to uncompress.
    :param content_type: mime-type of compression method used.

    """
    return get_decoder(content_type)(body).decode("utf-8")

register(zlib.compress,
         zlib.decompress,
         "application/x-gzip", aliases=["gzip", "zlib"])
try:
    import bz2
except ImportError:
    pass  # Jython?
else:
    register(bz2.compress,
             bz2.decompress,
             "application/x-bz2", aliases=["bzip2", "bzip"])


text:
<?xml version="1.0"?>
<!-- This file is part of Tryton.  The COPYRIGHT file at the top level of
this repository contains the full copyright notices and license terms. -->
<tryton>
    <data>
        <menuitem name="Configuration" parent="menu_elastic_search"
            id="menu_configuration" sequence="0" icon="tryton-preferences"/>
        <record model="ir.ui.menu-res.group"
            id="menu_configuration_group_admin">
            <field name="menu" ref="menu_configuration"/>
            <field name="group" ref="group_elasticsearch_admin"/>
        </record>

        <record model="ir.ui.view" id="es_configuration_view_form">
            <field name="model">elasticsearch.configuration</field>
            <field name="type">form</field>
            <field name="name">configuration_form</field>
        </record>
        <record model="ir.action.act_window" id="act_es_configuration_form">
            <field name="name">Configuration</field>
            <field name="res_model">elasticsearch.configuration</field>
        </record>
        <record model="ir.action.act_window.view"
            id="act_es_configuration_view1">
            <field name="sequence" eval="1"/>
            <field name="view" ref="es_configuration_view_form"/>
            <field name="act_window" ref="act_es_configuration_form"/>
        </record>
        <menuitem parent="menu_configuration"
            action="act_es_configuration_form"
            id="menu_es_configuration" icon="tryton-list"/>
    </data>
</tryton>


text:
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <title>base.rb</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <link rel="stylesheet" href="../../../../../../../../../../css/reset.css" type="text/css" media="screen" />
<link rel="stylesheet" href="../../../../../../../../../../css/main.css" type="text/css" media="screen" />
<link rel="stylesheet" href="../../../../../../../../../../css/github.css" type="text/css" media="screen" />

            Ruby on Rails 4.0.0

            base.rb

                /usr/local/rvm/gems/ruby-2.0.0-p0/gems/activerecord-4.0.0/lib/active_record/base.rb

Last modified: 2013-07-25 11:47:10 +0200

Required Files

yaml

set

active_support/benchmarkable

active_support/dependencies

active_support/descendants_tracker

active_support/time

active_support/core_ext/class/attribute_accessors

active_support/core_ext/class/delegating_attributes

active_support/core_ext/array/extract_options

active_support/core_ext/hash/deep_merge

active_support/core_ext/hash/slice

active_support/core_ext/string/behavior

active_support/core_ext/kernel/singleton_class

active_support/core_ext/module/introspection

active_support/core_ext/object/duplicable

active_support/core_ext/class/subclasses

arel

active_record/errors

active_record/log_subscriber

active_record/explain_subscriber

Namespace

          MODULE
          ActiveRecord

          CLASS
          ActiveRecord::Base


text:
package io.cattle.platform.configitem.context.impl;

import io.cattle.platform.configitem.context.dao.DnsInfoDao;
import io.cattle.platform.configitem.context.data.DnsEntryData;
import io.cattle.platform.configitem.server.model.ConfigItem;
import io.cattle.platform.configitem.server.model.impl.ArchiveContext;
import io.cattle.platform.core.dao.NetworkDao;
import io.cattle.platform.core.model.Agent;
import io.cattle.platform.core.model.Instance;
import io.cattle.platform.json.JsonMapper;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.inject.Inject;
import javax.inject.Named;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@Named
public class DnsInfoFactory extends AbstractAgentBaseContextFactory {
    private static final Logger log = LoggerFactory.getLogger(DnsInfoFactory.class);

    @Inject
    DnsInfoDao dnsInfoDao;
    @Inject
    NetworkDao networkDao;
    @Inject
    JsonMapper jsonMapper;

    @Override
    protected void populateContext(Agent agent, Instance instance, ConfigItem item, ArchiveContext context) {
        if (instance == null) {
            return;
        }
        List<DnsEntryData> dnsEntries = new ArrayList<DnsEntryData>();
        // 1. retrieve all instance links for the hosts
        dnsEntries.addAll(dnsInfoDao.getInstanceLinksDnsData(instance));
        // 2. retrieve service dns records with links
        dnsEntries.addAll(dnsInfoDao.getServiceDnsData(instance, false));
        // 3. get data for "default" section
        dnsEntries.addAll(dnsInfoDao.getServiceDnsData(instance, true));

        // aggregate the links based on the source ip address
        Map<String, DnsEntryData> processedDnsEntries = new HashMap<>();
        for (DnsEntryData newEntry : dnsEntries) {
            if (StringUtils.isEmpty(newEntry.getSourceIpAddress())) {
                continue;
            }
            DnsEntryData toAdd = null;
            if (processedDnsEntries.containsKey(newEntry.getSourceIpAddress())) {
                DnsEntryData processedEntry = processedDnsEntries.get(newEntry.getSourceIpAddress());
                toAdd = new DnsEntryData(newEntry.getSourceIpAddress(), DnsEntryData.mergeResolve(newEntry,
                        processedEntry),
                        DnsEntryData.mergeCname(newEntry, processedEntry), newEntry.getInstance(),
                        DnsEntryData.mergeSearchDomains(newEntry, processedEntry));
            } else {
                toAdd = newEntry;
            }

            processedDnsEntries.put(newEntry.getSourceIpAddress(), toAdd);
        }

        try {
            context.getData().put("config", jsonMapper.writeValueAsString(processedDnsEntries));
        } catch (IOException e) {
            log.error("Failed to marshal dns config", e);
        }
    }

}


text:
package apple.avfoundation;

import apple.NSObject;
import apple.avfoundation.protocol.AVContentKeyRecipient;
import apple.avfoundation.protocol.AVContentKeySessionDelegate;
import apple.foundation.NSArray;
import apple.foundation.NSData;
import apple.foundation.NSDictionary;
import apple.foundation.NSError;
import apple.foundation.NSMethodSignature;
import apple.foundation.NSSet;
import apple.foundation.NSURL;
import org.moe.natj.c.ann.FunctionPtr;
import org.moe.natj.general.NatJ;
import org.moe.natj.general.Pointer;
import org.moe.natj.general.ann.Generated;
import org.moe.natj.general.ann.Library;
import org.moe.natj.general.ann.Mapped;
import org.moe.natj.general.ann.MappedReturn;
import org.moe.natj.general.ann.NInt;
import org.moe.natj.general.ann.NUInt;
import org.moe.natj.general.ann.Owned;
import org.moe.natj.general.ann.Runtime;
import org.moe.natj.general.ptr.VoidPtr;
import org.moe.natj.objc.Class;
import org.moe.natj.objc.ObjCRuntime;
import org.moe.natj.objc.SEL;
import org.moe.natj.objc.ann.ObjCBlock;
import org.moe.natj.objc.ann.ObjCClassBinding;
import org.moe.natj.objc.ann.Selector;
import org.moe.natj.objc.map.ObjCObjectMapper;

@Generated
@Library("AVFoundation")
@Runtime(ObjCRuntime.class)
@ObjCClassBinding
public class AVContentKeySession extends NSObject {
    static {
        NatJ.register();
    }

    @Generated
    protected AVContentKeySession(Pointer peer) {
        super(peer);
    }

    @Generated
    @Selector("accessInstanceVariablesDirectly")
    public static native boolean accessInstanceVariablesDirectly();

    /**
     * addContentKeyRecipient:
     *

     * Informs the receiver that the specified recipient will be used for the session.
     *

     * It is an error to add recipient to sessions that have received an expire message. It is also an error to add
     * recipients after they have already begun to process media data (e.g. after an AVURLAsset has loaded the values of
     * any of its keys). Such errors will result in NSInternalInconsistencyExceptions. Sending this message to an
     * AVContentKeySession is atomic.
     */
    @Generated
    @Selector("addContentKeyRecipient:")
    public native void addContentKeyRecipient(@Mapped(ObjCObjectMapper.class) AVContentKeyRecipient recipient);

    @Generated
    @Owned
    @Selector("alloc")
    public static native AVContentKeySession alloc();

    @Owned
    @Generated
    @Selector("allocWithZone:")
    public static native AVContentKeySession allocWithZone(VoidPtr zone);

    @Generated
    @Selector("automaticallyNotifiesObserversForKey:")
    public static native boolean automaticallyNotifiesObserversForKey(String key);

    @Generated
    @Selector("cancelPreviousPerformRequestsWithTarget:")
    public static native void cancelPreviousPerformRequestsWithTarget(@Mapped(ObjCObjectMapper.class) Object aTarget);

    @Generated
    @Selector("cancelPreviousPerformRequestsWithTarget:selector:object:")
    public static native void cancelPreviousPerformRequestsWithTargetSelectorObject(
            @Mapped(ObjCObjectMapper.class) Object aTarget, SEL aSelector,
            @Mapped(ObjCObjectMapper.class) Object anArgument);

    @Generated
    @Selector("classFallbacksForKeyedArchiver")
    public static native NSArray<String> classFallbacksForKeyedArchiver();

    @Generated
    @Selector("classForKeyedUnarchiver")
    public static native Class classForKeyedUnarchiver();

    /**
     * [@property] contentKeyRecipients
     *

     * The array of recipients of content keys currently associated with the AVContentKeySession.
     */
    @Generated
    @Selector("contentKeyRecipients")
    public native NSArray<?> contentKeyRecipients();

    /**
     * contentKeySessionWithKeySystem:
     *

     * Creates a new instance of AVContentKeySession to manage a collection of media content keys.
     *

     * This method returns an AVContentKeySession instance that is capable of managing collection of media content keys
     * corresponding to the input keySystem. An NSInvalidArgumentException will be raised if the value of keySystem is
     * unsupported.
     *
     * @param keySystem A valid key system for retrieving keys.
     * @return A new AVContentKeySession.
     */
    @Generated
    @Selector("contentKeySessionWithKeySystem:")
    public static native AVContentKeySession contentKeySessionWithKeySystem(String keySystem);

    /**
     * contentKeySessionWithKeySystem:storageDirectoryAtURL:
     *

     * Creates a new instance of AVContentKeySession to manage a collection of media content keys.
     *

     * This method returns an AVContentKeySession instance that is capable of managing collection of media content keys
     * corresponding to the input keySystem. An NSInvalidArgumentException will be raised if the value of keySystem is
     * unsupported.
     *
     * @param keySystem  A valid key system for retrieving keys.
     * @param storageURL URL to a writable directory that the session will use to facilitate expired session reports
     *                   after abnormal session termination.
     * @return A new AVContentKeySession.
     */
    @Generated
    @Selector("contentKeySessionWithKeySystem:storageDirectoryAtURL:")
    public static native AVContentKeySession contentKeySessionWithKeySystemStorageDirectoryAtURL(String keySystem,
            NSURL storageURL);

    /**
     * [@property] contentProtectionSessionIdentifier
     *

     * An opaque identifier for the current content protection session.
     *

     * May be nil. Will call the delegate's contentKeySessionContentProtectionSessionIdentifierDidChange: when the
     * identifier changes. The protection session ID is a unique string identifier generated by the AVContentKeySession
     * that can be used by the application to identify content key session objects.
     */
    @Generated
    @Selector("contentProtectionSessionIdentifier")
    public native NSData contentProtectionSessionIdentifier();

    @Generated
    @Selector("debugDescription")
    public static native String debugDescription_static();

    /**
     * [@property] delegate
     *

     * The receiver's delegate.
     *

     * The value of this property is an object conforming to the AVContentKeySessionDelegate protocol. The delegate is
     * set using the setDelegate:queue: method.
     */
    @Generated
    @Selector("delegate")
    @MappedReturn(ObjCObjectMapper.class)
    public native AVContentKeySessionDelegate delegate();

    /**
     * [@property] delegateQueue
     *

     * The dispatch queue on which all delegate methods will be invoked whenever processes requiring content keys are
     * executed asynchronously.
     *

     * The value of this property is a dispatch_queue_t. The queue is set using the setDelegate:queue: method.
     */
    @Generated
    @Selector("delegateQueue")
    public native NSObject delegateQueue();

    @Generated
    @Selector("description")
    public static native String description_static();

    /**
     * expire
     *

     * Tells the receiver to treat the session as having been intentionally and normally expired.
     *

     * When an instance of AVContentKeySession receives an expire message, all of its associated objects conforming to
     * the AVContentKeyRecipient protocol will become inoperable. Send this message only after you have finished
     * operating on the media data.
     */
    @Generated
    @Selector("expire")
    public native void expire();

    @Generated
    @Selector("hash")
    @NUInt
    public static native long hash_static();

    @Generated
    @Selector("init")
    public native AVContentKeySession init();

    @Generated
    @Selector("instanceMethodForSelector:")
    @FunctionPtr(name = "call_instanceMethodForSelector_ret")
    public static native NSObject.Function_instanceMethodForSelector_ret instanceMethodForSelector(SEL aSelector);

    @Generated
    @Selector("instanceMethodSignatureForSelector:")
    public static native NSMethodSignature instanceMethodSignatureForSelector(SEL aSelector);

    @Generated
    @Selector("instancesRespondToSelector:")
    public static native boolean instancesRespondToSelector(SEL aSelector);

    @Generated
    @Selector("isSubclassOfClass:")
    public static native boolean isSubclassOfClass(Class aClass);

    @Generated
    @Selector("keyPathsForValuesAffectingValueForKey:")
    public static native NSSet<String> keyPathsForValuesAffectingValueForKey(String key);

    /**
     * [@property] keySystem
     *

     * The key system used for retrieving keys
     */
    @Generated
    @Selector("keySystem")
    public native String keySystem();

    /**
     * makeSecureTokenForExpirationDateOfPersistableContentKey:completionHandler:
     *

     * Creates a secure server playback context (SPC) that the client could send to the key server to obtain an
     * expiration date for the provided persistable content key data.
     *
     * @param persistableContentKeyData Persistable content key data that was previously created using
     *                                  -[AVContentKeyRequest persistableContentKeyFromKeyVendorResponse:options:error:]
     *                                  or obtained via AVContentKeySessionDelegate callback
     *                                  -contentKeySession:didUpdatePersistableContentKey:forContentKeyIdentifier:.
     * @param handler                   Once the secure token is ready, this block will be called with the token or an
     *                                  error describing the failure.
     */
    @Generated
    @Selector("makeSecureTokenForExpirationDateOfPersistableContentKey:completionHandler:")
    public native void makeSecureTokenForExpirationDateOfPersistableContentKeyCompletionHandler(
            NSData persistableContentKeyData,
            @ObjCBlock(name = "call_makeSecureTokenForExpirationDateOfPersistableContentKeyCompletionHandler") Block_makeSecureTokenForExpirationDateOfPersistableContentKeyCompletionHandler handler);

    @Runtime(ObjCRuntime.class)
    @Generated
    public interface Block_makeSecureTokenForExpirationDateOfPersistableContentKeyCompletionHandler {
        @Generated
        void call_makeSecureTokenForExpirationDateOfPersistableContentKeyCompletionHandler(NSData secureTokenData,
                NSError error);
    }

    @Generated
    @Owned
    @Selector("new")
    public static native AVContentKeySession new_objc();

    /**
     * pendingExpiredSessionReportsWithAppIdentifier:storageDirectoryAtURL:
     *

     * Provides "expired session reports" for prior AVContentKeySessions created with the specified app identifier that
     * have expired either normally or abnormally.
     *

     * Note that no reports for sessions still in progress will be included.
     *
     * @param appIdentifier An opaque identifier for the application. The contents of this identifier depend on the
     *                      particular protocol in use by the entity that controls the use of the media data.
     * @param storageURL    URL to a directory previously used with one or more instances of AVContentKeySession for the
     *                      storage of expired session reports.
     * @return An NSArray containing instances of NSData, each containing a pending expired session report as a
     *         property-list serialization of an NSDictionary object. The contents of expired session reports depend on
     *         the particular protocol in use by the entity that controls the use of the media data.
     */
    @Generated
    @Selector("pendingExpiredSessionReportsWithAppIdentifier:storageDirectoryAtURL:")
    public static native NSArray<? extends NSData> pendingExpiredSessionReportsWithAppIdentifierStorageDirectoryAtURL(
            NSData appIdentifier, NSURL storageURL);

    /**
     * processContentKeyRequestWithIdentifier:initializationData:options:
     *

     * Informs the receiver that it should attempt to instantiate a content decryption key using the specified
     * initialization data.
     *

     * May be used to generate an AVContentKeyRequest from request initialization data already in hand, without awaiting
     * such data during the processing of media data of an associated recipient.
     *
     * @param identifier         Container- and protocol-specific identifier to be used to obtain a key response. Either
     *                           identifier or initializationData must be non-nil. Both can be non-nil, if the content
     *                           protection protocol requires both.
     * @param initializationData Container- and protocol-specific data to be used to obtain a key response. Either
     *                           identifier or initializationData must be non-nil. Both can be non-nil, if the content
     *                           protection protocol requires both.
     * @param options            Additional information necessary to obtain the key, or nil if none. See
     *                           AVContentKeyRequest*Key below.
     */
    @Generated
    @Selector("processContentKeyRequestWithIdentifier:initializationData:options:")
    public native void processContentKeyRequestWithIdentifierInitializationDataOptions(
            @Mapped(ObjCObjectMapper.class) Object identifier, NSData initializationData,
            NSDictionary<String, ?> options);

    /**
     * removeContentKeyRecipient:
     *

     * Informs the receiver that the specified recipient will no longer be used.
     *

     * After the specified recipient is removed from the receiver it will become inoperable. Remove the recipient only
     * after you have finished operating on the media data associated with it. Sending this message to an
     * AVContentKeySession is atomic.
     */
    @Generated
    @Selector("removeContentKeyRecipient:")
    public native void removeContentKeyRecipient(@Mapped(ObjCObjectMapper.class) AVContentKeyRecipient recipient);

    /**
     * removePendingExpiredSessionReports:withAppIdentifier:storageDirectoryAtURL:
     *

     * Removes expired session reports for prior AVContentKeySessions from storage. Once they have been removed, they
     * will no longer be available via subsequent invocations of +pendingExpiredSessionReportsWithAppIdentifier:.
     *

     * This method is most suitable for use only after the specified expired session reports have been sent to the
     * entity that controls the use of the media data and the entity has acknowledged their receipt.
     *
     * @param expiredSessionReports An array of expired session reports to be discarded.
     * @param appIdentifier         An opaque identifier for the application. The contents of this identifier depend on
     *                              the particular protocol in use by the entity that controls the use of the media
     *                              data.
     * @param storageURL            URL to a writable folder.
     */
    @Generated
    @Selector("removePendingExpiredSessionReports:withAppIdentifier:storageDirectoryAtURL:")
    public static native void removePendingExpiredSessionReportsWithAppIdentifierStorageDirectoryAtURL(
            NSArray<? extends NSData> expiredSessionReports, NSData appIdentifier, NSURL storageURL);

    /**
     * renewExpiringResponseDataForContentKeyRequest:
     *

     * Informs the receiver that the already provided response data for an earlier AVContentKeyRequest will imminently
     * expire.
     *

     * In response the receiver will invoke your delegate with a new content key request entreating it to renew the
     * expiring response data, via -contentKeySession:didProvideRenewingContentKeyRequest:.
     */
    @Generated
    @Selector("renewExpiringResponseDataForContentKeyRequest:")
    public native void renewExpiringResponseDataForContentKeyRequest(AVContentKeyRequest contentKeyRequest);

    @Generated
    @Selector("resolveClassMethod:")
    public static native boolean resolveClassMethod(SEL sel);

    @Generated
    @Selector("resolveInstanceMethod:")
    public static native boolean resolveInstanceMethod(SEL sel);

    /**
     * setDelegate:queue:
     *

     * Sets the receiver's delegate. A delegate is required to handle content key initialization.
     *
     * @param delegate      An object conforming to the AVContentKeySessionDelegate protocol.
     * @param delegateQueue A dispatch queue on which delegate methods will be invoked whenever processes requiring
     *                      content keys are executed asynchronously. Passing a value of nil for the delegateQueue
     *                      parameter along with a non-nil value for the delegate parameter will result in an invalid
     *                      argument exception.
     */
    @Generated
    @Selector("setDelegate:queue:")
    public native void setDelegateQueue(@Mapped(ObjCObjectMapper.class) AVContentKeySessionDelegate delegate,
            NSObject delegateQueue);

    @Generated
    @Selector("setVersion:")
    public static native void setVersion_static(@NInt long aVersion);

    /**
     * [@property] storageURL
     *

     * The storage URL provided when the AVContentKeySession was created. May be nil.
     *

     * URL to a writable directory; may be nil. The session will use this to facilitate expired session reports after
     * abnormal session termination.
     */
    @Generated
    @Selector("storageURL")
    public native NSURL storageURL();

    @Generated
    @Selector("superclass")
    public static native Class superclass_static();

    @Generated
    @Selector("version")
    @NInt
    public static native long version_static();

    /**
     * invalidateAllPersistableContentKeysForApp:options:completionHandler:
     *

     * Invalidates all persistable content keys associated with the application and creates a secure server playback
     * context (SPC) that the client could send to the key server to verify the outcome of invalidation request.
     *

     * Once invalidated, persistable content keys cannot be used to answer key requests during later playback sessions.
     *
     * @param appIdentifier An opaque identifier for the application. The contents of this identifier depend on the
     *                      particular protocol in use by the entity that controls the use of the media data.
     * @param options       Additional information necessary to generate the server playback context, or nil if none.
     *                      See AVContentKeySessionServerPlaybackContextOption for supported options.
     * @param handler       Once the server playback context is ready, this block will be called with the data or an
     *                      error describing the failure.
     */
    @Generated
    @Selector("invalidateAllPersistableContentKeysForApp:options:completionHandler:")
    public native void invalidateAllPersistableContentKeysForAppOptionsCompletionHandler(NSData appIdentifier,
            NSDictionary<String, ?> options,
            @ObjCBlock(name = "call_invalidateAllPersistableContentKeysForAppOptionsCompletionHandler") Block_invalidateAllPersistableContentKeysForAppOptionsCompletionHandler handler);

    @Runtime(ObjCRuntime.class)
    @Generated
    public interface Block_invalidateAllPersistableContentKeysForAppOptionsCompletionHandler {
        @Generated
        void call_invalidateAllPersistableContentKeysForAppOptionsCompletionHandler(NSData secureTokenData,
                NSError error);
    }

    /**
     * invalidatePersistableContentKey:options:completionHandler:
     *

     * Invalidates the persistable content key and creates a secure server playback context (SPC) that the client could
     * send to the key server to verify the outcome of invalidation request.
     *

     * Once invalidated, a persistable content key cannot be used to answer key requests during later playback sessions.
     *
     * @param persistableContentKeyData Persistable content key data that was previously created using
     *                                  -[AVContentKeyRequest persistableContentKeyFromKeyVendorResponse:options:error:]
     *                                  or obtained via AVContentKeySessionDelegate callback
     *                                  -contentKeySession:didUpdatePersistableContentKey:forContentKeyIdentifier:.
     * @param options                   Additional information necessary to generate the server playback context, or nil
     *                                  if none. See AVContentKeySessionServerPlaybackContextOption for supported
     *                                  options.
     * @param handler                   Once the server playback context is ready, this block will be called with the
     *                                  data or an error describing the failure.
     */
    @Generated
    @Selector("invalidatePersistableContentKey:options:completionHandler:")
    public native void invalidatePersistableContentKeyOptionsCompletionHandler(NSData persistableContentKeyData,
            NSDictionary<String, ?> options,
            @ObjCBlock(name = "call_invalidatePersistableContentKeyOptionsCompletionHandler") Block_invalidatePersistableContentKeyOptionsCompletionHandler handler);

    @Runtime(ObjCRuntime.class)
    @Generated
    public interface Block_invalidatePersistableContentKeyOptionsCompletionHandler {
        @Generated
        void call_invalidatePersistableContentKeyOptionsCompletionHandler(NSData secureTokenData, NSError error);
    }
}


text:
DEBUG = True
TEMPLATE_DEBUG = False

LANGUAGE_CODE = 'zh-cn'
##LANGUAGE_CODE = 'fr'


text:
<?php
/**
 * @var SitePress $sitepress
 * @var wpdb $wpdb
 * @var Object $term
 *
 */

require dirname( __FILE__ ) . '/wpml-taxonomy-element-language-dropdown.class.php';

global $sitepress, $wpdb;

$sitepress->noscript_notice();

$element_id = isset( $term->term_taxonomy_id ) ? $term->term_taxonomy_id : false;

$element_type = isset( $_GET[ 'taxonomy' ] ) ? esc_sql( $_GET[ 'taxonomy' ] ) : 'post_tag';
$icl_element_type = 'tax_' . $element_type;

$default_language = $sitepress->get_default_language();
$current_language = $sitepress->get_current_language();

if ( $element_id ) {
	$res_prepared = $wpdb->prepare( "SELECT trid, language_code, source_language_code
				  FROM {$wpdb->prefix}icl_translations WHERE element_id=%d AND element_type=%s", array( $element_id, $icl_element_type ) );
	$res          = $wpdb->get_row( $res_prepared );
	$trid         = $res->trid;
	if ( $trid ) {
		$element_lang_code = $res->language_code;
	} else {
		$element_lang_code = $current_language;

		$translation_id = $sitepress->set_element_language_details( $element_id, $icl_element_type, null, $element_lang_code );
		//get trid of $translation_id
		$trid = $wpdb->get_var( $wpdb->prepare( "SELECT trid FROM {$wpdb->prefix}icl_translations WHERE translation_id=%d", array( $translation_id) ) );
	}
} else {
	$trid              = isset( $_GET[ 'trid' ] ) ? intval( $_GET[ 'trid' ] ) : false;
	$element_lang_code = isset( $_GET[ 'lang' ] ) ? strip_tags( $_GET[ 'lang' ] ) : $current_language;
}

$translations = false;
if ( $trid ) {
	$translations = $sitepress->get_element_translations( $trid, $icl_element_type );
}
$active_languages = $sitepress->get_active_languages();
$selected_language = $element_lang_code ? $element_lang_code : $default_language;
$source_language = isset( $_GET[ 'source_lang' ] ) ? strip_tags( filter_input ( INPUT_GET, 'source_lang', FILTER_SANITIZE_FULL_SPECIAL_CHARS ) ) : false;
$untranslated_ids = $sitepress->get_elements_without_translations( $icl_element_type, $selected_language, $default_language );

$dropdown = new WPML_Taxonomy_Element_Language_Dropdown();
$dropdown->add_language_selector_to_page (
	$active_languages,
	$selected_language,
	(array) $translations,
	$element_id,
	$icl_element_type
);

if ( icl_get_setting('setup_complete') ) {
    require ICL_PLUGIN_PATH . '/menu/wpml-translation-selector.class.php';
    $selector = new WPML_Translation_Selector( $sitepress, $default_language, $source_language, $element_id );
    $selector->add_translation_of_selector_to_page (
        $trid,
        $sitepress->get_current_language (),
        $selected_language,
        $untranslated_ids
    );
}
$sitepress->add_translate_options( $trid, $active_languages, $selected_language, empty( $translations ) ? array() : $translations, $icl_element_type );

?>


text:
Boot Procedure
=========================


text:
package certwatcher

import (
	"context"
	"crypto/tls"
	"sync"

	"github.com/fsnotify/fsnotify"
	"sigs.k8s.io/controller-runtime/pkg/certwatcher/metrics"
	logf "sigs.k8s.io/controller-runtime/pkg/internal/log"
)

var log = logf.RuntimeLog.WithName("certwatcher")

// CertWatcher watches certificate and key files for changes.  When either file
// changes, it reads and parses both and calls an optional callback with the new
// certificate.
type CertWatcher struct {
	sync.RWMutex

	currentCert *tls.Certificate
	watcher     *fsnotify.Watcher

	certPath string
	keyPath  string
}

// New returns a new CertWatcher watching the given certificate and key.
func New(certPath, keyPath string) (*CertWatcher, error) {
	var err error

	cw := &CertWatcher{
		certPath: certPath,
		keyPath:  keyPath,
	}

	// Initial read of certificate and key.
	if err := cw.ReadCertificate(); err != nil {
		return nil, err
	}

	cw.watcher, err = fsnotify.NewWatcher()
	if err != nil {
		return nil, err
	}

	return cw, nil
}

// GetCertificate fetches the currently loaded certificate, which may be nil.
func (cw *CertWatcher) GetCertificate(_ *tls.ClientHelloInfo) (*tls.Certificate, error) {
	cw.RLock()
	defer cw.RUnlock()
	return cw.currentCert, nil
}

// Start starts the watch on the certificate and key files.
func (cw *CertWatcher) Start(ctx context.Context) error {
	files := []string{cw.certPath, cw.keyPath}

	for _, f := range files {
		if err := cw.watcher.Add(f); err != nil {
			return err
		}
	}

	go cw.Watch()

	log.Info("Starting certificate watcher")

	// Block until the context is done.
	<-ctx.Done()

	return cw.watcher.Close()
}

// Watch reads events from the watcher's channel and reacts to changes.
func (cw *CertWatcher) Watch() {
	for {
		select {
		case event, ok := <-cw.watcher.Events:
			// Channel is closed.
			if !ok {
				return
			}

			cw.handleEvent(event)

		case err, ok := <-cw.watcher.Errors:
			// Channel is closed.
			if !ok {
				return
			}

			log.Error(err, "certificate watch error")
		}
	}
}

// ReadCertificate reads the certificate and key files from disk, parses them,
// and updates the current certificate on the watcher.  If a callback is set, it
// is invoked with the new certificate.
func (cw *CertWatcher) ReadCertificate() error {
	metrics.ReadCertificateTotal.Inc()
	cert, err := tls.LoadX509KeyPair(cw.certPath, cw.keyPath)
	if err != nil {
		metrics.ReadCertificateErrors.Inc()
		return err
	}

	cw.Lock()
	cw.currentCert = &cert
	cw.Unlock()

	log.Info("Updated current TLS certificate")

	return nil
}

func (cw *CertWatcher) handleEvent(event fsnotify.Event) {
	// Only care about events which may modify the contents of the file.
	if !(isWrite(event) || isRemove(event) || isCreate(event)) {
		return
	}

	log.V(1).Info("certificate event", "event", event)

	// If the file was removed, re-add the watch.
	if isRemove(event) {
		if err := cw.watcher.Add(event.Name); err != nil {
			log.Error(err, "error re-watching file")
		}
	}

	if err := cw.ReadCertificate(); err != nil {
		log.Error(err, "error re-reading certificate")
	}
}

func isWrite(event fsnotify.Event) bool {
	return event.Op&fsnotify.Write == fsnotify.Write
}

func isCreate(event fsnotify.Event) bool {
	return event.Op&fsnotify.Create == fsnotify.Create
}

func isRemove(event fsnotify.Event) bool {
	return event.Op&fsnotify.Remove == fsnotify.Remove
}


text:
require File.expand_path("../helper", __FILE__)

module Hurley
  class TestTest < TestCase

    def setup
      @stubs = Test.new do |stub|
        stub.get "/a/verboten" do |req|
          [403, {}, ""]
        end

        stub.get("/a", :expires => false) do |req|
          output = %w(fee fi fo fum)
          [200, {"Content-Length" => "13"}, output.join("\n")]
        end

        # forces the /a stub above to expire
        stub.get("/a") do |req|
          [200, {"Content-Length" => "4"}, "last"]
        end

        stub.get("/expires", :expires => true) do |req|
          [200, {}, "last"]
        end

        # different verb, does not expire
        stub.post("/expires") do |req|
          [200, {}, "ok"]
        end
      end

      @client = Client.new do |c|
        c.connection = @stubs
      end
    end

    def test_matches_most_specific_handler
      res = @client.get("/a")
      assert_equal 200, res.status_code

      res = @client.get("/a/verboten")
      assert_equal 403, res.status_code
    end

    def test_returns_404_if_no_handler_found
      res = @client.get("/a")
      assert_equal 200, res.status_code

      res = @client.get("/b")
      assert_equal 404, res.status_code
    end

    def test_get_expiring_stub
      res = @client.get("/a")
      assert_equal 200, res.status_code
      assert_equal "fee\nfi\nfo\nfum", res.body

      res = @client.get("/a")
      assert_equal 200, res.status_code
      assert_equal "last", res.body

      res = @client.get("/a")
      assert_equal 404, res.status_code
    end

    def test_head_expiring_stub
      res = @client.head("/a")
      assert_equal 200, res.status_code
      assert_equal "13", res.header[:content_length]

      res = @client.get("/a")
      assert_equal 200, res.status_code
      assert_equal "4", res.header[:content_length]

      res = @client.get("/a")
      assert_equal 404, res.status_code
    end

    def test_matches_explicitly_expiring_stub
      res = @client.get("/expires")
      assert_equal 200, res.status_code
      assert_equal "last", res.body

      res = @client.get("/expires")
      assert_equal 404, res.status_code
    end

    def test_matches_expiring_url_with_different_verb
      res = @client.post("/expires")
      assert_equal 200, res.status_code
      assert_equal "ok", res.body

      res = @client.post("/expires")
      assert_equal 200, res.status_code
      assert_equal "ok", res.body
    end
  end
end


text:
typedef struct
{
   GLKVector3 position;
   GLKVector3 normal;
   GLKVector2 texCoords0;
}
SceneMeshVertex;

@interface SceneMesh : NSObject

- (id)initWithVertexAttributeData:(NSData *)vertexAttributes
   indexData:(NSData *)indices;

- (id)initWithPositionCoords:(const GLfloat *)somePositions
   normalCoords:(const GLfloat *)someNormals
   texCoords0:(const GLfloat *)someTexCoords0
   numberOfPositions:(size_t)countPositions
   indices:(const GLushort *)someIndices
   numberOfIndices:(size_t)countIndices;

- (void)prepareToDraw;

- (void)drawUnidexedWithMode:(GLenum)mode
   startVertexIndex:(GLint)first
   numberOfVertices:(GLsizei)count;

- (void)makeDynamicAndUpdateWithVertices:
   (const SceneMeshVertex *)someVerts
   numberOfVertices:(GLsizei)count;

@end


text:
from maskgen.video_tools import x264
from maskgen import exif
import maskgen
"""
Save te image as MP4 using X264 loss encoding.
"""
def transform(img,source,target, **kwargs):

    crf = int(kwargs['crf']) if 'crf' in kwargs else 0
    x264(source,outputname=target,crf=crf)
    orientation_source = exif.getOrientationFromExif(source)
    orientation_target = exif.getOrientationFromExif(target)
    analysis = {"Image Rotated": "no"}
    if orientation_source is not None and orientation_source != orientation_target:
        analysis = {"Image Rotated": "yes"}
    return analysis,None

def operation():
    return {'name':'OutputAVI',
            'category':'Output',
            'description':'Save an video as .mp4 using codec X264',
            'software':'ffmpeg',
            'version':maskgen.video_tools.get_ffmpeg_version(),
            'arguments':{
                'crf':{
                    'type':'int[0:100]',
                    'defaultvalue':'0',
                    'description':'Constraint Rate Factor. 0 is lossless'
                }
            },
            'transitions': [
                'video.video'
            ]
        }

def suffix():
    return '.avi'


text:
namespace rocksdb {

class Env;
class Logger;

// SstFileManager is used to track SST files in the DB and control there
// deletion rate.
// All SstFileManager public functions are thread-safe.
class SstFileManagerImpl : public SstFileManager {
 public:
  explicit SstFileManagerImpl(Env* env, std::shared_ptr<Logger> logger,
                              const std::string& trash_dir,
                              int64_t rate_bytes_per_sec);

  ~SstFileManagerImpl();

  // DB will call OnAddFile whenever a new sst file is added.
  Status OnAddFile(const std::string& file_path);

  // DB will call OnDeleteFile whenever an sst file is deleted.
  Status OnDeleteFile(const std::string& file_path);

  // DB will call OnMoveFile whenever an sst file is move to a new path.
  Status OnMoveFile(const std::string& old_path, const std::string& new_path);

  // Update the maximum allowed space that should be used by RocksDB, if
  // the total size of the SST files exceeds max_allowed_space, writes to
  // RocksDB will fail.
  //
  // Setting max_allowed_space to 0 will disable this feature, maximum allowed
  // space will be infinite (Default value).
  //
  // thread-safe.
  void SetMaxAllowedSpaceUsage(uint64_t max_allowed_space) override;

  // Return true if the total size of SST files exceeded the maximum allowed
  // space usage.
  //
  // thread-safe.
  bool IsMaxAllowedSpaceReached() override;

  // Return the total size of all tracked files.
  uint64_t GetTotalSize() override;

  // Return a map containing all tracked files and there corresponding sizes.
  std::unordered_map<std::string, uint64_t> GetTrackedFiles() override;

  // Return delete rate limit in bytes per second.
  virtual int64_t GetDeleteRateBytesPerSecond() override;

  // Move file to trash directory and schedule it's deletion.
  virtual Status ScheduleFileDeletion(const std::string& file_path);

  // Wait for all files being deleteing in the background to finish or for
  // destructor to be called.
  virtual void WaitForEmptyTrash();

 private:
  // REQUIRES: mutex locked
  void OnAddFileImpl(const std::string& file_path, uint64_t file_size);
  // REQUIRES: mutex locked
  void OnDeleteFileImpl(const std::string& file_path);

  Env* env_;
  std::shared_ptr<Logger> logger_;
  // Mutex to protect tracked_files_, total_files_size_
  port::Mutex mu_;
  // The summation of the sizes of all files in tracked_files_ map
  uint64_t total_files_size_;
  // A map containing all tracked files and there sizes
  //  file_path => file_size
  std::unordered_map<std::string, uint64_t> tracked_files_;
  // The maximum allowed space (in bytes) for sst files.
  uint64_t max_allowed_space_;
  // DeleteScheduler used to throttle file deletition, if SstFileManagerImpl was
  // created with rate_bytes_per_sec == 0 or trash_dir == "", delete_scheduler_
  // rate limiting will be disabled and will simply delete the files.
  DeleteScheduler delete_scheduler_;
};

}  // namespace rocksdb

#endif  // ROCKSDB_LITE


text:
module.exports = {
  extends: 'eslint:recommended',
  parserOptions: {
    ecmaVersion: 6,
    sourceType: 'module',
    ecmaFeatures: {
      experimentalObjectRestSpread: true
    }
  },
  env: {
    es6: true,
    browser: true,
    node: true
  },
  globals: {
    jasmine: false,
    jest: false,
    describe: false,
    xdescribe: false,
    before: false,
    beforeEach: false,
    it: false,
    xit: false,
    after: false,
    afterEach: false,
    expect: false,
  },
  rules: {
    'no-console': ['warn'],
    'semi': ['error', 'always'],
    'no-var': ['error'],
    'no-unused-vars': ['error', { 'vars': 'all', 'args': 'none', 'caughtErrors': 'none' }],
    'object-curly-spacing': ['error', 'always'],
    'comma-dangle': ['error', 'always-multiline'],
    'arrow-parens': ['error', 'always'],
    'prefer-arrow-callback': ['error', { 'allowNamedFunctions': true }],
    'space-before-function-paren': ['error', 'never']
  }
}