text:
namespace TrueSnow.Web.Areas.Administration.Controllers
{
    using System.Web.Mvc;

    using Kendo.Mvc.Extensions;
    using Kendo.Mvc.UI;

    using Data.Models;
    using Infrastructure.Constants;
    using Services.Data.Contracts;
    using ViewModels;

    [Authorize(Roles = IdentityRoles.Administrator)]
    public class AdminPostsController : Controller
    {
        private readonly IPostsService posts;

        public AdminPostsController(IPostsService posts)
        {
            this.posts = posts;
        }

        public ActionResult Index()
        {
            return this.View();
        }

        public ActionResult Posts_Read([DataSourceRequest]DataSourceRequest request)
        {
            DataSourceResult result = this.posts
                .GetAll()
                .ToDataSourceResult(
                request,
                post => new AdminPostViewModel
                {
                    Id = post.Id,
                    Title = post.Title,
                    Content = post.Content,
                    CreatorId = post.CreatorId
                });

            return this.Json(result);
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Posts_Update([DataSourceRequest]DataSourceRequest request, AdminPostViewModel post)
        {
            if (this.ModelState.IsValid)
            {
                var entity = this.posts.GetById(post.Id);

                entity.Title = post.Title;
                entity.Content = post.Content;
                this.posts.Save();
            }

            return this.Json(new[] { post }.ToDataSourceResult(request, this.ModelState));
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Posts_Destroy([DataSourceRequest]DataSourceRequest request, Post post)
        {
            if (this.ModelState.IsValid)
            {
                this.posts.Delete(post.Id);
            }

            return this.Json(new[] { post }.ToDataSourceResult(request, this.ModelState));
        }
    }
}


text:
namespace Slash.Unity.StrangeIoC.Modules.Signals
{
    using System;
    using strange.extensions.signal.impl;

    public class UnloadModuleSignal : Signal<Type>
    {
    }
}

redpajama_set_name: RedPajamaGithub


text:
require File.expand_path(File.join(File.dirname(__FILE__), '..', 'spec_helper'))
require File.expand_path(File.join(File.dirname(__FILE__), 'shared_spec_node'))
require 'stringio'

describe CopyNode do

  it_should_behave_like AllStandardNodes

  before(:each) do
    @context = mock "Context"
    @source_path = mock "SourcePath"
    @path_handler = mock "PathHandler"
    @instance = CopyNode.new(@context, @source_path, @path_handler)
  end

  it "should have a dest_path equal to its source_path" do
    @instance.dest_path.should == @source_path
  end

  it "should have a constructor which accepts also a meta_info hash" do
    lambda {
      @instance = CopyNode.new(@context, @source_path, @path_handler, :hello => "world")
    }.should_not raise_error
    @instance.meta_info.should == { :hello => "world" }
  end

  it "should have a build method" do
    @instance.should respond_to(:build)
  end

  it "should be buildable" do
    @instance.should be_buildable
  end

  it "should correctly copy the node read from the input path_handler" do
    content = "the input string"
    input = StringIO.new(content)
    output = StringIO.new
    @path_handler.should_receive(:open).with(@source_path, "r").and_yield(input)
    @instance.build(output)
    output.string.should == content
  end
end


text:
module BillTrap
  module Adapters
    class Ooffice
      # uses Serenity for ODT output
      include ::Serenity::Generator
      include BillTrap::Helpers
      attr_reader :id

      def initialize attributes
        attributes.each do |key, val|
          # slurp attributes into instances variables
          instance_variable_set("@#{key}", val)
        end
      end

      def generate
        date = @invoice[:created]
        output_path = "#{Config['billtrap_archive']}/#{date.year}/#{date.month}/#{date.mday}"
        FileUtils.mkpath(output_path)

        render_odt Config['serenity_template'], "#{output_path}/#{@invoice.id}.odt"
        puts "Generated invoice has been output to: #{output_path}/#{@invoice.id}.odt"
    end

  end
end
end


text:
package com.apache.airavata.user.profile.server;

import org.apache.airavata.model.user.UserProfile;
import org.apache.airavata.registry.api.exception.RegistryServiceException;
import org.apache.airavata.registry.core.entities.workspacecatalog.UserProfileEntity;
import org.apache.airavata.registry.core.repositories.workspacecatalog.UserProfileRepository;
import org.apache.airavata.userprofile.crude.cpi.UserProfileCrudeService;
import org.apache.thrift.TException;

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

/**
 * Created by Airavata on 11/11/2016.
 */
public class UserProfileHandler implements UserProfileCrudeService.Iface {

    private UserProfileRepository userProfileRepository;

    public UserProfileHandler() {

        userProfileRepository = new UserProfileRepository(UserProfile.class, UserProfileEntity.class);
    }

    public String addUserProfile(UserProfile userProfile) throws RegistryServiceException, TException {

        userProfileRepository.create(userProfile);

        if (null != userProfile)
            return userProfile.getUserId();

        return null;
    }

    public boolean updateUserProfile(UserProfile userProfile) throws RegistryServiceException, TException {

        try {
            userProfileRepository.update(userProfile);
        } catch (Exception e) {

            return false;
        }

        return true;
    }

    public UserProfile getUserProfileById(String userId, String gatewayId) throws RegistryServiceException, TException {

        UserProfile userProfile = userProfileRepository.getUserProfileByIdAndGateWay(userId, gatewayId);

        return userProfile;
    }

    public boolean deleteUserProfile(String userId) throws RegistryServiceException, TException {

        boolean deleteResult = userProfileRepository.delete(userId);

        return deleteResult;
    }

    public List<UserProfile> getAllUserProfilesInGateway(String gatewayId, int offset, int limit) throws RegistryServiceException, TException {
        List<UserProfile> usersInGateway = userProfileRepository.getAllUserProfilesInGateway(gatewayId, offset, limit);
        return usersInGateway;
    }

    public UserProfile getUserProfileByName(String userName, String gatewayId) throws RegistryServiceException, TException {

        UserProfile userProfile = userProfileRepository.getUserProfileByNameAndGateWay(userName, gatewayId);
        return userProfile;
    }

    public boolean doesUserExist(String userName, String gatewayId) throws RegistryServiceException, TException {

        UserProfile userProfile = userProfileRepository.getUserProfileByNameAndGateWay(userName, gatewayId);

        if (null != userProfile)
            return true;
        return false;
    }
}


text:
from pyflink.shell import b_env, bt_env, FileSystem, OldCsv, DataTypes, Schema

import tempfile
import os
import shutil

sink_path = tempfile.gettempdir() + '/batch.csv'
if os.path.exists(sink_path):
    if os.path.isfile(sink_path):
        os.remove(sink_path)
    else:
        shutil.rmtree(sink_path)
b_env.set_parallelism(1)
t = bt_env.from_elements([(1, 'hi', 'hello'), (2, 'hi', 'hello')], ['a', 'b', 'c'])
bt_env.connect(FileSystem().path(sink_path)) \
    .with_format(OldCsv()
                 .field_delimiter(',')
                 .field("a", DataTypes.BIGINT())
                 .field("b", DataTypes.STRING())
                 .field("c", DataTypes.STRING())) \
    .with_schema(Schema()
                 .field("a", DataTypes.BIGINT())
                 .field("b", DataTypes.STRING())
                 .field("c", DataTypes.STRING())) \
    .create_temporary_table("batch_sink")

t.select("a + 1, b, c").execute_insert("batch_sink").wait()

with open(sink_path, 'r') as f:
    lines = f.read()
    assert lines == '2,hi,hello\n' + '3,hi,hello\n'

print('pip_test_code.py success!')


text:
namespace blink {

class FakeAreaSource : public GarbageCollected<FakeAreaSource>,
                       public CachedStorageArea::Source {
 public:
  explicit FakeAreaSource(const KURL& page_url,
                          LocalDOMWindow* local_dom_window)
      : page_url_(page_url), local_dom_window_(local_dom_window) {}

  void Trace(Visitor* visitor) const override {
    visitor->Trace(local_dom_window_);
    CachedStorageArea::Source::Trace(visitor);
  }

  KURL GetPageUrl() const override { return page_url_; }
  bool EnqueueStorageEvent(const String& key,
                           const String& old_value,
                           const String& new_value,
                           const String& url) override {
    events.push_back(Event{key, old_value, new_value, url});
    return true;
  }

  blink::WebScopedVirtualTimePauser CreateWebScopedVirtualTimePauser(
      const char* name,
      WebScopedVirtualTimePauser::VirtualTaskDuration duration) override {
    return blink::WebScopedVirtualTimePauser();
  }

  LocalDOMWindow* GetDOMWindow() override { return local_dom_window_; }

  struct Event {
    String key, old_value, new_value, url;

    bool operator==(const Event& other) const {
      return std::tie(key, old_value, new_value, url) ==
             std::tie(other.key, other.old_value, other.new_value, other.url);
    }
  };

  Vector<Event> events;

 private:
  KURL page_url_;
  Member<LocalDOMWindow> local_dom_window_;
};

}  // namespace blink

#endif  // THIRD_PARTY_BLINK_RENDERER_MODULES_STORAGE_TESTING_FAKE_AREA_SOURCE_H_


text:
package data_struct.labs.l03.a;
// ****************************************************************
// Labrador.java
//
// A class derived from Dog that holds information about
// a labrador retriever.  Overrides Dog speak method and includes
// information about avg weight for this breed.
// ****************************************************************
/**
 * @author Eddie Gurnee
 *
 */
public class Labrador extends Dog
{
	@SuppressWarnings("unused")
	private String color;              //black, yellow, or chocolate?
	@SuppressWarnings("unused")
	private int breedWeight = 75;

	//Initial Labrador constructor did not invoke the super()
	//constructor to access the dog class constructor
	public Labrador(String name,  String color)
	{
		super(name);
		this.color = color;
	}

	// ------------------------------------------------------------
	// Big bark -- overrides speak method in Dog
	// ------------------------------------------------------------
	public String speak()
	{
		return "WOOF";
	}
}


text:
<?php
namespace Icecave\Agenda\Schedule;

use Icecave\Agenda\TypeCheck\TypeCheck;
use Icecave\Chrono\DateTime;
use Icecave\Chrono\TimePointInterface;

/**
 * Run once a day at midnight.
 */
class DailySchedule extends AbstractSchedule
{
    public function __construct()
    {
        $this->typeCheck = TypeCheck::get(__CLASS__, func_get_args());
        parent::__construct();
    }

    /**
     * @param TimePointInterface $timePoint
     *
     * @return TimePointInterface|null The next scheduled time point.
     */
    public function firstEventFrom(TimePointInterface $timePoint)
    {
        TypeCheck::get(__CLASS__)->firstEventFrom(func_get_args());

        if ($timePoint->hour() === 0 &&
            $timePoint->minute() === 0 &&
            $timePoint->second() === 0
        ) {
            return $timePoint;
        }

        return new DateTime(
            $timePoint->year(),
            $timePoint->month(),
            $timePoint->day() + 1,
            0,
            0,
            0
        );
    }

    private $typeCheck;
}


text:
"""Client specific rdfvalue tests."""

import hashlib

from M2Crypto import RSA

from grr.lib import config_lib
from grr.lib import rdfvalue
from grr.lib import test_lib
from grr.lib.rdfvalues import crypto as rdf_crypto
from grr.lib.rdfvalues import test_base

class SignedBlobTest(test_base.RDFValueTestCase):
  rdfvalue_class = rdf_crypto.SignedBlob

  def setUp(self):
    super(SignedBlobTest, self).setUp()
    self.private_key = config_lib.CONFIG[
        "PrivateKeys.driver_signing_private_key"]
    self.public_key = config_lib.CONFIG[
        "Client.driver_signing_public_key"]

  def GenerateSample(self, number=0):
    result = self.rdfvalue_class()
    result.Sign("Sample %s" % number, self.private_key)

    return result

  def testSignVerify(self):
    sample = self.GenerateSample()

    self.assertTrue(sample.Verify(self.public_key))

    # Change the data - this should fail since the hash is incorrect.
    sample.data += "X"
    self.assertRaises(rdfvalue.DecodeError, sample.Verify, self.public_key)

    # Update the hash
    sample.digest = hashlib.sha256(sample.data).digest()

    # Should still fail.
    self.assertRaises(rdfvalue.DecodeError, sample.Verify, self.public_key)

    # If we change the digest verification should fail.
    sample = self.GenerateSample()
    sample.digest_type = sample.HashType.MD5

    self.assertRaises(rdfvalue.DecodeError, sample.Verify, self.public_key)

class TestCryptoTypeInfos(test_base.RDFValueBaseTest):
  """Test that invalid configuration types are rejected.

  There is no need to check for success here because if that did not work we
  would not be able to run any tests.
  """

  def setUp(self):
    super(TestCryptoTypeInfos, self).setUp()
    self.config_stubber = test_lib.PreserveConfig()
    self.config_stubber.Start()

  def tearDown(self):
    super(TestCryptoTypeInfos, self).tearDown()
    self.config_stubber.Stop()

  def testX509Certificates(self):
    """Deliberately try to parse an invalid certificate."""
    config_lib.CONFIG.Initialize(data="""
[Frontend]
certificate = -----BEGIN CERTIFICATE-----
        MIIDczCCAVugAwIBAgIJANdK3LO+9qOIMA0GCSqGSIb3DQEBCwUAMFkxCzAJBgNV
        uqnFquJfg8xMWHHJmPEocDpJT8Tlmbw=
        -----END CERTIFICATE-----
""")

    errors = config_lib.CONFIG.Validate("Frontend")
    self.assertItemsEqual(errors.keys(), ["Frontend.certificate"])

  def testX509PrivateKey(self):
    """Deliberately try to parse an invalid server key."""
    config_lib.CONFIG.Initialize(data="""
[PrivateKeys]
server_key = -----BEGIN PRIVATE KEY-----
        MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBAMdgLNxyvDnQsuqp
        jzITFeE6mjs3k1I=
        -----END PRIVATE KEY-----
driver_signing_private_key = -----BEGIN RSA PRIVATE KEY-----
    MIIBOgIBAAJBALnfFW1FffeKPs5PLUhFOSkNrr9TDCODQAI3WluLh0sW7/ro93eo
    IZ0FbipnTpzGkPpriONbSOXmxWNTo0b9ma8CAwEAAQJAfg37HBZK7bxGB+jOjvrT
    XzI2Vu7dhqAWouojT357DMKjGvkO+w7r6BmToZkgHRL4Nvh1KJ/APYdWWR+jTwJ3
    4QIhAOhY/Gx8xs1ngrQLfSK9AWzPeegZK0I9W1UQuLWt7MjHAiEAzMrr2huBFrM0
    NgTOlWdrKnI/DPDpR3jGfSoUTsAeT9kCIQCzgxzzjKvkQtb+1+mEj1ashNgA9IEx
    mkoYPOUYqRnKPQIgUV+8UcEmDRgOAfzs/U7HtWkKBqFfgGfMLwXeZeBO6xkCIHGq
    wDcAa2GW9htKHmv9/Rzg05iAD+FYTsp8Gi2r4icV
    -----END RSA PRIVATE KEY-----
""")

    key = config_lib.CONFIG.Get("PrivateKeys.server_key")
    self.assertRaises(RSA.RSAError, key.GetPrivateKey)

  def testPEMPublicKey(self):
    """Deliberately try to parse an invalid public key."""
    config_lib.CONFIG.Initialize(data="""
[Client]
executable_signing_public_key = -----BEGIN PUBLIC KEY-----
        GpJgTFkTIAgX0Ih5lxoFB5TUjUfJFbBkSmKQPRA/IyuLBtCLQgwkTNkCAwEAAQ==
        -----END PUBLIC KEY-----

driver_signing_public_key = -----BEGIN PUBLIC KEY-----
    MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBALnfFW1FffeKPs5PLUhFOSkNrr9TDCOD
    QAI3WluLh0sW7/ro93eoIZ0FbipnTpzGkPpriONbSOXmxWNTo0b9ma8CAwEAAQ==
    -----END PUBLIC KEY-----
""")
    errors = config_lib.CONFIG.Validate("Client")
    self.assertItemsEqual(errors.keys(),
                          ["Client.executable_signing_public_key"])

  def testPEMPrivate(self):
    """Deliberately try to parse an invalid private key."""
    config_lib.CONFIG.Initialize(data="""
[PrivateKeys]
driver_signing_private_key = -----BEGIN RSA PRIVATE KEY-----
        MIIBOgIBAAJBALnfFW1FffeKPs5PLUhFOSkNrr9TDCODQAI3WluLh0sW7/ro93eo
        -----END RSA PRIVATE KEY-----
""")

    key = config_lib.CONFIG.Get("PrivateKeys.driver_signing_private_key")
    self.assertRaises(RSA.RSAError, key.GetPrivateKey)


text:
package com.commercetools.sunrise.shoppingcart.checkout.shipping;

import com.commercetools.sunrise.framework.controllers.ControllerAction;
import com.google.inject.ImplementedBy;
import io.sphere.sdk.carts.Cart;

import java.util.concurrent.CompletionStage;
import java.util.function.BiFunction;

@ImplementedBy(DefaultCheckoutShippingControllerAction.class)
@FunctionalInterface
public interface CheckoutShippingControllerAction extends ControllerAction, BiFunction<ShippingMethodsWithCart, CheckoutShippingFormData, CompletionStage<Cart>> {

    @Override
    CompletionStage<Cart> apply(ShippingMethodsWithCart shippingMethodsWithCart, CheckoutShippingFormData formData);
}


text:
/*================================================================================
  code generated by: java2cpp
  author: Zoran Angelov, mailto://baldzar@gmail.com
  class: java.lang.reflect.UndeclaredThrowableException
================================================================================*/

#ifndef J2CPP_INCLUDE_IMPLEMENTATION

#ifndef J2CPP_JAVA_LANG_REFLECT_UNDECLAREDTHROWABLEEXCEPTION_HPP_DECL
#define J2CPP_JAVA_LANG_REFLECT_UNDECLAREDTHROWABLEEXCEPTION_HPP_DECL

namespace j2cpp { namespace java { namespace lang { class Exception; } } }
namespace j2cpp { namespace java { namespace lang { class String; } } }
namespace j2cpp { namespace java { namespace lang { class RuntimeException; } } }
namespace j2cpp { namespace java { namespace lang { class Throwable; } } }
namespace j2cpp { namespace java { namespace lang { class Object; } } }
namespace j2cpp { namespace java { namespace io { class Serializable; } } }

#include <java/io/Serializable.hpp>
#include <java/lang/Exception.hpp>
#include <java/lang/Object.hpp>
#include <java/lang/RuntimeException.hpp>
#include <java/lang/String.hpp>
#include <java/lang/Throwable.hpp>

namespace j2cpp {

namespace java { namespace lang { namespace reflect {

	class UndeclaredThrowableException;
	class UndeclaredThrowableException
		: public object<UndeclaredThrowableException>
	{
	public:

		J2CPP_DECLARE_CLASS

		J2CPP_DECLARE_METHOD(0)
		J2CPP_DECLARE_METHOD(1)
		J2CPP_DECLARE_METHOD(2)
		J2CPP_DECLARE_METHOD(3)

		explicit UndeclaredThrowableException(jobject jobj)
		: object<UndeclaredThrowableException>(jobj)
		{
		}

		operator local_ref<java::lang::Exception>() const;
		operator local_ref<java::lang::RuntimeException>() const;
		operator local_ref<java::lang::Throwable>() const;
		operator local_ref<java::lang::Object>() const;
		operator local_ref<java::io::Serializable>() const;

		UndeclaredThrowableException(local_ref< java::lang::Throwable > const&);
		UndeclaredThrowableException(local_ref< java::lang::Throwable > const&, local_ref< java::lang::String > const&);
		local_ref< java::lang::Throwable > getUndeclaredThrowable();
		local_ref< java::lang::Throwable > getCause();
	}; //class UndeclaredThrowableException

} //namespace reflect
} //namespace lang
} //namespace java

} //namespace j2cpp

#endif //J2CPP_JAVA_LANG_REFLECT_UNDECLAREDTHROWABLEEXCEPTION_HPP_DECL

#else //J2CPP_INCLUDE_IMPLEMENTATION

#ifndef J2CPP_JAVA_LANG_REFLECT_UNDECLAREDTHROWABLEEXCEPTION_HPP_IMPL
#define J2CPP_JAVA_LANG_REFLECT_UNDECLAREDTHROWABLEEXCEPTION_HPP_IMPL

namespace j2cpp {

java::lang::reflect::UndeclaredThrowableException::operator local_ref<java::lang::Exception>() const
{
	return local_ref<java::lang::Exception>(get_jobject());
}

java::lang::reflect::UndeclaredThrowableException::operator local_ref<java::lang::RuntimeException>() const
{
	return local_ref<java::lang::RuntimeException>(get_jobject());
}

java::lang::reflect::UndeclaredThrowableException::operator local_ref<java::lang::Throwable>() const
{
	return local_ref<java::lang::Throwable>(get_jobject());
}

java::lang::reflect::UndeclaredThrowableException::operator local_ref<java::lang::Object>() const
{
	return local_ref<java::lang::Object>(get_jobject());
}

java::lang::reflect::UndeclaredThrowableException::operator local_ref<java::io::Serializable>() const
{
	return local_ref<java::io::Serializable>(get_jobject());
}

java::lang::reflect::UndeclaredThrowableException::UndeclaredThrowableException(local_ref< java::lang::Throwable > const &a0)
: object<java::lang::reflect::UndeclaredThrowableException>(
	call_new_object<
		java::lang::reflect::UndeclaredThrowableException::J2CPP_CLASS_NAME,
		java::lang::reflect::UndeclaredThrowableException::J2CPP_METHOD_NAME(0),
		java::lang::reflect::UndeclaredThrowableException::J2CPP_METHOD_SIGNATURE(0)
	>(a0)
)
{
}

java::lang::reflect::UndeclaredThrowableException::UndeclaredThrowableException(local_ref< java::lang::Throwable > const &a0, local_ref< java::lang::String > const &a1)
: object<java::lang::reflect::UndeclaredThrowableException>(
	call_new_object<
		java::lang::reflect::UndeclaredThrowableException::J2CPP_CLASS_NAME,
		java::lang::reflect::UndeclaredThrowableException::J2CPP_METHOD_NAME(1),
		java::lang::reflect::UndeclaredThrowableException::J2CPP_METHOD_SIGNATURE(1)
	>(a0, a1)
)
{
}

local_ref< java::lang::Throwable > java::lang::reflect::UndeclaredThrowableException::getUndeclaredThrowable()
{
	return call_method<
		java::lang::reflect::UndeclaredThrowableException::J2CPP_CLASS_NAME,
		java::lang::reflect::UndeclaredThrowableException::J2CPP_METHOD_NAME(2),
		java::lang::reflect::UndeclaredThrowableException::J2CPP_METHOD_SIGNATURE(2),
		local_ref< java::lang::Throwable >
	>(get_jobject());
}

local_ref< java::lang::Throwable > java::lang::reflect::UndeclaredThrowableException::getCause()
{
	return call_method<
		java::lang::reflect::UndeclaredThrowableException::J2CPP_CLASS_NAME,
		java::lang::reflect::UndeclaredThrowableException::J2CPP_METHOD_NAME(3),
		java::lang::reflect::UndeclaredThrowableException::J2CPP_METHOD_SIGNATURE(3),
		local_ref< java::lang::Throwable >
	>(get_jobject());
}

J2CPP_DEFINE_CLASS(java::lang::reflect::UndeclaredThrowableException,"java/lang/reflect/UndeclaredThrowableException")
J2CPP_DEFINE_METHOD(java::lang::reflect::UndeclaredThrowableException,0,"<init>","(Ljava/lang/Throwable;)V")
J2CPP_DEFINE_METHOD(java::lang::reflect::UndeclaredThrowableException,1,"<init>","(Ljava/lang/Throwable;Ljava/lang/String;)V")
J2CPP_DEFINE_METHOD(java::lang::reflect::UndeclaredThrowableException,2,"getUndeclaredThrowable","()Ljava/lang/Throwable;")
J2CPP_DEFINE_METHOD(java::lang::reflect::UndeclaredThrowableException,3,"getCause","()Ljava/lang/Throwable;")

} //namespace j2cpp

#endif //J2CPP_JAVA_LANG_REFLECT_UNDECLAREDTHROWABLEEXCEPTION_HPP_IMPL

#endif //J2CPP_INCLUDE_IMPLEMENTATION


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Kew Bull. 51(4): 793 (1996)

#### Original name
Inocybe cinnamomea A. Pearson ex Pegler

### Remarks
null


text:
using System;

namespace Mapster
{
    [AttributeUsage(AttributeTargets.Field
                    | AttributeTargets.Property)]
    public class AdaptIgnoreAttribute : Attribute
    {
        public MemberSide? Side { get; set; }

        public AdaptIgnoreAttribute() { }

        public AdaptIgnoreAttribute(MemberSide side)
        {
            this.Side = side;
        }
    }
}


text:
package com.fabianachammer.procgenf.generation.impl.generators;

import static com.fabianachammer.procgenf.generation.impl.Utility.getChunkComponent;
import static com.fabianachammer.procgenf.generation.impl.Utility.getChunkComponentInAncestor;
import static com.fabianachammer.procgenf.generation.impl.Utility.getRoot;

import java.awt.geom.Rectangle2D;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Optional;
import java.util.Random;

import org.joml.Matrix3d;
import org.joml.Vector2d;

import com.fabianachammer.procgenf.generation.ChunkEntity;
import com.fabianachammer.procgenf.generation.ChunkGenerator;
import com.fabianachammer.procgenf.generation.impl.ChunkEntityImpl;
import com.fabianachammer.procgenf.generation.impl.components.GenerationBoundsChunkComponent;
import com.fabianachammer.procgenf.generation.impl.components.SeedChunkComponent;
import com.fabianachammer.procgenf.generation.impl.components.VoronoiChunkComponent;
import com.fabianachammer.procgenf.main.impl.PolygonTransformer;
import com.flowpowered.noise.Noise;
import com.flowpowered.noise.NoiseQuality;

import kn.uni.voronoitreemap.datastructure.OpenList;
import kn.uni.voronoitreemap.diagram.PowerDiagram;
import kn.uni.voronoitreemap.j2d.PolygonSimple;
import kn.uni.voronoitreemap.j2d.Site;

public class NoiseVoronoiChunkGenerator implements ChunkGenerator {

	public enum GenerationType {
		Noise, Square, Hexagon
	}

	private int maxDepth;

	public NoiseVoronoiChunkGenerator(int maxDepth) {
		this.maxDepth = maxDepth;
	}

	public boolean willGenerateChunk(ChunkEntity chunk) {
		return getChunkComponent(chunk, GenerationBoundsChunkComponent.class).isPresent()
				&& getChunkComponent(getRoot(chunk), SeedChunkComponent.class).isPresent()
				&& chunk.getDepth() < maxDepth;
	}

	@Override
	public Collection<ChunkEntity> generateChunkChildren(ChunkEntity chunk) {
		if(!willGenerateChunk(chunk))
			return null;

		GenerationBoundsChunkComponent generationBoundsComponent = getChunkComponent(chunk, GenerationBoundsChunkComponent.class).get();
		Rectangle2D.Double generationBounds = generationBoundsComponent.getGenerationBounds();
		double gridSize = generationBoundsComponent.getGridSize();

		SeedChunkComponent seedComponent = getChunkComponent(getRoot(chunk), SeedChunkComponent.class).get();
		int seed = seedComponent.getSeed();

		Optional<VoronoiChunkComponent> parent = getChunkComponentInAncestor(chunk, VoronoiChunkComponent.class);
		Vector2d parentPosition = parent.map(p -> p.getWorldPosition()).orElse(new Vector2d(0, 0));
		List<ChunkEntity> subChunks = new ArrayList<>();
		OpenList sites = new OpenList();
		for(double x = generationBounds.getMinX(); x < generationBounds.getMaxX(); x += gridSize) {
			for(double y = generationBounds.getMinY(); y < generationBounds.getMaxY(); y += gridSize) {
				Rectangle2D.Double gridBounds = new Rectangle2D.Double(x, y, gridSize, gridSize);
				Vector2d generatedPoint = generatePointInBounds(gridBounds, seedComponent.getType(), seed);
				generatedPoint.sub(parentPosition);
				Site site = new Site(generatedPoint.x, generatedPoint.y, 0);
				sites.add(site);
				subChunks.add(new ChunkEntityImpl()
						.addComponent(new VoronoiChunkComponent(site))
						.addComponent(new GenerationBoundsChunkComponent()
								.setGenerationBounds(gridBounds)
								.setGridSize(gridSize / 2)));
			}
		}

		Matrix3d parentToLocalMatrix = parent.map(p -> {
			Matrix3d parentToLocal = new Matrix3d(p.getLocalToParentTransform());
			parentToLocal.invert();
			return parentToLocal;
		}).orElse(new Matrix3d());

		PolygonSimple parentPolygon = parent.map(p -> p.getPolygon()).orElse(calculatePolygonForRectangle(generationBounds));

		PolygonSimple clipPolygon = parent.isPresent() ? PolygonTransformer.transformPolygon(parentPolygon, parentToLocalMatrix) : parentPolygon;

		PowerDiagram powerDiagram = new PowerDiagram(sites, clipPolygon);

		powerDiagram.computeDiagram();

		return subChunks;
	}

	public static PolygonSimple calculatePolygonForRectangle(Rectangle2D.Double rectangle) {
		return new PolygonSimple(
				new double[] { rectangle.getMinX(), rectangle.getMaxX(), rectangle.getMaxX(), rectangle.getMinX() },
				new double[] { rectangle.getMinY(), rectangle.getMinY(), rectangle.getMaxY(), rectangle.getMaxY() });
	}

	@Override
	public void degenerateChunk(ChunkEntity chunk) {
	}

	private Vector2d generatePointInBounds(Rectangle2D.Double bounds, GenerationType type, int seed) {
		switch(type) {
		case Noise:
			return generateNoisePointInBounds(bounds, seed);
		case Square:
			return generateSquarePointInBounds(bounds);
		case Hexagon:
			return generateHexagonPointInBounds(bounds, bounds.getWidth());
		}

		return null;
	}

	private static Random random = new Random();

	public static Vector2d generateNoisePointInBounds(Rectangle2D.Double bounds, int seed) {
		random.setSeed(seed);
		double x = Noise.valueCoherentNoise3D(bounds.getCenterX(), bounds.getCenterY(), 0, random.nextInt(),
				NoiseQuality.FAST);
		double y = Noise.valueCoherentNoise3D(bounds.getCenterX(), bounds.getCenterY(), 0, random.nextInt(),
				NoiseQuality.FAST);

		x = mapBetweenRanges(x, -1, 1, 0.1, 0.9);
		y = mapBetweenRanges(y, -1, 1, 0.1, 0.9);
		return new Vector2d(bounds.getMinX() + x * bounds.getWidth(), bounds.getMinY() + y * bounds.getHeight());
	}

	private static double mapBetweenRanges(double value, double inMin, double inMax, double outMin, double outMax) {
		return (value - inMin) * (outMax - outMin) / (inMax - inMin) + outMin;
	}

	public static Vector2d generateSquarePointInBounds(Rectangle2D.Double bounds) {
		double x = bounds.getCenterX();
		double y = bounds.getCenterY();
		return new Vector2d(x, y);
	}

	public static Vector2d generateHexagonPointInBounds(Rectangle2D.Double bounds, double gridSize) {
		int x = (int) Math.floor(bounds.getMinY() / gridSize);
		int offSetSign = x % 2 == 0 ? -1 : 1;
		double offset = offSetSign * bounds.getWidth() / 4;

		return new Vector2d(bounds.getCenterX() + offset, bounds.getCenterY());
	}
}


text:
import { ElementRef, NgZone, Optional, Directive, NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { DomHandler } from 'primeng/dom';
import { PrimeNGConfig } from 'primeng/api';

var Ripple = /** @class */ (function () {
    function Ripple(el, zone, config) {
        this.el = el;
        this.zone = zone;
        this.config = config;
    }
    Ripple.prototype.ngAfterViewInit = function () {
        var _this = this;
        if (this.config && this.config.ripple) {
            this.zone.runOutsideAngular(function () {
                _this.create();
                _this.mouseDownListener = _this.onMouseDown.bind(_this);
                _this.el.nativeElement.addEventListener('mousedown', _this.mouseDownListener);
            });
        }
    };
    Ripple.prototype.onMouseDown = function (event) {
        var ink = this.getInk();
        if (!ink || getComputedStyle(ink, null).display === 'none') {
            return;
        }
        DomHandler.removeClass(ink, 'p-ink-active');
        if (!DomHandler.getHeight(ink) && !DomHandler.getWidth(ink)) {
            var d = Math.max(DomHandler.getOuterWidth(this.el.nativeElement), DomHandler.getOuterHeight(this.el.nativeElement));
            ink.style.height = d + 'px';
            ink.style.width = d + 'px';
        }
        var offset = DomHandler.getOffset(this.el.nativeElement);
        var x = event.pageX - offset.left + document.body.scrollTop - DomHandler.getWidth(ink) / 2;
        var y = event.pageY - offset.top + document.body.scrollLeft - DomHandler.getHeight(ink) / 2;
        ink.style.top = y + 'px';
        ink.style.left = x + 'px';
        DomHandler.addClass(ink, 'p-ink-active');
    };
    Ripple.prototype.getInk = function () {
        for (var i = 0; i < this.el.nativeElement.children.length; i++) {
            if (this.el.nativeElement.children[i].className.indexOf('p-ink') !== -1) {
                return this.el.nativeElement.children[i];
            }
        }
        return null;
    };
    Ripple.prototype.resetInk = function () {
        var ink = this.getInk();
        if (ink) {
            DomHandler.removeClass(ink, 'p-ink-active');
        }
    };
    Ripple.prototype.onAnimationEnd = function (event) {
        DomHandler.removeClass(event.currentTarget, 'p-ink-active');
    };
    Ripple.prototype.create = function () {
        var ink = document.createElement('span');
        ink.className = 'p-ink';
        this.el.nativeElement.appendChild(ink);
        this.animationListener = this.onAnimationEnd.bind(this);
        ink.addEventListener('animationend', this.animationListener);
    };
    Ripple.prototype.remove = function () {
        var ink = this.getInk();
        if (ink) {
            this.el.nativeElement.removeEventListener('mousedown', this.mouseDownListener);
            ink.removeEventListener('animationend', this.animationListener);
            ink.remove();
        }
    };
    Ripple.prototype.ngOnDestroy = function () {
        if (this.config && this.config.ripple) {
            this.remove();
        }
    };
    Ripple.ctorParameters = function () { return [
        { type: ElementRef },
        { type: NgZone },
        { type: PrimeNGConfig, decorators: [{ type: Optional }] }
    ]; };
    Ripple.decorators = [
        { type: Directive, args: [{
                    selector: '[pRipple]',
                    host: {
                        '[class.p-ripple]': 'true'
                    }
                },] }
    ];
    Ripple.ctorParameters = function () { return [
        { type: ElementRef },
        { type: NgZone },
        { type: PrimeNGConfig, decorators: [{ type: Optional }] }
    ]; };
    return Ripple;
}());
var RippleModule = /** @class */ (function () {
    function RippleModule() {
    }
    RippleModule.decorators = [
        { type: NgModule, args: [{
                    imports: [CommonModule],
                    exports: [Ripple],
                    declarations: [Ripple]
                },] }
    ];
    return RippleModule;
}());

/**
 * Generated bundle index. Do not edit.
 */

export { Ripple, RippleModule };
//# sourceMappingURL=primeng-ripple.js.map


text:
using System.ComponentModel;

namespace LinqAn.Google.Dimensions
{
	/// <summary>
	/// 	The ID of the promotion (Enhanced Ecommerce).
	/// </summary>
	[Description("The ID of the promotion (Enhanced Ecommerce).")]
	public class InternalPromotionId: Dimension
	{
		/// <summary>
		/// 	Instantiates a <seealso cref="InternalPromotionId" />.
		/// </summary>
		public InternalPromotionId(): base("Internal Promotion ID",true,"ga:internalPromotionId")
		{

		}
	}
}


text:
module PageObjectModel
  class BookReaderYourBookmarksHighlightsPage < PageObjectModel::Page
    trait "UILabel marked:'Your bookmarks'"
    element :title, "UILabel marked:'Your bookmarks'"
    element :bookmarks_tab, "UISegment marked:'Bookmarks'"
    element :highlights_tab, "UISegment marked:'Highlights'"
    element :edit_button, "UIButtonLabel marked:'Edit'"
    element :bookmark_book_title, "* accessibilityIdentifier:'label_bookmark_title'"
    element :bookmark_book_progress_label, "* accessibilityIdentifier:'label_bookmark_progress'"

    #sign_in_popup
    element :sign_in_popup_title, "UILabel marked:'Sign in' index:0"
    element :sign_in_button, "UILabel marked:'Sign in' index:1"
    element :no_button, "UILabel marked:'No'"

    def to_have_a_bookmark
      title.wait_for_element_exists(timeout: timeout_short)
      bookmark_book_title.selector
      bookmark_book_progress_label.selector
    end

    def tap_on_bookmark_link
      bookmark_book_title.wait_for_element_exists(timeout: timeout_short)
      bookmark_book_title.touch
    end

    def click_on_no_button
      sign_in_popup_title.wait_for_element_exists(timeout: timeout_short)
      no_button.touch
    end
  end
end

module PageObjectModel
  def book_reader_your_bookmarks_highlights_page
    @_book_reader_your_bookmarks_highlights_page ||= page(BookReaderYourBookmarksHighlightsPage)
  end
end


text:
package com.github.susom.database;

import java.sql.Connection;
import java.util.Date;
import java.util.function.Supplier;

import javax.annotation.CheckReturnValue;
import javax.annotation.Nonnull;
import javax.annotation.Syntax;

/**
 * Primary class for accessing a relational (SQL) database.
 *
 * @author garricko
 */
public interface Database extends Supplier<Database> {
  /**
   * Create a SQL "insert" statement for further manipulation and execution.
   * Note this call does not actually execute the SQL.
   *
   * @param sql the SQL to execute, optionally containing indexed ("?") or
   *            named (":foo") parameters. To include the characters '?' or ':'
   *            in the SQL you must escape them with two ("??" or "::"). You
   *            MUST be careful not to pass untrusted strings in as SQL, since
   *            this will be executed in the database.
   * @return an interface for further manipulating the statement; never null
   */
  @Nonnull
  @CheckReturnValue
  SqlInsert toInsert(@Syntax("SQL") @Nonnull String sql);

  @Nonnull
  @CheckReturnValue
  SqlInsert toInsert(@Nonnull Sql sql);

  /**
   * Create a SQL "select" statement for further manipulation and execution.
   * Note this call does not actually execute the SQL.
   *
   * @param sql the SQL to execute, optionally containing indexed ("?") or
   *            named (":foo") parameters. To include the characters '?' or ':'
   *            in the SQL you must escape them with two ("??" or "::"). You
   *            MUST be careful not to pass untrusted strings in as SQL, since
   *            this will be executed in the database.
   * @return an interface for further manipulating the statement; never null
   */
  @Nonnull
  @CheckReturnValue
  SqlSelect toSelect(@Syntax("SQL") @Nonnull String sql);

  @Nonnull
  @CheckReturnValue
  SqlSelect toSelect(@Nonnull Sql sql);

  /**
   * Create a SQL "update" statement for further manipulation and execution.
   * Note this call does not actually execute the SQL.
   *
   * @param sql the SQL to execute, optionally containing indexed ("?") or
   *            named (":foo") parameters. To include the characters '?' or ':'
   *            in the SQL you must escape them with two ("??" or "::"). You
   *            MUST be careful not to pass untrusted strings in as SQL, since
   *            this will be executed in the database.
   * @return an interface for further manipulating the statement; never null
   */
  @Nonnull
  @CheckReturnValue
  SqlUpdate toUpdate(@Syntax("SQL") @Nonnull String sql);

  @Nonnull
  @CheckReturnValue
  SqlUpdate toUpdate(@Nonnull Sql sql);

  /**
   * Create a SQL "delete" statement for further manipulation and execution.
   * Note this call does not actually execute the SQL.
   *
   * @param sql the SQL to execute, optionally containing indexed ("?") or
   *            named (":foo") parameters. To include the characters '?' or ':'
   *            in the SQL you must escape them with two ("??" or "::"). You
   *            MUST be careful not to pass untrusted strings in as SQL, since
   *            this will be executed in the database.
   * @return an interface for further manipulating the statement; never null
   */
  @Nonnull
  @CheckReturnValue
  SqlUpdate toDelete(@Syntax("SQL") @Nonnull String sql);

  @Nonnull
  @CheckReturnValue
  SqlUpdate toDelete(@Nonnull Sql sql);

  /**
   * Create a DDL (schema modifying) statement for further manipulation and execution.
   * Note this call does not actually execute the SQL.
   *
   * @param sql the SQL to execute, optionally containing indexed ("?") or
   *            named (":foo") parameters. To include the characters '?' or ':'
   *            in the SQL you must escape them with two ("??" or "::"). You
   *            MUST be careful not to pass untrusted strings in as SQL, since
   *            this will be executed in the database.
   * @return an interface for further manipulating the statement; never null
   */
  @Nonnull
  @CheckReturnValue
  Ddl ddl(@Syntax("SQL") @Nonnull String sql);

  /**
   * Read the next value from a sequence. This method helps smooth over the
   * syntax differences across databases.
   */
  @CheckReturnValue
  Long nextSequenceValue(@Nonnull String sequenceName);

  /**
   * Get the value that would be used if you specify an argNowPerApp() parameter.
   */
  Date nowPerApp();

  /**
   * Cause the underlying connection to commit its transaction immediately. This
   * must be explicitly enabled (see {@link com.github.susom.database.Options},
   * or it will throw a {@link com.github.susom.database.DatabaseException}.
   */
  void commitNow();

  /**
   * Cause the underlying connection to roll back its transaction immediately. This
   * must be explicitly enabled (see {@link com.github.susom.database.Options},
   * or it will throw a {@link com.github.susom.database.DatabaseException}.
   */
  void rollbackNow();

  /**
   *
Obtain direct access to the connection being used by this instance. Be very
   * careful as this is highly likely to be unsafe and cause you great pain and
   * suffering. This method is included to help ease into the library in large
   * codebases where some parts still rely on direct JDBC access.

   *
   *
By default this method will throw a {@link DatabaseException}. If you want
   * to use this method you must explicitly enable it via
   * {@link com.github.susom.database.Options#allowConnectionAccess()}

   */
  @Nonnull
  Connection underlyingConnection();

  @Nonnull
  Options options();

  /**
   * Access information about what kind of database we are dealing with.
   */
  @Nonnull
  Flavor flavor();

  /**
   *
A little syntax sugar to make it easier to customize your SQL based on the
   * specific database. For example:

   *
   *
"select 1" + db.when().oracle(" from dual")

   *
"select " + db.when().postgres("date_trunc('day',").other("trunc(") + ") ..."

   *
   * @return an interface for chaining or terminating the conditionals
   */
  @Nonnull
  When when();

  /**
   * Convenience method to deal with mutually incompatible syntax for this. For example:
   *
   *
Oracle: 'drop sequence x'

   *
Derby: 'drop sequence x restrict'
"
   */
  void dropSequenceQuietly(String sequenceName);

  /**
   * Convenience method to deal with dropping tables that may or may not exist. Some
   * databases make it hard to check and conditionally drop things, so we will just
   * try to drop it and ignore the errors.
   *
   * @param tableName the table to be dropped
   */
  void dropTableQuietly(String tableName);

  /**
   * Convenience method to check if a table or view exists so that caller can decide
   * whether to create or update a table. The table name's case is normalized using
   * the database's convention unless tableName is enclosed in double quotes.
   * The default catalog and schema from the DB connection will be used.
   *
   * @param tableName the table to be checked
   * @return true if the table or view exists
   */
  boolean tableExists(@Nonnull String tableName);

  /**
   * Convenience method to check whether a table or view exists or not.
   * The table name's case is normalized using the database's convention
   * unless tableName is enclosed in double quotes.  The default catalog
   * from the DB connection will be used.
   *
   * @param tableName the table to be checked
   * @param schemaName the schema expected to contain the table
   * @return true if the table or view exists
   */
  boolean tableExists(@Nonnull String tableName, String schemaName);

  /**
   * Return the DB table name in the normalized form in which it is stored.
   * Databases like Oracle, Derby, HSQL store their tables in upper case.
   * Databases like postgres and sqlserver use lower case unless configured otherwise.
   * If the caller passes in a quoted string, we will leave the name as is, removing
   * the quotes.
   *
   * @param tableName this should be a name, not a pattern
   * @return table name in appropriate format for DB lookup - original case, uppercase, or lowercase
   */
  public String normalizeTableName(String tableName);

  /**
   * Check the JVM time (and timezone) against the database and log a warning
   * or throw an error if they are too far apart. It is a good idea to do this
   * before you store and dates, and maybe make it part of your health checks.
   * If the clocks differ by more than an hour, a DatabaseException is thrown
   * suggesting you check the timezones (under the assumptions the JVM and
   * database are running in different timezones).
   *
   * @param millisToWarn if the clocks disagree by more than this and less than
   *                     millisToError, a warning will be dropped in the log
   * @param millisToError if the clocks disagree by more than this a
   *                      DatabaseEception will be thrown
   */
  void assertTimeSynchronized(long millisToWarn, long millisToError);

  /**
   * Convenience method, same as {@link #assertTimeSynchronized(long, long)}
   * with millisToWarn=10000 and millisToError=30000.
   */
  void assertTimeSynchronized();
}


text:
// flow-typed signature: 598824305fb1125d8ba7ae481576c088
// flow-typed version: <<STUB>>/stylint-stylish_v1.4.0/flow_v0.43.0

/**
 * This is an autogenerated libdef stub for:
 *
 *   'stylint-stylish'
 *
 * Fill this stub out by replacing all the `any` types.
 *
 * Once filled out, we encourage you to share your work with the
 * community by sending a pull request to:
 * https://github.com/flowtype/flow-typed
 */

declare module 'stylint-stylish' {
  declare module.exports: any;
}

/**
 * We include stubs for each file inside this npm package in case you need to
 * require those files directly. Feel free to delete any files that aren't
 * needed.
 */

// Filename aliases
declare module 'stylint-stylish/index' {
  declare module.exports: $Exports<'stylint-stylish'>;
}
declare module 'stylint-stylish/index.js' {
  declare module.exports: $Exports<'stylint-stylish'>;
}


text:
#include "color/color.hpp"

int main( int argc, char *argv[] )
 {
  color::rgb<float>          c1; //!< Instead of float you may put std::uint8_t,std::uint16_t, std::uint32_t, std::uint64_t, double, long double
  color::hsv<std::uint32_t>  c2; //!< Instead of uint32_t you may put std::uint8_t,std::uint16_t, std::uint32_t, std::uint64_t, double, long double

  // Do some initialization
  c1 = color::constant::red_t{};

  // Here is how to reformat/convert from one to another
  c2 = c1;

  // And vice versa
  c1 = c2;

  return EXIT_SUCCESS;
 }


text:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <parent>
    <groupId>org.jetbrains.idea</groupId>
    <artifactId>parent.twelve.1200</artifactId>
    <version>12.0.0</version>
    <relativePath>../../pom.xml</relativePath>
  </parent>

  <artifactId>color-schemes</artifactId>

  <name>Maven Integration of colorSchemes module</name>
  <description>Maven module for colorSchemes jar</description>

  <dependencies>
  </dependencies>

  <build>
    <sourceDirectory>${idea.home}/colorSchemes/src</sourceDirectory>
    <resources>
      <resource>
        <directory>${idea.home}/colorSchemes/src</directory>
        <excludes>
          <exclude>**/*.java</exclude>
        </excludes>
      </resource>
    </resources>
  </build>
</project>


text: <!DOCTYPE html>


text:
package shapes;

import utils.Vect3D;

/**
 * @author Fabio Ticconi
 */
interface Shape
{
    Vect3D getCenter();

    Vect3D getExtent();

    boolean intersects(Shape s);

    boolean intersects(Box b);

    boolean intersects(Sphere s);

    boolean intersects(Vect3D p);
}


text:
package packet

// PUBACKOptions represents options for a PUBACK Packet.
type PUBACKOptions struct {
	// PacketID is the Packet Identifier of the variable header.
	PacketID uint16
}

// validate validates the options.
func (opts *PUBACKOptions) validate() error {
	// Check the Packet Identifier.
	if opts.PacketID == 0 {
		return ErrInvalidPacketID
	}

	return nil
}


text:
<body>
Provides the abstract test helper.
</body>


text:
<?php namespace Laracasts\Utilities\JavaScript\Facades;

use Illuminate\Support\Facades\Facade;

class JavaScript extends Facade {

    /**
     * Name of the binding in the IoC container
     *
     * @return string
     */
    protected static function getFacadeAccessor()
    {
	return 'JavaScript';
    }

}


text:
module Mail
  class MessageIdsElement

    include Mail::Utilities

    def initialize(string)
      raise Mail::Field::ParseError.new(Mail::MessageIdsElement, string, 'nil is invalid') if string.nil?
      @message_ids = Mail::Parsers::MessageIdsParser.new.parse(string).message_ids.map { |msg_id| clean_msg_id(msg_id) }
    end

    def message_ids
      @message_ids
    end

    def message_id
      @message_ids.first
    end

    def clean_msg_id( val )
      val =~ /.*<(.*)>.*/ ; $1
    end

  end
end


text:
using testing::ValuesIn;
using testing::Return;

namespace {

class a_vertical_scrollbar : public testing::Test
{
protected:
    std::shared_ptr<munin::vertical_scrollbar> scrollbar_ {
        munin::make_vertical_scrollbar()
    };
};

using a_new_vertical_scrollbar = a_vertical_scrollbar;

}

TEST_F(a_new_vertical_scrollbar, has_a_1x0_preferred_size)
{
    ASSERT_EQ(terminalpp::extent(1, 0), scrollbar_->get_preferred_size());
}

TEST_F(a_new_vertical_scrollbar, draws_nothing)
{
    terminalpp::canvas canvas({4, 4});
    munin::render_surface surface{canvas};

    terminalpp::for_each_in_region(
        canvas,
        {{}, canvas.size()},
        [](terminalpp::element &elem,
           terminalpp::coordinate_type column,
           terminalpp::coordinate_type row)
        {
            elem = 'X';
        });

    scrollbar_->draw(surface, {{0, 0}, {0, 0}});

    ASSERT_EQ(terminalpp::element{'X'}, canvas[0][0]);
    ASSERT_EQ(terminalpp::element{'X'}, canvas[1][0]);
    ASSERT_EQ(terminalpp::element{'X'}, canvas[2][0]);
    ASSERT_EQ(terminalpp::element{'X'}, canvas[3][0]);
    ASSERT_EQ(terminalpp::element{'X'}, canvas[0][1]);
    ASSERT_EQ(terminalpp::element{'X'}, canvas[1][1]);
    ASSERT_EQ(terminalpp::element{'X'}, canvas[2][1]);
    ASSERT_EQ(terminalpp::element{'X'}, canvas[3][1]);
    ASSERT_EQ(terminalpp::element{'X'}, canvas[0][2]);
    ASSERT_EQ(terminalpp::element{'X'}, canvas[1][2]);
    ASSERT_EQ(terminalpp::element{'X'}, canvas[2][2]);
    ASSERT_EQ(terminalpp::element{'X'}, canvas[3][2]);
    ASSERT_EQ(terminalpp::element{'X'}, canvas[0][3]);
    ASSERT_EQ(terminalpp::element{'X'}, canvas[1][3]);
    ASSERT_EQ(terminalpp::element{'X'}, canvas[2][3]);
    ASSERT_EQ(terminalpp::element{'X'}, canvas[3][3]);
}

TEST_F(a_vertical_scrollbar, has_a_preferred_size_relative_to_its_height)
{
    scrollbar_->set_size({4, 4});
    ASSERT_EQ(terminalpp::extent(1, 4), scrollbar_->get_preferred_size());

    scrollbar_->set_size({7, 3});
    ASSERT_EQ(terminalpp::extent(1, 3), scrollbar_->get_preferred_size());
}

TEST_F(a_vertical_scrollbar, with_size_but_no_slider_draws_a_frame_border)
{
    terminalpp::canvas canvas({4, 4});
    munin::render_surface surface{canvas};

    terminalpp::for_each_in_region(
        canvas,
        {{}, canvas.size()},
        [](terminalpp::element &elem,
           terminalpp::coordinate_type column,
           terminalpp::coordinate_type row)
        {
            elem = 'X';
        });

    scrollbar_->set_size({1, 4});
    scrollbar_->draw(surface, {{}, scrollbar_->get_size()});

    ASSERT_EQ(munin::detail::single_lined_vertical_beam, canvas[0][0]);
    ASSERT_EQ(munin::detail::single_lined_vertical_beam, canvas[0][1]);
    ASSERT_EQ(munin::detail::single_lined_vertical_beam, canvas[0][2]);
    ASSERT_EQ(munin::detail::single_lined_vertical_beam, canvas[0][3]);
    ASSERT_EQ(terminalpp::element{'X'}, canvas[1][0]);
    ASSERT_EQ(terminalpp::element{'X'}, canvas[1][1]);
    ASSERT_EQ(terminalpp::element{'X'}, canvas[1][2]);
    ASSERT_EQ(terminalpp::element{'X'}, canvas[1][3]);
    ASSERT_EQ(terminalpp::element{'X'}, canvas[2][0]);
    ASSERT_EQ(terminalpp::element{'X'}, canvas[2][1]);
    ASSERT_EQ(terminalpp::element{'X'}, canvas[2][2]);
    ASSERT_EQ(terminalpp::element{'X'}, canvas[2][3]);
    ASSERT_EQ(terminalpp::element{'X'}, canvas[3][0]);
    ASSERT_EQ(terminalpp::element{'X'}, canvas[3][1]);
    ASSERT_EQ(terminalpp::element{'X'}, canvas[3][2]);
    ASSERT_EQ(terminalpp::element{'X'}, canvas[3][3]);
}

namespace {

using slider_test_data = std::tuple<
    terminalpp::coordinate_type, // y_position
    terminalpp::coordinate_type, // height
    terminalpp::coordinate_type  // expected x co-ordinate of slider
>;

class vertical_scroll_bar_slider_position
  : public testing::TestWithParam<slider_test_data>
{
protected:
    vertical_scroll_bar_slider_position()
    {
        scrollbar_->set_size(canvas_.size());

        terminalpp::for_each_in_region(
            canvas_,
            {{}, canvas_.size()},
            [](terminalpp::element &elem,
               terminalpp::coordinate_type column,
               terminalpp::coordinate_type row)
            {
                elem = 'X';
            });

        scrollbar_->on_redraw.connect(
            [this](std::vector<terminalpp::rectangle> const &regions)
            {
                for (auto const &region : regions)
                {
                    scrollbar_->draw(surface_, region);
                }
            });
    }

    std::shared_ptr<munin::vertical_scrollbar> scrollbar_ {
        munin::make_vertical_scrollbar()
    };

    terminalpp::canvas canvas_{{1, 16}};
    munin::render_surface surface_{canvas_};
};

}

TEST_P(vertical_scroll_bar_slider_position, draws_slider_at_the_expected_position)
{
    using std::get;

    auto const &param = GetParam();
    auto const &y_position = get<0>(param);
    auto const &height = get<1>(param);
    auto const &expected_slider_y_position = get<2>(param);

    scrollbar_->set_slider_position(y_position, height);

    for (terminalpp::coordinate_type y = 0; y < canvas_.size().height_; ++y)
    {
        if (y == expected_slider_y_position)
        {
            ASSERT_EQ(munin::detail::single_lined_cross, canvas_[0][y])
                << "Expected slider cross at position " << y;
        }
        else
        {
            ASSERT_EQ(munin::detail::single_lined_vertical_beam, canvas_[0][y])
                << "Expected beam at position " << y;
        }
    }
}

static slider_test_data const test_data[] = {
    slider_test_data{ 0,  20, 0  },  // Special: 0
    slider_test_data{ 1,  20, 1  },  // 1
    slider_test_data{ 2,  20, 1  },  // 1 + 14/18 // (14 / 18 per step )
    slider_test_data{ 3,  20, 2  },  // 2 + 10/18
    slider_test_data{ 4,  20, 3  },  // 3 + 6/18

    slider_test_data{ 5,  20, 4  },  // 4 + 2/18
    slider_test_data{ 6,  20, 4  },  // 4 + 16/18
    slider_test_data{ 7,  20, 5  },  // 5 + 12/18
    slider_test_data{ 8,  20, 6  },  // 6 + 8/18
    slider_test_data{ 9,  20, 7  },  // 7 + 4/18

    slider_test_data{ 10, 20, 8  },  // 8 + 0/18
    slider_test_data{ 11, 20, 8  },  // 8 + 14/18
    slider_test_data{ 12, 20, 9  },  // 9 + 10/18
    slider_test_data{ 13, 20, 10 },  // 10 + 6/18
    slider_test_data{ 14, 20, 11 },  // 11 + 2/18

    slider_test_data{ 15, 20, 11 },  // 11 + 16/18
    slider_test_data{ 16, 20, 12 },  // 12 + 12/18
    slider_test_data{ 17, 20, 13 },  // 13 + 8/18
    slider_test_data{ 18, 20, 14 },  // 14 + 4/18

    slider_test_data{ 19, 20, 15 },  // Special: 15
};

INSTANTIATE_TEST_SUITE_P(
    setting_slider_position_shows_slider_in_expected_location,
    vertical_scroll_bar_slider_position,
    ValuesIn(test_data)
);

TEST_F(a_vertical_scrollbar, draws_the_correct_scroller_position_when_resized)
{
    terminalpp::canvas canvas({1, 8});
    munin::render_surface surface{canvas};

    terminalpp::for_each_in_region(
        canvas,
        {{}, canvas.size()},
        [](terminalpp::element &elem,
           terminalpp::coordinate_type column,
           terminalpp::coordinate_type row)
        {
            elem = 'X';
        });

    scrollbar_->set_size({1, 4});
    scrollbar_->set_slider_position(75, 100);
    scrollbar_->draw(surface, {{}, scrollbar_->get_size()});

    ASSERT_EQ(munin::detail::single_lined_vertical_beam, canvas[0][0]);
    ASSERT_EQ(munin::detail::single_lined_vertical_beam, canvas[0][1]);
    ASSERT_EQ(munin::detail::single_lined_cross,         canvas[0][2]);
    ASSERT_EQ(munin::detail::single_lined_vertical_beam, canvas[0][3]);
    ASSERT_EQ('X', canvas[0][4]);
    ASSERT_EQ('X', canvas[0][5]);
    ASSERT_EQ('X', canvas[0][6]);
    ASSERT_EQ('X', canvas[0][7]);

    scrollbar_->set_size({1, 8});
    scrollbar_->draw(surface, {{}, scrollbar_->get_size()});

    ASSERT_EQ(munin::detail::single_lined_vertical_beam, canvas[0][0]) << " expected beam on position 0";
    ASSERT_EQ(munin::detail::single_lined_vertical_beam, canvas[0][1]) << " expected beam on position 1";
    ASSERT_EQ(munin::detail::single_lined_vertical_beam, canvas[0][2]) << " expected beam on position 2";
    ASSERT_EQ(munin::detail::single_lined_vertical_beam, canvas[0][3]) << " expected beam on position 3";
    ASSERT_EQ(munin::detail::single_lined_vertical_beam, canvas[0][4]) << " expected beam on position 4";
    ASSERT_EQ(munin::detail::single_lined_cross,         canvas[0][5]) << " expected cross on position 5";
    ASSERT_EQ(munin::detail::single_lined_vertical_beam, canvas[0][6]) << " expected beam on position 6";
    ASSERT_EQ(munin::detail::single_lined_vertical_beam, canvas[0][7]) << " expected beam on position 7";
}

namespace {

constexpr auto lowlight_attribute = terminalpp::attribute{
    terminalpp::greyscale_colour{ 5 }
};

constexpr auto lowlight_vertical_beam = terminalpp::element{
    munin::detail::single_lined_vertical_beam,
    lowlight_attribute
};

constexpr auto highlight_attribute = terminalpp::attribute{
    terminalpp::high_colour{4, 5, 1}
};

constexpr auto highlight_vertical_beam = terminalpp::element{
    munin::detail::single_lined_vertical_beam,
    highlight_attribute
};

class a_vertical_scrollbar_with_an_associated_component
  : public a_vertical_scrollbar
{
public:
    a_vertical_scrollbar_with_an_associated_component()
    {
        scrollbar_->highlight_on_focus(associated_component_);
        scrollbar_->set_lowlight_attribute(lowlight_attribute);
        scrollbar_->set_highlight_attribute(highlight_attribute);
    }

protected:
    std::shared_ptr<mock_component> associated_component_ {
        make_mock_component()
    };
};

}

TEST_F(a_vertical_scrollbar_with_an_associated_component, draws_the_lowlight_attribute_by_default)
{
    terminalpp::canvas canvas({1, 8});
    munin::render_surface surface{canvas};

    scrollbar_->set_size({1, 8});
    scrollbar_->draw(surface, {{}, scrollbar_->get_size()});

    ASSERT_EQ(lowlight_vertical_beam, canvas[0][0]);
    ASSERT_EQ(lowlight_vertical_beam, canvas[0][1]);
    ASSERT_EQ(lowlight_vertical_beam, canvas[0][2]);
    ASSERT_EQ(lowlight_vertical_beam, canvas[0][3]);
}

TEST_F(a_vertical_scrollbar_with_an_associated_component, draws_the_highlight_attribute_after_the_associated_component_gains_focus)
{
    terminalpp::canvas canvas({1, 8});
    munin::render_surface surface{canvas};

    scrollbar_->set_size({1, 8});
    scrollbar_->draw(surface, {{}, scrollbar_->get_size()});

    scrollbar_->on_redraw.connect(
        [&, this](std::vector<terminalpp::rectangle> const &regions)
        {
            for (auto const &region : regions)
            {
                scrollbar_->draw(surface, region);
            }
        });

    ON_CALL(*associated_component_, do_has_focus())
        .WillByDefault(Return(true));
    associated_component_->on_focus_set();

    ASSERT_EQ(highlight_vertical_beam, canvas[0][0]);
    ASSERT_EQ(highlight_vertical_beam, canvas[0][1]);
    ASSERT_EQ(highlight_vertical_beam, canvas[0][2]);
    ASSERT_EQ(highlight_vertical_beam, canvas[0][3]);
}

TEST_F(a_vertical_scrollbar_with_an_associated_component, draws_the_lowlight_attribute_after_the_associated_component_loses_focus)
{
    terminalpp::canvas canvas({1, 8});
    munin::render_surface surface{canvas};

    scrollbar_->set_size({1, 4});
    scrollbar_->draw(surface, {{}, scrollbar_->get_size()});

    scrollbar_->on_redraw.connect(
        [&, this](std::vector<terminalpp::rectangle> const &regions)
        {
            for (auto const &region : regions)
            {
                scrollbar_->draw(surface, region);
            }
        });

    ON_CALL(*associated_component_, do_has_focus())
        .WillByDefault(Return(true));
    associated_component_->on_focus_set();

    ON_CALL(*associated_component_, do_has_focus())
        .WillByDefault(Return(false));
    associated_component_->on_focus_lost();

    ASSERT_EQ(lowlight_vertical_beam, canvas[0][0]);
    ASSERT_EQ(lowlight_vertical_beam, canvas[0][1]);
    ASSERT_EQ(lowlight_vertical_beam, canvas[0][2]);
    ASSERT_EQ(lowlight_vertical_beam, canvas[0][3]);
}

TEST_F(a_vertical_scrollbar, draws_the_highlight_attribute_when_associated_with_a_focused_component)
{
    terminalpp::canvas canvas({1, 8});
    munin::render_surface surface{canvas};

    scrollbar_->set_size({1, 4});
    scrollbar_->draw(surface, {{}, scrollbar_->get_size()});

    scrollbar_->on_redraw.connect(
        [&, this](std::vector<terminalpp::rectangle> const &regions)
        {
            for (auto const &region : regions)
            {
                scrollbar_->draw(surface, region);
            }
        });

    auto associated_component = make_mock_component();
    ON_CALL(*associated_component, do_has_focus())
        .WillByDefault(Return(true));

    scrollbar_->set_lowlight_attribute(lowlight_attribute);
    scrollbar_->set_highlight_attribute(highlight_attribute);
    scrollbar_->highlight_on_focus(associated_component);

    ASSERT_EQ(highlight_vertical_beam, canvas[0][0]);
    ASSERT_EQ(highlight_vertical_beam, canvas[0][1]);
    ASSERT_EQ(highlight_vertical_beam, canvas[0][2]);
    ASSERT_EQ(highlight_vertical_beam, canvas[0][3]);
}

TEST_F(a_vertical_scrollbar_with_an_associated_component, draws_the_new_lowlight_attribute_when_it_is_changed)
{
    terminalpp::canvas canvas({1, 8});
    munin::render_surface surface{canvas};

    scrollbar_->set_size({1, 4});
    scrollbar_->draw(surface, {{}, scrollbar_->get_size()});

    scrollbar_->on_redraw.connect(
        [&, this](std::vector<terminalpp::rectangle> const &regions)
        {
            for (auto const &region : regions)
            {
                scrollbar_->draw(surface, region);
            }
        });

    constexpr auto new_lowlight_attribute = terminalpp::attribute{
        terminalpp::high_colour(2, 2, 2)
    };

    constexpr auto new_lowlight_vertical_beam = terminalpp::element{
        munin::detail::single_lined_vertical_beam,
        new_lowlight_attribute
    };

    scrollbar_->set_lowlight_attribute(new_lowlight_attribute);

    ASSERT_EQ(new_lowlight_vertical_beam, canvas[0][0]);
    ASSERT_EQ(new_lowlight_vertical_beam, canvas[0][1]);
    ASSERT_EQ(new_lowlight_vertical_beam, canvas[0][2]);
    ASSERT_EQ(new_lowlight_vertical_beam, canvas[0][3]);
}

TEST_F(a_vertical_scrollbar_with_an_associated_component, draws_the_new_highlight_attribute_when_it_is_changed)
{
    terminalpp::canvas canvas({1, 8});
    munin::render_surface surface{canvas};

    scrollbar_->set_size({1, 4});
    scrollbar_->draw(surface, {{}, scrollbar_->get_size()});

    scrollbar_->on_redraw.connect(
        [&, this](std::vector<terminalpp::rectangle> const &regions)
        {
            for (auto const &region : regions)
            {
                scrollbar_->draw(surface, region);
            }
        });

    constexpr auto new_highlight_attribute = terminalpp::attribute{
        terminalpp::high_colour(6, 6, 5)
    };

    constexpr auto new_highlight_vertical_beam = terminalpp::element{
        munin::detail::single_lined_vertical_beam,
        new_highlight_attribute
    };

    ON_CALL(*associated_component_, do_has_focus())
        .WillByDefault(Return(true));
    associated_component_->on_focus_set();

    scrollbar_->set_highlight_attribute(new_highlight_attribute);

    ASSERT_EQ(new_highlight_vertical_beam, canvas[0][0]);
    ASSERT_EQ(new_highlight_vertical_beam, canvas[0][1]);
    ASSERT_EQ(new_highlight_vertical_beam, canvas[0][2]);
    ASSERT_EQ(new_highlight_vertical_beam, canvas[0][3]);
}

TEST_F(a_vertical_scrollbar, with_no_slider_emits_no_scroll_events_when_clicked)
{
    scrollbar_->set_size({1, 5});

    auto const mouse_event = terminalpp::mouse::event{
        terminalpp::mouse::event_type::left_button_down,
        {1, 0}
    };

    bool scroll_up_clicked = false;
    bool scroll_down_clicked = false;

    scrollbar_->on_scroll_up.connect(
        [&]{
            scroll_up_clicked = true;
        });

    scrollbar_->on_scroll_down.connect(
        [&]{
            scroll_down_clicked = true;
        });

    scrollbar_->event(mouse_event);

    ASSERT_FALSE(scroll_up_clicked);
    ASSERT_FALSE(scroll_down_clicked);
}

TEST_F(a_vertical_scrollbar, with_a_slider_emits_scroll_up_when_clicked_above_the_slider)
{
    scrollbar_->set_size({1, 5});
    scrollbar_->set_slider_position(50, 100);

    auto const mouse_event = terminalpp::mouse::event{
        terminalpp::mouse::event_type::left_button_down,
        {0, 0}
    };

    bool scroll_up_clicked = false;
    bool scroll_down_clicked = false;

    scrollbar_->on_scroll_up.connect(
        [&]{
            scroll_up_clicked = true;
        });

    scrollbar_->on_scroll_down.connect(
        [&]{
            scroll_down_clicked = true;
        });

    scrollbar_->event(mouse_event);

    ASSERT_TRUE(scroll_up_clicked);
    ASSERT_FALSE(scroll_down_clicked);
}

TEST_F(a_vertical_scrollbar, with_a_slider_emits_scroll_down_when_clicked_below_the_slider)
{
    scrollbar_->set_size({1, 5});
    scrollbar_->set_slider_position(50, 100);

    auto const mouse_event = terminalpp::mouse::event{
        terminalpp::mouse::event_type::left_button_down,
        {0, 4}
    };

    bool scroll_up_clicked = false;
    bool scroll_down_clicked = false;

    scrollbar_->on_scroll_up.connect(
        [&]{
            scroll_up_clicked = true;
        });

    scrollbar_->on_scroll_down.connect(
        [&]{
            scroll_down_clicked = true;
        });

    scrollbar_->event(mouse_event);

    ASSERT_FALSE(scroll_up_clicked);
    ASSERT_TRUE(scroll_down_clicked);
}

TEST_F(a_vertical_scrollbar, with_a_slider_emits_nothing_when_clicked_on_the_slider)
{
    scrollbar_->set_size({1, 5});
    scrollbar_->set_slider_position(50, 100);

    auto const mouse_event = terminalpp::mouse::event{
        terminalpp::mouse::event_type::left_button_down,
        {0, 2}
    };

    bool scroll_up_clicked = false;
    bool scroll_down_clicked = false;

    scrollbar_->on_scroll_up.connect(
        [&]{
            scroll_up_clicked = true;
        });

    scrollbar_->on_scroll_down.connect(
        [&]{
            scroll_down_clicked = true;
        });

    scrollbar_->event(mouse_event);

    ASSERT_FALSE(scroll_up_clicked);
    ASSERT_FALSE(scroll_down_clicked);
}


text:
//----------------------------------------------------------------------------------------------
//    Copyright 2014 Microsoft Corporation
//
//    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.
//----------------------------------------------------------------------------------------------

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

// The following using statements were added for this sample.
using System.Configuration;
using System.Diagnostics;
using System.Threading.Tasks;
using System.Security.Claims;
using TodoListWebApp.Models;
using Microsoft.Owin.Security.OpenIdConnect;
using System.Net.Http;
using System.Net.Http.Headers;
using Newtonsoft.Json;
using System.Globalization;
using Microsoft.IdentityModel.Clients.ActiveDirectory;
using System.Threading;

namespace TodoListWebApp.Controllers
{
    //[Authorize]
    public class TodoListController : Controller
    {
        //
        // The Client ID is used by the application to uniquely identify itself to Azure AD.
        // The App Key is a credential used by the application to authenticate to Azure AD.
        // The Tenant is the name of the Azure AD tenant in which this application is registered.
        // The AAD Instance is the instance of Azure, for example public Azure or Azure China.
        // The Authority is the sign-in URL of the tenant.
        //
        private static string aadInstance = ConfigurationManager.AppSettings["ida:AADInstance"];
        private static string tenant = ConfigurationManager.AppSettings["ida:Tenant"];
        private static string clientId = ConfigurationManager.AppSettings["ida:ClientId"];
        private static string appKey = ConfigurationManager.AppSettings["ida:AppKey"];

        static string authority = String.Format(CultureInfo.InvariantCulture, aadInstance, tenant);

        //
        // To authenticate to the To Do list service, the client needs to know the service's App ID URI.
        // To contact the To Do list service we need it's URL as well.
        //
        private static string todoListResourceId = ConfigurationManager.AppSettings["todo:TodoListResourceId"];
        private static string todoListBaseAddress = ConfigurationManager.AppSettings["todo:TodoListBaseAddress"];

        private static AuthenticationContext authContext = new AuthenticationContext(authority);
        private static ClientCredential clientCredential = new ClientCredential(clientId, appKey);

        private const string TenantIdClaimType = "http://schemas.microsoft.com/identity/claims/tenantid";

        private const string OwnerId = "B828255E-8A16-43D8-9A26-49AFD633A93C";

        //
        // GET: /TodoList/
        public async Task<ActionResult> Index()
        {
            List<TodoItem> itemList = new List<TodoItem>();

            //
            // Get a token to call the To Do list.
            // This sample uses the web app's identity to call the service, not the user's identity.
            // The web app has special privilege in the service to view and update any user's To Do list.
            // Since the web app is trusted to sign the user in, it is a trusted sub-system.
            //

            //
            // Get an access token from Azure AD using client credentials.
            // If the attempt to get a token fails because the server is unavailable, retry twice after 3 seconds each.
            //
            AuthenticationResult result = null;
            int retryCount = 0;
            bool retry = false;

            do
            {
                retry = false;
                try
                {
                    Trace.TraceInformation("items in token cache are [{0}].", authContext.TokenCache.Count);
                    authContext.TokenCache.Clear();

                    // ADAL includes an in memory cache, so this call will only send a message to the server if the cached token is expired.
                    result = authContext.AcquireToken(todoListResourceId, clientCredential);
                }
                catch (AdalException ex)
                {
                    if (ex.ErrorCode == "temporarily_unavailable")
                    {
                        retry = true;
                        retryCount++;
                        Thread.Sleep(3000);
                    }
                }

            } while ((retry == true) && (retryCount < 3));

            if (result == null)
            {
                // Handle unexpected errors.
                ViewBag.ErrorMessage = "UnexpectedError";
                TodoItem newItem = new TodoItem {Title = "(No items in list)"};
                itemList.Add(newItem);
                return View(itemList);
            }

            // Retrieve the user's Object Identifier claim, which is used as the key to the To Do list.
            //string ownerId = ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier").Value;

            //
            // Retrieve the user's To Do List.
            //
            HttpClient client = new HttpClient(new LoggingHandler(new HttpClientHandler()));

            HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, todoListBaseAddress + "/api/todolist?ownerid=" + OwnerId);
            request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", result.AccessToken);
            HttpResponseMessage response = await client.SendAsync(request);

            //
            // Return the To Do List in the view.
            //
            if (response.IsSuccessStatusCode)
            {
                List<Dictionary<String, String>> responseElements = new List<Dictionary<String, String>>();
                JsonSerializerSettings settings = new JsonSerializerSettings();
                String responseString = await response.Content.ReadAsStringAsync();
                responseElements = JsonConvert.DeserializeObject<List<Dictionary<String, String>>>(responseString, settings);
                foreach (Dictionary<String, String> responseElement in responseElements)
                {
                    TodoItem newItem = new TodoItem
                    {
                        Title = responseElement["Title"],
                        Owner = responseElement["Owner"]
                    };
                    itemList.Add(newItem);
                }

                return View(itemList);
            }
            else
            {
                // If the response is Unauthorized, drop the token cache to force getting a new token on the next try.
                if (response.StatusCode == System.Net.HttpStatusCode.Unauthorized)
                {
                    authContext.TokenCache.Clear();
                }

                // Handle unexpected errors.
                ViewBag.ErrorMessage = "UnexpectedError";
                TodoItem newItem = new TodoItem {Title = "(No items in list)"};
                itemList.Add(newItem);
                return View(itemList);
            }

        }

        [HttpPost]
        public async Task<ActionResult> Index(string item)
        {
            if (ModelState.IsValid)
            {
                List<TodoItem> itemList = new List<TodoItem>();

                //
                // Get an access token from Azure AD using client credentials.
                // If the attempt to get a token fails because the server is unavailable, retry twice after 3 seconds each.
                //
                AuthenticationResult result = null;
                int retryCount = 0;
                bool retry = false;

                do
                {
                    retry = false;
                    try
                    {
                        // ADAL includes an in memory cache, so this call will only send a message to the server if the cached token is expired.
                        result = authContext.AcquireToken(todoListResourceId, clientCredential);
                    }
                    catch (AdalException ex)
                    {
                        if (ex.ErrorCode == "temporarily_unavailable")
                        {
                            retry = true;
                            retryCount++;
                            Thread.Sleep(3000);
                        }
                    }

                } while ((retry == true) && (retryCount < 3));

                if (result == null)
                {
                    // Handle unexpected errors.
                    ViewBag.ErrorMessage = "UnexpectedError";
                    TodoItem newItem = new TodoItem {Title = "(No items in list)"};
                    itemList.Add(newItem);
                    return View(itemList);
                }

                // Retrieve the user's Object Identifier claim, which is used as the key to the To Do list.
                //string ownerId = ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier").Value;

                // Forms encode todo item, to POST to the todo list web api.
                HttpContent content = new FormUrlEncodedContent(new[] { new KeyValuePair<string, string>("Title", item), new KeyValuePair<string, string>("Owner", OwnerId) });

                //
                // Add the item to user's To Do List.
                //
                HttpClient client = new HttpClient();
                HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, todoListBaseAddress + "/api/todolist");
                request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", result.AccessToken);
                request.Content = content;
                HttpResponseMessage response = await client.SendAsync(request);

                //
                // Return the To Do List in the view.
                //
                if (response.IsSuccessStatusCode)
                {
                    return RedirectToAction("Index");
                }
                else
                {
                    // If the response is Unauthorized, drop the token cache to force getting a new token on the next try.
                    if (response.StatusCode == System.Net.HttpStatusCode.Unauthorized)
                    {
                        authContext.TokenCache.Clear();
                    }

                    // Handle unexpected errors.
                    ViewBag.ErrorMessage = "UnexpectedError";
                    TodoItem newItem = new TodoItem {Title = "(No items in list)"};
                    itemList.Add(newItem);
                    return View(itemList);
                }

            }

            return View("Error");
        }
	}
}


text:
package de.felixbruns.jotify.api.media;

import java.util.ArrayList;
import java.util.List;

import de.felixbruns.jotify.api.util.Hex;

/**
 * Holds information about an album.
 *
 * @author Felix Bruns <felixbruns@web.de>
 *
 * @category Media
 */
public class Album extends Media {
	/**
	 * Name of this album.
	 */
	private String name;

	/**
	 * Artist of this album.
	 */
	private Artist artist;

	/**
	 * The identifier for this albums cover image (32-character string).
	 */
	private String cover;

	/**
	 * The type of this album (compilation, album, single).
	 */
	private String type;

	/**
	 * The review of this album.
	 */
	private String review;

	/**
	 * Release year of this album.
	 */
	private int year;

	/**
	 * A {@link List} of discs of this album.
	 *
	 * @see Disc
	 */
	private List<Disc> discs;

	/**
	 * Similar albums of this album.
	 */
	private List<Album> similarAlbums;

	/**
	 * Creates an empty {@link Album} object.
	 */
	public Album(){
		this.name          = null;
		this.artist        = null;
		this.cover         = null;
		this.type          = null;
		this.review        = null;
		this.year          = -1;
		this.discs         = new ArrayList<Disc>();
		this.similarAlbums = new ArrayList<Album>();
	}

	/**
	 * Creates an {@link Album} object with the specified {@code id}.
	 *
	 * @param id A 32-character hex string or a Spotify URI.
	 */
	public Album(String id){
		this(id, null, null);
	}

	/**
	 * Creates an {@link Album} object with the specified {@code id}, {@code name} and {@code artist}.
	 *
	 * @param id     A 32-character hex string or a Spotify URI.
	 * @param name   Name of the album.
	 * @param artist Artist of the album.
	 */
	public Album(String id, String name, Artist artist){
		super(id);

		/* Set object properties. */
		this.name          = name;
		this.artist        = artist;
		this.cover         = null;
		this.type          = null;
		this.review        = null;
		this.year          = -1;
		this.discs         = new ArrayList<Disc>();
		this.similarAlbums = new ArrayList<Album>();
	}

	/**
	 * Create a link from this album.
	 *
	 * @return A {@link Link} object which can then
	 * 		   be used to retreive the Spotify URI.
	 */
	public Link getLink(){
		return Link.create(this);
	}

	/**
	 * Get the albums name.
	 *
	 * @return The name of this album.
	 */
	public String getName(){
		return this.name;
	}

	/**
	 * Set the albums name.
	 *
	 * @param name The desired name of this album.
	 */
	public void setName(String name){
		this.name = name;
	}

	/**
	 * Get the albums artist.
	 *
	 * @return An {@link Artist} object.
	 */
	public Artist getArtist(){
		return this.artist;
	}

	/**
	 * Set the albums artist.
	 *
	 * @param artist The desired {@link Artist} of this album.
	 */
	public void setArtist(Artist artist){
		this.artist = artist;
	}

	/**
	 * Get the albums cover image identifier.
	 *
	 * @return A 32-character image identifier.
	 */
	public String getCover(){
		return this.cover;
	}

	/**
	 * Set the albums cover image identifier.
	 *
	 * @param cover A 40-character image identifier.
	 */
	public void setCover(String cover){
		/* Check if portrait id string is valid. */
		if(cover == null || cover.length() != 40 || !Hex.isHex(cover)){
			throw new IllegalArgumentException("Expecting a 40-character hex string.");
		}

		this.cover = cover;
	}

	/**
	 * Get the albums type.
	 *
	 * @return One of "compilation", "album" or "single".
	 */
	public String getType(){
		return this.type;
	}

	/**
	 * Set the albums type.
	 *
	 * @param type One of "compilation", "album" or "single".
	 */
	public void setType(String type){
		this.type = type;
	}

	/**
	 * Get the albums review.
	 *
	 * @return A review of this album.
	 */
	public String getReview(){
		return this.review;
	}

	/**
	 * Set the albums review.
	 *
	 * @param review A review of this album.
	 */
	public void setReview(String review){
		this.review = review;
	}

	/**
	 * Get the albums release year.
	 *
	 * @return An integer denoting the release year or -1 if not available.
	 */
	public int getYear(){
		return this.year;
	}

	/**
	 * Set the albums release year.
	 *
	 * @param year A positive integer denoting the release year.
	 */
	public void setYear(int year){
		/* Check if year is valid. Years B.C. are not supported :-P */
		if(year < 0){
			throw new IllegalArgumentException("Expecting a positive year.");
		}

		this.year = year;
	}

	/**
	 * Get discs of this album.
	 *
	 * @return A {@link List} of {@link Disc} objects.
	 */
	public List<Disc> getDiscs(){
		return this.discs;
	}

	/**
	 * Set discs of this album.
	 *
	 * @param discs A {@link List} of {@link Disc} objects.
	 */
	public void setDiscs(List<Disc> discs){
		this.discs = discs;
	}

	/**
	 * Set discs for this album.
	 *
	 * @param discs A {@link List} of {@link Disc} objects.
	 */
	public void setTracks(List<Disc> discs){
		this.discs = discs;
	}

	/**
	 * Get tracks of this album. This automatically merges
	 * tracks from this albums discs.
	 *
	 * @return A {@link List} of {@link Track} objects.
	 */
	public List<Track> getTracks(){
		List<Track> tracks = new ArrayList<Track>();

		for(Disc disc : this.discs){
			tracks.addAll(disc.getTracks());
		}

		return tracks;
	}

	/**
	 * Get similar albums for this album.
	 *
	 * @return A {@link List} of {@link Album} objects.
	 */
	public List<Album> getSimilarAlbums(){
		return this.similarAlbums;
	}

	/**
	 * Set similar albums for this album.
	 *
	 * @param similarAlbums A {@link List} of {@link Album} objects.
	 */
	public void setSimilarAlbums(List<Album> similarAlbums){
		this.similarAlbums = similarAlbums;
	}

	/**
	 * Determines if an object is equal to this {@link Album} object.
	 * If both objects are {@link Album} objects, it will compare their identifiers.
	 *
	 * @param o Another object to compare.
	 *
	 * @return true of the objects are equal, false otherwise.
	 */
	public boolean equals(Object o){
		if(o instanceof Album){
			Album a = (Album)o;

			if(this.id.equals(a.id)){
				return true;
			}

			for(String id : this.redirects){
				if(id.equals(a.id)){
					return true;
				}
			}
		}

		return false;
	}

	/**
	 * Return the hash code of this {@link Album} object. This will give the value returned
	 * by the {@code hashCode} method of the identifier string.
	 *
	 * @return The {@link Album} objects hash code.
	 */
	public int hashCode(){
		return (this.id != null) ? this.id.hashCode() : 0;
	}

	public String toString(){
		return String.format("[Album: %s, %s]", this.artist, this.name);
	}
}