text:
namespace chainerx {
namespace cuda {
namespace cuda_internal {

class MemoryPoolTest {
public:
    static const FreeBinsMap& GetFreeBins(const MemoryPool& pool) { return pool.free_bins_; }
    static const Allocator* GetAllocator(const MemoryPool& pool) { return pool.allocator_.get(); }
};

}  // namespace cuda_internal

namespace {

void* AddOffset(void* ptr, size_t offset) {
    return reinterpret_cast<void*>(reinterpret_cast<intptr_t>(ptr) + offset);  // NOLINT(cppcoreguidelines-pro-type-reinterpret-cast)
}

using Chunk = cuda_internal::Chunk;

TEST(ChunkTest, Split) {
    size_t mem_bytesize = kAllocationUnitSize * 4;
    std::shared_ptr<void> mem = std::make_unique<uint8_t[]>(mem_bytesize);
    Chunk chunk{mem.get(), 0, mem_bytesize};

    // Split a chunk into two chunks: a chunk with smaller size and one with the remaining.
    std::unique_ptr<Chunk> tail = chunk.Split(kAllocationUnitSize * 2);
    EXPECT_EQ(chunk.ptr(), mem.get());
    EXPECT_EQ(chunk.bytesize(), kAllocationUnitSize * 2);
    EXPECT_EQ(chunk.prev(), nullptr);
    EXPECT_EQ(chunk.next()->ptr(), tail->ptr());
    EXPECT_EQ(tail->ptr(), AddOffset(mem.get(), kAllocationUnitSize * 2));
    EXPECT_EQ(tail->bytesize(), kAllocationUnitSize * 2);
    EXPECT_EQ(tail->prev()->ptr(), chunk.ptr());
    EXPECT_EQ(tail->next(), nullptr);

    // Split the chunk which was already once splitted.
    std::unique_ptr<Chunk> tail_of_head = chunk.Split(kAllocationUnitSize);
    EXPECT_EQ(chunk.ptr(), mem.get());
    EXPECT_EQ(chunk.bytesize(), kAllocationUnitSize);
    EXPECT_EQ(chunk.prev(), nullptr);
    EXPECT_EQ(chunk.next()->ptr(), tail_of_head->ptr());
    EXPECT_EQ(tail_of_head->ptr(), AddOffset(mem.get(), kAllocationUnitSize));
    EXPECT_EQ(tail_of_head->bytesize(), kAllocationUnitSize);
    EXPECT_EQ(tail_of_head->prev()->ptr(), chunk.ptr());
    EXPECT_EQ(tail_of_head->next()->ptr(), tail->ptr());

    // Split the remaining chunk.
    std::unique_ptr<Chunk> tail_of_tail = tail->Split(kAllocationUnitSize);
    EXPECT_EQ(tail->ptr(), AddOffset(chunk.ptr(), kAllocationUnitSize * 2));
    EXPECT_EQ(tail->bytesize(), kAllocationUnitSize);
    EXPECT_EQ(tail->prev()->ptr(), tail_of_head->ptr());
    EXPECT_EQ(tail->next()->ptr(), tail_of_tail->ptr());
    EXPECT_EQ(tail_of_tail->ptr(), AddOffset(mem.get(), kAllocationUnitSize * 3));
    EXPECT_EQ(tail_of_tail->bytesize(), kAllocationUnitSize);
    EXPECT_EQ(tail_of_tail->prev()->ptr(), tail->ptr());
    EXPECT_EQ(tail_of_tail->next(), nullptr);
}

TEST(ChunkTest, MergeWithNext) {
    size_t mem_bytesize = kAllocationUnitSize * 4;
    std::shared_ptr<void> mem = std::make_unique<uint8_t[]>(mem_bytesize);
    Chunk chunk{mem.get(), 0, mem_bytesize};

    void* chunk_ptr = chunk.ptr();
    size_t chunk_bytesize = chunk.bytesize();

    // Split chunk -> [1, 2, 3, 4]
    std::unique_ptr<Chunk> tail = chunk.Split(kAllocationUnitSize * 2);
    std::unique_ptr<Chunk> head = std::make_unique<Chunk>(chunk);
    void* head_ptr = head->ptr();
    size_t head_bytesize = head->bytesize();
    void* tail_ptr = tail->ptr();
    size_t tail_bytesize = tail->bytesize();
    std::unique_ptr<Chunk> tail_next = tail->Split(kAllocationUnitSize);
    std::unique_ptr<Chunk> head_next = head->Split(kAllocationUnitSize);

    // Merge [1] and [2] into [1, 2].
    head->MergeWithNext();
    EXPECT_EQ(head->ptr(), head_ptr);
    EXPECT_EQ(head->bytesize(), head_bytesize);
    EXPECT_EQ(head->prev(), nullptr);
    EXPECT_EQ(head->next()->ptr(), tail_ptr);

    // Merge [3] and [4] into [3, 4].
    tail->MergeWithNext();
    EXPECT_EQ(tail->ptr(), tail_ptr);
    EXPECT_EQ(tail->bytesize(), tail_bytesize);
    EXPECT_EQ(tail->prev()->ptr(), head_ptr);
    EXPECT_EQ(tail->next(), nullptr);

    // Merge [1, 2] and [3, 4] into [1, 2, 3, 4].
    // Merge chunks which were already one merged.
    head->MergeWithNext();
    EXPECT_EQ(head->ptr(), chunk_ptr);
    EXPECT_EQ(head->bytesize(), chunk_bytesize);
    EXPECT_EQ(head->prev(), nullptr);
    EXPECT_EQ(head->next(), nullptr);

    (void)head_next;
    (void)tail_next;
}

// A dummy allocator to test OutOfMemoryError
class FixedCapacityDummyAllocator : public Allocator {
public:
    explicit FixedCapacityDummyAllocator(size_t capacity) : capacity_{capacity} {}

    MallocStatus Malloc(void** ptr, size_t bytesize) override {
        CHAINERX_ASSERT(bytesize > 0);
        uint8_t* mem{};
        {
            std::lock_guard<std::mutex> lock{sizes_mutex_};
            ++malloc_called_;
            if (capacity_ < bytesize) {
                return MallocStatus::kErrorMemoryAllocation;
            }
            mem = new uint8_t[bytesize];
            sizes_[mem] = bytesize;
            capacity_ -= bytesize;
        }
        *ptr = mem;
        return MallocStatus::kSuccess;
    }
    void Free(void* ptr) noexcept override {
        uint8_t* mem = static_cast<uint8_t*>(ptr);
        {
            std::lock_guard<std::mutex> lock{sizes_mutex_};
            auto it = sizes_.find(mem);
            CHAINERX_ASSERT(it != sizes_.end());
            capacity_ += it->second;
            sizes_.erase(it);
            ++free_called_;
        }
        delete[] mem;
    }

    int malloc_called() const { return malloc_called_; }
    int free_called() const { return free_called_; }

private:
    size_t capacity_;
    int malloc_called_{0};
    int free_called_{0};
    std::mutex sizes_mutex_;
    std::map<void*, size_t> sizes_;
};

class MemoryPoolTestForEachAllocator : public ::testing::TestWithParam<std::shared_ptr<MemoryPool>> {};

TEST_P(MemoryPoolTestForEachAllocator, MallocAndFree) {
    MemoryPool& memory_pool = *GetParam();

    // Allocate two distinct memory areas via allocator.
    void* ptr1 = memory_pool.Malloc(1);
    void* ptr2 = memory_pool.Malloc(1);
    EXPECT_NE(ptr1, ptr2);

    // This memory is stored into the free bins.
    memory_pool.Free(ptr2);

    // Fetche a memory area from the free bins.
    void* ptr3 = memory_pool.Malloc(1);
    EXPECT_EQ(ptr2, ptr3);

    memory_pool.Free(ptr3);
    memory_pool.Free(ptr1);
}

TEST_P(MemoryPoolTestForEachAllocator, MallocAllocationUnitSize) {
    MemoryPool& memory_pool = *GetParam();

    // Allocate a memory area via allocator.
    void* ptr1 = memory_pool.Malloc(100);
    memory_pool.Free(ptr1);

    // Allocate a memory area via allocator, because the free bins do not have any consecutive memory area of such bytesize.
    void* ptr2 = memory_pool.Malloc(100 + kAllocationUnitSize);
    EXPECT_NE(ptr1, ptr2);

    memory_pool.Free(ptr2);
}

TEST_P(MemoryPoolTestForEachAllocator, MallocZeroByte) {
    MemoryPool& memory_pool = *GetParam();
    void* ptr = memory_pool.Malloc(0);
    EXPECT_EQ(nullptr, ptr);
    memory_pool.Free(ptr);  // no throw
}

TEST_P(MemoryPoolTestForEachAllocator, FreeTwice) {
    MemoryPool& memory_pool = *GetParam();
    void* ptr = memory_pool.Malloc(1);
    memory_pool.Free(ptr);
    EXPECT_THROW(memory_pool.Free(ptr), ChainerxError);
}

TEST_P(MemoryPoolTestForEachAllocator, FreeForeignPointer) {
    MemoryPool& memory_pool = *GetParam();
    void* ptr = &memory_pool;
    EXPECT_THROW(memory_pool.Free(ptr), ChainerxError);
}

TEST_P(MemoryPoolTestForEachAllocator, FreeUnusedBlocks) {
    MemoryPool& memory_pool = *GetParam();
    const cuda_internal::FreeBinsMap& free_bins = cuda_internal::MemoryPoolTest::GetFreeBins(memory_pool);

    void* ptr1 = memory_pool.Malloc(1);
    memory_pool.Free(ptr1);
    EXPECT_FALSE(free_bins.empty());

    memory_pool.FreeUnusedBlocks();
    EXPECT_TRUE(free_bins.empty());
}

TEST_P(MemoryPoolTestForEachAllocator, MallocSplit) {
    MemoryPool& memory_pool = *GetParam();

    // Allocate a memory area of 4 unit size length in free bins, and store it in free bins.
    void* ptr = memory_pool.Malloc(kAllocationUnitSize * 4);
    memory_pool.Free(ptr);

    // Take the memory area from free bins and split it into two memory areas.
    void* head = memory_pool.Malloc(kAllocationUnitSize * 2);
    void* tail = memory_pool.Malloc(kAllocationUnitSize * 2);
    EXPECT_EQ(ptr, head);
    EXPECT_EQ(AddOffset(ptr, kAllocationUnitSize * 2), tail);
    memory_pool.Free(head);
    memory_pool.Free(tail);
}

TEST_P(MemoryPoolTestForEachAllocator, FreeMerge) {
    MemoryPool& memory_pool = *GetParam();
    void* ptr = memory_pool.Malloc(kAllocationUnitSize * 4);
    memory_pool.Free(ptr);

    // Merge head into tail
    {
        void* head = memory_pool.Malloc(kAllocationUnitSize * 2);
        void* tail = memory_pool.Malloc(kAllocationUnitSize * 2);
        EXPECT_EQ(ptr, head);
        EXPECT_EQ(AddOffset(ptr, kAllocationUnitSize * 2), tail);
        memory_pool.Free(tail);
        memory_pool.Free(head);
        void* p = memory_pool.Malloc(kAllocationUnitSize * 4);
        EXPECT_EQ(ptr, p);
        memory_pool.Free(p);
    }

    // Merge tail into head
    {
        void* head = memory_pool.Malloc(kAllocationUnitSize * 2);
        void* tail = memory_pool.Malloc(kAllocationUnitSize * 2);
        EXPECT_EQ(ptr, head);
        EXPECT_EQ(AddOffset(ptr, kAllocationUnitSize * 2), tail);
        memory_pool.Free(head);
        memory_pool.Free(tail);
        void* p = memory_pool.Malloc(kAllocationUnitSize * 4);
        EXPECT_EQ(ptr, p);
        memory_pool.Free(p);
    }
}

TEST_P(MemoryPoolTestForEachAllocator, MallocSizeIncreasing) {
    static constexpr size_t size1 = kAllocationUnitSize * 4;
    static constexpr size_t size2 = kAllocationUnitSize * 8;

    MemoryPool& memory_pool = *GetParam();
    void* ptr1 = memory_pool.Malloc(size1);
    memory_pool.Free(ptr1);

    // Cannot take the memory area from free bins, because there is no memory area larger or equal to size2.
    void* ptr2 = memory_pool.Malloc(size2);
    memory_pool.Free(ptr2);
    EXPECT_NE(ptr1, ptr2);
}

TEST_P(MemoryPoolTestForEachAllocator, MallocSizeDecreasing) {
    static constexpr size_t size1 = kAllocationUnitSize * 8;
    static constexpr size_t size2 = kAllocationUnitSize * 4;

    MemoryPool& memory_pool = *GetParam();
    void* ptr1 = memory_pool.Malloc(size1);
    memory_pool.Free(ptr1);

    // Take the memory area from free bins, because there is a memory area larger or equal to size2.
    void* ptr2 = memory_pool.Malloc(size2);
    memory_pool.Free(ptr2);
    EXPECT_EQ(ptr1, ptr2);
}

INSTANTIATE_TEST_CASE_P(
        ForEachAllocator,
        MemoryPoolTestForEachAllocator,
        ::testing::Values(
                std::make_shared<MemoryPool>(0, std::make_unique<DeviceMemoryAllocator>()),
                std::make_shared<MemoryPool>(0, std::make_unique<PinnedMemoryAllocator>())));

TEST(MemoryPoolTest, MallocThrowOutOfMemory) {
    MemoryPool memory_pool{0, std::make_unique<FixedCapacityDummyAllocator>(0U)};
    EXPECT_THROW(memory_pool.Malloc(1), OutOfMemoryError);
}

TEST(MemoryPoolTest, MallocRetryOutOfMemory) {
    static constexpr size_t kCapacity = cuda::kAllocationUnitSize * 4;
    MemoryPool memory_pool{0, std::make_unique<FixedCapacityDummyAllocator>(kCapacity)};
    auto allocator = dynamic_cast<const FixedCapacityDummyAllocator*>(cuda_internal::MemoryPoolTest::GetAllocator(memory_pool));

    size_t size1 = 1U;
    size_t size2 = kCapacity;

    void* ptr1 = memory_pool.Malloc(size1);  // no throw
    memory_pool.Free(ptr1);

    // There is no memory area larger or equal to size2, so the memory pool tries to fetch an new memory area from the allocator. However,
    // there is no free space in the allocator, so the memory pool frees all unused blocks and tries to fetch an new memory area again.
    // Finally, the memory pool succeeds to obtain an memory area and returns it.
    void* ptr2 = memory_pool.Malloc(size2);  // no throw
    memory_pool.Free(ptr2);

    EXPECT_EQ(allocator->malloc_called(), 3);
}

TEST(MemoryPoolTest, FreeUnusedBlocksSplitAndFreeTail) {
    // Do not free splitted blocks
    static constexpr size_t kCapacity = cuda::kAllocationUnitSize * 4;
    MemoryPool memory_pool{0, std::make_unique<FixedCapacityDummyAllocator>(kCapacity)};
    auto allocator = dynamic_cast<const FixedCapacityDummyAllocator*>(cuda_internal::MemoryPoolTest::GetAllocator(memory_pool));

    void* ptr = memory_pool.Malloc(kAllocationUnitSize * 4);
    memory_pool.Free(ptr);

    memory_pool.Malloc(kAllocationUnitSize * 2);
    void* tail = memory_pool.Malloc(kAllocationUnitSize * 2);
    memory_pool.Free(tail);

    // The memory pool has an unused block in free bins, but it should not be freed because the previous memory area is in use.
    memory_pool.FreeUnusedBlocks();
    void* ptr2 = memory_pool.Malloc(kAllocationUnitSize * 2);
    EXPECT_EQ(tail, ptr2);
    EXPECT_EQ(allocator->free_called(), 0);
}

TEST(MemoryPoolTest, FreeUnusedBlocksSplitAndFreeHead) {
    // Do not free splitted blocks
    static constexpr size_t kCapacity = cuda::kAllocationUnitSize * 4;
    MemoryPool memory_pool{0, std::make_unique<FixedCapacityDummyAllocator>(kCapacity)};
    auto allocator = dynamic_cast<const FixedCapacityDummyAllocator*>(cuda_internal::MemoryPoolTest::GetAllocator(memory_pool));

    void* ptr = memory_pool.Malloc(kAllocationUnitSize * 4);
    memory_pool.Free(ptr);

    void* head = memory_pool.Malloc(kAllocationUnitSize * 2);
    memory_pool.Malloc(kAllocationUnitSize * 2);

    // The memory pool has an unused block in free bins, but it should not be freed because the next memory area is in use.
    memory_pool.Free(head);
    memory_pool.FreeUnusedBlocks();
    void* ptr2 = memory_pool.Malloc(kAllocationUnitSize * 2);
    EXPECT_EQ(head, ptr2);
    EXPECT_EQ(allocator->free_called(), 0);
}

TEST(MemoryPoolTest, FreeUnusedBlocksThreadSafe) {
    static constexpr size_t kRepeat = 100U;
    MemoryPool memory_pool{0, std::make_unique<FixedCapacityDummyAllocator>(0xffffffffU)};

    // TODO(niboshi): Use TEST_THREAD_SAFE. Currently it depends on thread sanitizer and does not work with CUDA.
    testing::RunThreads(2, [&memory_pool](size_t thread_index) {
        for (size_t i = 0; i < kRepeat; ++i) {
            switch (thread_index) {
                case 0: {
                    void* ptr = memory_pool.Malloc(1U);
                    memory_pool.Free(ptr);
                    break;
                }
                case 1:
                    memory_pool.FreeUnusedBlocks();
                    break;
                default:
                    CHAINERX_NEVER_REACH();
            }
        }
    });
}

TEST(MemoryPoolTest, MallocFreeThreadSafe) {
    static constexpr size_t kRepeat = 100U;
    MemoryPool memory_pool{0, std::make_unique<FixedCapacityDummyAllocator>(0xffffffffU)};

    // TODO(niboshi): Use TEST_THREAD_SAFE. Currently it depends on thread sanitizer and does not work with CUDA.
    testing::RunThreads(2, [&memory_pool](size_t thread_index) {
        for (size_t i = 0; i < kRepeat; ++i) {
            switch (thread_index) {
                case 0: {
                    void* ptr = memory_pool.Malloc(1U);
                    memory_pool.Free(ptr);
                    break;
                }
                case 1: {
                    void* ptr = memory_pool.Malloc(1U);
                    memory_pool.Free(ptr);
                    break;
                }
            }
        }
    });
}

TEST(MemoryPoolTest, Hook) {
    MemoryPool memory_pool{0, std::make_unique<FixedCapacityDummyAllocator>(0xffffffffU)};

    size_t total_memory = 0;
    std::map<void*, size_t> memories;
    auto malloc_postprocess_hook = [&total_memory, &memories](MemoryPool&, size_t bytesize, void* ptr) {
        memories[ptr] += bytesize;
        total_memory += bytesize;
    };
    auto free_preprocess_hook = [&total_memory, &memories](MemoryPool&, void* ptr) {
        auto found = memories.find(ptr);
        ASSERT_TRUE(found != memories.end());
        const size_t bytesize = found->second;
        memories.erase(found);
        total_memory -= bytesize;
    };
    memory_pool.SetMallocPostprocessHook(malloc_postprocess_hook);
    memory_pool.SetFreeHook(free_preprocess_hook);

    EXPECT_EQ(total_memory, 0U);
    EXPECT_EQ(memories.size(), 0U);

    void* ptr1 = memory_pool.Malloc(12);

    EXPECT_EQ(total_memory, 12U);
    EXPECT_EQ(memories.size(), 1U);

    void* ptr2 = memory_pool.Malloc(300);

    EXPECT_EQ(total_memory, 312U);
    EXPECT_EQ(memories.size(), 2U);

    memory_pool.Free(ptr1);

    EXPECT_EQ(total_memory, 300U);
    EXPECT_EQ(memories.size(), 1U);

    memory_pool.Free(ptr2);

    EXPECT_EQ(total_memory, 0U);
    EXPECT_EQ(memories.size(), 0U);
}

}  // namespace
}  // namespace cuda
}  // namespace chainerx


text:
package org.jboss.as.quickstarts.kitchensink.test.page;

import org.jboss.arquillian.graphene.findby.FindByJQuery;
import org.jboss.as.quickstarts.kitchensink.test.Member;
import org.openqa.selenium.WebElement;

import java.util.List;

import static org.jboss.arquillian.graphene.Graphene.waitModel;

public class MembersTablePageFragment {
    /**
     * Locator for rows of the members table
     */
    @FindByJQuery("[id*='memberList'] table tbody[id*='tb']")
    private WebElement table;

    /**
     * Locator for rows of the members table
     */
    @FindByJQuery("[id*='memberList'] table tbody[id*='tb'] tr")
    private List<MemberPageFragment> members;

    public void waitForNewMember(Member member) {
        waitModel().until().element(table).text().contains(member.getName());
    }

    public Member getLatestMember() {
        return members.get(0).getMember();
    }

    public int getMemberCount() {
        return members.size();
    }

}

redpajama_set_name: RedPajamaGithub


text:
package edu.iastate.cs.boa.conversion;

import org.eclipse.xtext.conversion.IValueConverter;
import org.eclipse.xtext.conversion.ValueConverter;
import org.eclipse.xtext.conversion.impl.AbstractDeclarativeValueConverterService;
import org.eclipse.xtext.conversion.impl.AbstractIDValueConverter;
import org.eclipse.xtext.conversion.impl.STRINGValueConverter;

import com.google.inject.Inject;

/**
 * @author rdyer
 */
public class BoaValueConverterService extends AbstractDeclarativeValueConverterService {
	@Inject
	private AbstractIDValueConverter idValueConverter;

	@ValueConverter(rule = "ID")
	public IValueConverter<String> ID() {
		return idValueConverter;
	}

	@Inject
	private LONGValueConverter longValueConverter;

	@ValueConverter(rule = "INTEGER_LIT")
	public IValueConverter<Long> INTEGER_LIT() {
		return longValueConverter;
	}

	@Inject
	private STRINGValueConverter stringValueConverter;

	@ValueConverter(rule = "STRING_LIT")
	public IValueConverter<String> STRING_LIT() {
		return stringValueConverter;
	}

	@Inject
	private REGEXValueConverter regexValueConverter;

	@ValueConverter(rule = "REGEX_LIT")
	public IValueConverter<String> REGEX_LIT() {
		return regexValueConverter;
	}

	@Inject
	private TIMEValueConverter timeValueConverter;

	@ValueConverter(rule = "TIME_LIT")
	public IValueConverter<Long> TIME_LIT() {
		return timeValueConverter;
	}
}


text:
python manage.py migrate
python manage.py collectstatic


text:
package strutils

import (
	"crypto/md5"
	"encoding/hex"
	"errors"
	"fmt"
	"html"
	"io"
	"math"
	"net/url"
	"os"
	"reflect"
	"regexp"
	"strconv"
	"strings"
	"sync"
	"unicode/utf8"
)

// referrer to https://golang.org/pkg/regexp/syntax/
var numericPattern = regexp.MustCompile(`^[-+]?[0-9]*\.?[0-9]+([eE][-+]?[0-9]+)?$`)

var (
	tagElementsPattern   = regexp.MustCompile(`(?ims)(?P<tag><(/*\s*|\?*|\!*)(figcaption|expression|blockquote|plaintext|textarea|progress|optgroup|noscript|noframes|menuitem|frameset|fieldset|!DOCTYPE|datalist|colgroup|behavior|basefont|summary|section|isindex|details|caption|bgsound|article|address|acronym|strong|strike|source|select|script|output|option|object|legend|keygen|ilayer|iframe|header|footer|figure|dialog|center|canvas|button|applet|video|track|title|thead|tfoot|tbody|table|style|small|param|meter|layer|label|input|frame|embed|blink|audio|aside|alert|time|span|samp|ruby|meta|menu|mark|main|link|html|head|form|font|code|cite|body|base|area|abbr|xss|xml|wbr|var|svg|sup|sub|pre|nav|map|kbd|ins|img|div|dir|dfn|del|col|big|bdo|bdi|!--|ul|tt|tr|th|td|rt|rp|ol|li|hr|em|dt|dl|dd|br|u|s|q|p|i|b|a|(h[0-9]+))([^><]*)([><]*))`)
	whiteSpacePattern    = regexp.MustCompile(`(?im)\s{2,}`)
	entityEncodedPattern = regexp.MustCompile(`(?ims)(&(?:[a-z0-9]{2,8}|#[0-9]{2,3});)`)
	urlEncodedPattern    = regexp.MustCompile(`(?ims)(%[a-zA-Z0-9]{2})`)
)

// for debug
// var detectUnicodeEntities = regexp.MustCompile(`(?ims)u([0-9a-z]{4})`)

// StringProc is String processing methods, All operations on this object
type StringProc struct {
	sync.RWMutex
}

// NewStringProc Creates and returns a String processing methods's pointer.
func NewStringProc() *StringProc {
	return &StringProc{}
}

// AddSlashes is quote string with slashes
func (s *StringProc) AddSlashes(str string) string {
	l := len(str)

	buf := make([]byte, 0, l*2) // prealloca

	for i := 0; i < l; i++ {

		buf = append(buf, str[i])

		switch str[i] {
		case 92: // Dec : /

			if l >= i+1 {
				buf = append(buf, 92)

				if l > i+1 && str[i+1] == 92 {
					i++
				}
			}
		}
	}

	return string(buf)
}

// StripSlashes is Un-quotes a quoted string
func (s *StringProc) StripSlashes(str string) string {
	l := len(str)
	buf := make([]byte, 0, l) // prealloca

	for i := 0; i < l; i++ {

		buf = append(buf, str[i])
		if l > i+1 && str[i+1] == 92 {
			i++
		}
	}

	return string(buf)
}

// Nl2Br is breakstr inserted before looks like space (CRLF , LFCR, SPACE, NL)
func (s *StringProc) Nl2Br(str string) string {
	// BenchmarkNl2Br-8                   	10000000	      3398 ns/op
	// BenchmarkNl2BrUseStringReplace-8   	10000000	      4535 ns/op
	brtag := []byte("
")
	l := len(str)
	buf := make([]byte, 0, l) // prealloca

	for i := 0; i < l; i++ {
		switch str[i] {

		case 10, 13: // NL or CR

			buf = append(buf, brtag...)

			if l >= i+1 {
				if l > i+1 && (str[i+1] == 10 || str[i+1] == 13) { // NL+CR or CR+NL
					i++
				}
			}
		default:
			buf = append(buf, str[i])
		}
	}

	return string(buf)
}

// Br2Nl is replaces HTML line breaks to a newline
func (s *StringProc) Br2Nl(str string) string {
	//
 ,
 ,

	//
 ,
 ,

	nlchar := []byte("\n")

	l := len(str)
	buf := make([]byte, 0, l) // prealloca

	for i := 0; i < l; i++ {
		switch str[i] {

		case 60: //<

			if l >= i+3 {

				/*
					b = 98
					B = 66
					r = 82
					R = 114
					SPACE = 32
					/ = 47
					> = 62
				*/

				if l >= i+3 && ((str[i+1] == 98 || str[i+1] == 66) && (str[i+2] == 82 || str[i+2] == 114) && str[i+3] == 62) { //
 ||

					buf = append(buf, nlchar...)
					i += 3
					continue
				}

				if l >= i+4 && ((str[i+1] == 98 || str[i+1] == 66) && (str[i+2] == 82 || str[i+2] == 114) && str[i+3] == 47 && str[i+4] == 62) { //
 ||

					buf = append(buf, nlchar...)
					i += 4
					continue
				}

				if l >= i+5 && ((str[i+1] == 98 || str[i+1] == 66) && (str[i+2] == 82 || str[i+2] == 114) && str[i+3] == 32 && str[i+4] == 47 && str[i+5] == 62) { //
 ||

					buf = append(buf, nlchar...)
					i += 5
					continue
				}
			}
			fallthrough

		default:
			buf = append(buf, str[i])
		}
	}

	return string(buf)
}

// WordWrapSimple is Wraps a string to a given number of characters using break characters (TAB, SPACE)
func (s *StringProc) WordWrapSimple(str string, wd int, breakstr string) (string, error) {
	if wd < 1 {
		err := errors.New("wd At least 1 or More")
		return str, err
	}

	strl := len(str)
	breakstrl := len(breakstr)

	buf := make([]byte, 0, (strl+breakstrl)*2)
	bufstr := []byte(str)

	brpos := 0
	for _, v := range bufstr {

		if (v == 9 || v == 32) && brpos >= wd {
			buf = append(buf, []byte(breakstr)...)
			brpos = -1

		} else {
			buf = append(buf, v)
		}
		brpos++
	}

	return string(buf), nil
}

// WordWrapAround is Wraps a string to a given number of characters using break characters (TAB, SPACE)
func (s *StringProc) WordWrapAround(str string, wd int, breakstr string) (string, error) {
	if wd < 1 {
		return "", errors.New("wd At least 1 or More")
	}

	strl := len(str)
	breakstrl := len(breakstr)

	buf := make([]byte, 0, (strl+breakstrl)*2)
	bufstr := []byte(str)

	lastspc := make([]int, 0, strl)
	strpos := 0

	// looking for space or tab
	for _, v := range bufstr {

		if v == 9 || v == 32 {
			lastspc = append(lastspc, strpos)
		}
		strpos++
	}

	inject := make([]int, 0, strl)

	// looking for break point
	beforeBp := 0
	width := wd

	for _, v := range lastspc {

		if beforeBp != v {
			beforeBp = v
		}

		// DEBUG: fmt.Printf("V(%v) (%d <= %d || %d <= %d || %d <= %d) && %d <= %d : ", v, width, beforeBp, width, beforeBp+1, width, beforeBp-1, width, v)
		if (width <= beforeBp || width <= beforeBp+1 || width <= beforeBp-1) && width <= v {
			inject = append(inject, beforeBp)
			width += wd
		} else if width < v && len(lastspc) == 1 {
			inject = append(inject, v)
		}
		// fmt.Println()
	}

	// injection
	breakno := 0
	loopcnt := 0
	injectcnt := len(inject)
	for _, v := range bufstr {

		// fmt.Printf("(%v) %d > %d && %d <= %d\n", v, injectcnt, breakno, inject[breakno], loopcnt)
		if injectcnt > breakno && inject[breakno] == loopcnt {

			buf = append(buf, []byte(breakstr)...)
			if injectcnt > breakno+1 {
				breakno++
			}
		} else {
			buf = append(buf, v)
		}

		loopcnt++
	}

	return string(buf), nil
}

func (s *StringProc) numberToString(obj interface{}) (string, error) {
	var strNum string

	switch obj.(type) {

	case string:
		strNum = obj.(string)
		if !numericPattern.MatchString(strNum) {
			return strNum, fmt.Errorf("Not Support obj.(%v) := %v ", reflect.TypeOf(obj), strNum)
		}
	case int:
		strNum = strconv.FormatInt(int64(obj.(int)), 10)
	case int8:
		strNum = strconv.FormatInt(int64(obj.(int8)), 10)
	case int16:
		strNum = strconv.FormatInt(int64(obj.(int16)), 10)
	case int32:
		strNum = strconv.FormatInt(int64(obj.(int32)), 10)
	case int64:
		strNum = strconv.FormatInt(obj.(int64), 10)
	case uint:
		strNum = strconv.FormatUint(uint64(obj.(uint)), 10)
	case uint8:
		strNum = strconv.FormatUint(uint64(obj.(uint8)), 10)
	case uint16:
		strNum = strconv.FormatUint(uint64(obj.(uint16)), 10)
	case uint32:
		strNum = strconv.FormatUint(uint64(obj.(uint32)), 10)
	case uint64:
		strNum = strconv.FormatUint(obj.(uint64), 10)
	case float32:
		strNum = fmt.Sprintf("%g", obj.(float32))
	case float64:
		strNum = fmt.Sprintf("%g", obj.(float64))
	case complex64:
		strNum = fmt.Sprintf("%g", obj.(complex64))
	case complex128:
		strNum = fmt.Sprintf("%g", obj.(complex128))

	default:
		return strNum, fmt.Errorf("Not Support obj.(%v)", reflect.TypeOf(obj))
	}

	return strNum, nil
}

// NumberFmt is format a number with english notation grouped thousands
// TODO : support other country notation
func (s *StringProc) NumberFmt(obj interface{}) (string, error) {
	// check : complex
	switch obj.(type) {
	case complex64, complex128:
		return "", fmt.Errorf("Not Support obj.(%v)", reflect.TypeOf(obj))
	}

	strNum, err := s.numberToString(obj)
	if err != nil {
		return "", err
	}

	bufbyteStr := []byte(strNum)
	bufbyteStrLen := len(bufbyteStr)

	// subffix after dot
	bufbyteTail := make([]byte, bufbyteStrLen-1)

	// init.
	var foundDot, foundPos, dotcnt, bufbyteSize int

	// looking for dot
	for i := bufbyteStrLen - 1; i >= 0; i-- {
		if bufbyteStr[i] == 46 {
			copy(bufbyteTail, bufbyteStr[i:])
			foundDot = i
			foundPos = i
			break
		}
	}

	// make bufbyte size
	if foundDot == 0 { // numeric without dot
		bufbyteSize = int(math.Ceil(float64(bufbyteStrLen) + float64(bufbyteStrLen)/3))
		foundDot = bufbyteStrLen
		foundPos = bufbyteSize - 2

		bufbyteSize--

	} else { // with dot

		var calFoundDot int

		if bufbyteStr[0] == 45 { // if startwith "-"(45)
			calFoundDot = foundDot - 1
		} else {
			calFoundDot = foundDot
		}

		bufbyteSize = int(math.Ceil(float64(calFoundDot) + float64(calFoundDot)/3 + float64(bufbyteStrLen-calFoundDot) - 1))
	}

	// make a buffer byte
	bufbyte := make([]byte, bufbyteSize)

	// skip : need to dot injection
	if 4 > foundDot {
		return strNum, nil
	}

	// injection
	intoPos := foundPos
	for i := foundDot - 1; i >= 0; i-- {
		if dotcnt >= 3 && (bufbyteStr[i] >= 48 && bufbyteStr[i] <= 57 || bufbyteStr[i] == 69 || bufbyteStr[i] == 101 || bufbyteStr[i] == 43) {
			bufbyte[intoPos] = 44
			intoPos--
			dotcnt = 0
		}
		bufbyte[intoPos] = bufbyteStr[i]
		intoPos--
		dotcnt++
	}

	// into dot to tail
	intoPos = foundPos + 1
	if foundDot != bufbyteStrLen {
		for _, v := range bufbyteTail {
			if v == 0 { // NULL
				break
			}

			bufbyte[intoPos] = v
			intoPos++
		}
	}

	return string(bufbyte), nil
}

// padding contol const
const (
	PadLeft  = 0 // left padding
	PadRight = 1 // right padding
	PadBoth  = 2 // both padding
)

// PaddingBoth is Padding method alias with PadBoth Option
func (s *StringProc) PaddingBoth(str string, fill string, mx int) string {
	return s.Padding(str, fill, PadBoth, mx)
}

// PaddingLeft is Padding method alias with PadRight Option
func (s *StringProc) PaddingLeft(str string, fill string, mx int) string {
	return s.Padding(str, fill, PadLeft, mx)
}

// PaddingRight is Padding method alias with PadRight Option
func (s *StringProc) PaddingRight(str string, fill string, mx int) string {
	return s.Padding(str, fill, PadRight, mx)
}

// Padding is Pad a string to a certain length with another string
// BenchmarkPadding-8                   10000000	       271 ns/op
// BenchmarkPaddingUseStringRepeat-8   	 3000000	       418 ns/op
func (s *StringProc) Padding(str string, fill string, m int, mx int) string {
	byteStr := []byte(str)
	byteStrLen := len(byteStr)
	if byteStrLen >= mx || mx < 1 {
		return str
	}

	var leftsize int
	var rightsize int

	switch m {
	case PadBoth:
		rlsize := float64(mx-byteStrLen) / 2
		leftsize = int(rlsize)
		rightsize = int(rlsize + math.Copysign(0.5, rlsize))

	case PadLeft:
		leftsize = mx - byteStrLen

	case PadRight:
		rightsize = mx - byteStrLen

	}

	buf := make([]byte, 0, mx)

	if m == PadLeft || m == PadBoth {
		for i := 0; i < leftsize; {
			for _, v := range []byte(fill) {
				buf = append(buf, v)
				if i >= leftsize-1 {
					i = leftsize
					break
				} else {
					i++
				}
			}
		}
	}

	buf = append(buf, byteStr...)

	if m == PadRight || m == PadBoth {
		for i := 0; i < rightsize; {
			for _, v := range []byte(fill) {
				buf = append(buf, v)
				if i >= rightsize-1 {
					i = rightsize
					break
				} else {
					i++
				}
			}
		}
	}

	return string(buf)
}

// LowerCaseFirstWords is Lowercase the first character of each word in a string
// INFO : (Support Token Are \t(9)\r(13)\n(10)\f(12)\v(11)\s(32))
func (s *StringProc) LowerCaseFirstWords(str string) string {
	upper := 1
	bufbyteStr := []byte(str)
	retval := make([]byte, len(bufbyteStr))
	for k, v := range bufbyteStr {

		if upper == 1 && v >= 65 && v <= 90 {
			v = v + 32
		}

		upper = 0

		if v >= 9 && v <= 13 || v == 32 {
			upper = 1
		}
		retval[k] = v
	}

	return string(retval)
}

// UpperCaseFirstWords is Uppercase the first character of each word in a string
// INFO : (Support Token Are \t(9)\r(13)\n(10)\f(12)\v(11)\s(32))
func (s *StringProc) UpperCaseFirstWords(str string) string {
	upper := 1
	bufbyteStr := []byte(str)
	retval := make([]byte, len(bufbyteStr))
	for k, v := range bufbyteStr {

		if upper == 1 && v >= 97 && v <= 122 {
			v = v - 32
		}

		upper = 0

		if v >= 9 && v <= 13 || v == 32 {
			upper = 1
		}
		retval[k] = v
	}

	return string(retval)
}

// SwapCaseFirstWords is Switch the first character case of each word in a string
func (s *StringProc) SwapCaseFirstWords(str string) string {
	upper := 1
	bufbyteStr := []byte(str)
	retval := make([]byte, len(bufbyteStr))
	for k, v := range bufbyteStr {

		switch {
		case upper == 1 && v >= 65 && v <= 90:
			v = v + 32

		case upper == 1 && v >= 97 && v <= 122:
			v = v - 32
		}

		upper = 0

		if v >= 9 && v <= 13 || v == 32 {
			upper = 1
		}
		retval[k] = v
	}

	return string(retval)
}

// Unit type control
const (
	_               = uint8(iota)
	LowerCaseSingle // Single Unit character converted to Lower-case
	LowerCaseDouble // Double Unit characters converted to Lower-case

	UpperCaseSingle // Single Unit character converted to Uppper-case
	UpperCaseDouble // Double Unit characters converted to Upper-case

	CamelCaseDouble // Double Unit characters converted to Camel-case
	CamelCaseLong   // Full Unit characters converted to Camel-case
)

var (
	sizeStrLowerCaseSingle = []string{"b", "k", "m", "g", "t", "p", "e", "z", "y"}
	sizeStrLowerCaseDouble = []string{"b", "kb", "mb", "gb", "tb", "pb", "eb", "zb", "yb"}
	sizeStrUpperCaseSingle = []string{"B", "K", "M", "G", "T", "P", "E", "Z", "Y"}
	sizeStrUpperCaseDouble = []string{"B", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"}
	sizeStrCamelCaseDouble = []string{"B", "Kb", "Mb", "Gb", "Tb", "Eb", "Zb", "Yb"}
	sizeStrCamelCaseLong   = []string{"Byte", "KiloByte", "MegaByte", "GigaByte", "TeraByte", "ExaByte", "ZettaByte", "YottaByte"}
)

// HumanByteSize is Byte Size convert to Easy Readable Size String
func (s *StringProc) HumanByteSize(obj interface{}, decimals int, unit uint8) (string, error) {
	if unit < LowerCaseSingle || unit > CamelCaseLong {
		return "", fmt.Errorf("Not allow unit parameter : %v", unit)
	}

	strNum, err := s.numberToString(obj)
	if err != nil {
		return "", err
	}

	var bufStrFloat64 float64

	switch obj.(type) {
	case string:
		bufStrFloat64, err = strconv.ParseFloat(strNum, 64)
		if err != nil {
			return "", fmt.Errorf("Not Support %v (obj.(%v))", obj, reflect.TypeOf(obj))
		}

	case int, int8, int16, int32, int64, uint, uint8, uint16, uint32, uint64, float32:

		float64Type := reflect.TypeOf(float64(0))
		tmpVal := reflect.Indirect(reflect.ValueOf(obj))

		/*
			//impossible?
			if tmpVal.Type().ConvertibleTo(float64Type) == false {
				bufStrFloat64, err = strconv.ParseFloat(reflect.ValueOf(obj).String(), 64)
				if err != nil {
					return "", fmt.Errorf("Not Support %v (obj.(%v))", obj, reflect.TypeOf(obj))
				}

			} else {
				bufStrFloat64 = tmpVal.Convert(float64Type).Float()
			}
		*/

		bufStrFloat64 = tmpVal.Convert(float64Type).Float()

	case float64:
		bufStrFloat64 = obj.(float64)

	default:
		return "", fmt.Errorf("Not Support obj.(%v)", reflect.TypeOf(obj))
	}

	var sizeStr []string

	switch unit {
	case LowerCaseSingle:
		sizeStr = sizeStrLowerCaseSingle
	case LowerCaseDouble:
		sizeStr = sizeStrLowerCaseDouble
	case UpperCaseSingle:
		sizeStr = sizeStrUpperCaseSingle
	case UpperCaseDouble:
		sizeStr = sizeStrUpperCaseDouble
	case CamelCaseDouble:
		sizeStr = sizeStrCamelCaseDouble
	case CamelCaseLong:
		sizeStr = sizeStrCamelCaseLong
	}

	strNumLen := len(strNum)

	factor := int(math.Floor(float64(strNumLen)-1) / 3)

	decimalsFmt := `%.` + strconv.Itoa(decimals) + `f%s`
	humanSize := bufStrFloat64 / math.Pow(1024, float64(factor))

	var unitStr string
	if len(sizeStr) > factor {
		unitStr = sizeStr[factor]
	} else {
		unitStr = "NaN"
	}

	return fmt.Sprintf(decimalsFmt, humanSize, unitStr), nil
}

// HumanFileSize is File Size convert to Easy Readable Size String
func (s *StringProc) HumanFileSize(filepath string, decimals int, unit uint8) (string, error) {
	fd, err := os.Open(filepath)
	if err != nil {
		return "", fmt.Errorf("%v", err)
	}

	defer s.closeFd(fd)

	stat, err := fd.Stat() // impossible?. maybe it can be broken fd after file open. anyway can't make a test case..
	if err != nil {
		return "", fmt.Errorf("%v", err)
	}

	if stat.IsDir() {
		return "", fmt.Errorf("%v isn't file", filepath)
	}

	return s.HumanByteSize(stat.Size(), decimals, unit)
}

// compare with map
var recursiveDepth = 0

var recursiveDepthKeypList = struct {
	sync.RWMutex
	ar []string
}{ar: make([]string, 32)}

func (s *StringProc) compareMap(compObj1 reflect.Value, compObj2 reflect.Value) (bool, error) {
	recursiveDepth++
	var valueCompareErr bool

	for _, k := range compObj1.MapKeys() {

		recursiveDepthKeypList.Lock()
		recursiveDepthKeypList.ar = append(recursiveDepthKeypList.ar, k.String())
		recursiveDepthKeypList.Unlock()

		// check : Type
		if compObj1.MapIndex(k).Kind() != compObj2.MapIndex(k).Kind() {
			return false, fmt.Errorf("Different Type : (obj1[%v] type is `%v`) != (obj2[%v] type is `%v`)", k, compObj1.MapIndex(k).Kind(), k, compObj2.MapIndex(k).Kind())
		}

		switch compObj1.MapIndex(k).Kind() {

		// String
		case reflect.String:
			if compObj1.MapIndex(k).String() != compObj2.MapIndex(k).String() {
				valueCompareErr = true
			}

		// Integer
		case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
			if compObj1.MapIndex(k).Int() != compObj2.MapIndex(k).Int() {
				valueCompareErr = true
			}

		// Un-signed Integer
		case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
			if compObj1.MapIndex(k).Uint() != compObj2.MapIndex(k).Uint() {
				valueCompareErr = true
			}

		// Float
		case reflect.Float32, reflect.Float64:
			if compObj1.MapIndex(k).Float() != compObj2.MapIndex(k).Float() {
				valueCompareErr = true
			}

		// Boolean
		case reflect.Bool:
			if compObj1.MapIndex(k).Bool() != compObj2.MapIndex(k).Bool() {
				valueCompareErr = true
			}

		// Complex
		case reflect.Complex64, reflect.Complex128:
			if compObj1.MapIndex(k).Complex() != compObj2.MapIndex(k).Complex() {
				valueCompareErr = true
			}

		// Map : recursive loop
		case reflect.Map:
			retval, err := s.compareMap(compObj1.MapIndex(k), compObj2.MapIndex(k))
			if !retval {
				return retval, err
			}

		default:
			return false, fmt.Errorf("Not Support Compare : (obj1[%v] := %v) != (obj2[%v] := %v)", k, compObj1.MapIndex(k), k, compObj2.MapIndex(k))
		}

		if valueCompareErr {
			if recursiveDepth == 1 {
				return false, fmt.Errorf("Different Value : (obj1[%v] := %v) != (obj2[%v] := %v)", k, compObj1.MapIndex(k), k, compObj2.MapIndex(k))
			}

			recursiveDepthKeypList.Lock()
			depthStr := strings.Join(recursiveDepthKeypList.ar, "][")
			recursiveDepthKeypList.Unlock()
			return false, fmt.Errorf("Different Value : (obj1[%v] := %v) != (obj2[%v] := %v)", depthStr, compObj1.MapIndex(k).Interface(), depthStr, compObj2.MapIndex(k))

		}
	}

	return true, nil
}

// AnyCompare is compares two same basic type (without prt) dataset (slice,map,single data).
// TODO : support interface, struct ...
// NOTE : Not safe , Not Test Complete. Require more test data based on the complex dataset.
func (s *StringProc) AnyCompare(obj1 interface{}, obj2 interface{}) (bool, error) {
	compObjVal1 := reflect.ValueOf(obj1)
	compObjVal2 := reflect.ValueOf(obj2)

	compObjType1 := reflect.TypeOf(obj1)
	compObjType2 := reflect.TypeOf(obj2)

	if !compObjVal1.IsValid() || !compObjVal2.IsValid() {
		return false, fmt.Errorf("Invalid, obj1(%v) != obj2(%v)", obj1, obj2)
	}

	if compObjType1.Kind() != compObjType2.Kind() {
		return false, fmt.Errorf("Not Compare type, obj1.(%v) != obj2.(%v)", compObjType1.Kind(), compObjType2.Kind())
	}

	recursiveDepthKeypList.Lock()
	recursiveDepthKeypList.ar = make([]string, 0)
	recursiveDepthKeypList.Unlock()

	switch obj1.(type) {

	case string, int, int8, int16, int32, int64, uint, uint8, uint16, uint32, uint64, float32, float64, complex64, complex128, bool:
		if compObjType1.Comparable() && compObjType2.Comparable() {
			return obj1 == obj2, nil
		}

	default:

		switch {

		case compObjVal1.Kind() == reflect.Slice:

			if compObjVal1.Len() != compObjVal2.Len() {
				return false, fmt.Errorf("Different Size : obj1(%d) != obj2(%d)", compObjVal1.Len(), compObjVal2.Len())
			}

			for i := 0; i < compObjVal1.Len(); i++ {
				if compObjVal1.Index(i).Interface() != compObjVal2.Index(i).Interface() {
					return false, fmt.Errorf("Different Value : (obj1[%d] := %v) != (obj2[%d] := %v)", i, compObjVal1.Index(i).Interface(), i, compObjVal2.Index(i).Interface())
				}
			}

		case compObjVal1.Kind() == reflect.Map:
			if compObjVal1.Len() != compObjVal2.Len() {
				return false, fmt.Errorf("Different Size : obj1(%d) != obj2(%d)", compObjVal1.Len(), compObjVal2.Len())
			}

			recursiveDepth = 0
			retval, err := s.compareMap(compObjVal1, compObjVal2)
			if !retval {
				return retval, err
			}

		default:
			return reflect.DeepEqual(obj1, obj2), nil
			// return false, fmt.Errorf("Not Support Compare : (obj1[%v]) , (obj2[%v])", compObjVal1.Kind(), compObjVal2.Kind())

		}
	}
	return true, nil
}

func (s *StringProc) isHex(c byte) bool {
	if (c >= 48 && c <= 57) || (c >= 65 && c <= 70) || (c >= 97 && c <= 102) { // 0~9, a~f, A~F
		return true
	}

	return false
}

func (s *StringProc) unHex(c byte) byte { // from golang. unhex

	switch {
	case '0' <= c && c <= '9':
		return c - '0'
	case 'a' <= c && c <= 'f':
		return c - 'a' + 10
	case 'A' <= c && c <= 'F':
		return c - 'A' + 10
	}

	return 0
}

// DecodeUnicodeEntities Decodes Unicode Entities
func (s *StringProc) DecodeUnicodeEntities(val string) (string, error) {
	var tmpret []byte

	l := len(val)
	for i := 0; i < l; i++ {
		if val[i] == 37 && val[i+1] == 117 && l >= i+6 { // % + u

			var tmpval []byte
			tmpval = append(tmpval, val[i+2], val[i+3], val[i+4], val[i+5])

			runeval, err := strconv.ParseInt(string(tmpval), 16, 64)
			if err != nil {
				return "", err
			}

			tmprune := []byte(string(rune(runeval)))
			tmpret = append(tmpret, tmprune...)
			i += 5 // jump %uXXXX

		} else if val[i] == 37 { // control character or other
			tmpret = append(tmpret, s.unHex(val[i+1])<<4|s.unHex(val[i+2]))
			i += 2
		} else {
			tmpret = append(tmpret, val[i])
		}
	}

	return string(tmpret), nil
}

// DecodeURLEncoded Decodes URL-encoded string (including unicode entities)
// NOTE : golang.url.unescape not support unicode entities (%uXXXX)
func (s *StringProc) DecodeURLEncoded(val string) (string, error) {
	var tmpret []byte

	l := len(val)
	for i := 0; i < l; i++ {

		if l <= i+1 { // panic: runtime error: index out of range
			tmpret = append(tmpret, val[i])
			break
		}

		// 37 = %, 117 = u (UnicodeEntity)
		if val[i] == 37 && val[i+1] != 117 && l >= i+3 && s.isHex(val[i+1]) && s.isHex(val[i+2]) {

			tmpret = append(tmpret, s.unHex(val[i+1])<<4|s.unHex(val[i+2]))
			i += 2
			continue
		}

		if val[i] == 37 && val[i+1] == 117 && l >= i+6 { // % + u

			var tmpval []byte
			tmpval = append(tmpval, val[i+2], val[i+3], val[i+4], val[i+5])

			runeval, err := strconv.ParseInt(string(tmpval), 16, 64)
			if err != nil {
				return "", err
			}

			tmprune := []byte(string(rune(runeval)))
			tmpret = append(tmpret, tmprune...)
			i += 5
			continue
		}

		tmpret = append(tmpret, val[i])
	}

	return string(tmpret), nil
}

// StripTags is remove all tag in string
func (s *StringProc) StripTags(str string) (string, error) {
	var retval bool
	notproccnt := 0

	// looking for html entities code in str
ENTITY_DECODE:

	if notproccnt > 3 {
		goto END
	}

	retval = entityEncodedPattern.MatchString(str)
	if retval {
		str = html.UnescapeString(str)
	}

	// looking for html entities code in str
	retval = urlEncodedPattern.MatchString(str)
	if retval {
		tmpstr, err := url.QueryUnescape(str)
		if err == nil {
			if tmpstr == str {
				notproccnt++
			}

			str = tmpstr
			goto ENTITY_DECODE
		} else {

			// url.QueryUnescape not support UnicodeEntities
			tmpstr, err := s.DecodeURLEncoded(str)
			if err == nil {
				if tmpstr == str {
					notproccnt++
				}
				str = tmpstr
				goto ENTITY_DECODE
			} else {
				return str, err
			}
		}
	}
END:

	// remove tag elements
	cleanedStr := tagElementsPattern.ReplaceAllString(str, "")

	// remove multiple whitespace
	cleanedStr = whiteSpacePattern.ReplaceAllString(cleanedStr, "\n")

	return cleanedStr, nil
}

// ConvertToStr is Convert basic data type to string
func (s *StringProc) ConvertToStr(obj interface{}) (string, error) {
	switch obj.(type) {
	case bool:
		if obj.(bool) {
			return "true", nil
		}
		return "false", nil

	default:
		return s.numberToString(obj)
	}
}

// ConvertToArByte returns Convert basic data type to []byte
func (s *StringProc) ConvertToArByte(obj interface{}) ([]byte, error) {
	switch obj.(type) {

	case bool:
		if obj.(bool) {
			return []byte("true"), nil
		}
		return []byte("false"), nil

		/*
			case byte:
				return []byte{obj.(byte)}, nil
		*/

	case []uint8:
		return reflect.ValueOf(obj).Bytes(), nil

	case string:
		return []byte(obj.(string)), nil

	case int:
		return []byte(strconv.FormatInt(int64(obj.(int)), 10)), nil
	case int8:
		return []byte(strconv.FormatInt(int64(obj.(int8)), 10)), nil
	case int16:
		return []byte(strconv.FormatInt(int64(obj.(int16)), 10)), nil
	case int32:
		return []byte(strconv.FormatInt(int64(obj.(int32)), 10)), nil
	case int64:
		return []byte(strconv.FormatInt(obj.(int64), 10)), nil
	case uint:
		return []byte(strconv.FormatUint(uint64(obj.(uint)), 10)), nil
	case uint8: // same byte
		return []byte(strconv.FormatUint(uint64(obj.(uint8)), 10)), nil
	case uint16:
		return []byte(strconv.FormatUint(uint64(obj.(uint16)), 10)), nil
	case uint32:
		return []byte(strconv.FormatUint(uint64(obj.(uint32)), 10)), nil
	case uint64:
		return []byte(strconv.FormatUint(obj.(uint64), 10)), nil
	case float32:
		return []byte(fmt.Sprintf("%g", obj.(float32))), nil
	case float64:
		return []byte(fmt.Sprintf("%g", obj.(float64))), nil
	case complex64:
		return []byte(fmt.Sprintf("%g", obj.(complex64))), nil
	case complex128:
		return []byte(fmt.Sprintf("%g", obj.(complex128))), nil

	default:
		return nil, fmt.Errorf("not support type(%s)", reflect.TypeOf(obj).String())
	}
}

// ReverseStr is Reverse a String , According to value type between ascii or rune
// TODO : improve performance (use goroutin)
func (s *StringProc) ReverseStr(str string) string {
	/*
	   data : "0123456789" * 100
	   BenchmarkReverseStr-8              	   50000	     34127 ns/op	    5120 B/op	       2 allocs/op
	   BenchmarkReverseNormalStr-8        	 1000000	      1187 ns/op	    2048 B/op	       2 allocs/op
	   BenchmarkReverseReverseUnicode-8   	  100000	     29343 ns/op	    5120 B/op	       2 allocs/op
	*/

	if len(str) != utf8.RuneCountInString(str) {
		return s.ReverseUnicode(str)
	}

	return s.ReverseNormalStr(str)
}

// ReverseNormalStr is Reverse a None-unicode String
func (s *StringProc) ReverseNormalStr(str string) string {
	bufbyteStr := []byte(str)
	bufbyteStrLen := len(bufbyteStr)
	swapSize := int(math.Ceil(float64(bufbyteStrLen) / 2))

	headNo := 0
	tailNo := bufbyteStrLen - 1
	for i := 0; i < swapSize; i++ {
		bufbyteStr[tailNo], bufbyteStr[headNo] = bufbyteStr[headNo], bufbyteStr[tailNo]
		headNo++
		tailNo--
	}

	return string(bufbyteStr[:])
}

// ReverseUnicode is Reverse a unicode String
func (s *StringProc) ReverseUnicode(str string) string {
	bufRuneStr := []rune(str)
	bufRuneStrl := len(bufRuneStr)
	swapSize := int(math.Ceil(float64(bufRuneStrl) / 2))

	headNo := 0
	tailNo := bufRuneStrl - 1
	for i := 0; i < swapSize; i++ {
		bufRuneStr[tailNo], bufRuneStr[headNo] = bufRuneStr[headNo], bufRuneStr[tailNo]
		headNo++
		tailNo--
	}

	return string(bufRuneStr[:])
}

// FileMD5Hash is MD5 checksum of the file
func (s *StringProc) FileMD5Hash(filepath string) (string, error) {
	fd, err := os.Open(filepath)
	if err != nil {
		return "", err
	}

	defer s.closeFd(fd)

	md5Hash := md5.New()
	if _, err := io.Copy(md5Hash, fd); err != nil {
		return "", err
	}

	return hex.EncodeToString(md5Hash.Sum(nil)), nil
}

// MD5Hash is MD5 checksum of the string
func (s *StringProc) MD5Hash(str string) (string, error) {
	md5Hash := md5.New()
	if _, err := io.WriteString(md5Hash, str); err != nil {
		return "", err
	}

	return hex.EncodeToString(md5Hash.Sum(nil)), nil
}

func (s *StringProc) closeFd(fd *os.File) {
	err := fd.Close()
	if err != nil {
		fmt.Printf("Error : %+v\n", err)
	}
}

// RegExpNamedGroups is Captures the text matched by regex into the group name
// NOTE : Not Support the Multiple Groups with The Same Name
func (s *StringProc) RegExpNamedGroups(regex *regexp.Regexp, val string) (map[string]string, error) {
	ok := false
	err := errors.New("not all success patterns were matched")

	retval := map[string]string{}
	extractSubExpNames := regex.SubexpNames()

	ret := regex.FindStringSubmatch(val)
	if len(ret) > 0 {
		for no, val := range ret {
			if no != 0 && val != "" {
				if extractSubExpNames[no] != "" {
					retval[extractSubExpNames[no]] = val
					ok = true
				}
			}
		}
	}

	if ok {
		err = nil
	}

	return retval, err
}


text:
import unittest
from unittest.mock import Mock, patch

import pytest

from streamlink.plugin.plugin import BIT_RATE_WEIGHT_RATIO, LOW_PRIORITY, NORMAL_PRIORITY, NO_PRIORITY
from streamlink.plugins.dash import MPEGDASH
from tests.plugins import PluginCanHandleUrl

class TestPluginCanHandleUrlMPEGDASH(PluginCanHandleUrl):
    __plugin__ = MPEGDASH

    should_match = [
        "example.com/foo.mpd",
        "http://example.com/foo.mpd",
        "https://example.com/foo.mpd",
        "dash://example.com/foo",
        "dash://http://example.com/foo",
        "dash://https://example.com/foo",
    ]

@pytest.mark.parametrize("url,priority", [
    ("http://example.com/foo.mpd", LOW_PRIORITY),
    ("dash://http://example.com/foo.mpd", NORMAL_PRIORITY),
    ("dash://http://example.com/bar", NORMAL_PRIORITY),
    ("http://example.com/bar", NO_PRIORITY),
])
def test_priority(url, priority):
    assert next((matcher.priority for matcher in MPEGDASH.matchers if matcher.pattern.match(url)), NO_PRIORITY) == priority

@pytest.mark.parametrize("url,expected", [
    ("example.com/foo.mpd", "https://example.com/foo.mpd"),
    ("http://example.com/foo.mpd", "http://example.com/foo.mpd"),
    ("https://example.com/foo.mpd", "https://example.com/foo.mpd"),
    ("dash://example.com/foo", "https://example.com/foo"),
    ("dash://http://example.com/foo", "http://example.com/foo"),
    ("dash://https://example.com/foo", "https://example.com/foo"),
])
@patch("streamlink.stream.DASHStream.parse_manifest")
def test_get_streams(parse_manifest, url, expected):
    session = Mock()
    p = MPEGDASH(session, url)
    p.streams()
    parse_manifest.assert_called_with(session, expected)

class TestPluginMPEGDASH(unittest.TestCase):
    def test_stream_weight(self):
        self.assertAlmostEqual(MPEGDASH.stream_weight("720p"), (720, 'pixels'))
        self.assertAlmostEqual(MPEGDASH.stream_weight("1080p"), (1080, 'pixels'))
        self.assertAlmostEqual(MPEGDASH.stream_weight("720p+a128k"), (720 + 128, 'pixels'))
        self.assertAlmostEqual(MPEGDASH.stream_weight("720p+a0k"), (720, 'pixels'))
        self.assertAlmostEqual(MPEGDASH.stream_weight("a128k"), (128 / BIT_RATE_WEIGHT_RATIO, 'bitrate'))


text:
@protocol PicoReadable <NSObject>

// Convert binary data to object of specific class
-(id)fromData:(NSData *)data withClass:(Class)clazz;

// Convert string to object of specific class
-(id)fromString:(NSString *)string withClass:(Class)clazz;

@end


text:
"""
Extended Room

Evennia Contribution - Griatch 2012

This is an extended Room typeclass for Evennia. It is supported
by an extended Look command and an extended @desc command, also
in this module.

Features:

1) Time-changing description slots

This allows to change the full description text the room shows
depending on larger time variations. Four seasons - spring, summer,
autumn and winter are used by default). The season is calculated
on-demand (no Script or timer needed) and updates the full text block.

There is also a general description which is used as fallback if
one or more of the seasonal descriptions are not set when their
time comes.

An updated @desc command allows for setting seasonal descriptions.

The room uses the src.utils.gametime.GameTime global script. This is
started by default, but if you have deactivated it, you need to
supply your own time keeping mechanism.

2) In-description changing tags

Within each seasonal (or general) description text, you can also embed
time-of-day dependent sections. Text inside such a tag will only show
during that particular time of day. The tags looks like <timeslot> ...
</timeslot>. By default there are four timeslots per day - morning,
afternoon, evening and night.

3) Details

The Extended Room can be "detailed" with special keywords. This makes
use of a special Look command. Details are "virtual" targets to look
at, without there having to be a database object created for it. The
Details are simply stored in a dictionary on the room and if the look
command cannot find an object match for a a "look <target>" command it
will also look through the available details at the current location
if applicable. An extended @desc command is used to set details.

4) Extra commands

  CmdExtendedLook - look command supporting room details
  CmdExtendedDesc - @desc command allowing to add seasonal descs and details,
                    as well as listing them
  CmdGameTime     - A simple "time" command, displaying the current time and season.

Installation/testing:

1) Add CmdExtendedLook, CmdExtendedDesc and CmdGameTime to the default cmdset (see wiki how to do this).
2) @dig a room of type contrib.extended_room.ExtendedRoom (or make it the default room type)
3) Use @desc and @detail to customize the room, then play around!

"""

import re
from django.conf import settings
from ev import Room
from ev import gametime
from ev import default_cmds
from ev import utils

# error return function, needed by Extended Look command
_AT_SEARCH_RESULT = utils.variable_from_module(*settings.SEARCH_AT_RESULT.rsplit('.', 1))

# regexes for in-desc replacements
RE_MORNING = re.compile(r"<morning>(.*?)</morning>", re.IGNORECASE)
RE_AFTERNOON = re.compile(r"<afternoon>(.*?)</afternoon>", re.IGNORECASE)
RE_EVENING = re.compile(r"<evening>(.*?)</evening>", re.IGNORECASE)
RE_NIGHT = re.compile(r"<night>(.*?)</night>", re.IGNORECASE)
# this map is just a faster way to select the right regexes (the first
# regex in each tuple will be parsed, the following will always be weeded out)
REGEXMAP = {"morning": (RE_MORNING, RE_AFTERNOON, RE_EVENING, RE_NIGHT),
            "afternoon": (RE_AFTERNOON, RE_MORNING, RE_EVENING, RE_NIGHT),
            "evening": (RE_EVENING, RE_MORNING, RE_AFTERNOON, RE_NIGHT),
            "night": (RE_NIGHT, RE_MORNING, RE_AFTERNOON, RE_EVENING)}

# set up the seasons and time slots. This assumes gametime started at the
# beginning of the year (so month 1 is equivalent to January), and that
# one CAN divive the game's year into four seasons in the first place ...
MONTHS_PER_YEAR = settings.TIME_MONTH_PER_YEAR
SEASONAL_BOUNDARIES = (3/12.0, 6/12.0, 9/12.0)
HOURS_PER_DAY = settings.TIME_HOUR_PER_DAY
DAY_BOUNDARIES = (0, 6/24.0, 12/24.0, 18/24.0)

# implements the Extended Room

class ExtendedRoom(Room):
    """
    This room implements a more advanced look functionality depending on time. It also
    allows for "details", together with a slightly modified look command.
    """
    def at_object_creation(self):
        "Called when room is first created only."
        self.db.spring_desc = ""
        self.db.summer_desc = ""
        self.db.autumn_desc = ""
        self.db.winter_desc = ""
        # the general desc is used as a fallback if a given seasonal one is not set
        self.db.general_desc = ""
        self.db.raw_desc = "" # will be set dynamically. Can contain raw timeslot codes
        self.db.desc = "" # this will be set dynamically at first look. Parsed for timeslot codes
        # these will be filled later
        self.ndb.last_season = None
        self.ndb.last_timeslot = None
        # detail storage
        self.db.details = {}

    def get_time_and_season(self):
        """
        Calcualte the current time and season ids
        """
        # get the current time as parts of year and parts of day
        time = gametime.gametime(format=True) # returns a tuple (years,months,weeks,days,hours,minutes,sec)
        month, hour = time[1], time[4]
        season = float(month) / MONTHS_PER_YEAR
        timeslot = float(hour) / HOURS_PER_DAY

        # figure out which slots these represent
        if SEASONAL_BOUNDARIES[0] <= season < SEASONAL_BOUNDARIES[1]: curr_season = "spring"
        elif SEASONAL_BOUNDARIES[1] <= season < SEASONAL_BOUNDARIES[2]: curr_season = "summer"
        elif SEASONAL_BOUNDARIES[2] <= season < 1.0 + SEASONAL_BOUNDARIES[0]: curr_season = "autumn"
        else: curr_season = "winter"

        if DAY_BOUNDARIES[0] <= timeslot < DAY_BOUNDARIES[1]: curr_timeslot = "night"
        elif DAY_BOUNDARIES[1] <= timeslot < DAY_BOUNDARIES[2]: curr_timeslot = "morning"
        elif DAY_BOUNDARIES[2] <= timeslot < DAY_BOUNDARIES[3]: curr_timeslot = "afternoon"
        else: curr_timeslot = "evening"

        return curr_season, curr_timeslot

    def replace_timeslots(self, raw_desc, curr_time):
        """
        Filter so that only time markers <timeslot>...</timeslot> of the correct timeslot
        remains in the description.
        """
        if raw_desc:
            regextuple = REGEXMAP[curr_time]
            raw_desc = regextuple[0].sub(r"\1", raw_desc)
            raw_desc = regextuple[1].sub("", raw_desc)
            raw_desc = regextuple[2].sub("", raw_desc)
            return regextuple[3].sub("", raw_desc)
        return raw_desc

    def return_detail(self, key):
        """
        This will attempt to match a "detail" to look for in the room. A detail
        is a way to offer more things to look at in a room without having to
        add new objects. For this to work, we require a custom look command that
        allows for "look <detail>" - the look command should defer to this method
        on the current location (if it exists) before giving up on finding the target.

        Details are not season-sensitive, but are parsed for timeslot markers.
        """
        try:
            detail = self.db.details.get(key.lower(), None)
        except AttributeError:
            # this happens if no attribute details is set at all
            return None
        if detail:
            season, timeslot = self.get_time_and_season()
            detail = self.replace_timeslots(detail, timeslot)
            return detail
        return None

    def return_appearance(self, looker):
        "This is called when e.g. the look command wants to retrieve the description of this object."
        raw_desc = self.db.raw_desc or ""
        update = False

        # get current time and season
        curr_season, curr_timeslot = self.get_time_and_season()

        # compare with previously stored slots
        last_season = self.ndb.last_season
        last_timeslot = self.ndb.last_timeslot

        if curr_season != last_season:
            # season changed. Load new desc, or a fallback.
            if curr_season == 'spring': new_raw_desc = self.db.spring_desc
            elif curr_season == 'summer': new_raw_desc = self.db.summer_desc
            elif curr_season == 'autumn': new_raw_desc = self.db.autumn_desc
            else: new_raw_desc = self.db.winter_desc
            if new_raw_desc:
                raw_desc = new_raw_desc
            else:
                # no seasonal desc set. Use fallback
                raw_desc = self.db.general_desc or self.db.desc
            self.db.raw_desc = raw_desc
            self.ndb.last_season = curr_season
            update = True

        if curr_timeslot != last_timeslot:
            # timeslot changed. Set update flag.
            self.ndb.last_timeslot = curr_timeslot
            update = True

        if update:
            # if anything changed we have to re-parse the raw_desc for time markers
            # and re-save the description again.
            self.db.desc = self.replace_timeslots(self.db.raw_desc, curr_timeslot)
        # run the normal return_appearance method, now that desc is updated.
        return super(ExtendedRoom, self).return_appearance(looker)

# Custom Look command supporting Room details. Add this to the Default cmdset to use.

class CmdExtendedLook(default_cmds.CmdLook):
    """
    look

    Usage:
      look
      look <obj>
      look <room detail>
      look *<player>

    Observes your location, details at your location or objects in your vicinity.
    """
    def func(self):
        """
        Handle the looking - add fallback to details.
        """
        caller = self.caller
        args = self.args
        if args:
            looking_at_obj = caller.search(args, use_nicks=True, ignore_errors=True)
            if not looking_at_obj:
                # no object found. Check if there is a matching detail at location.
                location = caller.location
                if location and hasattr(location, "return_detail") and callable(location.return_detail):
                    detail = location.return_detail(args)
                    if detail:
                        # we found a detail instead. Show that.
                        caller.msg(detail)
                        return
                # no detail found. Trigger delayed error messages
                _AT_SEARCH_RESULT(caller, args, looking_at_obj, False)
                return
            else:
                # we need to extract the match manually.
                looking_at_obj = utils.make_iter(looking_at_obj)[0]
        else:
            looking_at_obj = caller.location
            if not looking_at_obj:
                caller.msg("You have no location to look at!")
                return

        if not hasattr(looking_at_obj, 'return_appearance'):
            # this is likely due to us having a player instead
            looking_at_obj = looking_at_obj.character
        if not looking_at_obj.access(caller, "view"):
            caller.msg("Could not find '%s'." % args)
            return
        # get object's appearance
        caller.msg(looking_at_obj.return_appearance(caller))
        # the object's at_desc() method.
        looking_at_obj.at_desc(looker=caller)

# Custom build commands for setting seasonal descriptions and detailing extended rooms.

class CmdExtendedDesc(default_cmds.CmdDesc):
    """
    @desc - describe an object or room

    Usage:
      @desc[/switch] [<obj> =] <description>
      @detail[/del] [<key> = <description>]

    Switches for @desc:
      spring  - set description for <season> in current room
      summer
      autumn
      winter

    Switch for @detail:
      del   - delete a named detail

    Sets the "desc" attribute on an object. If an object is not given,
    describe the current room.

    The alias @detail allows to assign a "detail" (a non-object
    target for the look command) to the current room (only).

    You can also embed special time markers in your room description, like this:
      <night>In the darkness, the forest looks foreboding.</night>. Text
    marked this way will only display when the server is truly at the given
    time slot. The available times
    are night, morning, afternoon and evening.

    Note that @detail, seasons and time-of-day slots only works on rooms in this
    version of the @desc command.

    """
    aliases = ["@describe", "@detail"]

    def reset_times(self, obj):
        "By deleteting the caches we force a re-load."
        obj.ndb.last_season = None
        obj.ndb.last_timeslot = None

    def func(self):
        "Define extended command"
        caller = self.caller
        location = caller.location
        if self.cmdstring == '@detail':
            # switch to detailing mode. This operates only on current location
            if not location:
                caller.msg("No location to detail!")
                return
            if not self.rhs:
                # no '=' used - list content of given detail
                if self.args in location.db.details:
                    string = "{wDetail '%s' on %s:\n{n" % (self.args, location)
                    string += location.db.details[self.args]
                    caller.msg(string)
                    return
            if not self.args:
                # No args given. Return all details on location
                string = "{wDetails on %s{n:\n" % location
                string += "\n".join(" {w%s{n: %s" % (key, utils.crop(text)) for key, text in location.db.details.items())
                caller.msg(string)
                return
            if self.switches and self.switches[0] in 'del':
                # removing a detail.
                if self.lhs in location.db.details:
                    del location.db.detail
                caller.msg("Detail %s deleted, if it existed." % self.lhs)
                self.reset_times(location)
                return
            # setting a detail
            location.db.details[self.lhs] = self.rhs
            caller.msg("Set Detail %s to '%s'." % (self.lhs, self.rhs))
            self.reset_times(location)
            return
        else:
            # we are doing a @desc call
            if not self.args:
                if location:
                    string = "{wDescriptions on %s{n:\n" % location.key
                    string += " {wspring:{n %s\n" % location.db.spring_desc
                    string += " {wsummer:{n %s\n" % location.db.summer_desc
                    string += " {wautumn:{n %s\n" % location.db.autumn_desc
                    string += " {wwinter:{n %s\n" % location.db.winter_desc
                    string += " {wgeneral:{n %s" % location.db.general_desc
                    caller.msg(string)
                    return
            if self.switches and self.switches[0] in ("spring", "summer", "autumn", "winter"):
                # a seasonal switch was given
                if self.rhs:
                    caller.msg("Seasonal descs only works with rooms, not objects.")
                    return
                switch = self.switches[0]
                if not location:
                    caller.msg("No location was found!")
                    return
                if switch == 'spring': location.db.spring_desc = self.args
                elif switch == 'summer': location.db.summer_desc = self.args
                elif switch == 'autumn': location.db.autumn_desc = self.args
                elif switch == 'winter': location.db.winter_desc = self.args
                # clear flag to force an update
                self.reset_times(location)
                caller.msg("Seasonal description was set on %s." % location.key)
            else:
                # Not seasonal desc set, maybe this is not an extended room
                if self.rhs:
                    text = self.rhs
                    obj = caller.search(self.lhs)
                    if not obj:
                        return
                else:
                    text = self.args
                    obj = location
                obj.db.desc = self.rhs # this is set as a compatability fallback
                if utils.inherits_from(obj, ExtendedRoom):
                    # this is an extendedroom, we need to reset times and set general_desc
                    obj.db.general_desc = text
                    self.reset_times(obj)
                    caller.msg("General description was set on %s." % obj.key)
                else:
                    caller.msg("The description was set on %s." % obj.key)

# Simple command to view the current time and season

class CmdGameTime(default_cmds.MuxCommand):
    """
    Check the game time

    Usage:
      time

    Shows the current in-game time and season.
    """
    key = "time"
    locks = "cmd:all()"
    help_category = "General"

    def func(self):
        "Reads time info from current room"
        location = self.caller.location
        if not location or not hasattr(location, "get_time_and_season"):
            self.caller.msg("No location available - you are outside time.")
        else:
            season, timeslot = location.get_time_and_season()
            prep = "a"
            if season == "autumn":
                prep = "an"
            self.caller.msg("It's %s %s day, in the %s." % (prep, season, timeslot))


text:
from .parser import parse_all, parse

__all__ = ['parse_all', 'parse']


text:
@interface HSTableViewHeaderCell ()

@property (nonatomic, strong, readwrite) UILabel *titleLabel;

@end

@implementation HSTableViewHeaderCell

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];

    if (self) {
        float leftPadding = 15.0;
        if ([HSAppearance isIOS6]) {
            leftPadding = 10.0;
        }

        UILabel *headerTitle = [[UILabel alloc] initWithFrame:CGRectMake(leftPadding, 0, 200.0, 30.0)];
        [self addSubview:headerTitle];
        self.titleLabel = headerTitle;
        // Initialization code
        [self refreshCellProperties];
    }

    return self;
}

- (void)refreshCellProperties
{
    [[[HSHelpStack instance] appearance] customizeTableHeader:self];
    [[[HSHelpStack instance] appearance] customizeHeaderTitle:self.titleLabel];
}

@end


text:
{{ site.title }}

      {{ site.tagline }}

      <a class="sidebar-nav-item{% if page.url == site.baseurl %} active{% endif %}"

      {% comment %}
        The code below dynamically generates a sidebar nav of pages with
        `layout: page` in the front-matter. See readme for usage.
      {% endcomment %}

      {% assign pages_list = site.pages %}
      {% for node in pages_list %}
        {% if node.title != null %}
          {% if node.layout == "page" %}
            {{ node.title }}
          {% endif %}
        {% endif %}
      {% endfor %}

 |  |

credits

 {{ site.time | date: '%Y' }} {{ site.author.name }}

 -BY-SA


text:
from __future__ import unicode_literals

def get_jenv():
	import frappe

	if not getattr(frappe.local, 'jenv', None):
		from jinja2 import Environment, DebugUndefined

		# frappe will be loaded last, so app templates will get precedence
		jenv = Environment(loader = get_jloader(),
			undefined=DebugUndefined)
		set_filters(jenv)

		jenv.globals.update(get_allowed_functions_for_jenv())

		frappe.local.jenv = jenv

	return frappe.local.jenv

def get_template(path):
	return get_jenv().get_template(path)

def validate_template(html):
	"""Throws exception if there is a syntax error in the Jinja Template"""
	import frappe
	from jinja2 import TemplateSyntaxError

	jenv = get_jenv()
	try:
		jenv.from_string(html)
	except TemplateSyntaxError, e:
		frappe.msgprint('Line {}: {}'.format(e.lineno, e.message))
		frappe.throw(frappe._("Syntax error in template"))

def render_template(template, context, is_path=None):
	'''Render a template using Jinja

	:param template: path or HTML containing the jinja template
	:param context: dict of properties to pass to the template
	:param is_path: (optional) assert that the `template` parameter is a path'''

	# if it ends with .html then its a freaking path, not html
	if (is_path
		or template.startswith("templates/")
		or (template.endswith('.html') and '\n' not in template)):
		return get_jenv().get_template(template).render(context)
	else:
		return get_jenv().from_string(template).render(context)

def get_allowed_functions_for_jenv():
	import os
	import frappe
	import frappe.utils
	import frappe.utils.data
	from frappe.utils.autodoc import automodule, get_version
	from frappe.model.document import get_controller
	from frappe.website.utils import get_shade
	from frappe.modules import scrub
	import mimetypes

	datautils = {}
	for key, obj in frappe.utils.data.__dict__.items():
		if key.startswith("_"):
			# ignore
			continue

		if hasattr(obj, "__call__"):
			# only allow functions
			datautils[key] = obj

	if "_" in getattr(frappe.local, 'form_dict', {}):
		del frappe.local.form_dict["_"]

	out = {
		# make available limited methods of frappe
		"frappe": {
			"_": frappe._,
			"get_url": frappe.utils.get_url,
			"format_value": frappe.format_value,
			"format_date": frappe.utils.data.global_date_format,
			"form_dict": getattr(frappe.local, 'form_dict', {}),
			"local": frappe.local,
			"get_hooks": frappe.get_hooks,
			"get_meta": frappe.get_meta,
			"get_doc": frappe.get_doc,
			"get_list": frappe.get_list,
			"get_all": frappe.get_all,
			"utils": datautils,
			"user": getattr(frappe.local, "session", None) and frappe.local.session.user or "Guest",
			"get_fullname": frappe.utils.get_fullname,
			"get_gravatar": frappe.utils.get_gravatar_url,
			"full_name": getattr(frappe.local, "session", None) and frappe.local.session.data.full_name or "Guest",
			"render_template": frappe.render_template
		},
		"autodoc": {
			"get_version": get_version,
			"automodule": automodule,
			"get_controller": get_controller
		},
		"_": frappe._,
		"get_shade": get_shade,
		"scrub": scrub,
		"guess_mimetype": mimetypes.guess_type,
		"dev_server": 1 if os.environ.get('DEV_SERVER', False) else 0
	}

	if not frappe.flags.in_setup_help:
		out['get_visible_columns'] = frappe.get_attr("frappe.www.print.get_visible_columns")
		out['frappe']['date_format'] = frappe.db.get_default("date_format") or "yyyy-mm-dd"
		out['frappe']["db"] = {
			"get_value": frappe.db.get_value,
			"get_default": frappe.db.get_default,
		}

	return out

def get_jloader():
	import frappe
	if not getattr(frappe.local, 'jloader', None):
		from jinja2 import ChoiceLoader, PackageLoader, PrefixLoader

		if frappe.local.flags.in_setup_help:
			apps = ['frappe']
		else:
			apps = frappe.local.flags.web_pages_apps or frappe.get_installed_apps(sort=True)
			apps.reverse()

		if not "frappe" in apps:
			apps.append('frappe')

		frappe.local.jloader = ChoiceLoader(
			# search for something like app/templates/...
			[PrefixLoader(dict(
				(app, PackageLoader(app, ".")) for app in apps
			))]

			# search for something like templates/...
			+ [PackageLoader(app, ".") for app in apps]
		)

	return frappe.local.jloader

def set_filters(jenv):
	import frappe
	from frappe.utils import global_date_format, cint, cstr, flt, markdown
	from frappe.website.utils import get_shade, abs_url

	jenv.filters["global_date_format"] = global_date_format
	jenv.filters["markdown"] = markdown
	jenv.filters["json"] = frappe.as_json
	jenv.filters["get_shade"] = get_shade
	jenv.filters["len"] = len
	jenv.filters["int"] = cint
	jenv.filters["str"] = cstr
	jenv.filters["flt"] = flt
	jenv.filters["abs_url"] = abs_url

	if frappe.flags.in_setup_help: return

	# load jenv_filters from hooks.py
	for app in frappe.get_installed_apps():
		for jenv_filter in (frappe.get_hooks(app_name=app).jenv_filter or []):
			filter_name, filter_function = jenv_filter.split(":")
			jenv.filters[filter_name] = frappe.get_attr(filter_function)


text:
<?xml version="1.0" encoding="UTF-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="@dimen/nav_header_height"
    android:gravity="bottom"
    android:orientation="vertical"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:theme="@style/ThemeOverlay.AppCompat.Dark">

    <ImageView
        android:id="@+id/MyProfile"
        android:layout_width="64dp"
        android:layout_height="64dp"
        android:src="@drawable/ic_account_circle_black_48dp" />

    <TextView
        android:id="@+id/MyName"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:paddingTop="@dimen/nav_header_vertical_spacing"
        android:text="양성민"
        android:textAppearance="@style/TextAppearance.AppCompat.Body1" />

    <TextView
        android:id="@+id/MyEmail"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="ysm0622@gmail.com" />

</LinearLayout>


text:
#import <CorePDF/CPShape.h>

@interface CPShape (Additions)
- (id)initWithPDFShape:(struct CPPDFShape *)arg1;
@end


text:
package org.greencheek.spray.cache.memcached.clientbuilder.elasticache.configparsing

import org.greencheek.spray.cache.memcached.clientbuilder.elasticache.ElastiCacheHost
import org.junit.runner.RunWith
import org.specs2.mutable.Specification
import org.specs2.runner.JUnitRunner

/**
 * Created by dominictootell on 22/07/2014.
 */
@RunWith(classOf[JUnitRunner])
class ElastiCacheConfigParserSpec extends Specification {

  "Given two host, with ips, they should both be parsed" in {
    val exampleHosts : String = "myCluster.pc4ldq.0001.use1.cache.amazonaws.com|10.82.235.120|11211 myCluster.pc4ldq.0002.use1.cache.amazonaws.com|10.80.249.27|11211\n\r\n";

    val hosts : Seq[ElastiCacheHost] =  DefaultElastiCacheConfigParser.parseServers(exampleHosts)

    hosts.size should be equalTo(2)
    hosts(0).hasIP should beTrue
    hosts(1).hasIP should beTrue

    hosts(0).hostName must beEqualTo("myCluster.pc4ldq.0001.use1.cache.amazonaws.com")
    hosts(0).ip must beEqualTo("10.82.235.120")
    hosts(0).port must beEqualTo(11211)

    hosts(1).hostName must beEqualTo("myCluster.pc4ldq.0002.use1.cache.amazonaws.com")
    hosts(1).ip must beEqualTo("10.80.249.27")
    hosts(1).port must beEqualTo(11211)

  }

  "Given two host, one with an ip, they should both be parsed" in {
    val exampleHosts : String = "myCluster.pc4ldq.0001.use1.cache.amazonaws.com|10.82.235.120|11211 myCluster.pc4ldq.0002.use1.cache.amazonaws.com||11212\n\r\n";

    val hosts : Seq[ElastiCacheHost] =  DefaultElastiCacheConfigParser.parseServers(exampleHosts)

    hosts.size should be equalTo(2)
    hosts(0).hasIP should beTrue
    hosts(1).hasIP should beFalse

    hosts(0).hostName must beEqualTo("myCluster.pc4ldq.0001.use1.cache.amazonaws.com")
    hosts(0).ip must beEqualTo("10.82.235.120")
    hosts(0).port must beEqualTo(11211)

    hosts(1).hostName must beEqualTo("myCluster.pc4ldq.0002.use1.cache.amazonaws.com")
    hosts(1).ip must beEqualTo("")
    hosts(1).port must beEqualTo(11212)

  }

  "Given two host, one no ips, they should both be parsed" in {
    val exampleHosts : String = "myCluster.pc4ldq.0001.use1.cache.amazonaws.com\r\n||11211 myCluster.pc4ldq.0002.use1.cache.amazonaws.com||11212\n\r\n";

    val hosts : Seq[ElastiCacheHost] =  DefaultElastiCacheConfigParser.parseServers(exampleHosts)

    hosts.size should be equalTo(2)
    hosts(0).hasIP should beFalse
    hosts(1).hasIP should beFalse

    hosts(0).hostName must beEqualTo("myCluster.pc4ldq.0001.use1.cache.amazonaws.com")
    hosts(0).ip must beEqualTo("")
    hosts(0).port must beEqualTo(11211)

    hosts(1).hostName must beEqualTo("myCluster.pc4ldq.0002.use1.cache.amazonaws.com")
    hosts(1).ip must beEqualTo("")
    hosts(1).port must beEqualTo(11212)

  }

  "Given 5 hosts they should all be parsed" in {
    val exampleHosts : String = "myCluster.pc4ldq.0001.use1.cache.amazonaws.com\r\n||11211 myCluster.pc4ldq.0002.use1.cache.amazonaws.com||11212\n\r\n myCluster.pc4ldq.0001.use1.cache.amazonaws.com\r\n||11211 myCluster.pc4ldq.0001.use1.cache.amazonaws.com\r\n||11211 myCluster.pc4ldq.0001.use1.cache.amazonaws.com\r\n||11211 ";

    val hosts : Seq[ElastiCacheHost] =  DefaultElastiCacheConfigParser.parseServers(exampleHosts)

    hosts.size should be equalTo(5)
    hosts(0).hasIP should beFalse
    hosts(1).hasIP should beFalse

    hosts(0).hostName must beEqualTo("myCluster.pc4ldq.0001.use1.cache.amazonaws.com")
    hosts(0).ip must beEqualTo("")
    hosts(0).port must beEqualTo(11211)

    hosts(1).hostName must beEqualTo("myCluster.pc4ldq.0002.use1.cache.amazonaws.com")
    hosts(1).ip must beEqualTo("")
    hosts(1).port must beEqualTo(11212)

  }
}


text:
package org.eclipse.jnosql.artemis.document;

import jakarta.nosql.document.DocumentCollectionManager;
import jakarta.nosql.mapping.Converters;
import jakarta.nosql.mapping.document.DocumentEntityConverter;
import jakarta.nosql.mapping.document.DocumentEventPersistManager;
import jakarta.nosql.mapping.document.DocumentWorkflow;
import jakarta.nosql.mapping.reflection.ClassMappings;

import javax.enterprise.inject.Instance;
import javax.inject.Inject;

/**
 * The default implementation of {@link jakarta.nosql.mapping.document.DocumentTemplate}
 */
@SuppressWarnings("unchecked")
class DefaultDocumentTemplate extends AbstractDocumentTemplate {

    private DocumentEntityConverter converter;

    private Instance<DocumentCollectionManager> manager;

    private DocumentWorkflow workflow;

    private DocumentEventPersistManager persistManager;

    private ClassMappings classMappings;

    private Converters converters;

    @Inject
    DefaultDocumentTemplate(DocumentEntityConverter converter, Instance<DocumentCollectionManager> manager,
                            DocumentWorkflow workflow, DocumentEventPersistManager persistManager,
                            ClassMappings classMappings, Converters converters) {
        this.converter = converter;
        this.manager = manager;
        this.workflow = workflow;
        this.persistManager = persistManager;
        this.classMappings = classMappings;
        this.converters = converters;
    }

    DefaultDocumentTemplate() {
    }

    @Override
    protected DocumentEntityConverter getConverter() {
        return converter;
    }

    @Override
    protected DocumentCollectionManager getManager() {
        return manager.get();
    }

    @Override
    protected DocumentWorkflow getWorkflow() {
        return workflow;
    }

    @Override
    protected DocumentEventPersistManager getPersistManager() {
        return persistManager;
    }

    @Override
    protected ClassMappings getClassMappings() {
        return classMappings;
    }

    @Override
    protected Converters getConverters() {
        return converters;
    }

}


text:
/// <reference no-default-lib="true"/>

interface Symbol {
    /**
     * expose the [[Description]] internal slot of a symbol directly
     */
    readonly description: string;
}


text:
Unit::Unit(Platform& platform, ParameterRepository& params, Communicator& communicator)
  : data(platform, params, communicator) {
}

VehicleSystem& Unit::getSystem() {
  return data.system;
}


text:
package com.everythingisreally.objects.stars;

import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.math.MathUtils;

/**
 * Created by fen on 3/22/16.
 */
public class GreenStar extends Star {
    private int w = 19;
    private int h = 19;
    private int x_coord = MathUtils.random(200, 600); // Green Stars only appear in the middle of screen
    private int y_coord = 1150;
    private double nutrients = 2;
    private Texture image = new Texture(Gdx.files.internal("small_star.png")); // change to green Star

    public GreenStar(float x, float y, float width, float height, Texture starImage) {
        super(x, y, width, height, starImage);
    }
    public GreenStar(){
        this.x = x_coord;
        this.y = y_coord;
        this.width = w;
        this.height = h;
        this.setStarImage(image);
        this.setNutrients(nutrients);
    }

}


text:
import PropTypes from 'prop-types';
import React from 'react';
import focusTrap from 'focus-trap';

/* eslint-disable jsx-a11y/no-static-element-interactions */

const bodyActiveClass = 'u-body-modal-active';

function stopPropagation(event) {
    event.stopPropagation();
}

const propTypes = {
    children: PropTypes.node.isRequired,
    isOpen: PropTypes.bool.isRequired,
    onRequestClose: PropTypes.func,
    onAfterOpen: PropTypes.func,
    onAfterClose: PropTypes.func,
    overlayClick: PropTypes.bool,
    label: PropTypes.string,
    className: PropTypes.string,
    controls: PropTypes.object,
    insideControls: PropTypes.bool,
    ariaHideApp: PropTypes.bool,
};

const defaultProps = {
    ariaHideApp: true,
    onRequestClose: null,
    onAfterOpen: null,
    onAfterClose: null,
    overlayClick: true,
    className: '',
    label: null,
    controls: null,
    insideControls: false,
};

class Modal extends React.Component {
    constructor(props) {
        super(props);

        this.state = {
            // afterOpen: false,
            beforeClose: false,
        };

        this.afterClose = this.afterClose.bind(this);
        this.afterOpen = this.afterOpen.bind(this);
        this.cleanup = this.cleanup.bind(this);
        this.close = this.close.bind(this);
        this.handleClose = this.handleClose.bind(this);
        this.handleEnterKeyDown = this.handleEnterKeyDown.bind(this);
        this.handleEscapeKeyDown = this.handleEscapeKeyDown.bind(this);
        this.handleOverlayClick = this.handleOverlayClick.bind(this);
        this.open = this.open.bind(this);
        this.requestClose = this.requestClose.bind(this);
        this.setAriaHidden = this.setAriaHidden.bind(this);
        this.setFocusTrap = this.setFocusTrap.bind(this);
        this.shouldBeClosed = this.shouldBeClosed.bind(this);
    }

    componentDidMount() {
        const { isOpen } = this.props;

        // Focus needs to be set when mounting and already open
        if (isOpen) {
            this.open();
        }
    }

    componentWillReceiveProps(newProps) {
        const { isOpen } = this.props;

        if (isOpen && !newProps.isOpen) {
            this.handleClose();
        }
    }

    componentDidUpdate(prevProps) {
        const { isOpen } = this.props;

        // Focus only needs to be set once when the modal is being opened
        if (!prevProps.isOpen && isOpen) {
            this.open();
        }
    }

    componentWillUnmount() {
        const { isOpen } = this.props;

        if (isOpen) {
            this.cleanup();
        }
    }

    open() {
        document.body.classList.add(bodyActiveClass);

        this.modalRef.addEventListener('animationend', this.afterOpen);
    }

    afterOpen(e) {
        this.closeButton = this.modalRef.querySelector('.modal__close');

        // make sure we're listening to the modals animationEvent
        if (e) {
            const target = e.target || e.srcElement;
            if (target !== this.modalRef) {
                return;
            }
        }

        this.setAriaHidden(false);
        this.setFocusTrap();

        this.modalRef.removeEventListener('animationend', this.afterOpen);

        this.setState({ afterOpen: true }, () => {
            window.addEventListener('keydown', this.handleEscapeKeyDown);
            this.closeButton.addEventListener('keydown', this.handleEnterKeyDown);
            if (this.props.onAfterOpen) {
                this.props.onAfterOpen();
            }
        });
    }

    requestClose() {
        const { onRequestClose } = this.props;

        if (onRequestClose) {
            onRequestClose();
        }
    }

    handleClose() {
        const { onRequestClose } = this.props;

        document.body.classList.remove(bodyActiveClass);

        if (!onRequestClose) {
            return;
        }

        this.modalRef.addEventListener('animationend', this.close);
        this.modalRef.classList.remove('modal--active');
        this.modalRef.classList.add('modal--exit');
        this.setState({
            beforeClose: true,
        });
    }

    close(e) {
        // make sure we're listening to the modals animationEvent
        if (e) {
            const target = e.target || e.srcElement;
            if (target !== this.modalRef) {
                return;
            }
        }

        this.setAriaHidden(true);

        this.modalRef.removeEventListener('animationend', this.close);

        this.setState({
            afterOpen: false,
            beforeClose: false,
        }, this.afterClose);
    }

    cleanup() {
        document.body.classList.remove(bodyActiveClass);
        focusTrap.deactivate(this.modalRef);
        window.removeEventListener('keydown', this.handleEscapeKeyDown);
        this.closeButton.removeEventListener('keydown', this.handleEnterKeyDown);
    }

    afterClose() {
        const { onAfterClose } = this.props;
        this.cleanup();

        if (onAfterClose) {
            onAfterClose();
        }
    }

    handleEscapeKeyDown(e) {
        // ESC key
        if (e.keyCode === 27) {
            this.requestClose();
        }
    }

    handleEnterKeyDown(e) {
        // Enter key
        if (e.keyCode === 13) {
            this.requestClose();
        }
    }

    handleOverlayClick() {
        const { overlayClick } = this.props;
        if (!overlayClick) {
            return;
        }

        this.requestClose();
    }

    shouldBeClosed() {
        return !this.props.isOpen && !this.state.beforeClose;
    }

    setAriaHidden(isHidden) {
        const { ariaHideApp } = this.props;

        if (!ariaHideApp) {
            return;
        }

        if (!this.contentRef) {
            return;
        }

        this.contentRef.setAttribute('aria-hidden', isHidden);

        const mainContent = document.querySelector('[data-main-content]');
        if (mainContent) {
            mainContent.setAttribute('aria-hidden', !isHidden);
        }
    }

    setFocusTrap() {
        if (!this.contentRef) {
            return;
        }

        focusTrap.activate(this.modalRef, {
            initialFocus: this.contentRef,
            clickOutsideDeactivates: true,
            returnFocusOnDeactivate: true,
        });
    }

    render() {
        const { className, children, controls, label, insideControls } = this.props;
        let controlsMarkup;

        if (controls) {
            controlsMarkup = controls;
        } else {
            controlsMarkup = (
                <div className={`modal__control${insideControls ? ' modal__control--inside' : ''}`}>

                        ×

            );
        }

        return this.shouldBeClosed() ? null : (
            <div
                className={`modal modal--active ${className}`}
                ref={(elt) => { this.modalRef = elt; }}
            >

 { this.contentRef = elt; }}
                            className="modal__content"
                            onClick={stopPropagation}
                            aria-label={label}
                            aria-hidden="true"
                            role="dialog"
                        >
                            {children}

                            {insideControls && controlsMarkup}

                {!insideControls && controlsMarkup}

        );
    }
}

Modal.propTypes = propTypes;

Modal.defaultProps = defaultProps;

export default Modal;


text:
package com.docuware.dev.schema._public.services.platform;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlType;

@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "CountResultItem")
public class CountResultItem  {

    @XmlAttribute(name = "Name", required = true)
    protected String name;
    @XmlAttribute(name = "Count", required = true)
    protected int count;

    /**Name of the item that is counted*/
    public String getName() {
        return name;
    }

    /**Name of the item that is counted*/
    public void setName(String value) {
        this.name = value;
    }

    /**The items count*/
    public int getCount() {
        return count;
    }

    /**The items count*/
    public void setCount(int value) {
        this.count = value;
    }

}


text:
'use strict';

var fs = require('fs');
var path = require('path');

var _ = require('lodash');
var chalk = require('chalk');
var yaml = require('js-yaml');
var resolve = require('resolve');
var argv = require('optimist').argv;

var NODE_ENV = process.env.NODE_ENV;
var CONFIG_BASEDIR = process.env.CONFIG_BASEDIR || process.env.NODE_CONFIG_BASEDIR;
var CONFIG_DIR = process.env.CONFIG_DIR || process.env.NODE_CONFIG_DIR;
var CONFIG = _.assign({}, JSON.parse(process.env.CONFIG || process.env.NODE_CONFIG || '{}'), _.omit(argv, '_', '$0'));

module.exports = function configLite(customOpt) {
  var config = {};
  if (!_.isPlainObject(customOpt)) {
    if (customOpt && _.isString(customOpt)) {
      customOpt = { config_basedir: customOpt };
    } else {
      throw new TypeError('config-lite custom option should be a string or an object');
    }
  }
  var opt = {
    filename: NODE_ENV || customOpt.filename || 'default',
    config_basedir: CONFIG_BASEDIR || customOpt.config_basedir,
    config_dir: CONFIG_DIR || customOpt.config_dir || 'config'
  };

  if (opt.filename !== 'default') {
    try {
      config = loadConfigFile(opt.filename, opt);
    } catch (e) {
      console.error(chalk.red('config-lite load "' + opt.filename + '" failed.'));
      console.error(chalk.red(e.stack));
    }
  }

  try {
    config = _.assign({}, loadConfigFile('default', opt), config);
  } catch (e) {
    console.error(chalk.red('config-lite load "default" failed.'));
    console.error(chalk.red(e.stack));
  }
  return _.assign({}, config, customOpt.config, CONFIG);
}

function loadConfigFile(filename, opt) {
  var filepath = resolve.sync(filename, {
    basedir: opt.config_basedir,
    extensions: ['.js', '.json', '.node', '.yaml', '.yml'],
    moduleDirectory: opt.config_dir
  });
  if (/\.ya?ml$/.test(filepath)) {
    return yaml.safeLoad(fs.readFileSync(filepath , 'utf8'));
  } else {
    return require(filepath);
  }
}


text:
FROM sequenceiq/hadoop-docker:2.6.0
MAINTAINER medale

# automatically untars spark-1.3.1 at /usr/local
ADD spark-1.3.1-bin-hadoop2.6.tgz /usr/local/
RUN cd /usr/local && ln -s spark-1.3.1-bin-hadoop2.6 spark
ENV SPARK_HOME /usr/local/spark
ADD log4j.properties /usr/local/spark/conf/

# Upload sample files and jar file
ADD enron-small.avro /root/
ADD mailrecord-utils-1.0.0-shaded.jar /root/
ADD log4j.properties /root/
ADD start-spark.sh /root/
RUN chmod +x /root/start-spark.sh

# Copy spark libs and enron email to HDFS
RUN $BOOTSTRAP && $HADOOP_PREFIX/bin/hadoop dfsadmin -safemode leave && $HADOOP_PREFIX/bin/hdfs dfs -put $SPARK_HOME/lib /spark && $HADOOP_PREFIX/bin/hdfs dfs -put /root/enron-small.avro /user/root/enron.avro

ENV YARN_CONF_DIR $HADOOP_PREFIX/etc/hadoop
ENV HADOOP_CONF_DIR $HADOOP_PREFIX/etc/hadoop
ENV PATH $PATH:$SPARK_HOME/bin:$HADOOP_PREFIX/bin

# Now that enron.avro is in HDFS we don't need it in local
RUN rm /root/enron-small.avro

# update boot script
COPY bootstrap.sh /etc/bootstrap.sh
RUN chown root.root /etc/bootstrap.sh
RUN chmod 700 /etc/bootstrap.sh

ENTRYPOINT ["/etc/bootstrap.sh"]

EXPOSE 4040 8080 18080


text:
layout: post
date: 2015-10-14
title: "Joyce Young Paris Sleeveless Sweep/Brush Train Sheath/Column"
category: Joyce Young
tags: [Joyce Young ,Joyce Young,Sheath/Column,Sweep/Brush Train,Sleeveless]
---
### Joyce Young Paris
Just **$219.99**
###   Sleeveless Sweep/Brush Train Sheath/Column

BRANDS	Joyce Young

Silhouette	Sheath/Column

Hemline/Train	Sweep/Brush Train

Sleeve	Sleeveless

Buy it: [https://www.readybrides.com/en/joyce-young-/45858-joyce-young-paris.html](https://www.readybrides.com/en/joyce-young-/45858-joyce-young-paris.html)


text:
require "imap/backup/client/default"

module Imap::Backup
  class Client::AppleMail < Client::Default
    # With Apple Mails's IMAP, passing "/" to list
    # results in an empty list
    def provider_root
      ""
    end
  end
end


text:
"""
"""

import sys, os

sys.path.append('..')
from mendeley import API

def test_definitions():
    m = API(user_name='public')

    academic_statuses = m.definitions.academic_statuses()
    print('Retrieved academic statuses')

    subject_areas = m.definitions.subject_areas()
    print('Retrieved subject areas')

    document_types = m.definitions.document_types()
    print('Retrieved document types')

    print('Finished running "Definitions" tests')

if __name__ == '__main__':
    print('Running "Definitions" tests')
    test_definitions()


text:
package compare

import (
	"fmt"
	"path/filepath"
	"strings"

	"go.uber.org/thriftrw/compile"
)

// Diagnostic is a message associated with an error and a file name.
type Diagnostic struct {
	FilePath string // FilePath where error was discovered.
	Message  string // Message contains error message.
}

func (d *Diagnostic) String() string {
	return fmt.Sprintf("%s:%s", d.FilePath, d.Message)
}

// Pass provides all reported errors.
type Pass struct {
	lints  []Diagnostic
	GitDir string
}

// Report reports an error.
func (p *Pass) Report(d Diagnostic) {
	p.lints = append(p.lints, d)
}

// Lints returns all errors.
func (p *Pass) Lints() []Diagnostic {
	return p.lints
}

func (p *Pass) String() string {
	var b strings.Builder
	for _, l := range p.lints {
		_, _ = fmt.Fprintf(&b, "%s\n", l.String())
	}

	return b.String()
}

// CompareModules looks for removed methods and added required fields.
func (p *Pass) CompareModules(from, to *compile.Module) {
	for name, fromService := range from.Services {
		p.service(fromService, to.Services[name])
	}

	file := p.getRelativePath(from.ThriftPath)
	for n, fromType := range from.Types {
		p.typ(fromType, to.Types[n], file)
	}
}

func (p *Pass) typ(from, to compile.TypeSpec, file string) {
	if f, ok := from.(*compile.StructSpec); ok {
		t, ok := to.(*compile.StructSpec)
		if !ok {
			// A struct was deleted which is ok if it's unused or
			// it's usage was also removed.
			return
		}
		p.structSpecs(f, t, file)
	}
}

func (p *Pass) requiredField(fromField, toField *compile.FieldSpec, to *compile.StructSpec, file string) {
	fromRequired := fromField.Required
	if !fromRequired && toField.Required {
		p.Report(Diagnostic{
			FilePath: file,
			Message: fmt.Sprintf(
				"changing an optional field %q in %q to required",
				toField.ThriftName(), to.ThriftName()),
		})
	}
}

func (p *Pass) changedTypes(fromField, toField *compile.FieldSpec, to *compile.StructSpec, file string) {
	if fromField.Type == nil || toField.Type == nil {
		return
	}

	if fromField.Type.ThriftName() != toField.Type.ThriftName() {
		p.Report(Diagnostic{
			FilePath: file,
			Message: fmt.Sprintf(
				"changing type of field %q in struct %q from %q to %q",
				toField.ThriftName(), to.ThriftName(), fromField.Type.ThriftName(),
				toField.Type.ThriftName()),
		})
	}
}

// StructSpecs compares two structs defined in a Thrift file.
func (p *Pass) structSpecs(from, to *compile.StructSpec, file string) {
	fields := make(map[int16]*compile.FieldSpec, len(from.Fields))
	// Assume that these two should be compared.
	for _, f := range from.Fields {
		fields[f.ID] = f
	}
	for _, toField := range to.Fields {
		if fromField, ok := fields[toField.ID]; ok {
			p.requiredField(fromField, toField, to, file)
			p.changedTypes(fromField, toField, to, file)
		} else if toField.Required {
			p.Report(Diagnostic{
				FilePath: file,
				Message: fmt.Sprintf("adding a required field %q to %q",
					toField.ThriftName(), to.ThriftName()),
			})
		}
	}
}

func (p *Pass) service(from, to *compile.ServiceSpec) {
	if to == nil {
		// Service was deleted, which is not backwards compatible.
		p.Report(Diagnostic{
			FilePath: filepath.Base(from.File), // toModule could have been deleted.
			Message:  fmt.Sprintf("deleting service %q", from.Name),
		})

		return
	}
	file := p.getRelativePath(from.File)
	for n := range from.Functions {
		p.function(to.Functions[n], n, file, from.Name)
	}
}

// getRelativePath returns a relative path to a file or
// fallbacks to file name for cases when it was deleted.
func (p *Pass) getRelativePath(filePath string) string {
	if file, err := filepath.Rel(p.GitDir, filePath); err == nil {
		return file
	}
	// If a file was deleted, then we will not be able to
	// find a relative path to it.
	return filepath.Base(filePath)
}

func (p *Pass) function(to *compile.FunctionSpec, fn string, path string, service string) {
	file := p.getRelativePath(path)
	if to == nil {
		p.Report(Diagnostic{
			FilePath: file,
			Message:  fmt.Sprintf("removing method %q in service %q", fn, service),
		})
	}
}