text:
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
#pragma once

#include "striped_btree_lockable_map.h"
#include "btree_lockable_map.hpp"
#include <vespa/storage/common/bucket_stripe_utils.h>
#include <algorithm>
#include <cassert>
#include <queue>

namespace storage::bucketdb {

template <typename T>
StripedBTreeLockableMap<T>::StripedBTreeLockableMap(uint8_t n_stripe_bits)
    : _n_stripe_bits(n_stripe_bits),
      _n_stripes(1ULL << _n_stripe_bits),
      _stripes()
{
    assert(_n_stripe_bits > 0);
    assert(_n_stripe_bits <= MaxStripeBits);
    _stripes.reserve(_n_stripes);
    for (size_t i = 0; i < _n_stripes; ++i) {
        // TODO reduce initial sub-DB data store memory usage based on number of stripes
        _stripes.emplace_back(std::make_unique<BTreeLockableMap<T>>());
    }
}

template <typename T>
StripedBTreeLockableMap<T>::~StripedBTreeLockableMap() = default;

template <typename T>
size_t StripedBTreeLockableMap<T>::stripe_of(key_type key) const noexcept {
    return stripe_of_bucket_key(key, _n_stripe_bits);
}

template <typename T>
typename StripedBTreeLockableMap<T>::StripedDBType&
StripedBTreeLockableMap<T>::db_for(key_type key) noexcept {
    return *_stripes[stripe_of(key)];
}

template <typename T>
const typename StripedBTreeLockableMap<T>::StripedDBType&
StripedBTreeLockableMap<T>::db_for(key_type key) const noexcept {
    return *_stripes[stripe_of(key)];
}

template <typename T>
size_t StripedBTreeLockableMap<T>::size() const noexcept {
    size_t sz = 0;
    for (auto& s : _stripes) {
        sz += s->size();
    }
    return sz;
}

template <typename T>
size_t StripedBTreeLockableMap<T>::getMemoryUsage() const noexcept {
    size_t mem_usage = 0;
    for (auto& s : _stripes) {
        mem_usage += s->getMemoryUsage();
    }
    return mem_usage;
}

template <typename T>
vespalib::MemoryUsage StripedBTreeLockableMap<T>::detailed_memory_usage() const noexcept {
    vespalib::MemoryUsage mem_usage;
    for (auto& s : _stripes) {
        mem_usage.merge(s->detailed_memory_usage());
    }
    return mem_usage;
}

template <typename T>
bool StripedBTreeLockableMap<T>::empty() const noexcept {
    return std::all_of(_stripes.begin(), _stripes.end(), [](auto& s){ return s->empty(); });
}

template <typename T>
typename StripedBTreeLockableMap<T>::WrappedEntry
StripedBTreeLockableMap<T>::get(const key_type& key, const char* clientId, bool createIfNonExisting) {
    return db_for(key).get(key, clientId, createIfNonExisting);
}

template <typename T>
bool StripedBTreeLockableMap<T>::erase(const key_type& key, const char* client_id, bool has_lock) {
    return db_for(key).erase(key, client_id, has_lock);
}

template <typename T>
void StripedBTreeLockableMap<T>::insert(const key_type& key, const mapped_type& value,
                                        const char* clientId, bool has_lock, bool& pre_existed)
{
    db_for(key).insert(key, value, clientId, has_lock, pre_existed);
}

template <typename T>
void StripedBTreeLockableMap<T>::clear() {
    for (auto& s : _stripes) {
        s->clear();
    }
}

template <typename T>
void StripedBTreeLockableMap<T>::print(std::ostream& out, bool verbose,
                                       const std::string& indent) const
{
    // TODO more wrapped printing?
    for (auto& s : _stripes) {
        s->print(out, verbose, indent);
    }
}

template <typename T>
typename StripedBTreeLockableMap<T>::EntryMap
StripedBTreeLockableMap<T>::getContained(const BucketId& bucket, const char* clientId) {
    return db_for(bucket.toKey()).getContained(bucket, clientId);
}

template <typename T>
typename StripedBTreeLockableMap<T>::EntryMap
StripedBTreeLockableMap<T>::getAll(const BucketId& bucket, const char* clientId) {
    return db_for(bucket.toKey()).getAll(bucket, clientId);
}

template <typename T>
bool StripedBTreeLockableMap<T>::isConsistent(const StripedBTreeLockableMap::WrappedEntry& entry) {
    return db_for(entry.getKey()).isConsistent(entry);
}

template <typename T>
void StripedBTreeLockableMap<T>::showLockClients(vespalib::asciistream& out) const {
    for (auto& s : _stripes) {
        s->showLockClients(out);
    }
}

template <typename T>
void StripedBTreeLockableMap<T>::do_for_each_mutable_unordered(std::function<Decision(uint64_t, mapped_type&)> func,
                                                               const char* client_id)
{
    // This is by definition unordered in terms of bucket keys
    for (auto& stripe : _stripes) {
        // TODO pass functor by ref instead
        stripe->for_each_mutable_unordered(func, client_id);
    }
}

template <typename T>
void StripedBTreeLockableMap<T>::unlock(const key_type& key) {
    db_for(key).unlock(key);
}

template <typename T>
void StripedBTreeLockableMap<T>::do_for_each(std::function<Decision(uint64_t, const mapped_type&)> func,
                                             [[maybe_unused]] const char* client_id)
{
    auto guard = do_acquire_read_guard();
    for (auto iter = guard->create_iterator(); iter->valid(); iter->next()) {
        if (func(iter->key(), iter->value()) != Decision::CONTINUE) {
            break;
        }
    }
}

template <typename T>
void StripedBTreeLockableMap<T>::do_for_each_chunked(std::function<Decision(uint64_t, const mapped_type&)> func,
                                                     const char* client_id,
                                                     [[maybe_unused]] vespalib::duration yield_time,
                                                     [[maybe_unused]] uint32_t chunk_size)
{
    do_for_each(std::move(func), client_id);
}

template <typename T>
class StripedBTreeLockableMap<T>::ReadGuardImpl final
    : public bucketdb::ReadGuard<T, const T&>
{
    const StripedBTreeLockableMap<T>& _db;
    // There is a 1-1 relationship between DB stripes and guards.
    // This is essential to be able to choose the correct guard.
    std::vector<std::unique_ptr<bucketdb::ReadGuard<T, const T&>>> _stripe_guards;
public:
    explicit ReadGuardImpl(const StripedBTreeLockableMap<T>& db);
    ~ReadGuardImpl() override;

    std::vector<T> find_parents_and_self(const document::BucketId& bucket) const override;
    std::vector<T> find_parents_self_and_children(const document::BucketId& bucket) const override;
    void for_each(std::function<void(uint64_t, const T&)> func) const override;
    std::unique_ptr<ConstIterator<const T&>> create_iterator() const override;
    [[nodiscard]] uint64_t generation() const noexcept override { return 0; /*TODO*/ }
};

template <typename T>
StripedBTreeLockableMap<T>::ReadGuardImpl::ReadGuardImpl(const StripedBTreeLockableMap<T>& db)
    : _db(db),
      _stripe_guards()
{
    _stripe_guards.reserve(_db._stripes.size());
    for (auto& s : _db._stripes) {
        _stripe_guards.emplace_back(s->acquire_read_guard());
    }
}

template <typename T>
StripedBTreeLockableMap<T>::ReadGuardImpl::~ReadGuardImpl() = default;

template <typename T>
std::vector<T>
StripedBTreeLockableMap<T>::ReadGuardImpl::find_parents_and_self(const document::BucketId& bucket) const {
    return _stripe_guards[_db.stripe_of(bucket.toKey())]->find_parents_and_self(bucket);
}

template <typename T>
std::vector<T>
StripedBTreeLockableMap<T>::ReadGuardImpl::find_parents_self_and_children(const document::BucketId& bucket) const {
    return _stripe_guards[_db.stripe_of(bucket.toKey())]->find_parents_self_and_children(bucket);
}

template <typename T>
void StripedBTreeLockableMap<T>::ReadGuardImpl::for_each(std::function<void(uint64_t, const T&)> func) const {
    for (auto iter = create_iterator(); iter->valid(); iter->next()) {
        func(iter->key(), iter->value());
    }
}

template <typename T>
std::unique_ptr<ReadGuard<T>> StripedBTreeLockableMap<T>::do_acquire_read_guard() const {
    return std::make_unique<ReadGuardImpl>(*this);
}

namespace {

template <typename T> using Iter = ConstIterator<const T&>;
template <typename T> using KeyAndIterPtr = std::pair<uint64_t, Iter<T>*>;

template <typename T>
struct CompareFirstGreater {
    bool operator()(const KeyAndIterPtr<T>& lhs, const KeyAndIterPtr<T>& rhs) const noexcept {
        return (lhs.first > rhs.first);
    }
};

template <typename T>
class ConstIteratorImpl final : public ConstIterator<const T&> {
    using PriorityQueueType = std::priority_queue<KeyAndIterPtr<T>,
                                                  std::vector<KeyAndIterPtr<T>>,
                                                  CompareFirstGreater<T>>;
    // This is pretty heavy weight, but this iterator is only used for full DB sweeps
    // used by background maintenance operations, not by any realtime traffic.
    std::vector<std::unique_ptr<Iter<T>>> _iters;
    PriorityQueueType                     _iter_queue;
public:
    // Precondition: all iterators must be initially valid
    explicit ConstIteratorImpl(std::vector<std::unique_ptr<Iter<T>>> iters)
        : _iters(std::move(iters))
    {
        for (auto& iter : _iters) {
            _iter_queue.push(std::make_pair(iter->key(), iter.get()));
        }
    }

    void next() noexcept override {
        assert(!_iter_queue.empty());
        auto* top_iter = _iter_queue.top().second;
        top_iter->next();
        _iter_queue.pop();
        if (top_iter->valid()) {
            _iter_queue.push(std::make_pair(top_iter->key(), top_iter));
        }
    }

    bool valid() const noexcept override {
        return !_iter_queue.empty();
    }

    uint64_t key() const noexcept override {
        return _iter_queue.top().first;
    }

    const T& value() const override {
        return _iter_queue.top().second->value();
    }
};

}

template <typename T>
std::unique_ptr<ConstIterator<const T&>>
StripedBTreeLockableMap<T>::ReadGuardImpl::create_iterator() const {
    std::vector<std::unique_ptr<Iter<T>>> iters;
    iters.reserve(_db._n_stripes);
    for (auto& g : _stripe_guards) {
        auto iter = g->create_iterator();
        if (!iter->valid()) {
            continue;
        }
        iters.emplace_back(std::move(iter));
    }
    return std::make_unique<ConstIteratorImpl<T>>(std::move(iters));
}

}


text:
title: Week 1 - Goals and Objectives
...

# Week 1 - Goals and Objectives: Introduction # {#goals}

Internet mapping technologies are an important component of geospatial data capture, sharing, visualization, and delivery. This course provides a survey of current and emerging internet and geospatial interoperability standards, technologies, and capabilities. The emphasis of the work in this class will be hands-on experience in four critical aspects of Internet-enabled mapping:

* The basic concepts behind web development and web mapping technologies that enable the delivery of maps and mapped data through web browsers

* The Open Standards that facilitate the exchange of map images and geospatial data over the internet

* The use of published standards-based services in desktop mapping applications that implement those standards

* The deployment of standards-based geospatial map and data services that other systems and users may make use of

The specific class objectives that relate to these activities and departmental curriculum objectives for undergraduate and graduate students in the Geography Department include the following:

* Students will understand the concepts geospatial data and service interoperability

* Students will be able to define the specific requirements of a particular analysis or project and identify the interoperability standards that are capable of meeting those requirements

* Students will be knowledgeable in the core technologies that they may use to produce their own internet-enabled mapping capabilities

* Students will understand the strengths and limitations of current internet mapping technologies for generating cartographically effective map products.

The weekly goals, objectives and assignments are outlined below

redpajama_set_name: RedPajamaGithub


text:
from __future__ import absolute_import

import cli.log

from addition import signed, one_complement, two_complement

@cli.log.LoggingApp
def addition(app):
  representation = app.params.representation
  first = app.params.first
  second = app.params.second

  try:
    if representation == 'signed':
      print signed(first, second)
    if representation == 'one':
      print one_complement(first, second)
    if representation == 'two':
      print two_complement(first, second)
  except ValueError:
    print "Overflow"

addition.add_param("first", help="First number",
                   type=str)
addition.add_param("second", help="Second number",
                   type=str)

addition.add_param("-r", "--representation",
                   help="Specific the representation in which the number"
                   " is given")

if __name__ == "__main__":
  addition.run()


text: export { Home as default } from "./";


text:
namespace content {

class PepperFileSystemBrowserHost;

// Implementations of FileRef operations for internal filesystems.
class PepperInternalFileRefBackend : public PepperFileRefBackend {
 public:
  PepperInternalFileRefBackend(
      ppapi::host::PpapiHost* host,
      int render_process_id,
      base::WeakPtr<PepperFileSystemBrowserHost> fs_host,
      const std::string& path);

  PepperInternalFileRefBackend(const PepperInternalFileRefBackend&) = delete;
  PepperInternalFileRefBackend& operator=(const PepperInternalFileRefBackend&) =
      delete;

  ~PepperInternalFileRefBackend() override;

  // PepperFileRefBackend overrides.
  int32_t MakeDirectory(ppapi::host::ReplyMessageContext context,
                        int32_t make_directory_flags) override;
  int32_t Touch(ppapi::host::ReplyMessageContext context,
                PP_Time last_accessed_time,
                PP_Time last_modified_time) override;
  int32_t Delete(ppapi::host::ReplyMessageContext context) override;
  int32_t Rename(ppapi::host::ReplyMessageContext context,
                 PepperFileRefHost* new_file_ref) override;
  int32_t Query(ppapi::host::ReplyMessageContext context) override;
  int32_t ReadDirectoryEntries(
      ppapi::host::ReplyMessageContext context) override;
  int32_t GetAbsolutePath(ppapi::host::ReplyMessageContext context) override;
  storage::FileSystemURL GetFileSystemURL() const override;
  base::FilePath GetExternalFilePath() const override;

  int32_t CanRead() const override;
  int32_t CanWrite() const override;
  int32_t CanCreate() const override;
  int32_t CanReadWrite() const override;

 private:
  // Generic reply callback.
  void DidFinish(ppapi::host::ReplyMessageContext reply_context,
                 const IPC::Message& msg,
                 base::File::Error error);

  // Helper methods called on IO thread.
  static void DidFinishOnIOThread(
      base::WeakPtr<PepperInternalFileRefBackend> weak_ptr,
      ppapi::host::ReplyMessageContext reply_context,
      const IPC::Message& msg,
      base::File::Error error);
  static void ReadDirectoryCompleteOnIOThread(
      base::WeakPtr<PepperInternalFileRefBackend> weak_ptr,
      ppapi::host::ReplyMessageContext reply_context,
      storage::FileSystemOperation::FileEntryList* accumulated_file_list,
      base::File::Error error,
      storage::FileSystemOperation::FileEntryList file_list,
      bool has_more);
  static void GetMetadataCompleteOnIOThread(
      base::WeakPtr<PepperInternalFileRefBackend> weak_ptr,
      ppapi::host::ReplyMessageContext reply_context,
      base::File::Error result,
      const base::File::Info& file_info);

  // Operation specific callbacks.
  void GetMetadataComplete(ppapi::host::ReplyMessageContext reply_context,
                           base::File::Error error,
                           const base::File::Info& file_info);
  void ReadDirectoryComplete(
      ppapi::host::ReplyMessageContext context,
      storage::FileSystemOperation::FileEntryList* accumulated_file_list,
      base::File::Error error,
      storage::FileSystemOperation::FileEntryList file_list,
      bool has_more);

  scoped_refptr<storage::FileSystemContext> GetFileSystemContext() const;

  raw_ptr<ppapi::host::PpapiHost> host_;
  int render_process_id_;
  base::WeakPtr<PepperFileSystemBrowserHost> fs_host_;
  PP_FileSystemType fs_type_;
  std::string path_;

  mutable storage::FileSystemURL fs_url_;

  base::WeakPtrFactory<PepperInternalFileRefBackend> weak_factory_{this};
};

}  // namespace content

#endif  // CONTENT_BROWSER_RENDERER_HOST_PEPPER_PEPPER_INTERNAL_FILE_REF_BACKEND_H_


text:
package com.hazelcast.config;

import com.hazelcast.test.HazelcastParallelClassRunner;
import com.hazelcast.test.annotation.ParallelTest;
import com.hazelcast.test.annotation.QuickTest;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.junit.runner.RunWith;

import java.util.List;

import static java.util.Collections.singletonList;
import static org.junit.Assert.assertTrue;

@RunWith(HazelcastParallelClassRunner.class)
@Category({QuickTest.class, ParallelTest.class})
public class QueryCacheConfigReadOnlyTest {

    private QueryCacheConfig getReadOnlyConfig() {
        return new QueryCacheConfig().getAsReadOnly();
    }

    @Test(expected = UnsupportedOperationException.class)
    public void getIndexConfigsOfReadOnlyQueryCacheConfigShouldReturnUnmodifiable() {
        QueryCacheConfig config = new QueryCacheConfig()
                .addIndexConfig(new MapIndexConfig())
                .addIndexConfig(new MapIndexConfig());

        List<MapIndexConfig> indexConfigs = config.getAsReadOnly().getIndexConfigs();
        indexConfigs.add(new MapIndexConfig());
    }

    @Test(expected = UnsupportedOperationException.class)
    public void getEntryListenerConfigsOfReadOnlyQueryCacheConfigShouldReturnUnmodifiable() {
        QueryCacheConfig config = new QueryCacheConfig()
                .addEntryListenerConfig(new EntryListenerConfig())
                .addEntryListenerConfig(new EntryListenerConfig());

        List<EntryListenerConfig> entryListenerConfigs = config.getAsReadOnly().getEntryListenerConfigs();
        entryListenerConfigs.add(new EntryListenerConfig());
    }

    @Test
    public void getEvictionConfigShouldReturnReadOnlyConfig() {
        assertTrue(getReadOnlyConfig().getEvictionConfig() instanceof EvictionConfigReadOnly);
    }

    @Test
    public void getPredicateConfigShouldReturnReadOnlyConfig() {
        assertTrue(getReadOnlyConfig().getPredicateConfig() instanceof PredicateConfigReadOnly);
    }

    @Test(expected = UnsupportedOperationException.class)
    public void setBatchSizeOfReadOnlyMapStoreConfigShouldFail() {
        getReadOnlyConfig().setBatchSize(5);
    }

    @Test(expected = UnsupportedOperationException.class)
    public void setBufferSizeOfReadOnlyMapStoreConfigShouldFail() {
        getReadOnlyConfig().setBufferSize(3);
    }

    @Test(expected = UnsupportedOperationException.class)
    public void setDelaySecondsOfReadOnlyMapStoreConfigShouldFail() {
        getReadOnlyConfig().setDelaySeconds(3);
    }

    @Test(expected = UnsupportedOperationException.class)
    public void setEntryListenerConfigsOfReadOnlyMapStoreConfigShouldFail() {
        getReadOnlyConfig().setEntryListenerConfigs(singletonList(new EntryListenerConfig()));
    }

    @Test(expected = UnsupportedOperationException.class)
    public void setEvictionConfigOfReadOnlyMapStoreConfigShouldFail() {
        getReadOnlyConfig().setEvictionConfig(new EvictionConfig());
    }

    @Test(expected = UnsupportedOperationException.class)
    public void setIncludeValueOfReadOnlyMapStoreConfigShouldFail() {
        getReadOnlyConfig().setIncludeValue(true);
    }

    @Test(expected = UnsupportedOperationException.class)
    public void setIndexConfigsOfReadOnlyMapStoreConfigShouldFail() {
        getReadOnlyConfig().setIndexConfigs(singletonList(new MapIndexConfig()));
    }

    @Test(expected = UnsupportedOperationException.class)
    public void setInMemoryFormatOfReadOnlyMapStoreConfigShouldFail() {
        getReadOnlyConfig().setInMemoryFormat(InMemoryFormat.OBJECT);
    }

    @Test(expected = UnsupportedOperationException.class)
    public void setNameOfReadOnlyMapStoreConfigShouldFail() {
        getReadOnlyConfig().setName("myQueryCache");
    }

    @Test(expected = UnsupportedOperationException.class)
    public void setPredicateConfigOfReadOnlyMapStoreConfigShouldFail() {
        getReadOnlyConfig().setPredicateConfig(new PredicateConfig());
    }

    @Test(expected = UnsupportedOperationException.class)
    public void setPopulateOfReadOnlyMapStoreConfigShouldFail() {
        getReadOnlyConfig().setPopulate(true);
    }

    @Test(expected = UnsupportedOperationException.class)
    public void setCoalesceOfReadOnlyMapStoreConfigShouldFail() {
        getReadOnlyConfig().setCoalesce(true);
    }
}


text:
#ifndef TemplateContentDocumentFragment_h
#define TemplateContentDocumentFragment_h

#include "core/dom/DocumentFragment.h"

namespace blink {

class TemplateContentDocumentFragment final : public DocumentFragment {
public:
    static RawPtr<TemplateContentDocumentFragment> create(Document& document, Element* host)
    {
        return new TemplateContentDocumentFragment(document, host);
    }

    Element* host() const { return m_host; }
#if !ENABLE(OILPAN)
    void clearHost() { m_host = nullptr; }
#endif

    DEFINE_INLINE_VIRTUAL_TRACE()
    {
        visitor->trace(m_host);
        DocumentFragment::trace(visitor);
    }

private:
    TemplateContentDocumentFragment(Document& document, Element* host)
        : DocumentFragment(&document, CreateDocumentFragment)
        , m_host(host)
    {
    }

    bool isTemplateContent() const override { return true; }

    Member<Element> m_host;
};

} // namespace blink

#endif // TemplateContentDocumentFragment_h


text:
<?php

declare(strict_types=1);

namespace spec\Sylius\Component\Resource\Repository;

use Pagerfanta\Pagerfanta;
use PhpSpec\ObjectBehavior;
use spec\Sylius\Component\Resource\Fixtures\SampleBookResourceInterface;
use Sylius\Component\Resource\Exception\UnexpectedTypeException;
use Sylius\Component\Resource\Exception\UnsupportedMethodException;
use Sylius\Component\Resource\Model\ResourceInterface;
use Sylius\Component\Resource\Repository\Exception\ExistingResourceException;
use Sylius\Component\Resource\Repository\InMemoryRepository;
use Sylius\Component\Resource\Repository\RepositoryInterface;

require_once __DIR__ . '/../Fixtures/SampleBookResourceInterface.php';

/**
 * @author Jan Góralski <jan.goralski@lakion.com>
 */
final class InMemoryRepositorySpec extends ObjectBehavior
{
    function let()
    {
        $this->beConstructedWith(SampleBookResourceInterface::class);
    }

    function it_throws_invalid_argument_exception_when_constructing_with_null()
    {
        $this->beConstructedWith(null);

        $this->shouldThrow(\InvalidArgumentException::class)->duringInstantiation();
    }

    function it_throws_unexpected_type_exception_when_constructing_without_resource_interface()
    {
        $this->beConstructedWith(\stdClass::class);

        $this->shouldThrow(UnexpectedTypeException::class)->duringInstantiation();
    }

    function it_is_initializable()
    {
        $this->shouldHaveType(InMemoryRepository::class);
    }

    function it_implements_repository_interface()
    {
        $this->shouldImplement(RepositoryInterface::class);
    }

    function it_throws_invalid_argument_exception_when_adding_wrong_resource_type(ResourceInterface $resource)
    {
        $this->shouldThrow(\InvalidArgumentException::class)->during('add', [$resource]);
    }

    function it_adds_an_object(SampleBookResourceInterface $monocle)
    {
        $monocle->getId()->willReturn(2);

        $this->add($monocle);
        $this->findOneBy(['id' => 2])->shouldReturn($monocle);
    }

    function it_throws_existing_resource_exception_on_adding_a_resource_which_is_already_in_repository(SampleBookResourceInterface $bike)
    {
        $this->add($bike);
        $this->shouldThrow(ExistingResourceException::class)->during('add', [$bike]);
    }

    function it_removes_a_resource(SampleBookResourceInterface $shirt)
    {
        $shirt->getId()->willReturn(5);

        $this->add($shirt);
        $this->remove($shirt);

        $this->findOneBy(['id' => 5])->shouldReturn(null);
    }

    function it_finds_object_by_id(SampleBookResourceInterface $monocle)
    {
        $monocle->getId()->willReturn(2);

        $this->add($monocle);
        $this->find(2)->shouldReturn($monocle);
    }

    function it_returns_null_if_cannot_find_object_by_id()
    {
        $this->find(2)->shouldReturn(null);
    }

    function it_returns_all_objects_when_finding_by_an_empty_parameter_array(
        SampleBookResourceInterface $book,
        SampleBookResourceInterface $shirt
    ) {
        $book->getId()->willReturn(10);
        $book->getName()->willReturn('Book');

        $shirt->getId()->willReturn(5);
        $shirt->getName()->willReturn('Shirt');

        $this->add($book);
        $this->add($shirt);

        $this->findBy([])->shouldReturn([$book, $shirt]);
    }

    function it_finds_many_objects_by_multiple_criteria_orders_a_limit_and_an_offset(
        SampleBookResourceInterface $firstBook,
        SampleBookResourceInterface $secondBook,
        SampleBookResourceInterface $thirdBook,
        SampleBookResourceInterface $fourthBook,
        SampleBookResourceInterface $wrongIdBook,
        SampleBookResourceInterface $wrongNameBook
    ) {
        $id = 80;
        $name = 'Book';

        $firstBook->getId()->willReturn($id);
        $secondBook->getId()->willReturn($id);
        $thirdBook->getId()->willReturn($id);
        $fourthBook->getId()->willReturn($id);
        $wrongNameBook->getId()->willReturn($id);
        $wrongIdBook->getId()->willReturn(100);

        $firstBook->getName()->willReturn($name);
        $secondBook->getName()->willReturn($name);
        $thirdBook->getName()->willReturn($name);
        $fourthBook->getName()->willReturn($name);
        $wrongIdBook->getName()->willReturn($name);
        $wrongNameBook->getName()->willReturn('Tome');

        $firstBook->getRating()->willReturn(3);
        $secondBook->getRating()->willReturn(2);
        $thirdBook->getRating()->willReturn(2);
        $fourthBook->getRating()->willReturn(4);

        $firstBook->getTitle()->willReturn('World War Z');
        $secondBook->getTitle()->willReturn('World War Z');
        $thirdBook->getTitle()->willReturn('Call of Cthulhu');
        $fourthBook->getTitle()->willReturn('Art of War');

        $this->add($firstBook);
        $this->add($secondBook);
        $this->add($thirdBook);
        $this->add($fourthBook);
        $this->add($wrongIdBook);
        $this->add($wrongNameBook);

        $this->findBy(
            $criteria = [
                'name' => $name,
                'id' => $id,
            ],
            $orderBy = [
                'rating' => RepositoryInterface::ORDER_ASCENDING,
                'title' => RepositoryInterface::ORDER_DESCENDING,
            ],
            $limit = 2,
            $offset = 1
        )->shouldReturn([$secondBook, $thirdBook]);
    }

    function it_throws_invalid_argument_exception_when_finding_one_object_with_empty_parameter_array()
    {
        $this->shouldThrow(\InvalidArgumentException::class)->during('findOneBy', [[]]);
    }

    function it_finds_one_object_by_parameter(SampleBookResourceInterface $book, SampleBookResourceInterface $shirt)
    {
        $book->getName()->willReturn('Book');
        $shirt->getName()->willReturn('Shirt');

        $this->add($book);
        $this->add($shirt);

        $this->findOneBy(['name' => 'Book'])->shouldReturn($book);
    }

    function it_returns_first_result_while_finding_one_by_parameters(
        SampleBookResourceInterface $book,
        SampleBookResourceInterface $secondBook
    ) {
        $book->getName()->willReturn('Book');
        $secondBook->getName()->willReturn('Book');

        $this->add($book);
        $this->add($secondBook);

        $this->findOneBy(['name' => 'Book'])->shouldReturn($book);
    }

    function it_finds_all_objects_in_memory(SampleBookResourceInterface $book, SampleBookResourceInterface $shirt)
    {
        $this->add($book);
        $this->add($shirt);

        $this->findAll()->shouldReturn([$book, $shirt]);
    }

    function it_return_empty_array_when_memory_is_empty()
    {
        $this->findAll()->shouldReturn([]);
    }

    function it_creates_paginator()
    {
        $this->createPaginator()->shouldHaveType(Pagerfanta::class);
    }

    function it_returns_stated_class_name()
    {
        $this->getClassName()->shouldReturn(SampleBookResourceInterface::class);
    }
}


text:
=begin
#The Plaid API

#The Plaid REST API. Please see https://plaid.com/docs/api for more details.

The version of the OpenAPI document: 2020-09-14_1.205.3

Generated by: https://openapi-generator.tech
OpenAPI Generator version: 5.1.1

=end

require 'date'
require 'time'

module Plaid
  # Used to configure Sandbox test data for the Liabilities product
  class LiabilityOverride
    # The type of the liability object, either `credit` or `student`. Mortgages are not currently supported in the custom Sandbox.
    attr_accessor :type

    # The purchase APR percentage value. For simplicity, this is the only interest rate used to calculate interest charges. Can only be set if `type` is `credit`.
    attr_accessor :purchase_apr

    # The cash APR percentage value. Can only be set if `type` is `credit`.
    attr_accessor :cash_apr

    # The balance transfer APR percentage value. Can only be set if `type` is `credit`.
    attr_accessor :balance_transfer_apr

    # The special APR percentage value. Can only be set if `type` is `credit`.
    attr_accessor :special_apr

    # Override the `last_payment_amount` field. Can only be set if `type` is `credit`.
    attr_accessor :last_payment_amount

    # Override the `minimum_payment_amount` field. Can only be set if `type` is `credit` or `student`.
    attr_accessor :minimum_payment_amount

    # Override the `is_overdue` field
    attr_accessor :is_overdue

    # The date on which the loan was initially lent, in [ISO 8601](https://wikipedia.org/wiki/ISO_8601) (YYYY-MM-DD) format. Can only be set if `type` is `student`.
    attr_accessor :origination_date

    # The original loan principal. Can only be set if `type` is `student`.
    attr_accessor :principal

    # The interest rate on the loan as a percentage. Can only be set if `type` is `student`.
    attr_accessor :nominal_apr

    # If set, interest capitalization begins at the given number of months after loan origination. By default interest is never capitalized. Can only be set if `type` is `student`.
    attr_accessor :interest_capitalization_grace_period_months

    attr_accessor :repayment_model

    # Override the `expected_payoff_date` field. Can only be set if `type` is `student`.
    attr_accessor :expected_payoff_date

    # Override the `guarantor` field. Can only be set if `type` is `student`.
    attr_accessor :guarantor

    # Override the `is_federal` field. Can only be set if `type` is `student`.
    attr_accessor :is_federal

    # Override the `loan_name` field. Can only be set if `type` is `student`.
    attr_accessor :loan_name

    attr_accessor :loan_status

    # Override the `payment_reference_number` field. Can only be set if `type` is `student`.
    attr_accessor :payment_reference_number

    attr_accessor :pslf_status

    # Override the `repayment_plan.description` field. Can only be set if `type` is `student`.
    attr_accessor :repayment_plan_description

    # Override the `repayment_plan.type` field. Can only be set if `type` is `student`. Possible values are: `\"extended graduated\"`, `\"extended standard\"`, `\"graduated\"`, `\"income-contingent repayment\"`, `\"income-based repayment\"`, `\"interest only\"`, `\"other\"`, `\"pay as you earn\"`, `\"revised pay as you earn\"`, or `\"standard\"`.
    attr_accessor :repayment_plan_type

    # Override the `sequence_number` field. Can only be set if `type` is `student`.
    attr_accessor :sequence_number

    attr_accessor :servicer_address

    # Attribute mapping from ruby-style variable name to JSON key.
    def self.attribute_map
      {
        :'type' => :'type',
        :'purchase_apr' => :'purchase_apr',
        :'cash_apr' => :'cash_apr',
        :'balance_transfer_apr' => :'balance_transfer_apr',
        :'special_apr' => :'special_apr',
        :'last_payment_amount' => :'last_payment_amount',
        :'minimum_payment_amount' => :'minimum_payment_amount',
        :'is_overdue' => :'is_overdue',
        :'origination_date' => :'origination_date',
        :'principal' => :'principal',
        :'nominal_apr' => :'nominal_apr',
        :'interest_capitalization_grace_period_months' => :'interest_capitalization_grace_period_months',
        :'repayment_model' => :'repayment_model',
        :'expected_payoff_date' => :'expected_payoff_date',
        :'guarantor' => :'guarantor',
        :'is_federal' => :'is_federal',
        :'loan_name' => :'loan_name',
        :'loan_status' => :'loan_status',
        :'payment_reference_number' => :'payment_reference_number',
        :'pslf_status' => :'pslf_status',
        :'repayment_plan_description' => :'repayment_plan_description',
        :'repayment_plan_type' => :'repayment_plan_type',
        :'sequence_number' => :'sequence_number',
        :'servicer_address' => :'servicer_address'
      }
    end

    # Returns all the JSON keys this model knows about
    def self.acceptable_attributes
      attribute_map.values
    end

    # Attribute type mapping.
    def self.openapi_types
      {
        :'type' => :'String',
        :'purchase_apr' => :'Float',
        :'cash_apr' => :'Float',
        :'balance_transfer_apr' => :'Float',
        :'special_apr' => :'Float',
        :'last_payment_amount' => :'Float',
        :'minimum_payment_amount' => :'Float',
        :'is_overdue' => :'Boolean',
        :'origination_date' => :'Date',
        :'principal' => :'Float',
        :'nominal_apr' => :'Float',
        :'interest_capitalization_grace_period_months' => :'Float',
        :'repayment_model' => :'StudentLoanRepaymentModel',
        :'expected_payoff_date' => :'Date',
        :'guarantor' => :'String',
        :'is_federal' => :'Boolean',
        :'loan_name' => :'String',
        :'loan_status' => :'StudentLoanStatus',
        :'payment_reference_number' => :'String',
        :'pslf_status' => :'PSLFStatus',
        :'repayment_plan_description' => :'String',
        :'repayment_plan_type' => :'String',
        :'sequence_number' => :'String',
        :'servicer_address' => :'Address'
      }
    end

    # List of attributes with nullable: true
    def self.openapi_nullable
      Set.new([
      ])
    end

    # Initializes the object
    # @param [Hash] attributes Model attributes in the form of hash
    def initialize(attributes = {})
      if (!attributes.is_a?(Hash))
        fail ArgumentError, "The input argument (attributes) must be a hash in `Plaid::LiabilityOverride` initialize method"
      end

      # check to see if the attribute exists and convert string to symbol for hash key
      attributes = attributes.each_with_object({}) { |(k, v), h|
        if (!self.class.attribute_map.key?(k.to_sym))
          fail ArgumentError, "`#{k}` is not a valid attribute in `Plaid::LiabilityOverride`. Please check the name to make sure it's valid. List of attributes: " + self.class.attribute_map.keys.inspect
        end
        h[k.to_sym] = v
      }

      if attributes.key?(:'type')
        self.type = attributes[:'type']
      end

      if attributes.key?(:'purchase_apr')
        self.purchase_apr = attributes[:'purchase_apr']
      end

      if attributes.key?(:'cash_apr')
        self.cash_apr = attributes[:'cash_apr']
      end

      if attributes.key?(:'balance_transfer_apr')
        self.balance_transfer_apr = attributes[:'balance_transfer_apr']
      end

      if attributes.key?(:'special_apr')
        self.special_apr = attributes[:'special_apr']
      end

      if attributes.key?(:'last_payment_amount')
        self.last_payment_amount = attributes[:'last_payment_amount']
      end

      if attributes.key?(:'minimum_payment_amount')
        self.minimum_payment_amount = attributes[:'minimum_payment_amount']
      end

      if attributes.key?(:'is_overdue')
        self.is_overdue = attributes[:'is_overdue']
      end

      if attributes.key?(:'origination_date')
        self.origination_date = attributes[:'origination_date']
      end

      if attributes.key?(:'principal')
        self.principal = attributes[:'principal']
      end

      if attributes.key?(:'nominal_apr')
        self.nominal_apr = attributes[:'nominal_apr']
      end

      if attributes.key?(:'interest_capitalization_grace_period_months')
        self.interest_capitalization_grace_period_months = attributes[:'interest_capitalization_grace_period_months']
      end

      if attributes.key?(:'repayment_model')
        self.repayment_model = attributes[:'repayment_model']
      end

      if attributes.key?(:'expected_payoff_date')
        self.expected_payoff_date = attributes[:'expected_payoff_date']
      end

      if attributes.key?(:'guarantor')
        self.guarantor = attributes[:'guarantor']
      end

      if attributes.key?(:'is_federal')
        self.is_federal = attributes[:'is_federal']
      end

      if attributes.key?(:'loan_name')
        self.loan_name = attributes[:'loan_name']
      end

      if attributes.key?(:'loan_status')
        self.loan_status = attributes[:'loan_status']
      end

      if attributes.key?(:'payment_reference_number')
        self.payment_reference_number = attributes[:'payment_reference_number']
      end

      if attributes.key?(:'pslf_status')
        self.pslf_status = attributes[:'pslf_status']
      end

      if attributes.key?(:'repayment_plan_description')
        self.repayment_plan_description = attributes[:'repayment_plan_description']
      end

      if attributes.key?(:'repayment_plan_type')
        self.repayment_plan_type = attributes[:'repayment_plan_type']
      end

      if attributes.key?(:'sequence_number')
        self.sequence_number = attributes[:'sequence_number']
      end

      if attributes.key?(:'servicer_address')
        self.servicer_address = attributes[:'servicer_address']
      end
    end

    # Show invalid properties with the reasons. Usually used together with valid?
    # @return Array for valid properties with the reasons
    def list_invalid_properties
      invalid_properties = Array.new
      if @type.nil?
        invalid_properties.push('invalid value for "type", type cannot be nil.')
      end

      if @purchase_apr.nil?
        invalid_properties.push('invalid value for "purchase_apr", purchase_apr cannot be nil.')
      end

      if @cash_apr.nil?
        invalid_properties.push('invalid value for "cash_apr", cash_apr cannot be nil.')
      end

      if @balance_transfer_apr.nil?
        invalid_properties.push('invalid value for "balance_transfer_apr", balance_transfer_apr cannot be nil.')
      end

      if @special_apr.nil?
        invalid_properties.push('invalid value for "special_apr", special_apr cannot be nil.')
      end

      if @last_payment_amount.nil?
        invalid_properties.push('invalid value for "last_payment_amount", last_payment_amount cannot be nil.')
      end

      if @minimum_payment_amount.nil?
        invalid_properties.push('invalid value for "minimum_payment_amount", minimum_payment_amount cannot be nil.')
      end

      if @is_overdue.nil?
        invalid_properties.push('invalid value for "is_overdue", is_overdue cannot be nil.')
      end

      if @origination_date.nil?
        invalid_properties.push('invalid value for "origination_date", origination_date cannot be nil.')
      end

      if @principal.nil?
        invalid_properties.push('invalid value for "principal", principal cannot be nil.')
      end

      if @nominal_apr.nil?
        invalid_properties.push('invalid value for "nominal_apr", nominal_apr cannot be nil.')
      end

      if @interest_capitalization_grace_period_months.nil?
        invalid_properties.push('invalid value for "interest_capitalization_grace_period_months", interest_capitalization_grace_period_months cannot be nil.')
      end

      if @repayment_model.nil?
        invalid_properties.push('invalid value for "repayment_model", repayment_model cannot be nil.')
      end

      if @expected_payoff_date.nil?
        invalid_properties.push('invalid value for "expected_payoff_date", expected_payoff_date cannot be nil.')
      end

      if @guarantor.nil?
        invalid_properties.push('invalid value for "guarantor", guarantor cannot be nil.')
      end

      if @is_federal.nil?
        invalid_properties.push('invalid value for "is_federal", is_federal cannot be nil.')
      end

      if @loan_name.nil?
        invalid_properties.push('invalid value for "loan_name", loan_name cannot be nil.')
      end

      if @loan_status.nil?
        invalid_properties.push('invalid value for "loan_status", loan_status cannot be nil.')
      end

      if @payment_reference_number.nil?
        invalid_properties.push('invalid value for "payment_reference_number", payment_reference_number cannot be nil.')
      end

      if @pslf_status.nil?
        invalid_properties.push('invalid value for "pslf_status", pslf_status cannot be nil.')
      end

      if @repayment_plan_description.nil?
        invalid_properties.push('invalid value for "repayment_plan_description", repayment_plan_description cannot be nil.')
      end

      if @repayment_plan_type.nil?
        invalid_properties.push('invalid value for "repayment_plan_type", repayment_plan_type cannot be nil.')
      end

      if @sequence_number.nil?
        invalid_properties.push('invalid value for "sequence_number", sequence_number cannot be nil.')
      end

      if @servicer_address.nil?
        invalid_properties.push('invalid value for "servicer_address", servicer_address cannot be nil.')
      end

      invalid_properties
    end

    # Check to see if the all the properties in the model are valid
    # @return true if the model is valid
    def valid?
      return false if @type.nil?
      return false if @purchase_apr.nil?
      return false if @cash_apr.nil?
      return false if @balance_transfer_apr.nil?
      return false if @special_apr.nil?
      return false if @last_payment_amount.nil?
      return false if @minimum_payment_amount.nil?
      return false if @is_overdue.nil?
      return false if @origination_date.nil?
      return false if @principal.nil?
      return false if @nominal_apr.nil?
      return false if @interest_capitalization_grace_period_months.nil?
      return false if @repayment_model.nil?
      return false if @expected_payoff_date.nil?
      return false if @guarantor.nil?
      return false if @is_federal.nil?
      return false if @loan_name.nil?
      return false if @loan_status.nil?
      return false if @payment_reference_number.nil?
      return false if @pslf_status.nil?
      return false if @repayment_plan_description.nil?
      return false if @repayment_plan_type.nil?
      return false if @sequence_number.nil?
      return false if @servicer_address.nil?
      true
    end

    # Checks equality by comparing each attribute.
    # @param [Object] Object to be compared
    def ==(o)
      return true if self.equal?(o)
      self.class == o.class &&
          type == o.type &&
          purchase_apr == o.purchase_apr &&
          cash_apr == o.cash_apr &&
          balance_transfer_apr == o.balance_transfer_apr &&
          special_apr == o.special_apr &&
          last_payment_amount == o.last_payment_amount &&
          minimum_payment_amount == o.minimum_payment_amount &&
          is_overdue == o.is_overdue &&
          origination_date == o.origination_date &&
          principal == o.principal &&
          nominal_apr == o.nominal_apr &&
          interest_capitalization_grace_period_months == o.interest_capitalization_grace_period_months &&
          repayment_model == o.repayment_model &&
          expected_payoff_date == o.expected_payoff_date &&
          guarantor == o.guarantor &&
          is_federal == o.is_federal &&
          loan_name == o.loan_name &&
          loan_status == o.loan_status &&
          payment_reference_number == o.payment_reference_number &&
          pslf_status == o.pslf_status &&
          repayment_plan_description == o.repayment_plan_description &&
          repayment_plan_type == o.repayment_plan_type &&
          sequence_number == o.sequence_number &&
          servicer_address == o.servicer_address
    end

    # @see the `==` method
    # @param [Object] Object to be compared
    def eql?(o)
      self == o
    end

    # Calculates hash code according to all attributes.
    # @return [Integer] Hash code
    def hash
      [type, purchase_apr, cash_apr, balance_transfer_apr, special_apr, last_payment_amount, minimum_payment_amount, is_overdue, origination_date, principal, nominal_apr, interest_capitalization_grace_period_months, repayment_model, expected_payoff_date, guarantor, is_federal, loan_name, loan_status, payment_reference_number, pslf_status, repayment_plan_description, repayment_plan_type, sequence_number, servicer_address].hash
    end

    # Builds the object from hash
    # @param [Hash] attributes Model attributes in the form of hash
    # @return [Object] Returns the model itself
    def self.build_from_hash(attributes)
      new.build_from_hash(attributes)
    end

    # Builds the object from hash
    # @param [Hash] attributes Model attributes in the form of hash
    # @return [Object] Returns the model itself
    def build_from_hash(attributes)
      return nil unless attributes.is_a?(Hash)
      self.class.openapi_types.each_pair do |key, type|
        if attributes[self.class.attribute_map[key]].nil? && self.class.openapi_nullable.include?(key)
          self.send("#{key}=", nil)
        elsif type =~ /\AArray<(.*)>/i
          # check to ensure the input is an array given that the attribute
          # is documented as an array but the input is not
          if attributes[self.class.attribute_map[key]].is_a?(Array)
            self.send("#{key}=", attributes[self.class.attribute_map[key]].map { |v| _deserialize($1, v) })
          end
        elsif !attributes[self.class.attribute_map[key]].nil?
          self.send("#{key}=", _deserialize(type, attributes[self.class.attribute_map[key]]))
        end
      end

      self
    end

    # Deserializes the data based on type
    # @param string type Data type
    # @param string value Value to be deserialized
    # @return [Object] Deserialized data
    def _deserialize(type, value)
      case type.to_sym
      when :Time
        Time.parse(value)
      when :Date
        Date.parse(value)
      when :String
        value.to_s
      when :Integer
        value.to_i
      when :Float
        value.to_f
      when :Boolean
        if value.to_s =~ /\A(true|t|yes|y|1)\z/i
          true
        else
          false
        end
      when :Object
        # generic object (usually a Hash), return directly
        value
      when /\AArray<(?<inner_type>.+)>\z/
        inner_type = Regexp.last_match[:inner_type]
        value.map { |v| _deserialize(inner_type, v) }
      when /\AHash<(?<k_type>.+?), (?<v_type>.+)>\z/
        k_type = Regexp.last_match[:k_type]
        v_type = Regexp.last_match[:v_type]
        {}.tap do |hash|
          value.each do |k, v|
            hash[_deserialize(k_type, k)] = _deserialize(v_type, v)
          end
        end
      else # model
        # models (e.g. Pet) or oneOf
        klass = Plaid.const_get(type)
        klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value)
      end
    end

    # Returns the string representation of the object
    # @return [String] String presentation of the object
    def to_s
      to_hash.to_s
    end

    # to_body is an alias to to_hash (backward compatibility)
    # @return [Hash] Returns the object in the form of hash
    def to_body
      to_hash
    end

    # Returns the object in the form of hash
    # @return [Hash] Returns the object in the form of hash
    def to_hash
      hash = {}
      self.class.attribute_map.each_pair do |attr, param|
        value = self.send(attr)
        if value.nil?
          is_nullable = self.class.openapi_nullable.include?(attr)
          next if !is_nullable || (is_nullable && !instance_variable_defined?(:"@#{attr}"))
        end

        hash[param] = _to_hash(value)
      end
      hash
    end

    # Outputs non-array value in the form of hash
    # For object, use to_hash. Otherwise, just return the value
    # @param [Object] value Any valid value
    # @return [Hash] Returns the value in the form of hash
    def _to_hash(value)
      if value.is_a?(Array)
        value.compact.map { |v| _to_hash(v) }
      elsif value.is_a?(Hash)
        {}.tap do |hash|
          value.each { |k, v| hash[k] = _to_hash(v) }
        end
      elsif value.respond_to? :to_hash
        value.to_hash
      else
        value
      end
    end

  end

end


text:
/**
 * Created by edisonlascano on 1/13/15.
 */
//SOLUTION FROM
//Copyright (c) 2013 Fraser Tweedale
//The MIT License (MIT)

var http = require('http');
var url = require('url');
var port=process.argv[2]
var routes = {
    "/api/parsetime": function(parsedUrl) {
        var date = new Date(parsedUrl.query.iso);
        return {
            hour: date.getHours(),
            minute: date.getMinutes(),
            second: date.getSeconds()
        };
    },
    "/api/unixtime": function(parsedUrl) {
        return {unixtime: (new Date(parsedUrl.query.iso)).getTime()};
    }
}

server = http.createServer(function(request, response) {
    parsedUrl = url.parse(request.url, true);
    resource = routes[parsedUrl.pathname];
    if (resource) {
        response.writeHead(200, {"Content-Type": "application/json"});
        response.end(JSON.stringify(resource(parsedUrl)));
    }
    else {
        response.writeHead(404);
        response.end();
    }
});
server.listen(port);

// NODE SOLUTION
/*
var http = require('http')
var url = require('url')

function parsetime (time) {
    return {
        hour: time.getHours(),
        minute: time.getMinutes(),
        second: time.getSeconds()
    }
}

function unixtime (time) {
    return { unixtime : time.getTime() }
}

var server = http.createServer(function (req, res) {
    var parsedUrl = url.parse(req.url, true)
    var time = new Date(parsedUrl.query.iso)
    var result

    if (/^\/api\/parsetime/.test(req.url))
        result = parsetime(time)
    else if (/^\/api\/unixtime/.test(req.url))
        result = unixtime(time)

    if (result) {
        res.writeHead(200, { 'Content-Type': 'application/json' })
        res.end(JSON.stringify(result))
    } else {
        res.writeHead(404)
        res.end()
    }
})
server.listen(Number(process.argv[2]))
*/


text:
                    Categories

                         Category

                    My Events <button class="btn btn-xs btn-primary pull-right" data-bind="click: addEvent">
                     New Event</button>

                    <input type="text" class="form-control" placeholder="Search" data-bind="textInput: searchCriteria"/>


text:
package com.hpe.caf.services.job.scheduled.executor;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.time.Duration;
import java.time.Instant;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public final class DropTablesTask implements Runnable
{
    private static final Logger LOG = LoggerFactory.getLogger(DropTablesTask.class);

    @Override
    public void run()
    {
        try(final Connection connection = DBConnection.get();
            final PreparedStatement stmt = connection.prepareStatement("CALL  drop_deleted_task_tables()"))
        {
            if(LOG.isDebugEnabled())
            {
                LOG.debug("Calling drop_deleted_task_tables() database procedure ...");
                final Instant start = Instant.now();
                stmt.execute();
                final Instant end = Instant.now();
                LOG.debug("Total time taken to drop tables in ms. " + Duration.between(start, end).toMillis());
            }
            else
            {
                stmt.execute();
            }
        }
        catch(final Throwable t)
        {
            LOG.error("Caught exception while dropping soft deleted tables.", t);
        }
    }
}


text:
"""Tests for the swig wrapper of clusters."""

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

from tensorflow.core.protobuf import device_properties_pb2
from tensorflow.python.framework import meta_graph
from tensorflow.python.framework import ops
from tensorflow.python.grappler import cluster
from tensorflow.python.grappler import item
from tensorflow.python.ops import array_ops
from tensorflow.python.ops import math_ops
from tensorflow.python.ops import random_ops
from tensorflow.python.platform import test

class ClusterTest(test.TestCase):

  def testBasic(self):
    with ops.Graph().as_default() as g:
      a = random_ops.random_uniform(shape=())
      b = random_ops.random_uniform(shape=())
      c = a + b
      train_op = ops.get_collection_ref(ops.GraphKeys.TRAIN_OP)
      train_op.append(c)
      mg = meta_graph.create_meta_graph_def(graph=g)
      grappler_item = item.Item(mg)
      grappler_cluster = cluster.Cluster(
          disable_detailed_stats=False, disable_timeline=False)
      op_perfs, run_time, step_stats = grappler_cluster.MeasureCosts(
          grappler_item)
      self.assertTrue(run_time > 0)
      self.assertEqual(len(op_perfs), 4)
      self.assertTrue(step_stats.dev_stats)

  def testNoDetailedStats(self):
    with ops.Graph().as_default() as g:
      a = random_ops.random_uniform(shape=())
      b = random_ops.random_uniform(shape=())
      c = a + b
      train_op = ops.get_collection_ref(ops.GraphKeys.TRAIN_OP)
      train_op.append(c)
      mg = meta_graph.create_meta_graph_def(graph=g)
      grappler_item = item.Item(mg)
      grappler_cluster = cluster.Cluster(disable_detailed_stats=True)

      op_perfs, run_time, step_stats = grappler_cluster.MeasureCosts(
          grappler_item)
      self.assertTrue(run_time > 0)
      self.assertEqual(len(op_perfs), 0)
      self.assertEqual(len(step_stats.dev_stats), 0)

  def testMemoryEstimates(self):
    with ops.Graph().as_default() as g:
      with ops.device('/job:localhost/replica:0/task:0/device:CPU:0'):
        a = random_ops.random_uniform(shape=())
        b = random_ops.random_uniform(shape=())
        c = a + b
        train_op = ops.get_collection_ref(ops.GraphKeys.TRAIN_OP)
        train_op.append(c)
        mg = meta_graph.create_meta_graph_def(graph=g)
        grappler_item = item.Item(mg)
        grappler_cluster = cluster.Cluster(
            disable_detailed_stats=True, disable_timeline=True)
        peak_mem = grappler_cluster.DeterminePeakMemoryUsage(grappler_item)
        self.assertLessEqual(1, len(peak_mem))
        snapshot = peak_mem['/job:localhost/replica:0/task:0/device:CPU:0']
        peak_usage = snapshot[0]
        self.assertEqual(12, peak_usage)
        live_tensors = snapshot[1]
        self.assertEqual(5, len(live_tensors))

  def testVirtualCluster(self):
    with ops.Graph().as_default() as g:
      with ops.device('/device:GPU:0'):
        a = random_ops.random_uniform(shape=[1024, 1024])
        b = random_ops.random_uniform(shape=[1024, 1024])
        c = a + b
      train_op = ops.get_collection_ref(ops.GraphKeys.TRAIN_OP)
      train_op.append(c)
      mg = meta_graph.create_meta_graph_def(graph=g)
      grappler_item = item.Item(mg)
      device_properties = device_properties_pb2.DeviceProperties(
          type='GPU',
          frequency=1000,
          num_cores=60,
          environment={'architecture': '7'})
      named_device = device_properties_pb2.NamedDevice(
          properties=device_properties, name='/device:GPU:0')
      grappler_cluster = cluster.Cluster(
          disable_detailed_stats=False,
          disable_timeline=False,
          devices=[named_device])
      op_perfs, run_time, _ = grappler_cluster.MeasureCosts(grappler_item)
      self.assertEqual(run_time, 0.000209)
      self.assertEqual(len(op_perfs), 5)

      estimated_perf = grappler_cluster.EstimatePerformance(named_device)
      self.assertEqual(7680.0, estimated_perf)

  def testContext(self):
    with ops.Graph().as_default() as g:
      a = random_ops.random_uniform(shape=())
      b = random_ops.random_uniform(shape=())
      c = a + b
      train_op = ops.get_collection_ref(ops.GraphKeys.TRAIN_OP)
      train_op.append(c)
      mg = meta_graph.create_meta_graph_def(graph=g)
      grappler_item = item.Item(mg)

    with cluster.Provision(
        disable_detailed_stats=False, disable_timeline=False) as gcluster:
      op_perfs, run_time, step_stats = gcluster.MeasureCosts(grappler_item)
      self.assertTrue(run_time > 0)
      self.assertEqual(len(op_perfs), 4)
      self.assertTrue(step_stats.dev_stats)

  def testAvailableOps(self):
    with cluster.Provision() as gcluster:
      op_names = gcluster.ListAvailableOps()
      self.assertTrue('Add' in op_names)
      self.assertTrue('MatMul' in op_names)
      self.assertEqual(op_names, sorted(op_names))

  def testSupportDevices(self):
    with ops.Graph().as_default() as g:
      a = random_ops.random_uniform(shape=(2, 3))
      b = random_ops.random_uniform(shape=(2, 3))
      c = a + b
      dims = math_ops.range(0, array_ops.rank(c), 1)
      d = math_ops.reduce_sum(a, axis=dims)
      train_op = ops.get_collection_ref(ops.GraphKeys.TRAIN_OP)
      train_op.append(d)
      mg = meta_graph.create_meta_graph_def(graph=g)
      grappler_item = item.Item(mg)

      device_properties = device_properties_pb2.DeviceProperties(
          type='GPU', frequency=1000, num_cores=60)
      named_gpu = device_properties_pb2.NamedDevice(
          properties=device_properties, name='/GPU:0')
      device_properties = device_properties_pb2.DeviceProperties(
          type='CPU', frequency=3000, num_cores=6)
      named_cpu = device_properties_pb2.NamedDevice(
          properties=device_properties, name='/CPU:0')
      virtual_cluster = cluster.Cluster(devices=[named_cpu, named_gpu])
      supported_dev = virtual_cluster.GetSupportedDevices(grappler_item)
      self.assertEqual(supported_dev['add'], ['/CPU:0', '/GPU:0'])
      self.assertEqual(supported_dev['Sum'], ['/CPU:0', '/GPU:0'])
      self.assertEqual(supported_dev['range'], ['/CPU:0', '/GPU:0'])

      real_cluster = cluster.Cluster()
      supported_dev = real_cluster.GetSupportedDevices(grappler_item)
      if test.is_gpu_available():
        self.assertEqual(supported_dev['add'], [
            '/job:localhost/replica:0/task:0/device:CPU:0',
            '/job:localhost/replica:0/task:0/device:GPU:0'
        ])
        self.assertEqual(supported_dev['Sum'], [
            '/job:localhost/replica:0/task:0/device:CPU:0',
            '/job:localhost/replica:0/task:0/device:GPU:0'
        ])
        # The axis tensor must reside on the host
        self.assertEqual(supported_dev['range'],
                         ['/job:localhost/replica:0/task:0/device:CPU:0'])
      else:
        self.assertEqual(supported_dev['add'],
                         ['/job:localhost/replica:0/task:0/device:CPU:0'])

if __name__ == '__main__':
  test.main()


text:
require "spec_helper"

describe Mongoid::Matchers::Gte do

  describe "#matches?" do

    context "when the value is larger" do

      let(:matcher) do
        described_class.new(5)
      end

      it "returns true" do
        matcher.matches?("$gte" => 3).should be_true
      end
    end

    context "when the value is smaller" do

      let(:matcher) do
        described_class.new(5)
      end

      it "returns false" do
        matcher.matches?("$gte" => 10).should be_false
      end
    end

    context "when the value is equal" do

      let(:matcher) do
        described_class.new(5)
      end

      it "returns true" do
        matcher.matches?("$gte" => 5).should be_true
      end
    end

    context "when the value is nil" do

      let(:matcher) do
        described_class.new(nil)
      end

      it "returns false" do
        matcher.matches?("$gte" => 5).should be_false
      end
    end

    context "when the value is an array" do
      context "there are value valid" do
        let(:matcher) do
          described_class.new([6,4])
        end

        it "returns false" do
          matcher.matches?("$gte" => 5).should be_true
        end
      end

      context "there are not value valid" do
        let(:matcher) do
          described_class.new([3,4])
        end

        it "returns false" do
          matcher.matches?("$gte" => 5).should be_false
        end

      end
    end
  end
end


text:
[![Build Status](https://travis-ci.org/tamada/kushinada.svg)](https://travis-ci.org/tamada/kushinada)

## Overview

Web interface for birthmarking toolkit.

A birthmark is a set of native characteristics that the program
originally possesses. The birthmark is carefully extracted from
critical portions of class file. Hence, if a class file P has the same
birthmark as another class file Q's, Q is very likely to be a copy of
P. Thus, the birthmark can be used as a simple but powerful signature
to distinguish doubtful class files (those which seem to be copies).

## Features

The features of KUSHINADA are:
* to store birthmark into the database, and
    * the birthmarks are extracted from given jar files, and
    * from specified maven repository.
* to compare birthmarks from database and given jar files.

## Compile & Run

1. Simply type ```mvn package```.
2. to run KUSHINADA, type ```java -jar target/kushinada-1.0-SNAPSHOT.jar```
3. Access ```http://localhost:8080``` with Web browser.

## Requirements

* Maven 3.x
* DWR 3.0.0
* Servlet 2.5
* Winstone 2.8
* h2 database
* Apache Commons DBUtils
* Stigmata

All of dependencies automtically download from internet by Maven.

## Licenses

Apache License version 2.0.

## Developers

* Haruaki Tamada

Please notify us some bugs and requests on https://github.com/tamada/kushinada.


text:
/// <reference types="node" />
import { IncomingMessage } from 'http';

interface Options {
	/**
	 * Setting this to true will yield an array. In other words; instead of yielding once for every payload—we collect
	 * all complete payloads for a chunk and then yield.
	 *
	 * @default false
	 */
	multiple: boolean;
}

type Part<Body, Fallback> =
	| { json: false; headers: Record<string, string>; body: Fallback }
	| { json: true; headers: Record<string, string>; body: Body };

// Browser~

declare function meros<T = object>(
	response: Response,
	options: {
		multiple: true;
	},
): Promise<Response | AsyncGenerator<ReadonlyArray<Part<T, Buffer>>>>;
declare function meros<T = object>(
	response: Response,
	options?: {
		multiple: false;
	},
): Promise<Response | AsyncGenerator<Part<T, Buffer>>>;
/**
 * Yield immediately for every part made available on the response. If the `content-type` of the response isn't a
 * multipart body, then we'll resolve with {@link Response}.
 *
 * @example
 *
 * ```js
 * const parts = await fetch('/fetch-multipart')
 *      .then(meros);
 *
 * for await (const part of parts) {
 *     // do something with this part
 * }
 * ```
 */
declare function meros<T = object>(
	response: Response,
	options?: Options,
): Promise<Response | AsyncGenerator<Part<T, Buffer>>>;

// Node~

declare function meros<T = object>(
	response: IncomingMessage,
	options: {
		multiple: true;
	},
): Promise<IncomingMessage | AsyncGenerator<ReadonlyArray<Part<T, Buffer>>>>;
declare function meros<T = object>(
	response: IncomingMessage,
	options?: {
		multiple: false;
	},
): Promise<IncomingMessage | AsyncGenerator<Part<T, Buffer>>>;
/**
 * Yield immediately for every part made available on the response. If the `content-type` of the response isn't a
 * multipart body, then we'll resolve with {@link IncomingMessage}.
 *
 * @example
 *
 * ```js
 * const response = await new Promise((resolve) => {
 *   const request = http.get(`http://my-domain/mock-ep`, (response) => {
 *   	resolve(response);
 *   });
 *   request.end();
 * });
 *
 * const parts = await meros(response);
 *
 * for await (const part of parts) {
 *     // do something with this part
 * }
 * ```
 */
declare function meros<T = object>(
	response: IncomingMessage,
	options?: Options,
): Promise<IncomingMessage | AsyncGenerator<Part<T, Buffer>>>;

export { meros };


text: Personal Project Euler solutions.


text:
package org.apache.shardingsphere.dbtest.cases.dataset.row;

import com.google.common.base.Splitter;
import lombok.Getter;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import java.util.List;

/**
 * Data set row.
 */
@Getter
@XmlAccessorType(XmlAccessType.FIELD)
public final class DataSetRow {

    @XmlAttribute(name = "data-node")
    private String dataNode;

    @XmlAttribute(required = true)
    private String values;

    /**
     * Get values.
     *
     * @return value list
     */
    public List<String> getValues() {
        return Splitter.on(",").trimResults().splitToList(values);
    }
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Bull. natn. Sci. Mus. , Tokyo, B 25(3): 107 (1999)

#### Original name
Amanita orientigemmata Zhu L. Yang & Yoshim. Doi

### Remarks
null


text:
class ConfirmableEmail < ActiveRecord::Migration

  def up
    change_table :users do |t|
      t.string   :confirmation_token
      t.datetime :confirmed_at
      t.datetime :confirmation_sent_at
      t.string   :unconfirmed_email
    end
    User.all.each do |u|
      u.confirmed_at = Time.now
      u.save!
    end
  end

  def down
    change_table :users do |t|
      t.remove :confirmation_token
      t.remove :confirmed_at
      t.remove :confirmation_sent_at
      t.remove :unconfirmed_email
    end
  end
end


text:
package gew.logging.util;

public class LoggingContextFilter {

}


text:
package org.hisp.dhis.android.core.dataset.internal;

import org.hisp.dhis.android.core.arch.cleaners.internal.CollectionCleaner;
import org.hisp.dhis.android.core.arch.cleaners.internal.LinkCleaner;
import org.hisp.dhis.android.core.arch.cleaners.internal.OrphanCleaner;
import org.hisp.dhis.android.core.arch.db.stores.internal.IdentifiableObjectStore;
import org.hisp.dhis.android.core.arch.handlers.internal.HandleAction;
import org.hisp.dhis.android.core.arch.handlers.internal.Handler;
import org.hisp.dhis.android.core.arch.handlers.internal.LinkHandler;
import org.hisp.dhis.android.core.common.Access;
import org.hisp.dhis.android.core.common.DataAccess;
import org.hisp.dhis.android.core.dataelement.DataElementOperand;
import org.hisp.dhis.android.core.dataset.DataInputPeriod;
import org.hisp.dhis.android.core.dataset.DataSet;
import org.hisp.dhis.android.core.dataset.DataSetCompulsoryDataElementOperandLink;
import org.hisp.dhis.android.core.dataset.DataSetElement;
import org.hisp.dhis.android.core.dataset.DataSetInternalAccessor;
import org.hisp.dhis.android.core.dataset.Section;
import org.hisp.dhis.android.core.indicator.DataSetIndicatorLink;
import org.hisp.dhis.android.core.indicator.Indicator;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;

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

import static org.mockito.ArgumentMatchers.anyList;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.anyString;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;

@RunWith(JUnit4.class)
public class DataSetHandlerShould {

    @Mock
    private IdentifiableObjectStore<DataSet> dataSetStore;

    @Mock
    private Handler<Section> sectionHandler;

    @Mock
    private OrphanCleaner<DataSet, Section> sectionOrphanCleaner;

    @Mock
    private Handler<DataElementOperand> compulsoryDataElementOperandHandler;

    @Mock
    private LinkHandler<DataElementOperand, DataSetCompulsoryDataElementOperandLink>
            dataSetCompulsoryDataElementOperandLinkHandler;

    @Mock
    private LinkHandler<DataInputPeriod, DataInputPeriod> dataInputPeriodHandler;

    @Mock
    private DataSet dataSet;

    @Mock
    private List<DataSet> dataSets;

    @Mock
    private Access access;

    @Mock
    private DataAccess dataAccess;

    @Mock
    private Section section;

    @Mock
    private List<Section> sections;

    @Mock
    private DataElementOperand compulsoryDataElementOperand;

    @Mock
    private List<DataElementOperand> compulsoryDataElementOperands;

    @Mock
    private DataInputPeriod dataInputPeriod;

    @Mock
    private LinkHandler<DataSetElement, DataSetElement> dataSetElementLinkHandler;

    @Mock
    private LinkHandler<Indicator, DataSetIndicatorLink> dataSetIndicatorLinkHandler;

    @Mock
    private CollectionCleaner<DataSet> collectionCleaner;

    @Mock
    private LinkCleaner<DataSet> linkCleaner;

    @Mock
    private List<DataInputPeriod> dataInputPeriods;

    // object to test
    private DataSetHandler dataSetHandler;

    @Before
    public void setUp() throws Exception {

        MockitoAnnotations.initMocks(this);

        dataSetHandler = new DataSetHandler(dataSetStore,
                sectionHandler,
                sectionOrphanCleaner,
                compulsoryDataElementOperandHandler,
                dataSetCompulsoryDataElementOperandLinkHandler,
                dataInputPeriodHandler,
                dataSetElementLinkHandler,
                dataSetIndicatorLinkHandler,
                collectionCleaner,
                linkCleaner);

        when(dataSet.uid()).thenReturn("dataset_uid");
        when(dataSet.access()).thenReturn(access);
        when(access.data()).thenReturn(dataAccess);
        when(dataAccess.write()).thenReturn(true);

        dataSets = new ArrayList<>();
        dataSets.add(dataSet);

        sections = new ArrayList<>();
        sections.add(section);
        when(DataSetInternalAccessor.accessSections(dataSet)).thenReturn(sections);

        compulsoryDataElementOperands = new ArrayList<>();
        compulsoryDataElementOperands.add(compulsoryDataElementOperand);
        when(dataSet.compulsoryDataElementOperands()).thenReturn(compulsoryDataElementOperands);

        dataInputPeriods = new ArrayList<>();
        dataInputPeriods.add(dataInputPeriod);
        when(dataSet.dataInputPeriods()).thenReturn(dataInputPeriods);
    }

    @Test
    public void not_perform_any_action_passing_null_arguments() {

        dataSetHandler.handle(null);

        verify(dataSetStore, never()).delete(anyString());
        verify(dataSetStore, never()).update(any(DataSet.class));
        verify(dataSetStore, never()).insert(any(DataSet.class));

        verify(sectionHandler, never()).handleMany(anyList());

        verify(compulsoryDataElementOperandHandler, never()).handleMany(anyList());

        verify(dataInputPeriodHandler, never()).handleMany(anyString(), anyList(), any());
    }

    @Test
    public void handle_nested_sections() {

        dataSetHandler.handle(dataSet);

        verify(sectionHandler).handleMany(anyList());
    }

    @Test
    public void delete_orphan_sections() {

        when(dataSetStore.updateOrInsert(any(DataSet.class))).thenReturn(HandleAction.Update);
        dataSetHandler.handle(dataSet);

        verify(sectionOrphanCleaner).deleteOrphan(dataSet, sections);
    }

    @Test
    public void not_delete_orphan_sections_inserting() {

        when(dataSetStore.updateOrInsert(any(DataSet.class))).thenReturn(HandleAction.Insert);
        dataSetHandler.handle(dataSet);

        verify(sectionOrphanCleaner, never()).deleteOrphan(dataSet, sections);
    }

    @Test
    public void handle_nested_compulsory_data_elements_operands() {

        dataSetHandler.handle(dataSet);

        verify(compulsoryDataElementOperandHandler).handleMany(anyList());
    }

    @Test
    public void handle_data_set_compulsory_data_element_operand_link() {

        dataSetHandler.handle(dataSet);

        verify(dataSetCompulsoryDataElementOperandLinkHandler).handleMany(eq(dataSet.uid()), anyList(), any());
    }

    @Test
    public void handle_nested_data_input_periods() {

        dataSetHandler.handle(dataSet);

        verify(dataInputPeriodHandler).handleMany(anyString(), anyList(), any());
    }

    @Test
    public void handle_data_element_links() {

        dataSetHandler.handle(dataSet);

        verify(dataSetElementLinkHandler).handleMany(anyString(), anyList(), any());
    }

    @Test
    public void handle_indicator_links() {

        dataSetHandler.handle(dataSet);

        verify(dataSetIndicatorLinkHandler).handleMany(anyString(), anyList(), any());
    }
}


text:
/// <reference path="jqwidgets.d.ts" />
import { Component, Input, Output, EventEmitter, ElementRef, forwardRef, OnChanges, SimpleChanges, ChangeDetectionStrategy } from '@angular/core';
import { ControlValueAccessor, NG_VALUE_ACCESSOR } from '@angular/forms';

const noop = () => { };
declare let JQXLite: any;

export const CUSTOM_INPUT_CONTROL_VALUE_ACCESSOR: any = {
    provide: NG_VALUE_ACCESSOR,
    useExisting: forwardRef(() => jqxSliderComponent),
    multi: true
}

@Component({
    selector: 'jqxSlider',
    template: '
<ng-content></ng-content>
',
    providers: [CUSTOM_INPUT_CONTROL_VALUE_ACCESSOR],
    changeDetection: ChangeDetectionStrategy.OnPush
})

export class jqxSliderComponent implements ControlValueAccessor, OnChanges
{
   @Input('buttonsPosition') attrButtonsPosition: any;
   @Input('disabled') attrDisabled: any;
   @Input('layout') attrLayout: any;
   @Input('mode') attrMode: any;
   @Input('minorTicksFrequency') attrMinorTicksFrequency: any;
   @Input('minorTickSize') attrMinorTickSize: any;
   @Input('max') attrMax: any;
   @Input('min') attrMin: any;
   @Input('orientation') attrOrientation: any;
   @Input('rangeSlider') attrRangeSlider: any;
   @Input('rtl') attrRtl: any;
   @Input('step') attrStep: any;
   @Input('showTicks') attrShowTicks: any;
   @Input('showMinorTicks') attrShowMinorTicks: any;
   @Input('showTickLabels') attrShowTickLabels: any;
   @Input('showButtons') attrShowButtons: any;
   @Input('showRange') attrShowRange: any;
   @Input('template') attrTemplate: any;
   @Input('theme') attrTheme: any;
   @Input('ticksPosition') attrTicksPosition: any;
   @Input('ticksFrequency') attrTicksFrequency: any;
   @Input('tickSize') attrTickSize: any;
   @Input('tickLabelFormatFunction') attrTickLabelFormatFunction: any;
   @Input('tooltip') attrTooltip: any;
   @Input('tooltipHideDelay') attrTooltipHideDelay: any;
   @Input('tooltipPosition') attrTooltipPosition: any;
   @Input('tooltipFormatFunction') attrTooltipFormatFunction: any;
   @Input('value') attrValue: any;
   @Input('values') attrValues: any;
   @Input('width') attrWidth: any;
   @Input('height') attrHeight: any;

   @Input('auto-create') autoCreate: boolean = true;

   properties: string[] = ['buttonsPosition','disabled','height','layout','mode','minorTicksFrequency','minorTickSize','max','min','orientation','rangeSlider','rtl','step','showTicks','showMinorTicks','showTickLabels','showButtons','showRange','template','theme','ticksPosition','ticksFrequency','tickSize','tickLabelFormatFunction','tooltip','tooltipHideDelay','tooltipPosition','tooltipFormatFunction','value','values','width'];
   host: any;
   elementRef: ElementRef;
   widgetObject:  jqwidgets.jqxSlider;

   private onTouchedCallback: () => void = noop;
   private onChangeCallback: (_: any) => void = noop;

   constructor(containerElement: ElementRef) {
      this.elementRef = containerElement;
   }

   ngOnInit() {
      if (this.autoCreate) {
         this.createComponent();
      }
   };

   ngOnChanges(changes: SimpleChanges) {
      if (this.host) {
         for (let i = 0; i < this.properties.length; i++) {
            let attrName = 'attr' + this.properties[i].substring(0, 1).toUpperCase() + this.properties[i].substring(1);
            let areEqual: boolean;

            if (this[attrName] !== undefined) {
               if (typeof this[attrName] === 'object') {
                  if (this[attrName] instanceof Array) {
                     areEqual = this.arraysEqual(this[attrName], this.host.jqxSlider(this.properties[i]));
                  }
                  if (areEqual) {
                     return false;
                  }

                  this.host.jqxSlider(this.properties[i], this[attrName]);
                  continue;
               }

               if (this[attrName] !== this.host.jqxSlider(this.properties[i])) {
                  this.host.jqxSlider(this.properties[i], this[attrName]);
               }
            }
         }
      }
   }

   arraysEqual(attrValue: any, hostValue: any): boolean {
      if (attrValue.length != hostValue.length) {
         return false;
      }
      for (let i = 0; i < attrValue.length; i++) {
         if (attrValue[i] !== hostValue[i]) {
            return false;
         }
      }
      return true;
   }

   manageAttributes(): any {
      let options = {};
      for (let i = 0; i < this.properties.length; i++) {
         let attrName = 'attr' + this.properties[i].substring(0, 1).toUpperCase() + this.properties[i].substring(1);
         if (this[attrName] !== undefined) {
            options[this.properties[i]] = this[attrName];
         }
      }
      return options;
   }

   createComponent(options?: any): void {
      if (options) {
         JQXLite.extend(options, this.manageAttributes());
      }
      else {
        options = this.manageAttributes();
      }
      this.host = JQXLite(this.elementRef.nativeElement.firstChild);
      this.__wireEvents__();
      this.widgetObject = jqwidgets.createInstance(this.host, 'jqxSlider', options);

      this.__updateRect__();
   }

   createWidget(options?: any): void {
        this.createComponent(options);
   }

   __updateRect__() : void {
      this.host.css({ width: this.attrWidth, height: this.attrHeight });
   }

   get ngValue(): any {
       if (this.widgetObject)
           return this.host.val();
       return '';
   }

   set ngValue(value: any) {
       if (this.widgetObject) {
           this.onChangeCallback(value);
       }
   }

   writeValue(value: any): void {
       if(this.widgetObject) {
           this.onChangeCallback(this.host.val());
       }
   }

   registerOnChange(fn: any): void {
       this.onChangeCallback = fn;
   }

   registerOnTouched(fn: any): void {
       this.onTouchedCallback = fn;
   }

   setOptions(options: any) : void {
      this.host.jqxSlider('setOptions', options);
   }

   // jqxSliderComponent properties
   buttonsPosition(arg?: string) : any {
      if (arg !== undefined) {
          this.host.jqxSlider('buttonsPosition', arg);
      } else {
          return this.host.jqxSlider('buttonsPosition');
      }
   }

   disabled(arg?: boolean) : any {
      if (arg !== undefined) {
          this.host.jqxSlider('disabled', arg);
      } else {
          return this.host.jqxSlider('disabled');
      }
   }

   height(arg?: String | Number) : any {
      if (arg !== undefined) {
          this.host.jqxSlider('height', arg);
      } else {
          return this.host.jqxSlider('height');
      }
   }

   layout(arg?: string) : any {
      if (arg !== undefined) {
          this.host.jqxSlider('layout', arg);
      } else {
          return this.host.jqxSlider('layout');
      }
   }

   mode(arg?: string) : any {
      if (arg !== undefined) {
          this.host.jqxSlider('mode', arg);
      } else {
          return this.host.jqxSlider('mode');
      }
   }

   minorTicksFrequency(arg?: number) : any {
      if (arg !== undefined) {
          this.host.jqxSlider('minorTicksFrequency', arg);
      } else {
          return this.host.jqxSlider('minorTicksFrequency');
      }
   }

   minorTickSize(arg?: number) : any {
      if (arg !== undefined) {
          this.host.jqxSlider('minorTickSize', arg);
      } else {
          return this.host.jqxSlider('minorTickSize');
      }
   }

   max(arg?: number) : any {
      if (arg !== undefined) {
          this.host.jqxSlider('max', arg);
      } else {
          return this.host.jqxSlider('max');
      }
   }

   min(arg?: number) : any {
      if (arg !== undefined) {
          this.host.jqxSlider('min', arg);
      } else {
          return this.host.jqxSlider('min');
      }
   }

   orientation(arg?: string) : any {
      if (arg !== undefined) {
          this.host.jqxSlider('orientation', arg);
      } else {
          return this.host.jqxSlider('orientation');
      }
   }

   rangeSlider(arg?: boolean) : any {
      if (arg !== undefined) {
          this.host.jqxSlider('rangeSlider', arg);
      } else {
          return this.host.jqxSlider('rangeSlider');
      }
   }

   rtl(arg?: boolean) : any {
      if (arg !== undefined) {
          this.host.jqxSlider('rtl', arg);
      } else {
          return this.host.jqxSlider('rtl');
      }
   }

   step(arg?: number) : any {
      if (arg !== undefined) {
          this.host.jqxSlider('step', arg);
      } else {
          return this.host.jqxSlider('step');
      }
   }

   showTicks(arg?: boolean) : any {
      if (arg !== undefined) {
          this.host.jqxSlider('showTicks', arg);
      } else {
          return this.host.jqxSlider('showTicks');
      }
   }

   showMinorTicks(arg?: boolean) : any {
      if (arg !== undefined) {
          this.host.jqxSlider('showMinorTicks', arg);
      } else {
          return this.host.jqxSlider('showMinorTicks');
      }
   }

   showTickLabels(arg?: boolean) : any {
      if (arg !== undefined) {
          this.host.jqxSlider('showTickLabels', arg);
      } else {
          return this.host.jqxSlider('showTickLabels');
      }
   }

   showButtons(arg?: boolean) : any {
      if (arg !== undefined) {
          this.host.jqxSlider('showButtons', arg);
      } else {
          return this.host.jqxSlider('showButtons');
      }
   }

   showRange(arg?: boolean) : any {
      if (arg !== undefined) {
          this.host.jqxSlider('showRange', arg);
      } else {
          return this.host.jqxSlider('showRange');
      }
   }

   template(arg?: string) : any {
      if (arg !== undefined) {
          this.host.jqxSlider('template', arg);
      } else {
          return this.host.jqxSlider('template');
      }
   }

   theme(arg?: string) : any {
      if (arg !== undefined) {
          this.host.jqxSlider('theme', arg);
      } else {
          return this.host.jqxSlider('theme');
      }
   }

   ticksPosition(arg?: string) : any {
      if (arg !== undefined) {
          this.host.jqxSlider('ticksPosition', arg);
      } else {
          return this.host.jqxSlider('ticksPosition');
      }
   }

   ticksFrequency(arg?: number) : any {
      if (arg !== undefined) {
          this.host.jqxSlider('ticksFrequency', arg);
      } else {
          return this.host.jqxSlider('ticksFrequency');
      }
   }

   tickSize(arg?: number) : any {
      if (arg !== undefined) {
          this.host.jqxSlider('tickSize', arg);
      } else {
          return this.host.jqxSlider('tickSize');
      }
   }

   tickLabelFormatFunction(arg?: (value: any) => String) : any {
      if (arg !== undefined) {
          this.host.jqxSlider('tickLabelFormatFunction', arg);
      } else {
          return this.host.jqxSlider('tickLabelFormatFunction');
      }
   }

   tooltip(arg?: boolean) : any {
      if (arg !== undefined) {
          this.host.jqxSlider('tooltip', arg);
      } else {
          return this.host.jqxSlider('tooltip');
      }
   }

   tooltipHideDelay(arg?: number) : any {
      if (arg !== undefined) {
          this.host.jqxSlider('tooltipHideDelay', arg);
      } else {
          return this.host.jqxSlider('tooltipHideDelay');
      }
   }

   tooltipPosition(arg?: string) : any {
      if (arg !== undefined) {
          this.host.jqxSlider('tooltipPosition', arg);
      } else {
          return this.host.jqxSlider('tooltipPosition');
      }
   }

   tooltipFormatFunction(arg?: (value: any) => any) : any {
      if (arg !== undefined) {
          this.host.jqxSlider('tooltipFormatFunction', arg);
      } else {
          return this.host.jqxSlider('tooltipFormatFunction');
      }
   }

   value(arg?: any) : any {
      if (arg !== undefined) {
          this.host.jqxSlider('value', arg);
      } else {
          return this.host.jqxSlider('value');
      }
   }

   values(arg?: Array<Number>) : any {
      if (arg !== undefined) {
          this.host.jqxSlider('values', arg);
      } else {
          return this.host.jqxSlider('values');
      }
   }

   width(arg?: String | Number) : any {
      if (arg !== undefined) {
          this.host.jqxSlider('width', arg);
      } else {
          return this.host.jqxSlider('width');
      }
   }

   // jqxSliderComponent functions
   destroy(): void {
      this.host.jqxSlider('destroy');
   }

   decrementValue(): void {
      this.host.jqxSlider('decrementValue');
   }

   disable(): void {
      this.host.jqxSlider('disable');
   }

   enable(): void {
      this.host.jqxSlider('enable');
   }

   focus(): void {
      this.host.jqxSlider('focus');
   }

   getValue(): number {
      return this.host.jqxSlider('getValue');
   }

   incrementValue(): void {
      this.host.jqxSlider('incrementValue');
   }

   setValue(index: number): void {
      this.host.jqxSlider('setValue', index);
   }

   val(value?: string): any {
      if (value !== undefined) {
         this.host.jqxSlider("val", value);
      } else {
         return this.host.jqxSlider("val");
      }
   };

   // jqxSliderComponent events
   @Output() onChange = new EventEmitter();
   @Output() onCreated = new EventEmitter();
   @Output() onSlide = new EventEmitter();
   @Output() onSlideStart = new EventEmitter();
   @Output() onSlideEnd = new EventEmitter();

   __wireEvents__(): void {
      this.host.on('change', (eventData: any) => { this.onChange.emit(eventData); this.onChangeCallback(this.host.val()); });
      this.host.on('created', (eventData: any) => { this.onCreated.emit(eventData); });
      this.host.on('slide', (eventData: any) => { this.onSlide.emit(eventData); });
      this.host.on('slideStart', (eventData: any) => { this.onSlideStart.emit(eventData); });
      this.host.on('slideEnd', (eventData: any) => { this.onSlideEnd.emit(eventData); });
   }

} //jqxSliderComponent


text:
using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Azure.Management.Automation.Models;
using Microsoft.WindowsAzure;

namespace Microsoft.Azure.Management.Automation
{
    /// <summary>
    /// Service operation for automation schedules.  (see
    /// http://msdn.microsoft.com/en-us/library/windowsazure/XXXX.aspx for
    /// more information)
    /// </summary>
    public partial interface IScheduleOperations
    {
        /// <summary>
        /// Create a schedule.  (see
        /// http://msdn.microsoft.com/en-us/library/windowsazure/XXXXX.aspx
        /// for more information)
        /// </summary>
        /// <param name='automationAccount'>
        /// The automation account name.
        /// </param>
        /// <param name='parameters'>
        /// The parameters supplied to the create schedule operation.
        /// </param>
        /// <param name='cancellationToken'>
        /// Cancellation token.
        /// </param>
        /// <returns>
        /// The response model for the create schedule operation.
        /// </returns>
        Task<ScheduleCreateResponse> CreateAsync(string automationAccount, ScheduleCreateParameters parameters, CancellationToken cancellationToken);

        /// <summary>
        /// Delete the schedule identified by scheduleId.  (see
        /// http://msdn.microsoft.com/en-us/library/windowsazure/XXXXXXX.aspx
        /// for more information)
        /// </summary>
        /// <param name='automationAccount'>
        /// The automation account name.
        /// </param>
        /// <param name='scheduleId'>
        /// The schedule id.
        /// </param>
        /// <param name='cancellationToken'>
        /// Cancellation token.
        /// </param>
        /// <returns>
        /// A standard service response including an HTTP status code and
        /// request ID.
        /// </returns>
        Task<OperationResponse> DeleteAsync(string automationAccount, string scheduleId, CancellationToken cancellationToken);

        /// <summary>
        /// Retrieve the schedule identified by scheduleId.  (see
        /// http://msdn.microsoft.com/en-us/library/windowsazure/XXXXXXX.aspx
        /// for more information)
        /// </summary>
        /// <param name='automationAccount'>
        /// The automation account name.
        /// </param>
        /// <param name='scheduleId'>
        /// The schedule id.
        /// </param>
        /// <param name='cancellationToken'>
        /// Cancellation token.
        /// </param>
        /// <returns>
        /// The response model for the get schedule operation.
        /// </returns>
        Task<ScheduleGetResponse> GetAsync(string automationAccount, string scheduleId, CancellationToken cancellationToken);

        /// <summary>
        /// Retrieve a list of schedules for the given automation account.
        /// (see http://msdn.microsoft.com/en-us/library/windowsazure/XXXXXXX.aspx
        /// for more information)
        /// </summary>
        /// <param name='automationAccount'>
        /// The automation account name.
        /// </param>
        /// <param name='skipToken'>
        /// The skip token.
        /// </param>
        /// <param name='cancellationToken'>
        /// Cancellation token.
        /// </param>
        /// <returns>
        /// The response model for the list schedule operation.
        /// </returns>
        Task<ScheduleListResponse> ListAsync(string automationAccount, string skipToken, CancellationToken cancellationToken);

        /// <summary>
        /// Retrieve a list of one schedule identified by scheduleName.  (see
        /// http://msdn.microsoft.com/en-us/library/windowsazure/XXXXXXX.aspx
        /// for more information)
        /// </summary>
        /// <param name='automationAccount'>
        /// The automation account name.
        /// </param>
        /// <param name='scheduleName'>
        /// The schedule name.
        /// </param>
        /// <param name='cancellationToken'>
        /// Cancellation token.
        /// </param>
        /// <returns>
        /// The response model for the list schedule operation.
        /// </returns>
        Task<ScheduleListResponse> ListByNameAsync(string automationAccount, string scheduleName, CancellationToken cancellationToken);

        /// <summary>
        /// Update the schedule identified by scheduleId.  (see
        /// http://msdn.microsoft.com/en-us/library/windowsazure/XXXXXXX.aspx
        /// for more information)
        /// </summary>
        /// <param name='automationAccount'>
        /// The automation account name.
        /// </param>
        /// <param name='parameters'>
        /// The parameters supplied to the update schedule operation.
        /// </param>
        /// <param name='cancellationToken'>
        /// Cancellation token.
        /// </param>
        /// <returns>
        /// A standard service response including an HTTP status code and
        /// request ID.
        /// </returns>
        Task<OperationResponse> UpdateAsync(string automationAccount, ScheduleUpdateParameters parameters, CancellationToken cancellationToken);
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
	<string name="library_name">OperatorSettingsBuddy.Android</string>
</resources>


text:
Using a Neural Network to train a snake to play the snake game. This project uses the Keras module for the construction of the Neural Netowork and PyGame to create the User Interface.

## Keras: Deep Learning library for TensorFlow and Theano

Keras is a high-level neural networks library, written in Python and capable of running on top of either [TensorFlow](https://github.com/tensorflow/tensorflow) or [Theano](https://github.com/Theano/Theano). It was developed with a focus on enabling fast experimentation. *Being able to go from idea to result with the least possible delay is key to doing good research.*

Use Keras if you need a deep learning library that:

- Allows for easy and fast prototyping (through total modularity, minimalism, and extensibility).
- Supports both convolutional networks and recurrent networks, as well as combinations of the two.
- Supports arbitrary connectivity schemes (including multi-input and multi-output training).
- Runs seamlessly on CPU and GPU.

Read the documentation at [Keras.io](http://keras.io).

Keras is compatible with: __Python 2.7-3.5__.

------------------

## Installation

Keras uses the following dependencies:

- numpy, scipy
- pyyaml
- HDF5 and h5py (optional, required if you use model saving/loading functions)
- Optional but recommended if you use CNNs: cuDNN.

*When using the TensorFlow backend:*

- TensorFlow
    - [See installation instructions](https://github.com/tensorflow/tensorflow#download-and-setup).

*When using the Theano backend:*

- Theano
    - [See installation instructions](http://deeplearning.net/software/theano/install.html#install).

To install Keras, `cd` to the Keras folder and run the install command:
```sh
sudo python setup.py install
```

You can also install Keras from PyPI:
```sh
sudo pip install keras
```

------------------

## Switching from TensorFlow to Theano

By default, Keras will use TensorFlow as its tensor manipulation library. [Follow these instructions](http://keras.io/backend/) to configure the Keras backend.

------------------