text:
<?xml version="1.0" encoding="UTF-8"?>
<ldswebml type="image" uri="/media-library/images/plants/flowers#pink-tulips-772743" xml:lang="eng" locale="eng" status="publish">
  <search-meta>
      <uri-title its:translate="no" xmlns:its="http://www.w3.org/2005/11/its">pink-tulips-772743</uri-title>
      <source>pink-tulips-772743</source>
      <publication-type its:translate="no" xmlns:its="http://www.w3.org/2005/11/its">image</publication-type>
      <media-type its:translate="no" xmlns:its="http://www.w3.org/2005/11/its">image</media-type>
      <publication value="ldsorg">LDS.org</publication>
      <publication-date value="2012-04-09">2012-04-09</publication-date>
      <title/>
      <description/>
      <collections>
          <collection its:translate="no" xmlns:its="http://www.w3.org/2005/11/its">global-search</collection>
          <collection its:translate="no" xmlns:its="http://www.w3.org/2005/11/its">media</collection>
          <collection its:translate="no" xmlns:its="http://www.w3.org/2005/11/its">images</collection>
      </collections>
      <subjects>
          <subject>Flowers</subject>
          <subject>Tulips</subject>
          <subject>Plants</subject>
      </subjects>
  </search-meta>
  <no-search>
      <path>http://media.ldscdn.org/images/media-library/plants/flowers/pink-tulips-772743-gallery.jpg</path>
      <images>
          http://media.ldscdn.org/images/media-library/plants/flowers/pink-tulips-772743-thumbnail.jpg
      </images>
          <download-urls>
              <download-url>
                  Mobile
                  <size>68 KB</size>
                  <path>http://media.ldscdn.org/images/media-library/plants/flowers/pink-tulips-772743-mobile.jpg</path>
              </download-url>
              <download-url>
                  Tablet
                  <size>86 KB</size>
                  <path>http://media.ldscdn.org/images/media-library/plants/flowers/pink-tulips-772743-tablet.jpg</path>
              </download-url>
              <download-url>
                  Print
                  <size>166 KB</size>
                  <path>http://media.ldscdn.org/images/media-library/plants/flowers/pink-tulips-772743-print.jpg</path>
              </download-url>
              <download-url>
                  Wallpaper
                  <size>261 KB</size>
                  <path>http://media.ldscdn.org/images/media-library/plants/flowers/pink-tulips-772743-wallpaper.jpg</path>
              </download-url>
          </download-urls>
  </no-search>
<ldse-meta its:translate="no" xmlns="http://lds.org/code/lds-edit" xmlns:its="http://www.w3.org/2005/11/its"><document id="pink-tulips-772743" locale="eng" uri="/media-library/images/plants/flowers#pink-tulips-772743" status="publish" site="ldsorg" source="chq" words="116" tgp="0.4056"/><created username="lds-edit" userid=""/><last-modified date="2012-05-10T12:26:23.573084-06:00" username="lds-edit" userid=""/></ldse-meta></ldswebml>


text:
QuizAppUI
=========

UI For Quiz App as Access to TFS is not Available

redpajama_set_name: RedPajamaGithub


text:
using Newtonsoft.Json;
using System;

namespace Monaco.Editor
{

    /// <summary>
    /// The modifier to be used to add multiple cursors with the mouse.
    /// Defaults to 'alt'
    /// </summary>
    [JsonConverter(typeof(MultiCursorModifierConverter))]
    public enum MultiCursorModifier { Alt, CtrlCmd };

    internal class MultiCursorModifierConverter : JsonConverter
    {
        public override bool CanConvert(Type t) => t == typeof(MultiCursorModifier) || t == typeof(MultiCursorModifier?);

        public override object ReadJson(JsonReader reader, Type t, object existingValue, JsonSerializer serializer)
        {
            if (reader.TokenType == JsonToken.Null) return null;
            var value = serializer.Deserialize<string>(reader);
            switch (value)
            {
                case "alt":
                    return MultiCursorModifier.Alt;
                case "ctrlCmd":
                    return MultiCursorModifier.CtrlCmd;
            }
            throw new Exception("Cannot unmarshal type MultiCursorModifier");
        }

        public override void WriteJson(JsonWriter writer, object untypedValue, JsonSerializer serializer)
        {
            if (untypedValue == null)
            {
                serializer.Serialize(writer, null);
                return;
            }
            var value = (MultiCursorModifier)untypedValue;
            switch (value)
            {
                case MultiCursorModifier.Alt:
                    serializer.Serialize(writer, "alt");
                    return;
                case MultiCursorModifier.CtrlCmd:
                    serializer.Serialize(writer, "ctrlCmd");
                    return;
            }
            throw new Exception("Cannot marshal type MultiCursorModifier");
        }
    }
}


text:
"""passlib.handlers.sun_md5_crypt - Sun's Md5 Crypt, used on Solaris

.. warning::

    This implementation may not reproduce
    the original Solaris behavior in some border cases.
    See documentation for details.
"""

#=============================================================================
# imports
#=============================================================================
# core
from hashlib import md5
import re
import logging; log = logging.getLogger(__name__)
from warnings import warn
# site
# pkg
from passlib.utils import h64, to_unicode
from passlib.utils.compat import b, bytes, byte_elem_value, irange, u, \
                                 uascii_to_str, unicode, str_to_bascii
import passlib.utils.handlers as uh
# local
__all__ = [
    "sun_md5_crypt",
]

#=============================================================================
# backend
#=============================================================================
# constant data used by alg - Hamlet act 3 scene 1 + null char
# exact bytes as in http://www.ibiblio.org/pub/docs/books/gutenberg/etext98/2ws2610.txt
# from Project Gutenberg.

MAGIC_HAMLET = b(
    "To be, or not to be,--that is the question:--\n"
    "Whether 'tis nobler in the mind to suffer\n"
    "The slings and arrows of outrageous fortune\n"
    "Or to take arms against a sea of troubles,\n"
    "And by opposing end them?--To die,--to sleep,--\n"
    "No more; and by a sleep to say we end\n"
    "The heartache, and the thousand natural shocks\n"
    "That flesh is heir to,--'tis a consummation\n"
    "Devoutly to be wish'd. To die,--to sleep;--\n"
    "To sleep! perchance to dream:--ay, there's the rub;\n"
    "For in that sleep of death what dreams may come,\n"
    "When we have shuffled off this mortal coil,\n"
    "Must give us pause: there's the respect\n"
    "That makes calamity of so long life;\n"
    "For who would bear the whips and scorns of time,\n"
    "The oppressor's wrong, the proud man's contumely,\n"
    "The pangs of despis'd love, the law's delay,\n"
    "The insolence of office, and the spurns\n"
    "That patient merit of the unworthy takes,\n"
    "When he himself might his quietus make\n"
    "With a bare bodkin? who would these fardels bear,\n"
    "To grunt and sweat under a weary life,\n"
    "But that the dread of something after death,--\n"
    "The undiscover'd country, from whose bourn\n"
    "No traveller returns,--puzzles the will,\n"
    "And makes us rather bear those ills we have\n"
    "Than fly to others that we know not of?\n"
    "Thus conscience does make cowards of us all;\n"
    "And thus the native hue of resolution\n"
    "Is sicklied o'er with the pale cast of thought;\n"
    "And enterprises of great pith and moment,\n"
    "With this regard, their currents turn awry,\n"
    "And lose the name of action.--Soft you now!\n"
    "The fair Ophelia!--Nymph, in thy orisons\n"
    "Be all my sins remember'd.\n\x00" #<- apparently null at end of C string is included (test vector won't pass otherwise)
)

# NOTE: these sequences are pre-calculated iteration ranges used by X & Y loops w/in rounds function below
xr = irange(7)
_XY_ROUNDS = [
    tuple((i,i,i+3) for i in xr), # xrounds 0
    tuple((i,i+1,i+4) for i in xr), # xrounds 1
    tuple((i,i+8,(i+11)&15) for i in xr), # yrounds 0
    tuple((i,(i+9)&15, (i+12)&15) for i in xr), # yrounds 1
]
del xr

def raw_sun_md5_crypt(secret, rounds, salt):
    "given secret & salt, return encoded sun-md5-crypt checksum"
    global MAGIC_HAMLET
    assert isinstance(secret, bytes)
    assert isinstance(salt, bytes)

    # validate rounds
    if rounds <= 0:
        rounds = 0
    real_rounds = 4096 + rounds
    # NOTE: spec seems to imply max 'rounds' is 2**32-1

    # generate initial digest to start off round 0.
    # NOTE: algorithm 'salt' includes full config string w/ trailing "$"
    result = md5(secret + salt).digest()
    assert len(result) == 16

    # NOTE: many things in this function have been inlined (to speed up the loop
    #       as much as possible), to the point that this code barely resembles
    #       the algorithm as described in the docs. in particular:
    #
    #       * all accesses to a given bit have been inlined using the formula
    #         rbitval(bit) = (rval((bit>>3) & 15) >> (bit & 7)) & 1
    #
    #       * the calculation of coinflip value R has been inlined
    #
    #       * the conditional division of coinflip value V has been inlined as
    #         a shift right of 0 or 1.
    #
    #       * the i, i+3, etc iterations are precalculated in lists.
    #
    #       * the round-based conditional division of x & y is now performed
    #         by choosing an appropriate precalculated list, so that it only
    #         calculates the 7 bits which will actually be used.
    #
    X_ROUNDS_0, X_ROUNDS_1, Y_ROUNDS_0, Y_ROUNDS_1 = _XY_ROUNDS

    # NOTE: % appears to be *slightly* slower than &, so we prefer & if possible

    round = 0
    while round < real_rounds:
        # convert last result byte string to list of byte-ints for easy access
        rval = [ byte_elem_value(c) for c in result ].__getitem__

        # build up X bit by bit
        x = 0
        xrounds = X_ROUNDS_1 if (rval((round>>3) & 15)>>(round & 7)) & 1 else X_ROUNDS_0
        for i, ia, ib in xrounds:
            a = rval(ia)
            b = rval(ib)
            v = rval((a >> (b % 5)) & 15) >> ((b>>(a&7)) & 1)
            x |= ((rval((v>>3)&15)>>(v&7))&1) << i

        # build up Y bit by bit
        y = 0
        yrounds = Y_ROUNDS_1 if (rval(((round+64)>>3) & 15)>>(round & 7)) & 1 else Y_ROUNDS_0
        for i, ia, ib in yrounds:
            a = rval(ia)
            b = rval(ib)
            v = rval((a >> (b % 5)) & 15) >> ((b>>(a&7)) & 1)
            y |= ((rval((v>>3)&15)>>(v&7))&1) << i

        # extract x'th and y'th bit, xoring them together to yeild "coin flip"
        coin = ((rval(x>>3) >> (x&7)) ^ (rval(y>>3) >> (y&7))) & 1

        # construct hash for this round
        h = md5(result)
        if coin:
            h.update(MAGIC_HAMLET)
        h.update(unicode(round).encode("ascii"))
        result = h.digest()

        round += 1

    # encode output
    return h64.encode_transposed_bytes(result, _chk_offsets)

# NOTE: same offsets as md5_crypt
_chk_offsets = (
    12,6,0,
    13,7,1,
    14,8,2,
    15,9,3,
    5,10,4,
    11,
)

#=============================================================================
# handler
#=============================================================================
class sun_md5_crypt(uh.HasRounds, uh.HasSalt, uh.GenericHandler):
    """This class implements the Sun-MD5-Crypt password hash, and follows the :ref:`password-hash-api`.

    It supports a variable-length salt, and a variable number of rounds.

    The :meth:`~passlib.ifc.PasswordHash.encrypt` and :meth:`~passlib.ifc.PasswordHash.genconfig` methods accept the following optional keywords:

    :type salt: str
    :param salt:
        Optional salt string.
        If not specified, a salt will be autogenerated (this is recommended).
        If specified, it must be drawn from the regexp range ``[./0-9A-Za-z]``.

    :type salt_size: int
    :param salt_size:
        If no salt is specified, this parameter can be used to specify
        the size (in characters) of the autogenerated salt.
        It currently defaults to 8.

    :type rounds: int
    :param rounds:
        Optional number of rounds to use.
        Defaults to 5000, must be between 0 and 4294963199, inclusive.

    :type bare_salt: bool
    :param bare_salt:
        Optional flag used to enable an alternate salt digest behavior
        used by some hash strings in this scheme.
        This flag can be ignored by most users.
        Defaults to ``False``.
        (see :ref:`smc-bare-salt` for details).

    :type relaxed: bool
    :param relaxed:
        By default, providing an invalid value for one of the other
        keywords will result in a :exc:`ValueError`. If ``relaxed=True``,
        and the error can be corrected, a :exc:`~passlib.exc.PasslibHashWarning`
        will be issued instead. Correctable errors include ``rounds``
        that are too small or too large, and ``salt`` strings that are too long.

        .. versionadded:: 1.6
    """
    #===================================================================
    # class attrs
    #===================================================================
    name = "sun_md5_crypt"
    setting_kwds = ("salt", "rounds", "bare_salt", "salt_size")
    checksum_chars = uh.HASH64_CHARS
    checksum_size = 22

    # NOTE: docs say max password length is 255.
    # release 9u2

    # NOTE: not sure if original crypt has a salt size limit,
    # all instances that have been seen use 8 chars.
    default_salt_size = 8
    min_salt_size = 0
    max_salt_size = None
    salt_chars = uh.HASH64_CHARS

    default_rounds = 5000 # current passlib default
    min_rounds = 0
    max_rounds = 4294963199 ##2**32-1-4096
        # XXX: ^ not sure what it does if past this bound... does 32 int roll over?
    rounds_cost = "linear"

    ident_values = (u("$md5$"), u("$md5,"))

    #===================================================================
    # instance attrs
    #===================================================================
    bare_salt = False # flag to indicate legacy hashes that lack "$$" suffix

    #===================================================================
    # constructor
    #===================================================================
    def __init__(self, bare_salt=False, **kwds):
        self.bare_salt = bare_salt
        super(sun_md5_crypt, self).__init__(**kwds)

    #===================================================================
    # internal helpers
    #===================================================================
    @classmethod
    def identify(cls, hash):
        hash = uh.to_unicode_for_identify(hash)
        return hash.startswith(cls.ident_values)

    @classmethod
    def from_string(cls, hash):
        hash = to_unicode(hash, "ascii", "hash")

        #
        # detect if hash specifies rounds value.
        # if so, parse and validate it.
        # by end, set 'rounds' to int value, and 'tail' containing salt+chk
        #
        if hash.startswith(u("$md5$")):
            rounds = 0
            salt_idx = 5
        elif hash.startswith(u("$md5,rounds=")):
            idx = hash.find(u("$"), 12)
            if idx == -1:
                raise uh.exc.MalformedHashError(cls, "unexpected end of rounds")
            rstr = hash[12:idx]
            try:
                rounds = int(rstr)
            except ValueError:
                raise uh.exc.MalformedHashError(cls, "bad rounds")
            if rstr != unicode(rounds):
                raise uh.exc.ZeroPaddedRoundsError(cls)
            if rounds == 0:
                # NOTE: not sure if this is forbidden by spec or not;
                #      but allowing it would complicate things,
                #      and it should never occur anyways.
                raise uh.exc.MalformedHashError(cls, "explicit zero rounds")
            salt_idx = idx+1
        else:
            raise uh.exc.InvalidHashError(cls)

        #
        # salt/checksum separation is kinda weird,
        # to deal cleanly with some backward-compatible workarounds
        # implemented by original implementation.
        #
        chk_idx = hash.rfind(u("$"), salt_idx)
        if chk_idx == -1:
            # ''-config for $-hash
            salt = hash[salt_idx:]
            chk = None
            bare_salt = True
        elif chk_idx == len(hash)-1:
            if chk_idx > salt_idx and hash[-2] == u("$"):
                raise uh.exc.MalformedHashError(cls, "too many '$' separators")
            # $-config for $$-hash
            salt = hash[salt_idx:-1]
            chk = None
            bare_salt = False
        elif chk_idx > 0 and hash[chk_idx-1] == u("$"):
            # $$-hash
            salt = hash[salt_idx:chk_idx-1]
            chk = hash[chk_idx+1:]
            bare_salt = False
        else:
            # $-hash
            salt = hash[salt_idx:chk_idx]
            chk = hash[chk_idx+1:]
            bare_salt = True

        return cls(
            rounds=rounds,
            salt=salt,
            checksum=chk,
            bare_salt=bare_salt,
        )

    def to_string(self, withchk=True):
        ss = u('') if self.bare_salt else u('$')
        rounds = self.rounds
        if rounds > 0:
            hash = u("$md5,rounds=%d$%s%s") % (rounds, self.salt, ss)
        else:
            hash = u("$md5$%s%s") % (self.salt, ss)
        if withchk:
            chk = self.checksum
            if chk:
                hash = u("%s$%s") % (hash, chk)
        return uascii_to_str(hash)

    #===================================================================
    # primary interface
    #===================================================================
    # TODO: if we're on solaris, check for native crypt() support.
    #       this will require extra testing, to make sure native crypt
    #       actually behaves correctly. of particular importance:
    #       when using ""-config, make sure to append "$x" to string.

    def _calc_checksum(self, secret):
        # NOTE: no reference for how sun_md5_crypt handles unicode
        if isinstance(secret, unicode):
            secret = secret.encode("utf-8")
        config = str_to_bascii(self.to_string(withchk=False))
        return raw_sun_md5_crypt(secret, self.rounds, config).decode("ascii")

    #===================================================================
    # eoc
    #===================================================================

#=============================================================================
# eof
#=============================================================================


text:
require "#{File.dirname(__FILE__)}/default_adapter"
require "#{File.dirname(__FILE__)}/devise_adapter"

module Lolita
  class NoAuthenticationDefinedError < ArgumentError; end

  module Extensions
    module Authentication

      class Proxy
        attr_accessor :adapter

        def initialize context,options={}
          @context = context
          @options = options
          @adapter = get_adapter()
        end

        def current_user
          @adapter.current_user
        end

        def user_signed_in?
          @adapter.user_signed_in?
        end

        def authenticate_user!
          @adapter.authenticate_user!
        end

        def sign_out_via
          @adapter.sign_out_via unless default_adapter?
        end

        def edit_path
          @adapter.edit_path unless default_adapter?
        end

        def sign_out_path
          @adapter.sign_out_path unless default_adapter?
        end

        def default_adapter?
          self.adapter.is_a?(Lolita::Extensions::Authentication::DefaultAdapter)
        end

        private

        def get_adapter
          if Lolita.authentication
            Lolita::Extensions::Authentication::DeviseAdapter.new @context, @options
          else
            Lolita::Extensions::Authentication::DefaultAdapter.new @context, @options
          end
        end
      end

    end
  end
end


text:
<?php

namespace Symfony\Component\Serializer\Tests\Normalizer;

use Doctrine\Common\Annotations\AnnotationReader;
use PHPUnit\Framework\TestCase;
use Symfony\Component\PropertyInfo\Extractor\PhpDocExtractor;
use Symfony\Component\PropertyInfo\Type;
use Symfony\Component\Serializer\Exception\NotNormalizableValueException;
use Symfony\Component\Serializer\Mapping\ClassDiscriminatorFromClassMetadata;
use Symfony\Component\Serializer\Mapping\ClassDiscriminatorMapping;
use Symfony\Component\Serializer\Mapping\ClassMetadata;
use Symfony\Component\Serializer\Mapping\Factory\ClassMetadataFactory;
use Symfony\Component\Serializer\Mapping\Factory\ClassMetadataFactoryInterface;
use Symfony\Component\Serializer\Mapping\Loader\AnnotationLoader;
use Symfony\Component\Serializer\Normalizer\AbstractObjectNormalizer;
use Symfony\Component\Serializer\Normalizer\DenormalizerInterface;
use Symfony\Component\Serializer\Normalizer\ObjectNormalizer;
use Symfony\Component\Serializer\Serializer;
use Symfony\Component\Serializer\SerializerAwareInterface;
use Symfony\Component\Serializer\SerializerInterface;
use Symfony\Component\Serializer\Tests\Fixtures\AbstractDummy;
use Symfony\Component\Serializer\Tests\Fixtures\AbstractDummyFirstChild;
use Symfony\Component\Serializer\Tests\Fixtures\AbstractDummySecondChild;
use Symfony\Component\Serializer\Tests\Fixtures\DummySecondChildQuux;

class AbstractObjectNormalizerTest extends TestCase
{
    public function testDenormalize()
    {
        $normalizer = new AbstractObjectNormalizerDummy();
        $normalizedData = $normalizer->denormalize(['foo' => 'foo', 'bar' => 'bar', 'baz' => 'baz'], __NAMESPACE__.'\Dummy');

        $this->assertSame('foo', $normalizedData->foo);
        $this->assertNull($normalizedData->bar);
        $this->assertSame('baz', $normalizedData->baz);
    }

    public function testInstantiateObjectDenormalizer()
    {
        $data = ['foo' => 'foo', 'bar' => 'bar', 'baz' => 'baz'];
        $class = __NAMESPACE__.'\Dummy';
        $context = [];

        $normalizer = new AbstractObjectNormalizerDummy();

        $this->assertInstanceOf(__NAMESPACE__.'\Dummy', $normalizer->instantiateObject($data, $class, $context, new \ReflectionClass($class), []));
    }

    /**
     * @expectedException \Symfony\Component\Serializer\Exception\ExtraAttributesException
     * @expectedExceptionMessage Extra attributes are not allowed ("fooFoo", "fooBar" are unknown).
     */
    public function testDenormalizeWithExtraAttributes()
    {
        $factory = new ClassMetadataFactory(new AnnotationLoader(new AnnotationReader()));
        $normalizer = new AbstractObjectNormalizerDummy($factory);
        $normalizer->denormalize(
            ['fooFoo' => 'foo', 'fooBar' => 'bar'],
            __NAMESPACE__.'\Dummy',
            'any',
            ['allow_extra_attributes' => false]
        );
    }

    /**
     * @expectedException \Symfony\Component\Serializer\Exception\ExtraAttributesException
     * @expectedExceptionMessage Extra attributes are not allowed ("fooFoo", "fooBar" are unknown).
     */
    public function testDenormalizeWithExtraAttributesAndNoGroupsWithMetadataFactory()
    {
        $normalizer = new AbstractObjectNormalizerWithMetadata();
        $normalizer->denormalize(
            ['fooFoo' => 'foo', 'fooBar' => 'bar', 'bar' => 'bar'],
            Dummy::class,
            'any',
            ['allow_extra_attributes' => false]
        );
    }

    public function testDenormalizeCollectionDecodedFromXmlWithOneChild()
    {
        $denormalizer = $this->getDenormalizerForDummyCollection();

        $dummyCollection = $denormalizer->denormalize(
            [
                'children' => [
                    'bar' => 'first',
                ],
            ],
            DummyCollection::class,
            'xml'
        );

        $this->assertInstanceOf(DummyCollection::class, $dummyCollection);
        $this->assertInternalType('array', $dummyCollection->children);
        $this->assertCount(1, $dummyCollection->children);
        $this->assertInstanceOf(DummyChild::class, $dummyCollection->children[0]);
    }

    public function testDenormalizeCollectionDecodedFromXmlWithTwoChildren()
    {
        $denormalizer = $this->getDenormalizerForDummyCollection();

        $dummyCollection = $denormalizer->denormalize(
            [
                'children' => [
                    ['bar' => 'first'],
                    ['bar' => 'second'],
                ],
            ],
            DummyCollection::class,
            'xml'
        );

        $this->assertInstanceOf(DummyCollection::class, $dummyCollection);
        $this->assertInternalType('array', $dummyCollection->children);
        $this->assertCount(2, $dummyCollection->children);
        $this->assertInstanceOf(DummyChild::class, $dummyCollection->children[0]);
        $this->assertInstanceOf(DummyChild::class, $dummyCollection->children[1]);
    }

    private function getDenormalizerForDummyCollection()
    {
        $extractor = $this->getMockBuilder(PhpDocExtractor::class)->getMock();
        $extractor->method('getTypes')
            ->will($this->onConsecutiveCalls(
                [
                    new Type(
                        'array',
                        false,
                        null,
                        true,
                        new Type('int'),
                        new Type('object', false, DummyChild::class)
                    ),
                ],
                null
            ));

        $denormalizer = new AbstractObjectNormalizerCollectionDummy(null, null, $extractor);
        $arrayDenormalizer = new ArrayDenormalizerDummy();
        $serializer = new SerializerCollectionDummy([$arrayDenormalizer, $denormalizer]);
        $arrayDenormalizer->setSerializer($serializer);
        $denormalizer->setSerializer($serializer);

        return $denormalizer;
    }

    public function testDenormalizeWithDiscriminatorMapUsesCorrectClassname()
    {
        $factory = new ClassMetadataFactory(new AnnotationLoader(new AnnotationReader()));
        $loaderMock = $this->getMockBuilder(ClassMetadataFactoryInterface::class)->getMock();
        $loaderMock->method('hasMetadataFor')->willReturnMap([
            [
                AbstractDummy::class,
                true,
            ],
        ]);

        $loaderMock->method('getMetadataFor')->willReturnMap([
            [
                AbstractDummy::class,
                new ClassMetadata(
                    AbstractDummy::class,
                    new ClassDiscriminatorMapping('type', [
                        'first' => AbstractDummyFirstChild::class,
                        'second' => AbstractDummySecondChild::class,
                    ])
                ),
            ],
        ]);

        $discriminatorResolver = new ClassDiscriminatorFromClassMetadata($loaderMock);
        $normalizer = new AbstractObjectNormalizerDummy($factory, null, new PhpDocExtractor(), $discriminatorResolver);
        $serializer = new Serializer([$normalizer]);
        $normalizer->setSerializer($serializer);
        $normalizedData = $normalizer->denormalize(['foo' => 'foo', 'baz' => 'baz', 'quux' => ['value' => 'quux'], 'type' => 'second'], AbstractDummy::class);

        $this->assertInstanceOf(DummySecondChildQuux::class, $normalizedData->quux);
    }

    /**
     * Test that additional attributes throw an exception if no metadata factory is specified.
     *
     * @expectedException \Symfony\Component\Serializer\Exception\LogicException
     * @expectedExceptionMessage A class metadata factory must be provided in the constructor when setting "allow_extra_attributes" to false.
     */
    public function testExtraAttributesException()
    {
        $normalizer = new ObjectNormalizer();

        $normalizer->denormalize([], \stdClass::class, 'xml', [
            'allow_extra_attributes' => false,
        ]);
    }
}

class AbstractObjectNormalizerDummy extends AbstractObjectNormalizer
{
    protected function extractAttributes($object, $format = null, array $context = [])
    {
    }

    protected function getAttributeValue($object, $attribute, $format = null, array $context = [])
    {
    }

    protected function setAttributeValue($object, $attribute, $value, $format = null, array $context = [])
    {
        $object->$attribute = $value;
    }

    protected function isAllowedAttribute($classOrObject, $attribute, $format = null, array $context = [])
    {
        return \in_array($attribute, ['foo', 'baz', 'quux', 'value']);
    }

    public function instantiateObject(array &$data, $class, array &$context, \ReflectionClass $reflectionClass, $allowedAttributes, string $format = null)
    {
        return parent::instantiateObject($data, $class, $context, $reflectionClass, $allowedAttributes, $format);
    }
}

class Dummy
{
    public $foo;
    public $bar;
    public $baz;
}

class AbstractObjectNormalizerWithMetadata extends AbstractObjectNormalizer
{
    public function __construct()
    {
        parent::__construct(new ClassMetadataFactory(new AnnotationLoader(new AnnotationReader())));
    }

    protected function extractAttributes($object, $format = null, array $context = [])
    {
    }

    protected function getAttributeValue($object, $attribute, $format = null, array $context = [])
    {
    }

    protected function setAttributeValue($object, $attribute, $value, $format = null, array $context = [])
    {
        $object->$attribute = $value;
    }
}

class DummyCollection
{
    /** @var DummyChild[] */
    public $children;
}

class DummyChild
{
    public $bar;
}

class SerializerCollectionDummy implements SerializerInterface, DenormalizerInterface
{
    private $normalizers;

    /**
     * @param DenormalizerInterface[] $normalizers
     */
    public function __construct($normalizers)
    {
        $this->normalizers = $normalizers;
    }

    public function serialize($data, $format, array $context = [])
    {
    }

    public function deserialize($data, $type, $format, array $context = [])
    {
    }

    public function denormalize($data, $type, $format = null, array $context = [])
    {
        foreach ($this->normalizers as $normalizer) {
            if ($normalizer instanceof DenormalizerInterface && $normalizer->supportsDenormalization($data, $type, $format, $context)) {
                return $normalizer->denormalize($data, $type, $format, $context);
            }
        }
    }

    public function supportsDenormalization($data, $type, $format = null)
    {
        return true;
    }
}

class AbstractObjectNormalizerCollectionDummy extends AbstractObjectNormalizer
{
    protected function extractAttributes($object, $format = null, array $context = [])
    {
    }

    protected function getAttributeValue($object, $attribute, $format = null, array $context = [])
    {
    }

    protected function setAttributeValue($object, $attribute, $value, $format = null, array $context = [])
    {
        $object->$attribute = $value;
    }

    protected function isAllowedAttribute($classOrObject, $attribute, $format = null, array $context = [])
    {
        return true;
    }

    public function instantiateObject(array &$data, $class, array &$context, \ReflectionClass $reflectionClass, $allowedAttributes, string $format = null)
    {
        return parent::instantiateObject($data, $class, $context, $reflectionClass, $allowedAttributes, $format);
    }

    public function serialize($data, $format, array $context = [])
    {
    }

    public function deserialize($data, $type, $format, array $context = [])
    {
    }
}

class ArrayDenormalizerDummy implements DenormalizerInterface, SerializerAwareInterface
{
    /**
     * @var SerializerInterface|DenormalizerInterface
     */
    private $serializer;

    /**
     * {@inheritdoc}
     *
     * @throws NotNormalizableValueException
     */
    public function denormalize($data, $class, $format = null, array $context = [])
    {
        $serializer = $this->serializer;
        $class = substr($class, 0, -2);

        foreach ($data as $key => $value) {
            $data[$key] = $serializer->denormalize($value, $class, $format, $context);
        }

        return $data;
    }

    /**
     * {@inheritdoc}
     */
    public function supportsDenormalization($data, $type, $format = null, array $context = [])
    {
        return '[]' === substr($type, -2)
            && $this->serializer->supportsDenormalization($data, substr($type, 0, -2), $format, $context);
    }

    /**
     * {@inheritdoc}
     */
    public function setSerializer(SerializerInterface $serializer)
    {
        $this->serializer = $serializer;
    }
}


text:
package org.jabe.neverland.download.core;

public class DownloadManager extends DownloadEngineWraper {

	private DownloadConfig mDownloadConfig;

	public DownloadManager(DownloadConfig downloadConfig) {
		super(downloadConfig.mDownloadEngine);
		this.mDownloadConfig = downloadConfig;
	}

	public void downloadOperation(DownloadInfo downloadInfo, DownloadStatus lastStatus) {
		mDownloadConfig.mDownloadOperationMaper.operationMap(downloadInfo, lastStatus);
	}

}


text:
body {
	background: #e1edf9;
	background-size: cover;
	font-family: Helvetica Neue, sans-serif;
}

h3 {
	color: #797979;
	font-family: Helvetica Neue Light, Helvetica Neue, sans-serif;
	padding-bottom: 18px;
}

.center {
	margin-left: auto;
	margin-right: auto;
	display: block;
}

.markWithColor {
	color: #F15D4E;
}

.markWithColorBorder {
    border: 2px solid #F15D4E;
}


text:
<?xml version="1.0" encoding="utf-8"?>
<!--
   Copyright (C) 2013 Google Inc.

   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.
-->
<resources>
    <!-- TODO: Replace this by your app's app ID! -->
    <string name="app_id">84331009874</string>

    <!-- TODO: Replace these by your achievement/leaderboard IDs! -->
    <string name="achievement_welcome">CgkI0q6UlLoCEAIQAQ</string>
    <string name="achievement_thisisyourkingdom">CgkI0q6UlLoCEAIQAg</string>
    <string name="achievement_whatisthis">CgkI0q6UlLoCEAIQBA</string>
    <string name="achievement_notbadfirsttime">CgkI0q6UlLoCEAIQAw</string>
    <string name="achievement_bereadyfortheparty">CgkI0q6UlLoCEAIQBg</string>
    <string name="achievement_beachfiesta">CgkI0q6UlLoCEAIQBQ</string>

    <string name="leaderboard_easy">CgkI0q6UlLoCEAIQBw</string>
    <string name="leaderboard_medium">CgkI0q6UlLoCEAIQCA</string>
    <string name="leaderboard_hero">CgkI0q6UlLoCEAIQCQ</string>
</resources>


text:
var assert = require('assert');
var listXf = require('./helpers/listXf');

var R = require('..');

describe('all', function() {
  var even = function(n) {return n % 2 === 0;};
  var T = function() {return true;};
  var isFalse = function(x) { return x === false; };
  var intoArray = R.into([]);

  it('returns true if all elements satisfy the predicate', function() {
    assert.strictEqual(R.all(even, [2, 4, 6, 8, 10, 12]), true);
    assert.strictEqual(R.all(isFalse, [false, false, false]), true);
  });

  it('returns false if any element fails to satisfy the predicate', function() {
    assert.strictEqual(R.all(even, [2, 4, 6, 8, 9, 10]), false);
  });

  it('returns true for an empty list', function() {
    assert.strictEqual(R.all(T, []), true);
  });

  it('returns true into array if all elements satisfy the predicate', function() {
    assert.deepEqual(intoArray(R.all(even), [2, 4, 6, 8, 10, 12]), [true]);
    assert.deepEqual(intoArray(R.all(isFalse), [false, false, false]), [true]);
  });

  it('returns false into array if any element fails to satisfy the predicate', function() {
    assert.deepEqual(intoArray(R.all(even), [2, 4, 6, 8, 9, 10]), [false]);
  });

  it('returns true into array for an empty list', function() {
    assert.deepEqual(intoArray(R.all(T), []), [true]);
  });

  it('works with more complex objects', function() {
    var xs = [{x: 'abc'}, {x: 'ade'}, {x: 'fghiajk'}];
    function len3(o) { return o.x.length === 3; }
    function hasA(o) { return o.x.indexOf('a') > -1; }
    assert.strictEqual(R.all(len3, xs), false);
    assert.strictEqual(R.all(hasA, xs), true);
  });

  it('dispatches when given a transformer in list position', function() {
    assert.deepEqual(R.all(even, listXf), {
      all: true,
      f: even,
      xf: listXf
    });
  });

  it('is curried', function() {
    var count = 0;
    var test = function(n) {count += 1; return even(n);};
    assert.strictEqual(R.all(test)([2, 4, 6, 7, 8, 10]), false);
  });
});


text:
package org.apereo.cas.web.support;

import org.apereo.cas.authentication.principal.ServiceFactory;
import org.apereo.cas.authentication.principal.WebApplicationService;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * The default argument extractor is responsible for creating service
 * objects based on requests. The task of creating services is delegated to
 * a service factory that is pluggable for each instance of the extractor.
 *
 * @author Misagh Moayyed
 * @since 4.2
 */
public class DefaultArgumentExtractor extends AbstractArgumentExtractor {

    /**
     * Default extractor.
     */
    public DefaultArgumentExtractor() {
    }

    /**
     * Instantiates a new argument extractor.
     *
     * @param serviceFactory the service factory
     */
    public DefaultArgumentExtractor(final ServiceFactory<? extends WebApplicationService> serviceFactory) {
        super(serviceFactory);
    }

    /**
     * Instantiates a new argument extractor.
     *
     * @param serviceFactoryList the service factory list
     */
    public DefaultArgumentExtractor(final List<ServiceFactory<? extends WebApplicationService>> serviceFactoryList) {
        super(serviceFactoryList);
    }

    @Override
    public WebApplicationService extractServiceInternal(final HttpServletRequest request) {
        return getServiceFactories().stream().map(factory -> {
            final WebApplicationService service = factory.createService(request);
            if (service != null) {
                logger.debug("Created {} based on {}", service, factory);
                return service;
            }
            return null;
        }).filter(service -> service != null).findFirst().orElseGet(() -> {
            logger.debug("No service could be extracted based on the given request");
            return null;
        });
    }
}


text:
// vim:filetype=java:ts=4

package junit.com.mcdermottroe.exemplar.generated.schema.support;

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

import com.mcdermottroe.exemplar.Copyable;
import com.mcdermottroe.exemplar.generated.schema.support.W3CSchemaException;
import com.mcdermottroe.exemplar.generated.schema.support.W3CSchemaTreeOp;
import com.mcdermottroe.exemplar.generated.schema.support.XMLComponent;

import junit.com.mcdermottroe.exemplar.NormalClassTestCase;

/** Parent class to all subclasses of {@link W3CSchemaTreeOp}.

	@author		Conor McDermottroe
	@since		0.2
	@param	<T>	The type of {@link W3CSchemaTreeOp} to test.
*/
public abstract class
	W3CSchemaTreeOpTestCase<T extends W3CSchemaTreeOp & Copyable<T>>
extends NormalClassTestCase<T>
{
	/** The set of cases to test for in {@link #testShouldApply()}. */
	private Map<XMLComponent<?>, Boolean> shouldApplyTestCases;

	/** The set of cases for test for in {@link #testExecute()}. */
	private Map<XMLComponent<?>, Boolean> executeTestCases;

	/** {@inheritDoc} */
	@Override public void setUp()
	throws Exception
	{
		super.setUp();

		shouldApplyTestCases = new HashMap<XMLComponent<?>, Boolean>();
		executeTestCases = new HashMap<XMLComponent<?>, Boolean>();
	}

	/** Add a test case for {@link #testShouldApply()}.

		@param	test	The test to pass to {@link
						W3CSchemaTreeOp#shouldApply(XMLComponent)}.
		@param	res		The result that should come back from the call to
						{@link W3CSchemaTreeOp#shouldApply(XMLComponent)}.
	*/
	protected void addShouldApplyTestCase(XMLComponent<?> test, boolean res) {
		shouldApplyTestCases.put(test, res);
	}

	/** Add a test case for {@link #testExecute()}.

		@param	test		The test to pass to {@link
							W3CSchemaTreeOp#execute(XMLComponent)}.
		@param	willThrow	True if the call to {@link
							W3CSchemaTreeOp#execute(XMLComponent)} throws an
							exception, false if it doesn't.
	*/
	protected void addExecuteTestCase(XMLComponent<?> test, boolean willThrow) {
		executeTestCases.put(test, willThrow);
	}

	/** Test {@link W3CSchemaTreeOp#shouldApply(XMLComponent)}. */
	public void testShouldApply() {
		if (shouldApplyTestCases.isEmpty()) {
			fail("No tests for shouldApply(XMLComponent)");
			return;
		}

		for (T sample : samples()) {
			if (sample != null) {
				for (XMLComponent<?> test : shouldApplyTestCases.keySet()) {
					Boolean result = sample.shouldApply(test);
					assertEquals(
						"Result not as expected",
						shouldApplyTestCases.get(test),
						result
					);
				}
			}
		}
	}

	/** Test {@link W3CSchemaTreeOp#execute(XMLComponent)}. */
	public void testExecute() {
		if (executeTestCases.isEmpty()) {
			fail("No tests for execute(XMLComponent)");
			return;
		}

		for (T sample : samples()) {
			if (sample != null) {
				for (XMLComponent<?> test : executeTestCases.keySet()) {
					Boolean threw = false;
					try {
						sample.execute(test);
					} catch (W3CSchemaException e) {
						assertNotNull("W3CSchemaException was null", e);
						threw = true;
					} catch (Exception e) {
						assertNotNull("Exception was null", e);
						e.printStackTrace();
						fail("Unexpected exception thrown");
					}

					assertEquals(
						"Result not as expected",
						executeTestCases.get(test),
						threw
					);
				}
			}
		}
	}
}


text:
"""Decorators for adding dynamic tuning of object properties.

```python
# Decorate with `register_class_properties` to allow registering tunable
# properties.
@register_class_properties
class Foo(object)

  def __init__(self, ...):
    # Call `register_dynamic_object` during init to tell registry that this
    # object has tunables.
    register_dynamic_object(self)

  @property
  @register_property  Label this property as a tunable getter.
  def some_property(self):
    return self._some_property

  @some_property.setter
  @register_property  Label this property as a tunable setter.
  def some_property(self, val):
    self._some_property = val
```

Follow this pattern for all objects you wish to expose for tuning.
----

To tune properties on all decorated classes add the following to your app main:
```python
gui = property_editor.PropertyEditor(poll_freq=1.)
gui.run()
```
"""

import inspect
from typing import Any, Dict, List, Text
import weakref

registered_properties = {}  # type: Dict[type, Dict[Text, 'PropertyType']]
registered_objects = {}  # type: Dict[type, 'DynamicObjects']

def overrides(interface):
  """Overrides decorator to annotate method overrides parent's."""

  def overrider(method):
    if not hasattr(interface, method.__name__):
      raise Exception(
          'method %s declared to be @override is not defined in %s' %
          (method.__name__, interface.__name__))
    return method

  return overrider

class PropertyType(object):
  """Whether a property has a getter and setter."""

  def __init__(self,
               getter: bool = False,
               setter: bool = False):
    self.getter = getter
    self.setter = setter

  def __str__(self):
    return self.__repr__()

  def __repr__(self):
    return 'PropertyType(setter={}, getter={})'.format(
        self.setter, self.getter)

class DynamicObjects(object):
  """A container for a list of objects.

  DynamicObjects stores weak-references to objects to allow the cache to reflect
  only the currently existing objects whose __init__ was decorated with
  `regregister_dynamic_object`.
  """

  def __init__(self):
    self._object_refs = []

  def add_object(self, obj):
    self._object_refs.append(weakref.ref(obj))

  def get_objects(self) -> List[Any]:
    all_objs = [obj_ref() for obj_ref in self._object_refs]
    return [obj for obj in all_objs if obj is not None]

  def __str__(self):
    return self.__repr__()

  def __repr__(self):
    return 'DynamicObjects(objects={})'.format(self.get_objects())

def register_class_properties(leaf_cls):
  """Decorate a class with this in order to use @register_property.

  This decorator will look for properties (setter or getter) on the provided
  class and any of its parent classes that are decorated with
  `register_property` and register them under this class.

  Args:
    leaf_cls: A class of some type.

  Returns:
    The class.
  """

  classes_to_add = (leaf_cls,) + leaf_cls.__bases__
  for cls in classes_to_add:
    for name, method in cls.__dict__.items():
      # Add property to registry as getter.
      if (hasattr(method, 'fget') and
          hasattr(method.fget, 'register_getter')) or hasattr(
              method, 'register_getter'):
        registered_properties.setdefault(leaf_cls, {})
        registered_properties.get(leaf_cls).setdefault(name, PropertyType())  # pytype: disable=attribute-error
        registered_properties.get(leaf_cls).get(name).getter = True  # pytype: disable=attribute-error

      # Add property to registry as setter.
      if (hasattr(method, 'fset') and
          hasattr(method.fset, 'register_setter')) or hasattr(
              method, 'register_setter'):
        registered_properties.setdefault(leaf_cls, {})
        registered_properties.get(leaf_cls).setdefault(name, PropertyType())  # pytype: disable=attribute-error
        registered_properties.get(leaf_cls).get(name).setter = True  # pytype: disable=attribute-error

  return leaf_cls

def register_property(func):
  """Adds a property to registered_properties. must appear after @property."""
  if isinstance(func, property):
    raise AssertionError('@register_property must be after @property')

  argspec = inspect.getfullargspec(func)  # pytype: disable=wrong-arg-types
  if len(argspec.args) == 1:
    func.register_getter = True
  elif len(argspec.args) == 2:
    func.register_setter = True
  return func

def register_dynamic_object(obj):
  """Stores the provided object in the registry of dynamic objects.

  This function should be called during __init__ on all objects that utilize
  `register_property` to expose tunable properties.

  Args:
    obj: The `self` argument to the object to register.
  """
  # Add obj reference to registered objects.
  cls = obj.__class__
  registered_objects.setdefault(cls, DynamicObjects())
  registered_objs = registered_objects.get(cls)
  assert registered_objs is not None
  registered_objs.add_object(obj)


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

namespace ModestTree
{
    public static class LinqExtensions
    {
        public static IEnumerable<T> Append<T>(this IEnumerable<T> first, T item)
        {
            foreach (T t in first)
            {
                yield return t;
            }

            yield return item;
        }

        public static IEnumerable<T> Prepend<T>(this IEnumerable<T> first, T item)
        {
            yield return item;

            foreach (T t in first)
            {
                yield return t;
            }
        }

        // Return the first item when the list is of length one and otherwise returns default
        public static TSource OnlyOrDefault<TSource>(this IEnumerable<TSource> source)
        {
            if (source == null)
            {
                throw new ArgumentNullException("source");
            }

            var results = source.Take(2).ToArray();
            return results.Length == 1 ? results[0] : default(TSource);
        }

        public static IEnumerable<T> Prepend<T>(this IEnumerable<T> first, IEnumerable<T> second)
        {
            foreach (T t in second)
            {
                yield return t;
            }

            foreach (T t in first)
            {
                yield return t;
            }
        }

        // These are more efficient than Count() in cases where the size of the collection is not known
        public static bool HasAtLeast<T>(this IEnumerable<T> enumerable, int amount)
        {
            return enumerable.Take(amount).Count() == amount;
        }

        public static bool HasMoreThan<T>(this IEnumerable<T> enumerable, int amount)
        {
            return enumerable.HasAtLeast(amount+1);
        }

        public static bool HasLessThan<T>(this IEnumerable<T> enumerable, int amount)
        {
            return enumerable.HasAtMost(amount-1);
        }

        public static bool HasAtMost<T>(this IEnumerable<T> enumerable, int amount)
        {
            return enumerable.Take(amount + 1).Count() <= amount;
        }

        public static bool IsEmpty<T>(this IEnumerable<T> enumerable)
        {
            return !enumerable.Any();
        }

        public static IEnumerable<T> GetDuplicates<T>(this IEnumerable<T> list)
        {
            return list.GroupBy(x => x).Where(x => x.Skip(1).Any()).Select(x => x.Key);
        }

        public static IEnumerable<T> ReplaceOrAppend<T>(
            this IEnumerable<T> enumerable, Predicate<T> match, T replacement)
        {
            bool replaced = false;

            foreach (T t in enumerable)
            {
                if (match(t))
                {
                    replaced = true;
                    yield return replacement;
                }
                else
                {
                    yield return t;
                }
            }

            if (!replaced)
            {
                yield return replacement;
            }
        }

        public static IEnumerable<T> ToEnumerable<T>(this IEnumerator enumerator)
        {
            while (enumerator.MoveNext())
            {
                yield return (T)enumerator.Current;
            }
        }

        public static IEnumerable<T> ToEnumerable<T>(this IEnumerator<T> enumerator)
        {
            while (enumerator.MoveNext())
            {
                yield return enumerator.Current;
            }
        }

        public static HashSet<T> ToHashSet<T>(this IEnumerable<T> enumerable)
        {
            return new HashSet<T>(enumerable);
        }

        // This is more efficient than just Count() < x because it will end early
        // rather than iterating over the entire collection
        public static bool IsLength<T>(this IEnumerable<T> enumerable, int amount)
        {
            return enumerable.Take(amount + 1).Count() == amount;
        }

        public static T GetSingle<T>(this object[] objectArray, bool required)
        {
            if (required)
            {
                return objectArray.Where(x => x is T).Cast<T>().Single();
            }
            else
            {
                return objectArray.Where(x => x is T).Cast<T>().SingleOrDefault();
            }
        }

        public static IEnumerable<T> OfType<T>(this IEnumerable<T> source, Type type)
        {
            Assert.That(type.DerivesFromOrEqual<T>());
            return source.Where(x => x.GetType() == type);
        }

        public static IEnumerable<TSource> DistinctBy<TSource, TKey>(this IEnumerable<TSource> source,
            Func<TSource, TKey> keySelector)
        {
            return source.DistinctBy(keySelector, null);
        }

        public static IEnumerable<TSource> DistinctBy<TSource, TKey>(this IEnumerable<TSource> source,
            Func<TSource, TKey> keySelector, IEqualityComparer<TKey> comparer)
        {
            if (source == null)
                throw new ArgumentNullException("source");
            if (keySelector == null)
                throw new ArgumentNullException("keySelector");
            return DistinctByImpl(source, keySelector, comparer);
        }

        static IEnumerable<TSource> DistinctByImpl<TSource, TKey>(IEnumerable<TSource> source,
            Func<TSource, TKey> keySelector, IEqualityComparer<TKey> comparer)
        {
            var knownKeys = new HashSet<TKey>(comparer);
            foreach (var element in source)
            {
                if (knownKeys.Add(keySelector(element)))
                {
                    yield return element;
                }
            }
        }

        public static T Second<T>(this IEnumerable<T> list)
        {
            return list.Skip(1).First();
        }

        public static T SecondOrDefault<T>(this IEnumerable<T> list)
        {
            return list.Skip(1).FirstOrDefault();
        }

        public static int RemoveAll<T>(this LinkedList<T> list, Func<T, bool> predicate)
        {
            int numRemoved = 0;

            var currentNode = list.First;
            while (currentNode != null)
            {
                if (predicate(currentNode.Value))
                {
                    var toRemove = currentNode;
                    currentNode = currentNode.Next;
                    list.Remove(toRemove);
                    numRemoved++;
                }
                else
                {
                    currentNode = currentNode.Next;
                }
            }

            return numRemoved;
        }
    }
}


text:
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { Router, RouterModule } from '@angular/router';
import { NgbTooltip } from '@ng-bootstrap/ng-bootstrap';
import { Course } from 'app/entities/course.model';
import { HttpResponse } from '@angular/common/http';
import { Exam } from 'app/entities/exam.model';
import { ExamExerciseRowButtonsComponent } from 'app/exercises/shared/exam-exercise-row-buttons/exam-exercise-row-buttons.component';
import { DeleteButtonDirective } from 'app/shared/delete-dialog/delete-button.directive';
import { ArtemisTranslatePipe } from 'app/shared/pipes/artemis-translate.pipe';
import { ExerciseType } from 'app/entities/exercise.model';
import { ExerciseGroupsComponent } from 'app/exam/manage/exercise-groups/exercise-groups.component';
import { HasAnyAuthorityDirective } from 'app/shared/auth/has-any-authority.directive';
import dayjs from 'dayjs/esm';
import { of } from 'rxjs';
import { MockTranslateService, TranslateTestingModule } from '../../../helpers/mocks/service/mock-translate.service';
import { MockComponent, MockDirective, MockPipe } from 'ng-mocks';
import { MockRouter } from '../../../helpers/mocks/mock-router';
import { ArtemisTestModule } from '../../../test.module';
import { FileUploadExerciseGroupCellComponent } from 'app/exam/manage/exercise-groups/file-upload-exercise-cell/file-upload-exercise-group-cell.component';
import { ModelingExerciseGroupCellComponent } from 'app/exam/manage/exercise-groups/modeling-exercise-cell/modeling-exercise-group-cell.component';
import { ProgrammingExerciseGroupCellComponent } from 'app/exam/manage/exercise-groups/programming-exercise-cell/programming-exercise-group-cell.component';
import { QuizExerciseGroupCellComponent } from 'app/exam/manage/exercise-groups/quiz-exercise-cell/quiz-exercise-group-cell.component';
import { QuizExerciseService } from 'app/exercises/quiz/manage/quiz-exercise.service';
import { ProgrammingExerciseService } from 'app/exercises/programming/manage/services/programming-exercise.service';
import { QuizExercise } from 'app/entities/quiz/quiz-exercise.model';
import { TextExerciseService } from 'app/exercises/text/manage/text-exercise/text-exercise.service';
import { DueDateStat } from 'app/course/dashboards/due-date-stat.model';
import { ModelingExerciseService } from 'app/exercises/modeling/manage/modeling-exercise.service';
import { FileUploadExerciseService } from 'app/exercises/file-upload/manage/file-upload-exercise.service';
import { TranslateService } from '@ngx-translate/core';

describe('Exam Exercise Row Buttons Component', () => {
    const course = new Course();
    course.id = 456;
    course.isAtLeastInstructor = true;

    const exam = new Exam();
    exam.course = course;
    exam.id = 123;

    const dueDateStat = { inTime: 0, late: 0 } as DueDateStat;

    const quizQuestions = [
        {
            id: 1,
            text: 'text1',
            invalid: false,
            exportQuiz: false,
            randomizeOrder: true,
        },
        {
            id: 2,
            text: 'text2',
            invalid: false,
            exportQuiz: false,
            randomizeOrder: true,
        },
    ];

    const fileExercise = {
        id: 1,
        type: ExerciseType.FILE_UPLOAD,
        maxPoints: 100,
        secondCorrectionEnabled: false,
        studentAssignedTeamIdComputed: false,
        numberOfAssessmentsOfCorrectionRounds: [dueDateStat],
    };
    const programmingExercise = {
        id: 2,
        type: ExerciseType.PROGRAMMING,
        maxPoints: 100,
        secondCorrectionEnabled: false,
        studentAssignedTeamIdComputed: false,
        numberOfAssessmentsOfCorrectionRounds: [dueDateStat],
    };
    const modelingExercise = {
        id: 3,
        type: ExerciseType.MODELING,
        maxPoints: 100,
        secondCorrectionEnabled: false,
        studentAssignedTeamIdComputed: false,
        numberOfAssessmentsOfCorrectionRounds: [dueDateStat],
    };
    const textExercise = {
        id: 4,
        type: ExerciseType.TEXT,
        maxPoints: 100,
        secondCorrectionEnabled: false,
        studentAssignedTeamIdComputed: false,
        numberOfAssessmentsOfCorrectionRounds: [dueDateStat],
    };
    const quizExercise = {
        title: 'MyQuiz',
        id: 5,
        type: ExerciseType.QUIZ,
        maxPoints: 100,
        secondCorrectionEnabled: false,
        studentAssignedTeamIdComputed: false,
        numberOfAssessmentsOfCorrectionRounds: [dueDateStat],
        quizQuestions,
    };

    let comp: ExamExerciseRowButtonsComponent;
    let fixture: ComponentFixture<ExamExerciseRowButtonsComponent>;
    let textExerciseService: TextExerciseService;
    let modelingExerciseService: ModelingExerciseService;
    let fileUploadExerciseService: FileUploadExerciseService;
    let quizExerciseService: QuizExerciseService;
    let programmingExerciseService: ProgrammingExerciseService;

    beforeEach(() => {
        TestBed.configureTestingModule({
            imports: [ArtemisTestModule, TranslateTestingModule, RouterModule],
            declarations: [
                ExerciseGroupsComponent,
                ExamExerciseRowButtonsComponent,
                MockDirective(DeleteButtonDirective),
                MockDirective(HasAnyAuthorityDirective),
                MockDirective(NgbTooltip),
                MockPipe(ArtemisTranslatePipe),
                MockComponent(ProgrammingExerciseGroupCellComponent),
                MockComponent(QuizExerciseGroupCellComponent),
                MockComponent(FileUploadExerciseGroupCellComponent),
                MockComponent(ModelingExerciseGroupCellComponent),
            ],
            providers: [
                { provide: Router, useClass: MockRouter },
                { provide: TranslateService, useClass: MockTranslateService },
            ],
        }).compileComponents();

        fixture = TestBed.createComponent(ExamExerciseRowButtonsComponent);
        comp = fixture.componentInstance;

        textExerciseService = TestBed.inject(TextExerciseService);
        modelingExerciseService = TestBed.inject(ModelingExerciseService);
        fileUploadExerciseService = TestBed.inject(FileUploadExerciseService);
        quizExerciseService = TestBed.inject(QuizExerciseService);
        programmingExerciseService = TestBed.inject(ProgrammingExerciseService);
    });

    beforeEach(() => {
        comp.course = course;
        comp.exam = exam;
    });

    afterEach(() => {
        jest.restoreAllMocks();
    });

    describe('check exam is over', () => {
        it('should check exam is over is true', () => {
            comp.latestIndividualEndDate = dayjs().subtract(1, 'days');

            const isExamOver = comp.isExamOver();

            expect(isExamOver).toBeTrue();
        });

        it('should check exam is over is false', () => {
            comp.latestIndividualEndDate = dayjs().add(1, 'days');

            const isExamOver = comp.isExamOver();

            expect(isExamOver).toBeFalse();
        });
    });

    describe('check exercise deletion', () => {
        it('should delete textExercise', () => {
            comp.exercise = textExercise;
            const textExerciseServiceDeleteStub = jest.spyOn(textExerciseService, 'delete').mockReturnValue(of(new HttpResponse<{}>({ body: [] })));

            comp.deleteExercise();

            expect(textExerciseServiceDeleteStub).toHaveBeenCalledWith(textExercise.id);
        });

        it('should delete modelingExercise', () => {
            comp.exercise = modelingExercise;
            const modelingExerciseServiceDeleteStub = jest.spyOn(modelingExerciseService, 'delete').mockReturnValue(of(new HttpResponse<{}>({ body: [] })));

            comp.deleteExercise();

            expect(modelingExerciseServiceDeleteStub).toHaveBeenCalledWith(modelingExercise.id);
        });

        it('should delete fileExercise', () => {
            comp.exercise = fileExercise;
            const fileExerciseServiceDeleteStub = jest.spyOn(fileUploadExerciseService, 'delete').mockReturnValue(of(new HttpResponse<{}>({ body: [] })));

            comp.deleteExercise();

            expect(fileExerciseServiceDeleteStub).toHaveBeenCalledWith(fileExercise.id);
        });

        it('should delete quizExercise', () => {
            comp.exercise = quizExercise;
            const quizExerciseServiceDeleteStub = jest.spyOn(quizExerciseService, 'delete').mockReturnValue(of(new HttpResponse<{}>({ body: [] })));

            comp.deleteExercise();

            expect(quizExerciseServiceDeleteStub).toHaveBeenCalledWith(quizExercise.id);
        });

        it('should delete programmingExercise', () => {
            comp.exercise = programmingExercise;
            const programmingExerciseServiceDeleteStub = jest.spyOn(programmingExerciseService, 'delete').mockReturnValue(of(new HttpResponse<{}>({ body: [] })));

            comp.deleteProgrammingExercise({ deleteStudentReposBuildPlans: true, deleteBaseReposBuildPlans: false });

            expect(programmingExerciseServiceDeleteStub).toHaveBeenCalledWith(programmingExercise.id, true, false);
        });
    });

    describe('check quiz is being exported', () => {
        it('should export quiz exercise by id', () => {
            comp.exercise = quizExercise;
            const quizExerciseServiceFindSpy = jest.spyOn(quizExerciseService, 'find').mockReturnValue(of(new HttpResponse<QuizExercise>({ body: quizExercise })));
            const quizExerciseServiceExportQuizSpy = jest.spyOn(quizExerciseService, 'exportQuiz');

            comp.exportQuizById(true);

            expect(quizExerciseServiceFindSpy).toHaveBeenCalledWith(quizExercise.id);
            expect(quizExerciseServiceExportQuizSpy).toHaveBeenCalledWith(quizQuestions, true, quizExercise.title);
        });
    });
});


text:
namespace CycleC {

ClockedObject::ClockedObject() {
  Circuit* parentcircuit = Circuit::the_circuit_hierarchy.top();
  set_parent(*parentcircuit);
  parentcircuit->m_clockedobjects.push_back(this);
}

std::string Object::name() const {
  if (m_parent != NULL) {
    return m_parent->name() + "." + myname();
  } else {
    return myname();
  }
}

const std::string& Object::myname() const {
  if (m_myname.empty()) {
    // default: RTTI class name
    int status = 999;
    char* full = abi::__cxa_demangle(typeid(*this).name(), NULL, 0, &status);
    if (full != NULL) {
      const char* last = std::strrchr(full, ':');
      m_myname = (last == NULL) ? full : last+1;
      free(full);		// may leak when the above line throws exception
    } else {
      m_myname = "???";
    }
  }
  return m_myname;
}

void Object::set_parent(const Object& parent) {
  if (m_parent != NULL) {
    std::ostringstream strm;
    strm << "CycleC::Object : multiple parent for " << name() << " : "
	 << m_parent->name() << " and " << parent.name();
    throw std::logic_error(strm.str());
  }
  m_parent = &parent;
}

std::stack<Circuit*> Circuit::the_circuit_hierarchy;
std::stack<Circuit::Name*> Circuit::the_name_hierarchy;

Circuit::Name::Name(const char* name) : m_str(name), m_pushed(true) {
  Circuit::the_name_hierarchy.push(this);
}
Circuit::Name::Name(const Name& name) : m_str(name.m_str), m_pushed(false) {}

Circuit::Name::~Name() {
  if (m_pushed) {
    Circuit::the_name_hierarchy.pop();
    Circuit::the_circuit_hierarchy.pop();
  }
}

Circuit::Circuit()
#ifdef CYCLEC_MULTICLOCK
 : m_clockmap(1<<0)
#endif
{
  const Name* namep = the_name_hierarchy.top();
  set_myname(namep->m_str);
  if (! the_circuit_hierarchy.empty()) {
    Circuit* parentcircuit = the_circuit_hierarchy.top();
    set_parent(*parentcircuit);
    parentcircuit->m_subcircuits.push_back(this);
  }
  the_circuit_hierarchy.push(this);
}

void Circuit::evaluate() {
#ifdef CYCLEC_MULTICLOCK
  if ((the_active_clock_map & m_clockmap) == 0)  return;
#endif
  evaluate_self();
  int n = m_subcircuits.size();
  for (int i=0; i<n; ++i)  m_subcircuits[i]->evaluate();
}

void Circuit::update() {
#ifdef CYCLEC_MULTICLOCK
  if ((the_active_clock_map & m_clockmap) == 0)  return;
#endif
  update_self();
  int ns = m_subcircuits.size();
  for (int i=0; i<ns; ++i)  m_subcircuits[i]->update();
#ifdef CYCLEC_MULTICLOCK
  // Tick all ClockedObjects only when the circuit has single clock.
  // When the circuit has multiple clocks,
  // update_self() must tick its ClockedObjects explicitly.
  if ((m_clockmap & (m_clockmap-1)) != 0)  return;
#endif
  int nc = m_clockedobjects.size();
  for (int i=0; i<nc; ++i)  m_clockedobjects[i]->tick();
}

void Circuit::reset() {
  reset_self();
  int ns = m_subcircuits.size();
  for (int i=0; i<ns; ++i)  m_subcircuits[i]->reset();
  int nc = m_clockedobjects.size();
  for (int i=0; i<nc; ++i)  m_clockedobjects[i]->reset();
}

#ifdef CYCLEC_MULTICLOCK
Circuit::clkmap_t Circuit::the_active_clock_map = (1<<0);

void Circuit::assign_clock(int clknr) {
  m_clockmap = 1<<clknr;
  int n = m_subcircuits.size();
  for (int i=0; i<n; ++i)  m_subcircuits[i]->assign_clock(clknr);
}
#endif

#ifdef CYCLEC_MULTICLOCK
TimeKeeper::TimeKeeper() : m_time(0), m_clockmap(0) {}

void TimeKeeper::define_clock(int id, unsigned int period, unsigned int start_time) {
  if (start_time == 0)  start_time = period;
  ClockInfo info = { id, period, start_time, start_time, 0 };
  m_clockinfo.push_back(info);
}

void TimeKeeper::reset() {
  int n = m_clockinfo.size();
  for (int i=0; i<n; ++i) {
    ClockInfo& info = m_clockinfo[i];
    info.rest = info.start_time;
    info.cycle = 0;
  }
  m_time = 0;
  m_clockmap = 0;
}

void TimeKeeper::advance() {
  int n = m_clockinfo.size();
  //assert(sz != 0);
  unsigned int minrest = m_clockinfo[0].rest;
  for (int i=1; i<n; ++i) {
    minrest = std::min(minrest, m_clockinfo[i].rest);
  }
  Circuit::clkmap_t  map = 0;
  for (int i=0; i<n; ++i) {
    ClockInfo& info = m_clockinfo[i];
    info.rest -= minrest;
    if (info.rest == 0) {
      ++ info.cycle;
      info.rest = info.period;
      map |= (1<<info.id);
    }
  }
  //assert(map != 0);
  m_time += minrest;
  m_clockmap = map;
}

unsigned int TimeKeeper::time() const { return m_time; }
unsigned int TimeKeeper::cycle(int clkid) const {
  int n = m_clockinfo.size();
  for (int i=0; i<n; ++i) {
    if (m_clockinfo[i].id == clkid)  return m_clockinfo[i].cycle;
  }
  throw std::logic_error("TimeKeeper::cycle(): invalid clock id");
}
unsigned int TimeKeeper::clockmap() const { return m_clockmap; }

#endif

} // namespace CycleC


text:
	<?php _e('Slider shortcode', 'rc_slider') ?>
	<input class="widefat" type="text" readonly value='<?php echo (!empty($slider_id))? '[rcs_slider id="'.$slider_id.'"]' : ''; ?>' />
	<?php _e('Copy and past this shortcode anywhere you want to display the slider', 'rc_slider') ?>

	<?php _e('Slider php code', 'rc_slider') ?>
	<input class="widefat" type="text" readonly
	value="<?php echo (!empty($slider_id))? '<?php if(function_exists(\'rc_slider\')){ rc_slider(\''.$slider_id.'\'); } ?>' : ''; ?>" />
	<?php _e('Copy and past this php code anywhere you want to display the slider in the template files', 'rc_slider') ?>


text:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <androidx.appcompat.widget.Toolbar
        android:id="@+id/toolbar"
        style="@style/ToolBar"
        app:contentInsetStart="@dimen/tool_bar_content_inset_start" />

    <androidx.fragment.app.FragmentContainerView
        android:id="@+id/container"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_below="@id/toolbar"
        tools:background="@android:color/holo_green_dark"
        tools:context=".changes.ChangeListActivity"
        tools:ignore="MergeRootFrame"
        tools:layout="@layout/fragment_session_list" />

</RelativeLayout>


text:
ROOT_UID=0
SOURCES="/etc/apt/sources.list"
SOURCES_TMP="/tmp/sources.txt"
SOURCES_BACKUP="/etc/apt/sources.list.backup.blankon"
EXISTS="no"
RECOMMENT="no"

if grep -q "7.10" /etc/issue ; then VERSION="gutsy"
elif grep -q "7.04" /etc/issue ; then VERSION="feisty"
elif grep -q "6.10" /etc/issue ; then VERSION="edgy"
elif grep -q "6.06" /etc/issue ; then VERSION="dapper"
else
	echo "BlankOn linux tersedia dalam Ubuntu Gutsy jika anda menggunakan versi lama mungkin akan lain jadinya :p"
	exit 1
fi

# Need sudo privileges
if [ "$UID" -ne "$ROOT_UID" ]
then
  echo "Anda harus memiliki hak root untuk menjalakan skript ini atau silakan coba sudo ./install-blankon."
  exit $E_NOTROOT
fi

#Make sure no processes which will conflict are running
function conflict_check {
sleep 1
if ps -U root -u root u | grep "synaptic" | grep -v grep > /dev/null;
then echo "Instalasi Gagal!. Tutup Synaptic dahulu kemudian coba lagi ya....";
exit 1;
elif ps -U root -u root u | grep "update-manager" | grep -v grep > /dev/null;
then echo "Instalasi Gagal!. Tutup update-manager dahulu kemudian coba lagi ya....";
exit 1;
elif ps -U root -u root u | grep "apt-get" | grep -v grep > /dev/null;
then echo "Instalasi Gagal!. Menunggu proses apt-get hingga selesai, atau tutup proses yang sedang berjalan, kemudian coba lagi ya....";
exit 1;
elif ps -U root -u root u | grep "dpkg" | grep -v grep > /dev/null;
then
   killall -9 dpkg
   sleep 1
   if ps -U root -u root u | grep "dpkg" | grep -v grep > /dev/null;
   then echo "Instalasi Gagal!. Tutup segala yang berkaitan dengan dpkg.";
       exit 1;
   fi
fi
}

conflict_check

echo "Mempersiapkan sistem untuk instalasi BlankOn"

#Sort out sources.list
cat $SOURCES > $SOURCES_TMP
echo "" >> $SOURCES_TMP

if grep -q "http://arsip.blankonlinux.or.id/blankon" $SOURCES_TMP ; then EXISTS="yes"
else
 	echo "Menambahkan repository BlankOn dalam sources.list"
	echo "#BlankOn Linux" >> $SOURCES_TMP
 	echo "deb http://arsip.blankonlinux.or.id/blankon main restricted universe multiverse #BlankOn Linux" >> $SOURCES_TMP
# jika anda ingin mengupdate dari server foss-id
# 	echo "deb http://dl2.foss-id.web.id/ubuntu/ $VERSION main universe restricted multiverse #temp" >> $SOURCES_TMP
# memasukkan update Blankon Konde
	echo deb http://arsip.blankonlinux.or.id/blankon konde-updates main restricted
# memasukkan update keamanan BlankOn Konde
	echo deb http://security.blankonlinux.or.id/blankon konde-security main restricted
fi

echo "Membuat bakingup sources.list"
cp $SOURCES $SOURCES_BACKUP
mv $SOURCES_TMP $SOURCES
chown root:root $SOURCES

# menambahkan GPG
echo "Mengunduh Kunci GPG"
wget -q http://cdimage.blankonlinux.or.id/blankon-archive-keyring.gpg -O- | apt-key add -

# menginstall paket Blankon
echo "Menginstall Paket BlankOn"
apt-get update
apt-get upgrade
apt-get install blankon-desktop blankon-minimal blankon-standard germinate-blankon gfxboot-theme-blankon multimedia-blankon

# membersihkan cache
apt-get clean
apt-get autoclean

# greet
echo "instalasi telah selesai, Alhamdulillah"
echo "Silakan kunjugi http://groups.google.com/group/Blankon untuk mendapatkan bantuan teknis dan dukungan"

exit 0


text:
var DEBUG = true;
var PORT = 3000;

var app = require('express')(),
  server = require('http').createServer(app),
  io = require('socket.io').listen(server);

server.listen(PORT)

/** Setup express web server */
app.get('/', function(req, res) {
  res.sendfile(__dirname + '/index.html');
});

/** Setup Redis store for socket.io */
/*
var redis = require('socket.io/node_modules/redis');
var RedisStore = require('socket.io/lib/stores/redis'),
  redis = require('socket.io/node_modules/redis'),
  pub = redis.createClient(),
  sub = redis.createClient(),
  client = redis.createClient();

pub.auth(password, function(err) {
  if (err) throw err;
});
sub.auth(password, function(err) {
  if (err) throw err;
});
client.auth(password, function(err) {
  if (err) throw err;
});

io.set('store', new RedisStore({
  redis: redis,
  redisPub: pub,
  redisSub: sub,
  redisClient: client
}));

createClient(port, hostname, options)
*/

/**
 * socket.io
 */
io.sockets.on('connection', function(socket) {
  // join the room and send back some initial info
  // DEBUGGING, should be gotten from inital connection handshake and auth
  data = {
    room: socket.handshake.query.r
  }
  console.log(' --- ' + socket.id + ' wants to join room ' + data.room);
  socket.room = data.room; // use socket.set() instead?
  var members = io.sockets.clients(socket.room);

  if (members.length >= 2) {
    // room is full
    var response = {
      type: 'hello',
      id: socket.id,
      error: "full",
      makeOffer: false,
    };
    socket.emit('message', response);
  } else {
    socket.join(socket.room);
    var members = io.sockets.clients(socket.room);
    var response = {
      type: 'hello',
      id: socket.id,
      makeOffer: members.length == 2, // there is someone else in the room
    };
    socket.emit('message', response);

    // notify room that a new client has connected
    var response = {
      type: 'client-connected',
      id: socket.id,
    };
    socket.broadcast.to(socket.room).emit('message', response);
  }

  // relay messages from one client to another
  socket.on('message', function(data) {
    data.from = socket.id; // disallow source forgery

    //TODO DEBUG just broadcast all messages for now
    socket.broadcast.to(socket.room).emit('message', data);
    return;

    if (data.type == 'hello') {
      return; // only server allowed to send 'hello' messages
    }

    if (data.broadcast) {
      socket.broadcast.to(socket.room).emit('message', data);
    } else {
      io.sockets.socket(data.to).emit('message', data);
    }
  });

  socket.on('disconnect', function() {
    // notify room that a client has disconnected
    var response = {
      type: 'client-disconnected',
      id: socket.id,
    };
    socket.broadcast.to(socket.room).emit('message', response);

    console.log('-- END connection: ' + socket.id);
  });

}); // end socket.on


text:
<?php
/**
 * Created by PhpStorm.
 * User: Algorism
 * Date: 07/11/2017
 * Time: 15:43
 */

namespace Amadosi\Documentary\Resource;

class Table extends ResourceAbstract
{

    /**
     * @var array
     */
    protected $headers = [];

    /**
     * Column constructor.
     * @param int $span
     * @return $this
     */
    public function __construct(array $data=[], $headers=[], $style = null)
    {
        parent::__construct($data, $style);
        $this -> headers = $headers;
    }

    /**
     * @return array
     */
    public function getHeaders()
    {
        return $this->headers;
    }

    /**
     * @param array $headers
     */
    public function setHeaders(array $headers)
    {
        $this->headers = $headers;
    }

}


text:
package DTExpansionBengali;

import java.io.*;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * Created by krayush on 08-07-2015.
 */
public class ComparePolaritiesBengali {
    String rootDirectory;
    ComparePolaritiesBengali()throws IOException
    {
        rootDirectory = System.getProperty("user.dir");
        mainFunction(rootDirectory);
    }

    //public static void main(String[] args)throws IOException {
    private void mainFunction(String rootDirectory)throws IOException
    {
        File fR = new File(rootDirectory+"\\resources\\DTExpansionBengali\\IndianSentCooc\\polarity.txt");
        //PrintWriter writer = new PrintWriter("D:\\Course\\Semester VII\\Internship\\Results\\Maggie TUD\\sentimentJavaWords.txt");
        BufferedReader bf = new BufferedReader(new InputStreamReader(new FileInputStream(fR), "UTF-8"));

        LinkedHashMap<String, Double> cooc = new LinkedHashMap<String, Double>();
        String line;
        while((line = bf.readLine()) != null)
        {
            String tokens[] = line.split("\\|");
            cooc.put(tokens[0], Double.parseDouble(tokens[1]));
        }

        File fR1 = new File(rootDirectory+"\\resources\\DTExpansionBengali\\HTTPResults\\sortedDT.txt");
        //PrintWriter writer = new PrintWriter("D:\\Course\\Semester VII\\Internship\\Results\\Maggie TUD\\sentimentJavaWords.txt");
        BufferedReader bf1 = new BufferedReader(new InputStreamReader(new FileInputStream(fR1), "UTF-8"));

        LinkedHashMap<String, Double> dt = new LinkedHashMap<String, Double>();
        while((line = bf1.readLine()) != null)
        {
            String tokens[] = line.split("\\|");
            //System.out.println(tokens[1]);
            dt.put(tokens[0], Double.parseDouble(tokens[1]));
        }

        //System.out.println(dt.size());

        Writer polWriter = new OutputStreamWriter(
                new FileOutputStream(rootDirectory+"\\resources\\DT_COOCBengaliLexicon.txt"), "UTF-8");
        BufferedWriter pfout = new BufferedWriter(polWriter);
        Iterator polarityIterator = cooc.entrySet().iterator();
        int count=1;

        while(polarityIterator.hasNext()) {
            Map.Entry me = (Map.Entry) polarityIterator.next();
            String key = me.getKey().toString();
            Double val = Double.parseDouble(me.getValue().toString());
            //System.out.println("pqr");
            if(dt.containsKey(key))
            {
                //System.out.println("abc");
                count++;
                if(val*dt.get(key) > 0)
                {
                    if(val > 0)
                    {
                        pfout.write(key+"|"+val+"|"+dt.get(key)+"|"+"1"+"\n");
                        //pfout.write(key+"|"+"1"+"\n");
                    }
                    else
                    {
                        pfout.write(key+"|"+val+"|"+dt.get(key)+"|"+"-1"+"\n");
                        //pfout.write(key+"|"+"-1"+"\n");
                    }
                }
                else if(val ==0 && dt.get(key)==0)
                {
                    pfout.write(key+"|"+val+"|"+dt.get(key)+"|"+"0"+"\n");
                    //pfout.write(key+"|"+"0"+"\n");
                }
                //else
            }

        }
        System.out.println(count);
        pfout.close();

    }
}


text:
<!doctype html>

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

  <title>page.js example page</title>
  <meta name='description' content='a simple example for the page.js javascript plugin.'>
  <meta name='author' content='Lucas Mazza'>
  <meta name='viewport' content='width=device-width,initial-scale=1'>

Check the 'index'

Or another page.


text:
<?php
/**
 * Example Activation
 *
 * Activation class for Example plugin.
 * This is optional, and is required only if you want to perform tasks when your plugin is activated/deactivated.
 *
 * @package  Croogo
 * @author   Fahad Ibnay Heylaal <contact@fahad19.com>
 * @license  http://www.opensource.org/licenses/mit-license.php The MIT License
 * @link     http://www.croogo.org
 */
class BraintreeActivation {
/**
 * onActivate will be called if this returns true
 *
 * @param  object $controller Controller
 * @return boolean
 */
    public function beforeActivation(&$controller) {
        return true;
    }
/**
 * Called after activating the plugin in ExtensionsPluginsController::admin_toggle()
 *
 * @param object $controller Controller
 * @return void
 */
    public function onActivation(&$controller) {
        // ACL: set ACOs with permissions
        $controller->Croogo->addAco('Braintree'); // ExampleController
        $controller->Croogo->addAco('BraintreeTransaction/index'); // ExampleController::admin_index()
        //$controller->Croogo->addAco('BraintreeTransaction/index', array('registered', 'public')); // ExampleController::index()

        // Main menu: add an Example link
        $mainMenu = $controller->Link->Menu->findByAlias('main');
        $controller->Link->Behaviors->attach('Tree', array(
            'scope' => array(
                'Link.menu_id' => $mainMenu['Menu']['id'],
            ),
        ));
        $controller->Link->save(array(
            'menu_id' => $mainMenu['Menu']['id'],
            'title' => 'FullCalendar',
            'link' => 'plugin:braintree/controller:braintree_transaction/action:index',
            'status' => 1,
        ));
    }
/**
 * onDeactivate will be called if this returns true
 *
 * @param  object $controller Controller
 * @return boolean
 */
    public function beforeDeactivation(&$controller) {
        return true;
    }
/**
 * Called after deactivating the plugin in ExtensionsPluginsController::admin_toggle()
 *
 * @param object $controller Controller
 * @return void
 */
    public function onDeactivation(&$controller) {
        // ACL: remove ACOs with permissions
        $controller->Croogo->removeAco('Braintree'); // ExampleController ACO and it's actions will be removed

        // Main menu: delete Example link
        $link = $controller->Link->find('first', array(
            'conditions' => array(
                'Menu.alias' => 'main',
                'Link.link' => 'plugin:braintree/controller:braintree_transaction/action:index',
            ),
        ));
        $controller->Link->Behaviors->attach('Tree', array(
            'scope' => array(
                'Link.menu_id' => $link['Link']['menu_id'],
            ),
        ));
        if (isset($link['Link']['id'])) {
            $controller->Link->delete($link['Link']['id']);
        }
    }
}
?>


text:
import primaryColor from '@material-ui/core/colors/teal';
import CssBaseline from '@material-ui/core/CssBaseline';
import { createMuiTheme, MuiThemeProvider } from '@material-ui/core/styles';
import * as React from 'react';
import { BrowserRouter as Router, Redirect, Route, Switch } from "react-router-dom";
import 'typeface-roboto';
import List from './List';
import Player from './Player';

const theme = createMuiTheme({
	palette: {
		primary: primaryColor,
		type: 'dark',
	},
	typography: {
		useNextVariants: true
	},
});

function App() {
	return (
		<MuiThemeProvider theme={theme}>
			<CssBaseline />
			<Router>
				<Switch>
					<Route name="list" path="/list/**" component={List} />
					<Route name="play" path="/play/**" component={Player} />
					<Redirect to="/list/" />
				</Switch>
			</Router>
		</MuiThemeProvider>
	);
}

export default App;


text:
package org.jbpm.formModeler.core.processing.formStatus;

import org.jbpm.formModeler.api.model.Form;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.Serializable;
import java.util.*;

/**
 * Defines the status of a form with the submited values, each FormStatus is identified with a namespace and a formId.
 */
public class FormStatus implements Serializable {
    private static transient Logger log = LoggerFactory.getLogger(FormStatus.class);

    private Map<String, Object> inputValues = new HashMap<String, Object>();
    private Map lastParameterMap;
    private Form relatedForm;
    private Set wrongFields = new TreeSet();
    private Map<String, List> wrongFieldsMessages = new HashMap<String, List>();
    private String namespace;
    private Map attributes = new HashMap();
    private Map<String, Object> loadedObjects = new HashMap<String, Object>();

    public FormStatus(Form relatedForm, String namespace, Map currentValues) {
        this.relatedForm = relatedForm;
        this.namespace = namespace;
        if (currentValues != null) inputValues.putAll(currentValues);
    }

    public Map getInputValues() {
        return inputValues;
    }

    public Map getLastParameterMap() {
        return lastParameterMap;
    }

    public void setLastParameterMap(Map lastParameterMap) {
        this.lastParameterMap = lastParameterMap;
    }

    public Set getWrongFields() {
        return wrongFields;
    }

    public Form getRelatedForm() {
        return relatedForm;
    }

    public String getNamespace() {
        return namespace;
    }

    public void setNamespace(String namespace) {
        this.namespace = namespace;
    }

    protected void clear() {
        inputValues.clear();
        attributes.clear();
        lastParameterMap = null;
    }

    public Map getAttributes() {
        return attributes;
    }

    public void setAttributes(Map attributes) {
        this.attributes = attributes;
    }

    public void clearFormErrors() {
        wrongFields.clear();
        wrongFieldsMessages.clear();
    }

    public void removeWrongField(String fieldName) {
        wrongFields.remove(fieldName);
        wrongFieldsMessages.remove(fieldName);
    }

    public List getErrorMessage(String fieldName) {
        return wrongFieldsMessages.get(fieldName);
    }

    public void addErrorMessages(String fieldName, List messages) {
        wrongFields.add(fieldName);
        wrongFieldsMessages.put(fieldName, messages);
    }

    public Map getWrongFieldsMessages() {
        return wrongFieldsMessages;
    }

    public void setWrongFieldsMessages(Map wrongFieldsMessages) {
        this.wrongFieldsMessages = wrongFieldsMessages;
    }

    public Map<String, Object> getLoadedObjects() {
        return loadedObjects;
    }

    public void setLoadedObjects(Map<String, Object> loadedObjects) {
        this.loadedObjects = loadedObjects;
    }

    public void addLoadedObject(String id, Object obj) {
        loadedObjects.put(id, obj);
    }

    public Object getLoadedObject(String id) {
        return loadedObjects.get(id);
    }
}


text:
//
//  ZXYAlmanacModel.h
//  ChooseDay
//
//  Created by Rockeen on 16/1/18.
//  Copyright © 2016年 DreamThreeMusketeers. All rights reserved.
//

#import <Foundation/Foundation.h>

/*

 error_code	INT	返回码
 reason	STRING	返回说明
 yangli	DATE	阳历
 yinli	STRING	阴历
 wuxing	STRING	五行
 chongsha	STRING	冲煞
 baiji	STRING	彭祖百忌
 jishen	STRING	吉神宜趋
 yi	STRING	宜
 xiongshen	STRING	凶神宜忌
 ji	STRING	忌

 */

@interface ZXYAlmanacModel : NSObject

@property (nonatomic, strong) NSString *yinli;
@property (nonatomic, strong) NSString* yangli;
@property (nonatomic, strong) NSString *wuxing;
@property (nonatomic, strong) NSString *chongsha;
@property (nonatomic, strong) NSString *baiji;
@property (nonatomic, strong) NSString *jishen;
@property (nonatomic, strong) NSString *yi;
@property (nonatomic, strong) NSString *ji;

@end


text:
use std::error;
use std::ffi::{CString, NulError};
use std::fmt;
use std::os::raw::{c_char, c_int};
use std::ptr;

use crate::get_error;
use crate::video::Window;

use crate::sys;

bitflags! {
    pub struct MessageBoxFlag: u32 {
        const ERROR =
            sys::SDL_MessageBoxFlags::SDL_MESSAGEBOX_ERROR as u32;
        const WARNING =
            sys::SDL_MessageBoxFlags::SDL_MESSAGEBOX_WARNING as u32;
        const INFORMATION =
            sys::SDL_MessageBoxFlags::SDL_MESSAGEBOX_INFORMATION as u32;
    }
}

bitflags! {
    pub struct MessageBoxButtonFlag: u32 {
        const ESCAPEKEY_DEFAULT =
            sys::SDL_MessageBoxButtonFlags::SDL_MESSAGEBOX_BUTTON_ESCAPEKEY_DEFAULT as u32;
        const RETURNKEY_DEFAULT =
            sys::SDL_MessageBoxButtonFlags::SDL_MESSAGEBOX_BUTTON_RETURNKEY_DEFAULT as u32;
        const NOTHING = 0;
    }
}

#[derive(Debug)]
pub struct MessageBoxColorScheme {
    pub background: (u8, u8, u8),
    pub text: (u8, u8, u8),
    pub button_border: (u8, u8, u8),
    pub button_background: (u8, u8, u8),
    pub button_selected: (u8, u8, u8),
}

impl Into<sys::SDL_MessageBoxColorScheme> for MessageBoxColorScheme {
    fn into(self) -> sys::SDL_MessageBoxColorScheme {
        sys::SDL_MessageBoxColorScheme {
            colors: self.into(),
        }
    }
}

impl From<sys::SDL_MessageBoxColorScheme> for MessageBoxColorScheme {
    fn from(prim: sys::SDL_MessageBoxColorScheme) -> MessageBoxColorScheme {
        prim.colors.into()
    }
}

/// `button_id` is the integer that will be returned
/// by `show_message_box`. It is not sed by SDL2,
/// and should only be used to know which button has been triggered
#[derive(Debug)]
pub struct ButtonData<'a> {
    pub flags: MessageBoxButtonFlag,
    pub button_id: i32,
    pub text: &'a str,
}

#[derive(Debug)]
pub enum ClickedButton<'a> {
    CloseButton,
    CustomButton(&'a ButtonData<'a>),
}

impl From<MessageBoxColorScheme> for [sys::SDL_MessageBoxColor; 5] {
    fn from(scheme: MessageBoxColorScheme) -> [sys::SDL_MessageBoxColor; 5] {
        fn to_message_box_color(t: (u8, u8, u8)) -> sys::SDL_MessageBoxColor {
            sys::SDL_MessageBoxColor {
                r: t.0,
                g: t.1,
                b: t.2,
            }
        }
        [
            to_message_box_color(scheme.background),
            to_message_box_color(scheme.text),
            to_message_box_color(scheme.button_border),
            to_message_box_color(scheme.button_background),
            to_message_box_color(scheme.button_selected),
        ]
    }
}

impl Into<MessageBoxColorScheme> for [sys::SDL_MessageBoxColor; 5] {
    fn into(self) -> MessageBoxColorScheme {
        fn from_message_box_color(prim_color: sys::SDL_MessageBoxColor) -> (u8, u8, u8) {
            (prim_color.r, prim_color.g, prim_color.b)
        }
        MessageBoxColorScheme {
            background: from_message_box_color(self[0]),
            text: from_message_box_color(self[1]),
            button_border: from_message_box_color(self[2]),
            button_background: from_message_box_color(self[3]),
            button_selected: from_message_box_color(self[4]),
        }
    }
}

#[derive(Debug, Clone)]
pub enum ShowMessageError {
    InvalidTitle(NulError),
    InvalidMessage(NulError),
    /// Second argument of the tuple (i32) corresponds to the
    /// first button_id having an error
    InvalidButton(NulError, i32),
    SdlError(String),
}

impl fmt::Display for ShowMessageError {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        use self::ShowMessageError::*;

        match *self {
            InvalidTitle(ref e) => write!(f, "Invalid title: {}", e),
            InvalidMessage(ref e) => write!(f, "Invalid message: {}", e),
            InvalidButton(ref e, value) => write!(f, "Invalid button ({}): {}", value, e),
            SdlError(ref e) => write!(f, "SDL error: {}", e),
        }
    }
}

impl error::Error for ShowMessageError {
    fn description(&self) -> &str {
        use self::ShowMessageError::*;

        match *self {
            InvalidTitle(_) => "invalid title",
            InvalidMessage(_) => "invalid message",
            InvalidButton(..) => "invalid button",
            SdlError(ref e) => e,
        }
    }
}

/// Show a simple message box, meant to be informative only.
///
/// There is no way to know if the user clicked "Ok" or closed the message box,
/// If you want to retrieve which button was clicked and customize a bit more
/// your message box, use `show_message_box` instead.
#[doc(alias = "SDL_ShowSimpleMessageBox")]
pub fn show_simple_message_box<'a, W>(
    flags: MessageBoxFlag,
    title: &str,
    message: &str,
    window: W,
) -> Result<(), ShowMessageError>
where
    W: Into<Option<&'a Window>>,
{
    use self::ShowMessageError::*;
    let result = unsafe {
        let title = match CString::new(title) {
            Ok(s) => s,
            Err(err) => return Err(InvalidTitle(err)),
        };
        let message = match CString::new(message) {
            Ok(s) => s,
            Err(err) => return Err(InvalidMessage(err)),
        };
        sys::SDL_ShowSimpleMessageBox(
            flags.bits(),
            title.as_ptr() as *const c_char,
            message.as_ptr() as *const c_char,
            window.into().map_or(ptr::null_mut(), |win| win.raw()),
        )
    } == 0;

    if result {
        Ok(())
    } else {
        Err(SdlError(get_error()))
    }
}

/// Show a customizable message box.
///
/// An array of buttons is required for it to work. The array can be empty,
/// but it will have no button beside the close button.
///
/// On success, it will return either the button clicked or the close button.
/// Note that the variant of the `ClickedButton` enum will also be returned if the message box
/// has been forcefully closed (Alt-F4, ...)
///
#[doc(alias = "SDL_ShowMessageBox")]
pub fn show_message_box<'a, 'b, W, M>(
    flags: MessageBoxFlag,
    buttons: &'a [ButtonData],
    title: &str,
    message: &str,
    window: W,
    scheme: M,
) -> Result<ClickedButton<'a>, ShowMessageError>
where
    W: Into<Option<&'b Window>>,
    M: Into<Option<MessageBoxColorScheme>>,
{
    let window = window.into();
    let scheme = scheme.into();

    use self::ShowMessageError::*;
    let mut button_id: c_int = 0;
    let title = match CString::new(title) {
        Ok(s) => s,
        Err(err) => return Err(InvalidTitle(err)),
    };
    let message = match CString::new(message) {
        Ok(s) => s,
        Err(err) => return Err(InvalidMessage(err)),
    };
    let button_texts: Result<Vec<_>, (_, i32)> = buttons
        .iter()
        .map(|b| CString::new(b.text).map_err(|e| (e, b.button_id)))
        .collect(); // Create CString for every button; and catch any CString Error
    let button_texts = match button_texts {
        Ok(b) => b,
        Err(e) => return Err(InvalidButton(e.0, e.1)),
    };
    let raw_buttons: Vec<sys::SDL_MessageBoxButtonData> = buttons
        .iter()
        .zip(button_texts.iter())
        .map(|(b, b_text)| sys::SDL_MessageBoxButtonData {
            flags: b.flags.bits(),
            buttonid: b.button_id as c_int,
            text: b_text.as_ptr(),
        })
        .collect();
    let result = unsafe {
        let msg_box_data = sys::SDL_MessageBoxData {
            flags: flags.bits(),
            window: window.map_or(ptr::null_mut(), |win| win.raw()),
            title: title.as_ptr() as *const c_char,
            message: message.as_ptr() as *const c_char,
            numbuttons: raw_buttons.len() as c_int,
            buttons: raw_buttons.as_ptr(),
            colorScheme: if let Some(scheme) = scheme {
                &sys::SDL_MessageBoxColorScheme {
                    colors: From::from(scheme),
                } as *const _
            } else {
                ptr::null()
            },
        };
        sys::SDL_ShowMessageBox(&msg_box_data as *const _, &mut button_id as &mut _)
    } == 0;
    if result {
        match button_id {
            -1 => Ok(ClickedButton::CloseButton),
            id => {
                let button = buttons.iter().find(|b| b.button_id == id);
                Ok(ClickedButton::CustomButton(button.unwrap()))
            }
        }
    } else {
        Err(SdlError(get_error()))
    }
}