text:
/**
 * @file
 * Declaration of a fully associative LRU tag store.
 */

#ifndef __MEM_CACHE_TAGS_FA_LRU_HH__
#define __MEM_CACHE_TAGS_FA_LRU_HH__

#include <cstdint>
#include <functional>
#include <string>
#include <unordered_map>
#include <vector>

#include "base/bitfield.hh"
#include "base/intmath.hh"
#include "base/logging.hh"
#include "base/statistics.hh"
#include "base/types.hh"
#include "mem/cache/cache_blk.hh"
#include "mem/cache/tags/base.hh"
#include "mem/packet.hh"
#include "params/FALRU.hh"

namespace gem5
{

// Uncomment to enable sanity checks for the FALRU cache and the
// TrackedCaches class
//#define FALRU_DEBUG

class BaseCache;
class ReplaceableEntry;

// A bitmask of the caches we are keeping track of. Currently the
// lowest bit is the smallest cache we are tracking, as it is
// specified by the corresponding parameter. The rest of the bits are
// for exponentially growing cache sizes.
typedef uint32_t CachesMask;

/**
 * A fully associative cache block.
 */
class FALRUBlk : public CacheBlk
{
  public:
    FALRUBlk() : CacheBlk(), prev(nullptr), next(nullptr), inCachesMask(0) {}

    /** The previous block in LRU order. */
    FALRUBlk *prev;
    /** The next block in LRU order. */
    FALRUBlk *next;

    /** A bit mask of the caches that fit this block. */
    CachesMask inCachesMask;

    /**
     * Pretty-print inCachesMask and other CacheBlk information.
     *
     * @return string with basic state information
     */
    std::string print() const override;
};

/**
 * A fully associative LRU cache. Keeps statistics for accesses to a number of
 * cache sizes at once.
 */
class FALRU : public BaseTags
{
  public:
    /** Typedef the block type used in this class. */
    typedef FALRUBlk BlkType;

  protected:
    /** The cache blocks. */
    FALRUBlk *blks;

    /** The MRU block. */
    FALRUBlk *head;
    /** The LRU block. */
    FALRUBlk *tail;

    /** Hash table type mapping addresses to cache block pointers. */
    struct PairHash
    {
        template <class T1, class T2>
        std::size_t operator()(const std::pair<T1, T2> &p) const
        {
            return std::hash<T1>()(p.first) ^ std::hash<T2>()(p.second);
        }
    };
    typedef std::pair<Addr, bool> TagHashKey;
    typedef std::unordered_map<TagHashKey, FALRUBlk *, PairHash> TagHash;

    /** The address hash table. */
    TagHash tagHash;

    /**
     * Move a cache block to the MRU position.
     *
     * @param blk The block to promote.
     */
    void moveToHead(FALRUBlk *blk);

    /**
     * Move a cache block to the LRU position.
     *
     * @param blk The block to demote.
     */
    void moveToTail(FALRUBlk *blk);

  public:
    typedef FALRUParams Params;

    /**
     * Construct and initialize this cache tagstore.
     */
    FALRU(const Params &p);
    ~FALRU();

    /**
     * Initialize blocks as FALRUBlk instances.
     */
    void tagsInit() override;

    /**
     * Invalidate a cache block.
     * @param blk The block to invalidate.
     */
    void invalidate(CacheBlk *blk) override;

    /**
     * Access block and update replacement data.  May not succeed, in which
     * case nullptr pointer is returned.  This has all the implications of a
     * cache access and should only be used as such.
     * Returns tag lookup latency and the inCachesMask flags as a side effect.
     *
     * @param pkt The packet holding the address to find.
     * @param lat The latency of the tag lookup.
     * @param in_cache_mask Mask indicating the caches in which the blk fits.
     * @return Pointer to the cache block.
     */
    CacheBlk* accessBlock(const PacketPtr pkt, Cycles &lat,
                          CachesMask *in_cache_mask);

    /**
     * Just a wrapper of above function to conform with the base interface.
     */
    CacheBlk* accessBlock(const PacketPtr pkt, Cycles &lat) override;

    /**
     * Find the block in the cache, do not update the replacement data.
     * @param addr The address to look for.
     * @param is_secure True if the target memory space is secure.
     * @param asid The address space ID.
     * @return Pointer to the cache block.
     */
    CacheBlk* findBlock(Addr addr, bool is_secure) const override;

    /**
     * Find a block given set and way.
     *
     * @param set The set of the block.
     * @param way The way of the block.
     * @return The block.
     */
    ReplaceableEntry* findBlockBySetAndWay(int set, int way) const override;

    /**
     * Find replacement victim based on address. The list of evicted blocks
     * only contains the victim.
     *
     * @param addr Address to find a victim for.
     * @param is_secure True if the target memory space is secure.
     * @param size Size, in bits, of new block to allocate.
     * @param evict_blks Cache blocks to be evicted.
     * @return Cache block to be replaced.
     */
    CacheBlk* findVictim(Addr addr, const bool is_secure,
                         const std::size_t size,
                         std::vector<CacheBlk*>& evict_blks) override;

    /**
     * Insert the new block into the cache and update replacement data.
     *
     * @param pkt Packet holding the address to update
     * @param blk The block to update.
     */
    void insertBlock(const PacketPtr pkt, CacheBlk *blk) override;

    void moveBlock(CacheBlk *src_blk, CacheBlk *dest_blk) override;

    /**
     * Generate the tag from the addres. For fully associative this is just the
     * block address.
     * @param addr The address to get the tag from.
     * @return The tag.
     */
    Addr extractTag(Addr addr) const override
    {
        return blkAlign(addr);
    }

    /**
     * Regenerate the block address from the tag.
     *
     * @param block The block.
     * @return the block address.
     */
    Addr regenerateBlkAddr(const CacheBlk* blk) const override
    {
        return blk->getTag();
    }

    void forEachBlk(std::function<void(CacheBlk &)> visitor) override {
        for (int i = 0; i < numBlocks; i++) {
            visitor(blks[i]);
        }
    }

    bool anyBlk(std::function<bool(CacheBlk &)> visitor) override {
        for (int i = 0; i < numBlocks; i++) {
            if (visitor(blks[i])) {
                return true;
            }
        }
        return false;
    }

  private:
    /**
     * Mechanism that allows us to simultaneously collect miss
     * statistics for multiple caches. Currently, we keep track of
     * caches from a set minimum size of interest up to the actual
     * cache size.
     */
    class CacheTracking : public statistics::Group
    {
      public:
        CacheTracking(unsigned min_size, unsigned max_size,
                      unsigned block_size, statistics::Group *parent);

        /**
         * Initialiaze cache blocks and the tracking mechanism
         *
         * All blocks in the cache need to be initialized once.
         *
         * @param blk the MRU block
         * @param blk the LRU block
         */
        void init(FALRUBlk *head, FALRUBlk *tail);

        /**
         * Update boundaries as a block will be moved to the MRU.
         *
         * For all caches that didn't fit the block before moving it,
         * we move their boundaries one block closer to the MRU. We
         * also update InCacheMasks as neccessary.
         *
         * @param blk the block that will be moved to the head
         */
        void moveBlockToHead(FALRUBlk *blk);

        /**
         * Update boundaries as a block will be moved to the LRU.
         *
         * For all caches that fitted the block before moving it, we
         * move their boundaries one block closer to the LRU. We
         * also update InCacheMasks as neccessary.
         *
         * @param blk the block that will be moved to the head
         */
        void moveBlockToTail(FALRUBlk *blk);

        /**
         * Notify of a block access.
         *
         * This should be called every time a block is accessed and it
         * updates statistics. If the input block is nullptr then we
         * treat the access as a miss. The block's InCacheMask
         * determines the caches in which the block fits.
         *
         * @param blk the block to record the access for
         */
        void recordAccess(FALRUBlk *blk);

        /**
         * Check that the tracking mechanism is in consistent state.
         *
         * Iterate from the head (MRU) to the tail (LRU) of the list
         * of blocks and assert the inCachesMask and the boundaries
         * are in consistent state.
         *
         * @param head the MRU block of the actual cache
         * @param head the LRU block of the actual cache
         */
        void check(const FALRUBlk *head, const FALRUBlk *tail) const;

      private:
        /** The size of the cache block */
        const unsigned blkSize;
        /** The smallest cache we are tracking */
        const unsigned minTrackedSize;
        /** The number of different size caches being tracked. */
        const int numTrackedCaches;
        /** A mask for all cache being tracked. */
        const CachesMask inAllCachesMask;
        /** Array of pointers to blocks at the cache boundaries. */
        std::vector<FALRUBlk*> boundaries;

      protected:
        /**
         * @defgroup FALRUStats Fully Associative LRU specific statistics
         * The FA lru stack lets us track multiple cache sizes at once. These
         * statistics track the hits and misses for different cache sizes.
         * @{
         */

        /** Hits in each cache */
        statistics::Vector hits;
        /** Misses in each cache */
        statistics::Vector misses;
        /** Total number of accesses */
        statistics::Scalar accesses;

        /**
         * @}
         */
    };
    CacheTracking cacheTracking;
};

} // namespace gem5

#endif // __MEM_CACHE_TAGS_FA_LRU_HH__


text:
This is an example dashboard to display the data that is collected by the [metrics handler](../metrics_handler).

This guide assumes you have a Google Cloud Platform project and you are running the metrics handler to collect data in BigQuery.

## Running locally

```
export JOB_HISTORY_TABLE_NAME='your-project-name.metrics_handler_dataset.job_history'
export METRIC_HISTORY_TABLE_NAME='your-project-name.metrics_handler_dataset.metric_history'
<optional, if you want to to split tests into multiple tabs or exclude tests>
export TEST_NAME_PREFIXES='prefix1,prefix2'

python3 -m bokeh serve --show dashboard/dashboard.py dashboard/metrics.py dashboard/compare.py
```

The arguments to `bokeh serve --show` are paths to dashboard Python files. The command above assumes you are running the command from `ml-testing-accelerators/`

## Hosting your dashboard

You can host your dashboard using App Engine.

Query caching with redis is strongly recommended but not strictly required - you can ignore the redis steps and the dashboard will work but will log warnings about failing to connect to the cache.

1. Set up env vars
```
export REGION=us-west2
export PROJECT_ID=my-project
export INSTANCE_NAME=my-redis-instance
```

2. `gcloud redis instances create $INSTANCE_NAME --size=2 --region=$REGION --redis-version=redis_4_0 --project=$PROJECT_ID`

3. Edit `app.yaml` in 3 ways:
  * Update redis info if using redis:
    * REDISHOST = Find this value using: `echo $(gcloud redis instances describe $INSTANCE_NAME --region=$REGION --project=$PROJECT_ID --format='value(host)')`
    * REDISPORT = Find this value using: `echo $(gcloud redis instances describe $INSTANCE_NAME --region=$REGION --project=$PROJECT_ID --format='value(port)')`
  * Update `JOB_HISTORY_TABLE_NAME` and `METRIC_HISTORY_TABLE_NAME`.
    * You can find these table names [here](https://console.cloud.google.com/bigquery) by clicking your project name in the left sidebar.
  * Change `--allow-websocket-origin` arg in `entrypoint` to be the URL of your app engine project. You can find this URL in your [App Engine Dashboard](https://console.cloud.google.com/appengine) (top right of that UI). If you don't see the URL there, try deploying first (see next step) and at that point you should receive your URL.

4. Make sure you are in the dir where `app.yaml` lives and then run `gcloud app deploy`

## Clean up your hosted dashboard

1. `gcloud redis instances delete $INSTANCE_NAME --region=$REGION --project=$PROJECT_ID`

2. Click "Disable Application" on [this page](https://console.cloud.google.com/appengine/settings)

# Advanced Usage

## Multiple dashboard versions

When you run `gcloud app deploy`, the command defaults to using `app.yaml`. You can specify a different yaml with e.g. `gcloud app deploy custom.yaml` or deploy multiple versions with `gcloud app deploy custom.yaml custom2.yaml`.

Check out `pytorch-dashboard.yaml` for an example of a secondary dashboard and note the `allow-websocket-origin` argument for an example of how the URL looks for the secondary dashboard(s).

## Privacy / authentication

You can restrict which tests are shown in the dashboard by using the `TEST_NAME_PREFIXES` environment variable in the .yaml file. If this variable is set, only tests with the supplied prefixes will be shown and each prefix will appear in its own tab. If this variable is not set, all tests will be shown and will not be divided into tabs.

The hosted dashboard runs as an App Engine app. You can restrict the URL to specific group(s) of people by following the instructions [here](https://cloud.google.com/iap/docs/app-engine-quickstart). You can configure the IAP (identity-aware proxy) rules such that each dashboard version has its own group of restricted viewers. See also the `Multiple dashboard versions` section above.

## Pre-generated URLs for the compare dashboard

The `compare.py` dashboard allows you to specify a list of test names and a list of metric names and renders 1 graph+table for each combination of test and metric.

Since it's tedious to type the same list of test and metric names for a commonly-used query, you can generate a URL with the test and metric names encoded in it.

Note that you can use the SQL wildcard `%` to use prefix or suffix matching.

The URL should be of the form `$APP_URL/compare?test_names=$B64_TEST_NAMES&metric_names=$B64_METRIC_NAMES`. For example, if your `APP_URL` is 'https://xl-ml-test.appspot.com', then a simple snippet to generate the URL could be:

```
python3
 > import base64
 > my_url = 'https://xl-ml-test.appspot.com'
 > b64_test_names = base64.b64encode('tf-nightly-%,my-other-test1,my-other-test-2'.encode('utf-8')).decode()
 > b64_metric_names = base64.b64encode('%examples/sec%,accuracy_final'.encode('utf-8')).decode()
 > print(f'{my_url}/compare?test_names={b64_test_names}&metric_names={b64_metric_names}')
```
(note the syntax would be a little different in python2)

redpajama_set_name: RedPajamaGithub


text:
package com.pourtois.symbolette.expr
import Expr._

import scala.collection.mutable.ListBuffer

/**
  * Created by manu on 24.10.16.
  */
trait UnaryOperator extends Expr {

  val op:Expr

  def build(op: Expr): UnaryOperator

  lazy val optimized = {
      val optimizedUnaries: Seq[UnaryOperator] = op.optimized.map(this.build(_))

       UnaryOperator.rules.flatMap(optimizedUnaries.collect(_)).sorted
    }
}
object UnaryOperator {
  type Rule = PartialFunction[UnaryOperator, Expr]

  val rules: List[Rule] = {
    val buffer = new ListBuffer[Rule]()
    def rule(r: Rule): Unit = {
      buffer += r
    }

    rule({ case oper : UnaryOperator => oper }) // Maybe this is the best optimization
    rule({ case Negate(Integer(a)) => Integer(-a) })
    rule({ case Negate(Negate(a)) => a })
    rule({ case Exp( Plus(a,b)) => exp(a)*exp(b) })

    buffer.toList
  }

}

case class Negate(  op:Expr) extends UnaryOperator {
  def derivative(d:Expr) = -op.derivative(d)

  def build(op: Expr): UnaryOperator = Negate(op)

  lazy val cost = 2 + op.cost
}

case class Exp(op :Expr) extends UnaryOperator {
  def build(op: Expr): UnaryOperator = Exp(op)

  def derivative(d: Expr): Expr = op.derivative(d)*Exp(op)

  lazy val cost = 4 + op.cost
}


text:
define(['userDetail/options', 'jquery', 'text!views/userDetail/userDetailRow/template.html'],
    function(userDetailViewOptions, $, template) {
        'use strict';

        return $.extend(true, {}, userDetailViewOptions, {
            template : template
        });
    });


text:
package nz.rafikn.movierates.model;

import java.util.ArrayList;
import java.util.Collection;

/**
 * Created by rafik on 26/06/16.
 */
public class RawSearch {

    private Movie movie;
    private Collection<SearchResponse> pages = new ArrayList<>();

    public RawSearch() {
    }

    public RawSearch(Movie movie) {
        this.movie = movie;
    }

    public Movie getMovie() {
        return movie;
    }

    public void setMovie(Movie movie) {
        this.movie = movie;
    }

    public Collection<SearchResponse> getPages() {
        return pages;
    }

    public void setPages(Collection<SearchResponse> pages) {
        this.pages = pages;
    }

    @Override
    public String toString() {
        return "RawSearch{" +
                "movie=" + movie +
                ", pages=" + pages +
                '}';
    }
}


text:
#ifndef _MGL_WAVE_MGL_
#define _MGL_WAVE_MGL_

#include <cstring>
#include <fstream>
#include <min/mem_chunk.h>
#include <string>
#include <vector>

// Reads a RIFF WAV File with two subchunks, 'fmt' and 'data'
// chunk_id (RIFF) - 4B - offset 0 == 'RIFF'
// chunk_size      - 4B - offset 4 == file_size - 8
// format (WAVE)   - 4B - offset 8 == 'WAVE'
// subchunk1_id    - 4B - offset 12 == "fmt "
// subchunk1_size  - 4B - offset 16 == 16 for PCM
// audio_format    - 2B - offset 20 == 1 (Linear Uncompressed PCM)
// num_channels    - 2B - offset 22 == Mono = 1, Stereo = 2
// sample_rate     - 4B - offset 24 == 44100 Hz (CD Quality)
// byte_rate       - 4B - offset 28 == sample_rate * num_channels * bytes_per_sample
// block_align     - 2B - offset 32 == num_channels * bytes_per_sample
// bits_per_sample - 2B - offset 34 == 'N' bits
// subchunk2_id    - 4B - offset 36 == "data"
// subchunk2_size  - 4B - offset 40 == data_size
// data            - ^^ - offset 44 == start of sound data

namespace min
{

class wave
{
  private:
    uint16_t _num_channels;
    uint32_t _sample_rate;
    uint32_t _bits_per_sample;
    std::vector<uint8_t> _data;

    inline void load(const std::string _file)
    {
        std::ifstream file(_file, std::ios::in | std::ios::binary | std::ios::ate);
        if (file.is_open())
        {
            // Get the size of the file
            const size_t size = static_cast<size_t>(file.tellg());

            // Adjust file pointer to beginning
            file.seekg(0, std::ios::beg);

            // Allocate space for new file
            std::vector<uint8_t> data(size);

            // Read bytes and close the file
            char *ptr = reinterpret_cast<char *>(data.data());
            file.read(ptr, size);

            // Close the file
            file.close();

            // Process the WAVE file
            load<std::vector<uint8_t>>(data);
        }
        else
        {
            throw std::runtime_error("wave: Could not load file '" + _file + "'");
        }
    }
    template <class T>
    inline void load(const T &data)
    {
        // Check that nothing funky is going on with char and uint8_t
        static_assert(sizeof(char) == 1, "Size of char is not 1");
        static_assert(sizeof(uint8_t) == 1, "Size of uint8_t is not 1");
        static_assert(std::is_same<std::uint8_t, unsigned char>::value,
                      "std::uint8_t must be implemented as unsigned char");

        // Get the size of the file
        const size_t size = data.size();
        if (size < 44)
        {
            throw std::runtime_error("wave: File not large enough to be WAV file");
        }

        // Asserted that size is unsigned previously
        const size_t file_size = static_cast<size_t>(size);

        // Check if this is a RIFF file
        size_t offset = 0;
        const uint32_t chunk_id = min::read_le<uint32_t>(data, offset);
        if (chunk_id != 0x46464952)
        {
            throw std::runtime_error("wave: File not a RIFF file");
        }

        // Read the chunk size in little endian
        const uint32_t chunk_size = min::read_le<uint32_t>(data, offset);
        if (chunk_size != file_size - 8)
        {
            throw std::runtime_error("wave: Invalid chunk size");
        }

        // Check if this is a WAVE file
        const uint32_t format = min::read_le<uint32_t>(data, offset);
        if (format != 0x45564157)
        {
            throw std::runtime_error("wave: File not a WAVE file");
        }

        // Check the first subchunk ID
        const uint32_t subchunk1_id = min::read_le<uint32_t>(data, offset);
        if (subchunk1_id != 0x20746D66)
        {
            throw std::runtime_error("wave: Invalid subchunk1 ID");
        }

        // Check that the subchunk1 size equates to PCM
        const uint32_t subchunk1_size = min::read_le<uint32_t>(data, offset);
        if (subchunk1_size != 16)
        {
            throw std::runtime_error("wave: WAV not storing PCM data");
        }

        // Check that the audio format is linear PCM
        const uint16_t audio_format = min::read_le<uint16_t>(data, offset);
        if (audio_format != 1)
        {
            throw std::runtime_error("wave: WAV not storing linear quantized PCM data");
        }

        // Read the num_channels and sample rate
        _num_channels = min::read_le<uint16_t>(data, offset);
        _sample_rate = min::read_le<uint32_t>(data, offset);

        // Read the byte rate, block align, and bits per sample
        const uint32_t byte_rate = min::read_le<uint32_t>(data, offset);
        const uint16_t block_align = min::read_le<uint16_t>(data, offset);

        _bits_per_sample = min::read_le<uint16_t>(data, offset);

        // Store the bytes per sample
        const uint16_t bytes_per_sample = _bits_per_sample / 8;

        // Check that the byte rate is correct
        if (byte_rate != _sample_rate * _num_channels * bytes_per_sample)
        {
            throw std::runtime_error("wave: Incorrect byte rate specified");
        }

        // Check that the block align is correct
        if (block_align != _num_channels * bytes_per_sample)
        {
            throw std::runtime_error("wave: Incorrect block align specified");
        }

        // Read the next subchunk ID and size
        uint32_t subchunk2_id = min::read_le<uint32_t>(data, offset);
        uint32_t subchunk2_size = min::read_le<uint32_t>(data, offset);

        // Check the second subchunk ID
        while (subchunk2_id != 0x61746164)
        {
            // Check that we didn't read past the end of file
            if (offset >= file_size)
            {
                throw std::runtime_error("wave: Can't find data chunk ID in file");
            }

            // Skip over the chunk
            offset += subchunk2_size;

            // Read the chunk contents
            subchunk2_id = min::read_le<uint32_t>(data, offset);
            subchunk2_size = min::read_le<uint32_t>(data, offset);
        }

        // Check that the subchunk2 size is valid
        if (subchunk2_size > file_size - 44)
        {
            throw std::runtime_error("wave: not enough sound data found in file");
        }

        // Allocate data and write into data buffer
        _data.resize(subchunk2_size);
        std::memcpy(&_data[0], &data[offset], subchunk2_size);
    }

  public:
    wave(const std::string &file)
    {
        load(file);
    }
    wave(const mem_file &mem)
    {
        load<mem_file>(mem);
    }
    inline void clear()
    {
        // Delete WAV data and reset WAV
        _data.clear();

        // Zero out fields so we dont try to use it later
        _num_channels = 0;
        _sample_rate = 0;
        _bits_per_sample = 0;
    }
    inline bool is_mono() const
    {
        return _num_channels == 1;
    }
    inline bool is_stereo() const
    {
        return _num_channels > 1;
    }
    inline const std::vector<uint8_t> &data() const
    {
        return _data;
    }
    inline uint32_t get_bits_per_sample() const
    {
        return _bits_per_sample;
    }
    inline size_t get_data_samples() const
    {
        // Calculate number of samples in data buffer
        return (_data.size() * 8) / _bits_per_sample;
    }
    inline uint32_t get_sample_rate() const
    {
        return _sample_rate;
    }
};
}
#endif


text:
using namespace node;
using namespace v8;

Persistent<Function> MediaStream::constructor;

MediaStream::MediaStream(webrtc::MediaStreamInterface* msi)
: _internalMediaStream(msi)
{
  msi->Release();
  _inactive = !IsMediaStreamActive();
  uv_mutex_init(&lock);
  uv_async_init(uv_default_loop(), &async, Run);

  async.data = this;
}

MediaStream::~MediaStream()
{

}

NAN_METHOD(MediaStream::New) {
  TRACE_CALL;
  NanScope();

  if(!args.IsConstructCall()) {
    return NanThrowTypeError("Use the new operator to construct the MediaStream.");
  }

  v8::Local<v8::External> _msi = v8::Local<v8::External>::Cast(args[0]);
  webrtc::MediaStreamInterface* msi = static_cast<webrtc::MediaStreamInterface*>(_msi->Value());

  MediaStream* obj = new MediaStream(msi);
  msi->RegisterObserver(obj);
  obj->Wrap( args.This() );

  TRACE_END;
  NanReturnValue( args.This() );
}

void MediaStream::QueueEvent(AsyncEventType type, void* data)
{
  TRACE_CALL;
  AsyncEvent evt;
  evt.type = type;
  evt.data = data;
  uv_mutex_lock(&lock);
  _events.push(evt);
  uv_mutex_unlock(&lock);

  uv_async_send(&async);
  TRACE_END;
}

void MediaStream::Run(uv_async_t* handle, int status)
{
  TRACE_CALL;
  NanScope();
  MediaStream* self = static_cast<MediaStream*>(handle->data);
  v8::Handle<v8::Object> ms = NanObjectWrapHandle(self);

  while(true)
  {
    uv_mutex_lock(&self->lock);
    bool empty = self->_events.empty();
    if(empty)
    {
      uv_mutex_unlock(&self->lock);
      break;
    }
    AsyncEvent evt = self->_events.front();
    self->_events.pop();
    uv_mutex_unlock(&self->lock);

    TRACE_U("evt.type", evt.type);
    if(MediaStream::CHANGE & evt.type)
    {
      // find current state and send appropriate events
      bool inactive = !self->IsMediaStreamActive();
      if (self->_inactive != inactive)
      {
        if (!inactive)
          evt.type = MediaStream::ACTIVE;
        else
          evt.type = MediaStream::INACTIVE;
        self->_inactive = inactive;
      }
    }

    if(MediaStream::ACTIVE & evt.type)
    {
      v8::Local<v8::Function> callback = v8::Local<v8::Function>::Cast(ms->Get(String::New("onactive")));
      if(!callback.IsEmpty())
      {
        v8::Local<v8::Value> argv[0];
        NanMakeCallback(ms, callback, 0, argv);
      }
    } else if(MediaStream::INACTIVE & evt.type)
    {
      v8::Local<v8::Function> callback = v8::Local<v8::Function>::Cast(ms->Get(String::New("oninactive")));
      if(!callback.IsEmpty())
      {
        v8::Local<v8::Value> argv[0];
        NanMakeCallback(ms, callback, 0, argv);
      }
    }
    if(MediaStream::ADDTRACK & evt.type)
    {
      webrtc::MediaStreamTrackInterface* msti = static_cast<webrtc::MediaStreamTrackInterface*>(evt.data);
      v8::Local<v8::Value> cargv[1];
      cargv[0] = v8::External::New(static_cast<void*>(msti));
      v8::Local<v8::Value> mst = NanPersistentToLocal(MediaStreamTrack::constructor)->NewInstance(1, cargv);
      v8::Local<v8::Function> callback = v8::Local<v8::Function>::Cast(ms->Get(String::New("onaddtrack")));
      if(!callback.IsEmpty())
      {
        v8::Local<v8::Value> argv[1];
        argv[0] = mst;
        NanMakeCallback(ms, callback, 1, argv);
      }
    }
    if(MediaStream::REMOVETRACK & evt.type)
    {
      webrtc::MediaStreamTrackInterface* msti = static_cast<webrtc::MediaStreamTrackInterface*>(evt.data);
      v8::Local<v8::Value> cargv[1];
      cargv[0] = v8::External::New(static_cast<void*>(msti));
      v8::Local<v8::Value> mst = NanPersistentToLocal(MediaStreamTrack::constructor)->NewInstance(1, cargv);
      v8::Local<v8::Function> callback = v8::Local<v8::Function>::Cast(ms->Get(String::New("onremovetrack")));
      if(!callback.IsEmpty())
      {
        v8::Local<v8::Value> argv[1];
        argv[0] = mst;
        NanMakeCallback(ms, callback, 1, argv);
      }
    }
  }
  scope.Close(Undefined());
  TRACE_END;
}

bool MediaStream::IsMediaStreamActive()
{
  webrtc::VideoTrackVector videoTracks = _internalMediaStream->GetVideoTracks();
  for (webrtc::VideoTrackVector::iterator track = videoTracks.begin(); track != videoTracks.end(); track++)
  {
    if ((*track)->state() == webrtc::MediaStreamTrackInterface::kLive)
      return true;
  }

  webrtc::AudioTrackVector audioTracks = _internalMediaStream->GetAudioTracks();
  for (webrtc::AudioTrackVector::iterator track = audioTracks.begin(); track != audioTracks.end(); track++)
  {
    if ((*track)->state() == webrtc::MediaStreamTrackInterface::kLive)
      return true;
  }

  return false;
}

void MediaStream::OnChanged()
{
  TRACE_CALL;
  QueueEvent(MediaStream::CHANGE, static_cast<void*>(NULL));
  TRACE_END;
}

webrtc::MediaStreamInterface* MediaStream::GetInterface() {
    return _internalMediaStream;
}

NAN_METHOD(MediaStream::getAudioTracks) {
  TRACE_CALL;
  NanScope();

  MediaStream* self = ObjectWrap::Unwrap<MediaStream>( args.Holder() );
  webrtc::AudioTrackVector audioTracks = self->_internalMediaStream->GetAudioTracks();

  v8::Local<v8::Array> array = v8::Array::New(audioTracks.size());
  int index = 0;
  for (webrtc::AudioTrackVector::iterator track = audioTracks.begin(); track != audioTracks.end(); track++, index++) {
    v8::Local<v8::Value> cargv[1];
    cargv[0] = v8::External::New(static_cast<void*>(track->get()));
    array->Set(index, NanPersistentToLocal(MediaStreamTrack::constructor)->NewInstance(1, cargv));
  }

  TRACE_END;
  NanReturnValue(array);
}

NAN_METHOD(MediaStream::getVideoTracks) {
  TRACE_CALL;
  NanScope();

  MediaStream* self = ObjectWrap::Unwrap<MediaStream>( args.Holder() );
  webrtc::VideoTrackVector videoTracks = self->_internalMediaStream->GetVideoTracks();

  v8::Local<v8::Array> array = v8::Array::New(videoTracks.size());
  int index = 0;
  for (webrtc::VideoTrackVector::iterator track = videoTracks.begin(); track != videoTracks.end(); track++, index++) {
    v8::Local<v8::Value> cargv[1];
    cargv[0] = v8::External::New(static_cast<void*>(track->get()));
    array->Set(index, NanPersistentToLocal(MediaStreamTrack::constructor)->NewInstance(1, cargv));
  }

  TRACE_END;
  NanReturnValue(array);
}

NAN_METHOD(MediaStream::getTrackById) {
  TRACE_CALL;
  NanScope();

  MediaStream* self = ObjectWrap::Unwrap<MediaStream>( args.Holder() );
  v8::String::Utf8Value param1(args[0]->ToString());
  std::string _id = std::string(*param1);

  talk_base::scoped_refptr<webrtc::MediaStreamTrackInterface> audioTrack = self->_internalMediaStream->FindAudioTrack(_id);
  talk_base::scoped_refptr<webrtc::MediaStreamTrackInterface> videoTrack = self->_internalMediaStream->FindVideoTrack(_id);

  talk_base::scoped_refptr<webrtc::MediaStreamTrackInterface> track = audioTrack.get() ? audioTrack : videoTrack;
  webrtc::MediaStreamTrackInterface* msti = track.get();
  msti->AddRef();

  v8::Local<v8::Value> cargv[1];
  cargv[0] = v8::External::New(static_cast<void*>(msti));
  v8::Local<v8::Value> mst = NanPersistentToLocal(MediaStreamTrack::constructor)->NewInstance(1, cargv);

  TRACE_END;
  NanReturnValue(mst);
}

NAN_METHOD(MediaStream::addTrack) {
  TRACE_CALL;
  NanScope();

  MediaStream* self = ObjectWrap::Unwrap<MediaStream>( args.Holder() );
  MediaStreamTrack* _track = ObjectWrap::Unwrap<MediaStreamTrack>(args[0]->ToObject());

  if (_track->GetInterface()->kind() == "audio") {
    self->_internalMediaStream->AddTrack((webrtc::AudioTrackInterface*)_track->GetInterface());
  } else if (_track->GetInterface()->kind() == "video") {
    self->_internalMediaStream->AddTrack((webrtc::VideoTrackInterface*)_track->GetInterface());
  }

  TRACE_END;
  NanReturnValue(Undefined());
}

NAN_METHOD(MediaStream::removeTrack) {
  TRACE_CALL;
  NanScope();

  MediaStream* self = ObjectWrap::Unwrap<MediaStream>( args.Holder() );
  MediaStreamTrack* _track = ObjectWrap::Unwrap<MediaStreamTrack>(args[0]->ToObject());

  if (_track->GetInterface()->kind() == "audio") {
    self->_internalMediaStream->RemoveTrack((webrtc::AudioTrackInterface*)_track->GetInterface());
  } else if (_track->GetInterface()->kind() == "video") {
    self->_internalMediaStream->RemoveTrack((webrtc::VideoTrackInterface*)_track->GetInterface());
  }

  TRACE_END;
  NanReturnValue(Undefined());
}

NAN_METHOD(MediaStream::clone) {
  TRACE_CALL;
  NanScope();

  TRACE_END;
  NanReturnValue(Undefined());
}

NAN_GETTER(MediaStream::GetId) {
  TRACE_CALL;
  NanScope();

  MediaStream* self = ObjectWrap::Unwrap<MediaStream>( args.Holder() );

  std::string label = self->_internalMediaStream->label();

  TRACE_END;
  NanReturnValue(String::New(label.c_str()));
}

NAN_GETTER(MediaStream::IsInactive) {
  TRACE_CALL;
  NanScope();

  MediaStream* self = ObjectWrap::Unwrap<MediaStream>( args.Holder() );
  bool inactive = self->_inactive;

  TRACE_END;
  NanReturnValue(Boolean::New(inactive));
}

NAN_SETTER(MediaStream::ReadOnly) {
  INFO("MediaStream::ReadOnly");
}

void MediaStream::Init( Handle<Object> exports ) {
  Local<FunctionTemplate> tpl = FunctionTemplate::New( New );
  tpl->SetClassName( String::NewSymbol( "MediaStream" ) );
  tpl->InstanceTemplate()->SetInternalFieldCount(1);
  tpl->PrototypeTemplate()->Set( String::NewSymbol( "getaudiotracks" ),
    FunctionTemplate::New( getAudioTracks )->GetFunction() );
  tpl->PrototypeTemplate()->Set( String::NewSymbol( "getvideotracks" ),
    FunctionTemplate::New( getVideoTracks )->GetFunction() );
  tpl->PrototypeTemplate()->Set( String::NewSymbol( "gettrackbyid" ),
    FunctionTemplate::New( getTrackById )->GetFunction() );

  tpl->PrototypeTemplate()->Set( String::NewSymbol( "addtrack" ),
    FunctionTemplate::New( addTrack )->GetFunction() );
  tpl->PrototypeTemplate()->Set( String::NewSymbol( "removetrack" ),
    FunctionTemplate::New( removeTrack )->GetFunction() );

  tpl->PrototypeTemplate()->Set( String::NewSymbol( "clone" ),
    FunctionTemplate::New( clone )->GetFunction() );

  tpl->InstanceTemplate()->SetAccessor(String::New("id"), GetId, ReadOnly);
  tpl->InstanceTemplate()->SetAccessor(String::New("inactive"), IsInactive, ReadOnly);

  NanAssignPersistent(Function, constructor, tpl->GetFunction());
  exports->Set( String::NewSymbol("MediaStream"), tpl->GetFunction() );
}


text:
using System;
using System.Linq;
using NUnit.Framework;
using Outlander.Core;

namespace Outlander.Core.Container.Tests
{
	[TestFixture]
	public class IoCTester
	{
		private SimpleContainer theContainer;

		[SetUp]
		public void SetUp()
		{
			theContainer = new SimpleContainer();
			theContainer.PerRequest<ILog, NullLog>();

			IoC.BuildUp = theContainer.BuildUp;
			IoC.GetInstance = theContainer.GetInstance;
			IoC.GetAllInstances = theContainer.GetAllInstances;
		}

		[Test]
		public void should_get_log()
		{
			var logger = IoC.Get<ILog>();
			Assert.NotNull(logger);
			Assert.AreEqual(typeof(NullLog), logger.GetType());
		}

		[Test]
		public void should_get_game_server()
		{
			theContainer.PerRequest<IGameState, SimpleGameState>();
			theContainer.PerRequest<IGameServer, SimpleGameServer>();

			var server = IoC.Get<IGameServer>();
			Assert.NotNull(server);
		}
	}
}


text:
package com.eazyfill.parser.textual;

import java.io.IOException;
import java.io.InputStream;

import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.util.PDFTextStripper;

public class PDFParser {

	private final PDDocument document;
	private String text;

	public PDFParser(final InputStream pdfContentStream) throws IOException {
		PDFTextStripper pdfStripper = new PDFTextStripper();
		document = PDDocument.load(pdfContentStream);
		this.text = pdfStripper.getText(document);
		close();
	}

	private void close() {
		try {
			document.close();
		} catch (IOException ignored) {
		}
	}

	public String getText() {
		return text;
	}

}


text:
var configMaster = require('./config-master');
var should = require('should');
var async = require('async');
var Kaiseki = require('../lib/kaiseki');
var request = require('request');
var _ = require('underscore');

var parse = new Kaiseki(configMaster);

xdescribe('push', function() {
  it('can broadcast a notification', function(done) {
    async.parallel([
      // Android
      function(callback) {
        var notification = {
          channels: [''],
          type: 'android',
          data: {
            alert: 'The next World Series has been announced'
          }
        };
        parse.sendPushNotification(notification, function(err, res, body, success) {
          success.should.be.true;
          should.exist(body.result);
          should.exist(res);
          body.result.should.be.true;

          callback(err);
        });
      },
      // iOS. We're expecting that this will fail because we didn't set up Push certificates yet.
      function(callback) {
        var notification = {
          channels: [''],
          type: 'ios',
          data: {
            alert: 'The next World Series has been announced'
          }
        };

        parse.sendPushNotification(notification, function(err, res, body, success) {
          success.should.be.false;
          body.error.should.eql('To push to ios devices, you must first configure a valid certificate.');
          body.code.should.eql(115);

          should.not.exist(body.data);
          should.exist(res);

          callback(err);
        });
      }
    ], function(err, results) {
      done(err);
    });
  });
});


text:
<?php
/**
 * @author  Sergey Melukov
 * @link    http://smelukov.com
 * @license MIT
 */
spl_autoload_register(function ($className) {
    $target = __DIR__ . "/" . str_replace('\\', '/', $className) . ".php";
    is_file($target) && is_readable($target) && require_once $target;
});


text: School group assignment using phonegap


text:
import * as React from 'react';
import Box from '@mui/material/Box';
import Button from '@mui/material/Button';
import Dialog from '@mui/material/Dialog';
import DialogActions from '@mui/material/DialogActions';
import DialogContent from '@mui/material/DialogContent';
import DialogTitle from '@mui/material/DialogTitle';
import InputLabel from '@mui/material/InputLabel';
import OutlinedInput from '@mui/material/OutlinedInput';
import MenuItem from '@mui/material/MenuItem';
import FormControl from '@mui/material/FormControl';
import Select from '@mui/material/Select';

export default function DialogSelect() {
  const [open, setOpen] = React.useState(false);
  const [age, setAge] = React.useState('');

  const handleChange = (event) => {
    setAge(Number(event.target.value) || '');
  };

  const handleClickOpen = () => {
    setOpen(true);
  };

  const handleClose = (event, reason) => {
    if (reason !== 'backdropClick') {
      setOpen(false);
    }
  };

  return (

      <Button onClick={handleClickOpen}>Open select dialog</Button>
      <Dialog disableEscapeKeyDown open={open} onClose={handleClose}>
        <DialogTitle>Fill the form</DialogTitle>
        <DialogContent>
          <Box component="form" sx={{ display: 'flex', flexWrap: 'wrap' }}>
            <FormControl sx={{ m: 1, minWidth: 120 }}>
              <InputLabel htmlFor="demo-dialog-native">Age</InputLabel>
              <Select
                native
                value={age}
                onChange={handleChange}
                input={<OutlinedInput label="Age" id="demo-dialog-native" />}
              >
                <option aria-label="None" value="" />
                <option value={10}>Ten</option>
                <option value={20}>Twenty</option>
                <option value={30}>Thirty</option>
              </Select>
            </FormControl>
            <FormControl sx={{ m: 1, minWidth: 120 }}>
              <InputLabel id="demo-dialog-select-label">Age</InputLabel>
              <Select
                labelId="demo-dialog-select-label"
                id="demo-dialog-select"
                value={age}
                onChange={handleChange}
                input={<OutlinedInput label="Age" />}
              >
                <MenuItem value="">
                  None
                </MenuItem>
                <MenuItem value={10}>Ten</MenuItem>
                <MenuItem value={20}>Twenty</MenuItem>
                <MenuItem value={30}>Thirty</MenuItem>
              </Select>
            </FormControl>
          </Box>
        </DialogContent>
        <DialogActions>
          <Button onClick={handleClose}>Cancel</Button>
          <Button onClick={handleClose}>Ok</Button>
        </DialogActions>
      </Dialog>

  );
}


text:
  {% if notice.unread %}

    mark as read

  {% endif %}

    {{ notice.actor }}
    {{ notice.verb }}
    {% if notice.target %}
      of {{ notice.target }}
    {% endif %}

{{ notice.timesince }} ago

  {% if notice.description %}

{{ notice.description|linebreaksbr }}

  {% endif %}


text:
__author__ = 'jonathan'

class ModelsObjectComparatorMixin(object):
    def _dict_from_object(self, obj, ignored_keys):
        if ignored_keys is None:
            ignored_keys = []
        return dict([(k, v) for k, v in obj.iteritems()
                                if k not in ignored_keys])

    def _assertEqualObjects(self, obj1, obj2, ignored_keys=None):
        obj1 = self._dict_from_object(obj1, ignored_keys)
        obj2 = self._dict_from_object(obj2, ignored_keys)

        self.assertEqual(len(obj1),
                         len(obj2),
                         "Keys mismatch: %s" %
                          str(set(obj1.keys()) ^ set(obj2.keys())))
        for key, value in obj1.iteritems():
            self.assertEqual(value, obj2[key])

    def _assertEqualListsOfObjects(self, objs1, objs2, ignored_keys=None):
        obj_to_dict = lambda o: self._dict_from_object(o, ignored_keys)
        sort_key = lambda d: [d[k] for k in sorted(d)]
        conv_and_sort = lambda obj: sorted(map(obj_to_dict, obj), key=sort_key)

        self.assertEqual(conv_and_sort(objs1), conv_and_sort(objs2))

    def _assertEqualOrderedListOfObjects(self, objs1, objs2,
                                         ignored_keys=None):
        obj_to_dict = lambda o: self._dict_from_object(o, ignored_keys)
        conv = lambda obj: map(obj_to_dict, obj)

        self.assertEqual(conv(objs1), conv(objs2))

    def _assertEqualListsOfPrimitivesAsSets(self, primitives1, primitives2):
        self.assertEqual(len(primitives1), len(primitives2))
        for primitive in primitives1:
            self.assertIn(primitive, primitives2)

        for primitive in primitives2:
            self.assertIn(primitive, primitives1)


text:
require 'rails_helper'

module Nizza
  RSpec.describe Hotel, type: :model do
    pending "add some examples to (or delete) #{__FILE__}"
  end
end


text:
require 'sexp_processor'
require 'set'

#Looks for request parameters. Not used currently.
class Brakeman::ParamsProcessor < SexpProcessor
  attr_reader :result

  def initialize
    super()
    self.strict = false
    self.auto_shift_type = false
    self.require_empty = false
    self.default_method = :process_default
    self.warn_on_default = false
    @result = []
    @matched = false
    @mark = false
    @watch_nodes = Set[:call, :iasgn, :lasgn, :gasgn, :cvasgn, :return, :attrasgn]
    @params = Sexp.new(:call, nil, :params, Sexp.new(:arglist))
  end

  def process_default exp
    if @watch_nodes.include?(exp.node_type) and not @mark
      @mark = true
      @matched = false
      process_these exp[1..-1]
      if @matched
        @result << exp
        @matched = false
      end
      @mark = false
    else
      process_these exp[1..-1]
    end

    exp
  end

  def process_these exp
    exp.each do |e|
      if sexp? e and not e.empty?
        process e
      end
    end
  end

  def process_call exp
    if @mark
      actually_process_call exp
    else
      @mark = true
      actually_process_call exp
      if @matched
        @result << exp
      end
      @mark = @matched = false
    end

    exp
  end

  def actually_process_call exp
    process exp[1]
    process exp[3]
    if exp[1] == @params or exp == @params
      @matched = true
    end
  end

  #Don't really care about condition
  def process_if exp
    process_these exp[2..-1]
    exp
  end

end


text:
using Newtonsoft.Json;
using System;
using System.IO;
using System.Threading;
using System.Xml.Linq;
using Wexflow.Core;
using YamlDotNet.Serialization;

namespace Wexflow.Tasks.YamlToJson
{
    public class YamlToJson : Task
    {
        public YamlToJson(XElement xe, Workflow wf) : base(xe, wf)
        {
        }

        public override TaskStatus Run()
        {
            Info("Converting YAML files to JSON files...");

            bool success;
            var atLeastOneSuccess = false;
            try
            {
                success = ConvertFiles(ref atLeastOneSuccess);
            }
            catch (ThreadAbortException)
            {
                throw;
            }
            catch (Exception e)
            {
                ErrorFormat("An error occured while copying files.", e);
                success = false;
            }

            var status = Status.Success;

            if (!success && atLeastOneSuccess)
            {
                status = Status.Warning;
            }
            else if (!success)
            {
                status = Status.Error;
            }

            Info("Task finished.");
            return new TaskStatus(status);
        }

        private bool ConvertFiles(ref bool atLeastOneSuccess)
        {
            var success = true;
            var yamlFiles = SelectFiles();

            foreach (var yamlFile in yamlFiles)
            {
                try
                {
                    var source = File.ReadAllText(yamlFile.Path);

                    var deserializer = new Deserializer();
                    var yamlObject = deserializer.Deserialize(new StringReader(source));

                    var serializer = new JsonSerializer();
                    var writer = new StringWriter();
                    serializer.Serialize(writer, yamlObject);
                    string json = writer.ToString();

                    var destPath = Path.Combine(Workflow.WorkflowTempFolder, Path.GetFileNameWithoutExtension(yamlFile.FileName) + ".json");
                    File.WriteAllText(destPath, json);
                    Files.Add(new FileInf(destPath, Id));
                    InfoFormat("The YAML file {0} has been converted -> {1}", yamlFile.Path, destPath);
                    if (!atLeastOneSuccess) atLeastOneSuccess = true;
                }
                catch (ThreadAbortException)
                {
                    throw;
                }
                catch (Exception e)
                {
                    ErrorFormat("An error occured while converting the YAML file {0}: {1}", yamlFile.Path, e.Message);
                    success = false;
                }
            }
            return success;
        }
    }
}


text:
function test() {
  var src = document.location.search;
  // NOT OK: Closure expands internal entities by default
  goog.dom.xml.loadXml(src);
}


text:
% $Author: Peter Gagarinov, PhD <pgagarinov@gmail.com> $
% $Copyright: 2015-2016 Peter Gagarinov, PhD
%             2012-2015 Moscow State University,
%            Faculty of Applied Mathematics and Computer Science,
%            System Analysis Department$
[methodName,className]=mxberry.core.getcallernameext(1);


text:
import webapp2

class MainHandler(webapp2.RequestHandler):
    def get(self):
        self.response.write('Hello, World!')

def handle_404(request, response, exception):
    response.write('Sorry, nothing at this URL.')
    response.set_status(404)

application = webapp2.WSGIApplication([
    ('/', MainHandler),
], debug=False)
application.error_handlers[404] = handle_404


text:
Develop a standalone Spark Structured Streaming application (using IntelliJ IDEA) that uses `rate` streaming source and prints the result of query processing out to the console (using `console` streaming sink).

Use `sbt package` the application and `spark-submit` it.

Protip™: Use the available options of the rate and console data sources:

1. [RateStreamSource](https://jaceklaskowski.gitbooks.io/spark-structured-streaming/spark-sql-streaming-RateStreamSource.html#options)
1. [ConsoleSinkProvider](https://jaceklaskowski.gitbooks.io/spark-structured-streaming/spark-sql-streaming-ConsoleSinkProvider.html#options)

Module: **Spark Structured Streaming**

Duration: **30 mins**

<!--
## Solution

```scala
```
-->


text:
namespace Merchello.Core.Strategies.Packaging
{
    using System;
    using System.Collections.Generic;
    using System.IO;
    using System.Linq;

    using Merchello.Core.Logging;
    using Merchello.Core.Models;

    using Umbraco.Core.Logging;

    /// <summary>
    /// Represents the default warehouse packaging strategy.
    ///
    /// The class is responsible for breaking a collection of products into one or more shipments.
    /// </summary>
    /// <remarks>
    ///
    /// for initial version we are only exposing a single warehouse and a single warehouse catalog
    /// TODO : add business logic to test for for catalog and warehouse variations.  This will also need to account for
    /// various inventory possibilities
    ///
    /// </remarks>
    public class DefaultWarehousePackagingStrategy : PackagingStrategyBase
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="DefaultWarehousePackagingStrategy"/> class.
        /// </summary>
        /// <param name="lineItemCollection">
        /// The line item collection.
        /// </param>
        /// <param name="destination">
        /// The destination.
        /// </param>
        /// <param name="versionKey">
        /// The version key.
        /// </param>
        public DefaultWarehousePackagingStrategy(
            LineItemCollection lineItemCollection,
            IAddress destination,
            Guid versionKey)
            : this(Core.MerchelloContext.Current, lineItemCollection, destination, versionKey)
        {
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="DefaultWarehousePackagingStrategy"/> class.
        /// </summary>
        /// <param name="merchelloContext">
        /// The merchello context.
        /// </param>
        /// <param name="lineItemCollection">
        /// The line item collection.
        /// </param>
        /// <param name="destination">
        /// The destination.
        /// </param>
        /// <param name="versionKey">
        /// The version key.
        /// </param>
        public DefaultWarehousePackagingStrategy(
            IMerchelloContext merchelloContext,
            LineItemCollection lineItemCollection,
            IAddress destination,
            Guid versionKey)
            : base(merchelloContext, lineItemCollection, destination, versionKey)
        {
        }

        /// <summary>
        /// Creates a collection of shipments for the current basket
        /// </summary>
        /// <returns>
        /// A collection of <see cref="IShipment"/>.
        /// </returns>
        public override IEnumerable<IShipment> PackageShipments()
        {
            // All packaged shipments will start with a shipment status of "Quoted" as these are being used for the Shipment Rate Quote
            // NOTE:  the "Packaging" status to indicate the shipment is physically being packaged/boxed up.
            var quoted = MerchelloContext.Services.ShipmentService.GetShipmentStatusByKey(Constants.DefaultKeys.ShipmentStatus.Quoted);

            // filter basket items for shippable items
            var shippableVisitor = new ShippableProductVisitor();
            LineItemCollection.Accept(shippableVisitor);

            if (!shippableVisitor.ShippableItems.Any()) return new List<IShipment>();

            // the origin address will be the default warehouse
            // For the initial version we are only exposing a single warehouse
            var warehouse = MerchelloContext.Services.WarehouseService.GetDefaultWarehouse();
            var origin = warehouse.AsAddress();

            ////For the initial version we are only exposing a single shipment
            var shipment = new Shipment(quoted, origin, Destination)
                {
                    VersionKey = VersionKey // this is used in cache keys
                };

            // get the variants for each of the shippable line items
            var variants =
                   MerchelloContext.Services.ProductVariantService.GetByKeys(
                       shippableVisitor.ShippableItems
                       .Select(x => x.ExtendedData.GetProductVariantKey())
                       .Where(x => !Guid.Empty.Equals(x))).ToArray();

            foreach (var lineItem in shippableVisitor.ShippableItems)
            {
                // We need to know what Warehouse Catalog this product is associated with for shipping and inventory
                var variant = variants.FirstOrDefault(x => x.Key.Equals(lineItem.ExtendedData.GetProductVariantKey()));
                if (variant == null) throw new InvalidOperationException("This packaging strategy cannot handle null ProductVariants");

                if (!variant.CatalogInventories.Any())
                {
                    MultiLogHelper.Error<ShippableProductVisitor>(
                        "ProductVariant marked as shippable was not assoicated with a WarehouseCatalog.  Product was: "
                        + variant.Key.ToString() + " -  " + variant.Name,
                        new InvalidDataException());
                }
                else
                {
                    if (lineItem.ExtendedData.GetWarehouseCatalogKey().Equals(Guid.Empty))
                    {
                        // TODO this needs to be refactored to look at the entire shipment
                        // since products could be in multiple catalogs which could have
                        // opposing shippng rules and we have the destination address.
                        lineItem.ExtendedData.SetValue(
                            Constants.ExtendedDataKeys.WarehouseCatalogKey,
                            variant.CatalogInventories.First().CatalogKey.ToString());
                    }

                    shipment.Items.Add(lineItem);
                }
            }

            return new List<IShipment> { shipment };
        }
    }
}


text:
import { Light } from './Light';
import { AmbientLight } from './AmbientLight';
import { PointLight } from './PointLight';

export { Light };
export { AmbientLight };
export { PointLight };


text:
/**
 * Autogenerated by Avro
 *
 * DO NOT EDIT DIRECTLY
 */
package graphene.model.idl;
@SuppressWarnings("all")
@org.apache.avro.specific.AvroGenerated
public class G_LegendItem extends org.apache.avro.specific.SpecificRecordBase implements org.apache.avro.specific.SpecificRecord {
  public static final org.apache.avro.Schema SCHEMA$ = new org.apache.avro.Schema.Parser().parse("{\"type\":\"record\",\"name\":\"G_LegendItem\",\"namespace\":\"graphene.model.idl\",\"fields\":[{\"name\":\"description\",\"type\":[{\"type\":\"string\",\"avro.java.string\":\"String\"},\"null\"],\"doc\":\"usually a longer explanation\"},{\"name\":\"style\",\"type\":[{\"type\":\"string\",\"avro.java.string\":\"String\"},\"null\"],\"doc\":\"the css style or hex color\"},{\"name\":\"label\",\"type\":{\"type\":\"string\",\"avro.java.string\":\"String\"},\"doc\":\"the text that will be visible,REQUIRED\"},{\"name\":\"icon\",\"type\":[{\"type\":\"string\",\"avro.java.string\":\"String\"},\"null\"],\"doc\":\"the icon that will be visible\"}]}");
  public static org.apache.avro.Schema getClassSchema() { return SCHEMA$; }
  /** usually a longer explanation */
   private java.lang.String description;
  /** the css style or hex color */
   private java.lang.String style;
  /** the text that will be visible,REQUIRED */
   private java.lang.String label;
  /** the icon that will be visible */
   private java.lang.String icon;

  /**
   * Default constructor.  Note that this does not initialize fields
   * to their default values from the schema.  If that is desired then
   * one should use newBuilder().
   */
  public G_LegendItem() {}

  /**
   * All-args constructor.
   */
  public G_LegendItem(java.lang.String description, java.lang.String style, java.lang.String label, java.lang.String icon) {
    this.description = description;
    this.style = style;
    this.label = label;
    this.icon = icon;
  }

  public org.apache.avro.Schema getSchema() { return SCHEMA$; }
  // Used by DatumWriter.  Applications should not call.
  public java.lang.Object get(int field$) {
    switch (field$) {
    case 0: return description;
    case 1: return style;
    case 2: return label;
    case 3: return icon;
    default: throw new org.apache.avro.AvroRuntimeException("Bad index");
    }
  }
  // Used by DatumReader.  Applications should not call.
  @SuppressWarnings(value="unchecked")
  public void put(int field$, java.lang.Object value$) {
    switch (field$) {
    case 0: description = (java.lang.String)value$; break;
    case 1: style = (java.lang.String)value$; break;
    case 2: label = (java.lang.String)value$; break;
    case 3: icon = (java.lang.String)value$; break;
    default: throw new org.apache.avro.AvroRuntimeException("Bad index");
    }
  }

  /**
   * Gets the value of the 'description' field.
   * usually a longer explanation   */
  public java.lang.String getDescription() {
    return description;
  }

  /**
   * Sets the value of the 'description' field.
   * usually a longer explanation   * @param value the value to set.
   */
  public void setDescription(java.lang.String value) {
    this.description = value;
  }

  /**
   * Gets the value of the 'style' field.
   * the css style or hex color   */
  public java.lang.String getStyle() {
    return style;
  }

  /**
   * Sets the value of the 'style' field.
   * the css style or hex color   * @param value the value to set.
   */
  public void setStyle(java.lang.String value) {
    this.style = value;
  }

  /**
   * Gets the value of the 'label' field.
   * the text that will be visible,REQUIRED   */
  public java.lang.String getLabel() {
    return label;
  }

  /**
   * Sets the value of the 'label' field.
   * the text that will be visible,REQUIRED   * @param value the value to set.
   */
  public void setLabel(java.lang.String value) {
    this.label = value;
  }

  /**
   * Gets the value of the 'icon' field.
   * the icon that will be visible   */
  public java.lang.String getIcon() {
    return icon;
  }

  /**
   * Sets the value of the 'icon' field.
   * the icon that will be visible   * @param value the value to set.
   */
  public void setIcon(java.lang.String value) {
    this.icon = value;
  }

  /** Creates a new G_LegendItem RecordBuilder */
  public static graphene.model.idl.G_LegendItem.Builder newBuilder() {
    return new graphene.model.idl.G_LegendItem.Builder();
  }

  /** Creates a new G_LegendItem RecordBuilder by copying an existing Builder */
  public static graphene.model.idl.G_LegendItem.Builder newBuilder(graphene.model.idl.G_LegendItem.Builder other) {
    return new graphene.model.idl.G_LegendItem.Builder(other);
  }

  /** Creates a new G_LegendItem RecordBuilder by copying an existing G_LegendItem instance */
  public static graphene.model.idl.G_LegendItem.Builder newBuilder(graphene.model.idl.G_LegendItem other) {
    return new graphene.model.idl.G_LegendItem.Builder(other);
  }

  /**
   * RecordBuilder for G_LegendItem instances.
   */
  public static class Builder extends org.apache.avro.specific.SpecificRecordBuilderBase<G_LegendItem>
    implements org.apache.avro.data.RecordBuilder<G_LegendItem> {

    private java.lang.String description;
    private java.lang.String style;
    private java.lang.String label;
    private java.lang.String icon;

    /** Creates a new Builder */
    private Builder() {
      super(graphene.model.idl.G_LegendItem.SCHEMA$);
    }

    /** Creates a Builder by copying an existing Builder */
    private Builder(graphene.model.idl.G_LegendItem.Builder other) {
      super(other);
      if (isValidValue(fields()[0], other.description)) {
        this.description = data().deepCopy(fields()[0].schema(), other.description);
        fieldSetFlags()[0] = true;
      }
      if (isValidValue(fields()[1], other.style)) {
        this.style = data().deepCopy(fields()[1].schema(), other.style);
        fieldSetFlags()[1] = true;
      }
      if (isValidValue(fields()[2], other.label)) {
        this.label = data().deepCopy(fields()[2].schema(), other.label);
        fieldSetFlags()[2] = true;
      }
      if (isValidValue(fields()[3], other.icon)) {
        this.icon = data().deepCopy(fields()[3].schema(), other.icon);
        fieldSetFlags()[3] = true;
      }
    }

    /** Creates a Builder by copying an existing G_LegendItem instance */
    private Builder(graphene.model.idl.G_LegendItem other) {
            super(graphene.model.idl.G_LegendItem.SCHEMA$);
      if (isValidValue(fields()[0], other.description)) {
        this.description = data().deepCopy(fields()[0].schema(), other.description);
        fieldSetFlags()[0] = true;
      }
      if (isValidValue(fields()[1], other.style)) {
        this.style = data().deepCopy(fields()[1].schema(), other.style);
        fieldSetFlags()[1] = true;
      }
      if (isValidValue(fields()[2], other.label)) {
        this.label = data().deepCopy(fields()[2].schema(), other.label);
        fieldSetFlags()[2] = true;
      }
      if (isValidValue(fields()[3], other.icon)) {
        this.icon = data().deepCopy(fields()[3].schema(), other.icon);
        fieldSetFlags()[3] = true;
      }
    }

    /** Gets the value of the 'description' field */
    public java.lang.String getDescription() {
      return description;
    }

    /** Sets the value of the 'description' field */
    public graphene.model.idl.G_LegendItem.Builder setDescription(java.lang.String value) {
      validate(fields()[0], value);
      this.description = value;
      fieldSetFlags()[0] = true;
      return this;
    }

    /** Checks whether the 'description' field has been set */
    public boolean hasDescription() {
      return fieldSetFlags()[0];
    }

    /** Clears the value of the 'description' field */
    public graphene.model.idl.G_LegendItem.Builder clearDescription() {
      description = null;
      fieldSetFlags()[0] = false;
      return this;
    }

    /** Gets the value of the 'style' field */
    public java.lang.String getStyle() {
      return style;
    }

    /** Sets the value of the 'style' field */
    public graphene.model.idl.G_LegendItem.Builder setStyle(java.lang.String value) {
      validate(fields()[1], value);
      this.style = value;
      fieldSetFlags()[1] = true;
      return this;
    }

    /** Checks whether the 'style' field has been set */
    public boolean hasStyle() {
      return fieldSetFlags()[1];
    }

    /** Clears the value of the 'style' field */
    public graphene.model.idl.G_LegendItem.Builder clearStyle() {
      style = null;
      fieldSetFlags()[1] = false;
      return this;
    }

    /** Gets the value of the 'label' field */
    public java.lang.String getLabel() {
      return label;
    }

    /** Sets the value of the 'label' field */
    public graphene.model.idl.G_LegendItem.Builder setLabel(java.lang.String value) {
      validate(fields()[2], value);
      this.label = value;
      fieldSetFlags()[2] = true;
      return this;
    }

    /** Checks whether the 'label' field has been set */
    public boolean hasLabel() {
      return fieldSetFlags()[2];
    }

    /** Clears the value of the 'label' field */
    public graphene.model.idl.G_LegendItem.Builder clearLabel() {
      label = null;
      fieldSetFlags()[2] = false;
      return this;
    }

    /** Gets the value of the 'icon' field */
    public java.lang.String getIcon() {
      return icon;
    }

    /** Sets the value of the 'icon' field */
    public graphene.model.idl.G_LegendItem.Builder setIcon(java.lang.String value) {
      validate(fields()[3], value);
      this.icon = value;
      fieldSetFlags()[3] = true;
      return this;
    }

    /** Checks whether the 'icon' field has been set */
    public boolean hasIcon() {
      return fieldSetFlags()[3];
    }

    /** Clears the value of the 'icon' field */
    public graphene.model.idl.G_LegendItem.Builder clearIcon() {
      icon = null;
      fieldSetFlags()[3] = false;
      return this;
    }

    @Override
    public G_LegendItem build() {
      try {
        G_LegendItem record = new G_LegendItem();
        record.description = fieldSetFlags()[0] ? this.description : (java.lang.String) defaultValue(fields()[0]);
        record.style = fieldSetFlags()[1] ? this.style : (java.lang.String) defaultValue(fields()[1]);
        record.label = fieldSetFlags()[2] ? this.label : (java.lang.String) defaultValue(fields()[2]);
        record.icon = fieldSetFlags()[3] ? this.icon : (java.lang.String) defaultValue(fields()[3]);
        return record;
      } catch (Exception e) {
        throw new org.apache.avro.AvroRuntimeException(e);
      }
    }
  }
}


text:
<?php

namespace Umg\VotacionBundle\Controller;

use Symfony\Component\HttpFoundation\Request;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Umg\VotacionBundle\Entity\Catedratico;
use Umg\VotacionBundle\Form\CatedraticoType;

/**
 * Catedratico controller.
 *
 * @Route("/catedratico")
 */
class CatedraticoController extends Controller
{

    /**
     * Lists all Catedratico entities.
     *
     * @Route("/", name="catedratico")
     * @Method("GET")
     * @Template()
     */
    public function indexAction(Request $request)
    {
        $dataTable = $this->get('data_tables.manager')->getTable('catedraticoTable');
        if ($response = $dataTable->ProcessRequest($request)) {
            return $response;
        }

        $em = $this->getDoctrine()->getManager();

        return array(
            'dataTable' => $dataTable,
        );
    }
    /**
     * Creates a new Catedratico entity.
     *
     * @Route("/", name="catedratico_create")
     * @Method("POST")
     * @Template("UmgVotacionBundle:Catedratico:new.html.twig")
     */
    public function createAction(Request $request)
    {
        $entity = new Catedratico();
        $form = $this->createCreateForm($entity);
        $form->handleRequest($request);

        if ($form->isValid()) {
            $em = $this->getDoctrine()->getManager();
            $em->getConnection()->beginTransaction();
            try
            {
                $em->persist($entity);
                $em->flush();

                $userManager = $this->container->get('fos_user.user_manager');
                $userAdmin = $userManager->createUser();

                $userAdmin->setUsername($entity->getCodigo());
                $userAdmin->setEmail($entity->getCodigo().'cat@example.com');
                $userAdmin->setPlainPassword($entity->getColegiado().$entity->getNit());
                $userAdmin->setEnabled(true);
                $userManager->updateUser($userAdmin, true);

                $entity->setUsuario($userAdmin);
                $em->persist($entity);
                $em->flush();

                $em->getConnection()->commit();
                return $this->redirect($this->generateUrl('catedratico'));
            }
            catch (Exception $e)
            {
                $em->getConnection()->rollback();
                return array(
                    'entity' => $entity,
                    'form'   => $form->createView(),
                );
                throw $e;
            }
        }

        return array(
            'entity' => $entity,
            'form'   => $form->createView(),
        );
    }

    /**
     * Creates a form to create a Catedratico entity.
     *
     * @param Catedratico $entity The entity
     *
     * @return \Symfony\Component\Form\Form The form
     */
    private function createCreateForm(Catedratico $entity)
    {
        $form = $this->createForm(new CatedraticoType(), $entity, array(
            'action' => $this->generateUrl('catedratico_create'),
            'method' => 'POST',
        ));

        $form->add('submit', 'submit', array(
            'label' => 'Guardar',
            'attr'  => array('class' => 'btn btn-primary'),
        ));

        return $form;
    }

    /**
     * Displays a form to create a new Catedratico entity.
     *
     * @Route("/new", name="catedratico_new")
     * @Method("GET")
     * @Template()
     */
    public function newAction()
    {
        $entity = new Catedratico();
        $form   = $this->createCreateForm($entity);

        return array(
            'entity' => $entity,
            'form'   => $form->createView(),
        );
    }

    /**
     * Finds and displays a Catedratico entity.
     *
     * @Route("/{id}", name="catedratico_show")
     * @Method("GET")
     * @Template()
     */
    public function showAction($id)
    {
        $em = $this->getDoctrine()->getManager();

        $entity = $em->getRepository('UmgVotacionBundle:Catedratico')->find($id);

        if (!$entity) {
            throw $this->createNotFoundException('Unable to find Catedratico entity.');
        }

        $deleteForm = $this->createDeleteForm($id);

        return array(
            'entity'      => $entity,
            'delete_form' => $deleteForm->createView(),
        );
    }

    /**
     * Displays a form to edit an existing Catedratico entity.
     *
     * @Route("/{id}/edit", name="catedratico_edit")
     * @Method("GET")
     * @Template()
     */
    public function editAction($id)
    {
        $em = $this->getDoctrine()->getManager();

        $entity = $em->getRepository('UmgVotacionBundle:Catedratico')->find($id);

        if (!$entity) {
            throw $this->createNotFoundException('Unable to find Catedratico entity.');
        }

        $editForm = $this->createEditForm($entity);
        $deleteForm = $this->createDeleteForm($id);

        return array(
            'entity'      => $entity,
            'edit_form'   => $editForm->createView(),
            'delete_form' => $deleteForm->createView(),
        );
    }

    /**
    * Creates a form to edit a Catedratico entity.
    *
    * @param Catedratico $entity The entity
    *
    * @return \Symfony\Component\Form\Form The form
    */
    private function createEditForm(Catedratico $entity)
    {
        $form = $this->createForm(new CatedraticoType(), $entity, array(
            'action' => $this->generateUrl('catedratico_update', array('id' => $entity->getId())),
            'method' => 'PUT',
        ));

        $form->add('submit', 'submit', array(
            'label' => 'Actualizar',
            'attr'  => array('class' => 'btn btn-primary'),
        ));

        return $form;
    }
    /**
     * Edits an existing Catedratico entity.
     *
     * @Route("/{id}", name="catedratico_update")
     * @Method("PUT")
     * @Template("UmgVotacionBundle:Catedratico:edit.html.twig")
     */
    public function updateAction(Request $request, $id)
    {
        $em = $this->getDoctrine()->getManager();

        $entity = $em->getRepository('UmgVotacionBundle:Catedratico')->find($id);

        if (!$entity) {
            throw $this->createNotFoundException('Unable to find Catedratico entity.');
        }

        $deleteForm = $this->createDeleteForm($id);
        $editForm = $this->createEditForm($entity);
        $editForm->handleRequest($request);

        if ($editForm->isValid()) {
            $em->flush();

            return $this->redirect($this->generateUrl('catedratico_edit', array('id' => $id)));
        }

        return array(
            'entity'      => $entity,
            'edit_form'   => $editForm->createView(),
            'delete_form' => $deleteForm->createView(),
        );
    }
    /**
     * Deletes a Catedratico entity.
     *
     * @Route("/{id}", name="catedratico_delete")
     * @Method("DELETE")
     */
    public function deleteAction(Request $request, $id)
    {
        $form = $this->createDeleteForm($id);
        $form->handleRequest($request);

        if ($form->isValid()) {
            $em = $this->getDoctrine()->getManager();
            $entity = $em->getRepository('UmgVotacionBundle:Catedratico')->find($id);

            if (!$entity) {
                throw $this->createNotFoundException('Unable to find Catedratico entity.');
            }

            $em->remove($entity);
            $em->flush();
        }

        return $this->redirect($this->generateUrl('catedratico'));
    }

    /**
     * Creates a form to delete a Catedratico entity by id.
     *
     * @param mixed $id The entity id
     *
     * @return \Symfony\Component\Form\Form The form
     */
    private function createDeleteForm($id)
    {
        return $this->createFormBuilder()
            ->setAction($this->generateUrl('catedratico_delete', array('id' => $id)))
            ->setMethod('DELETE')
            ->add('submit', 'submit', array('label' => 'Delete'))
            ->getForm()
        ;
    }
}


text:
ACCEPTED

#### According to
Interim Register of Marine and Nonmarine Genera

#### Published in
Proc. blol. Soc. Wash. 79: 89.

#### Original name
Euglyphella Valkanov, 1962

### Remarks
null


text:
package session

import (
	"github.com/Cristofori/kmud/types"
	"github.com/Cristofori/kmud/utils"
)

type mapBuilder struct {
	width    int
	height   int
	depth    int
	data     [][][]mapTile
	userRoom types.Room
}

type mapTile struct {
	char  rune
	color types.Color
}

func (self *mapTile) toString() string {
	if self.char == ' ' {
		return string(self.char)
	}

	return types.Colorize(self.color, string(self.char))
}

func newMapBuilder(width int, height int, depth int) mapBuilder {
	var builder mapBuilder

	// Double the X/Y axis to account for extra space to draw exits
	width *= 2
	height *= 2

	builder.data = make([][][]mapTile, depth)

	for z := 0; z < depth; z++ {
		builder.data[z] = make([][]mapTile, height)
		for y := 0; y < height; y++ {
			builder.data[z][y] = make([]mapTile, width)
		}
	}

	builder.width = width
	builder.height = height
	builder.depth = depth

	for z := 0; z < depth; z++ {
		for y := 0; y < height; y++ {
			for x := 0; x < width; x++ {
				builder.data[z][y][x].char = ' '
			}
		}
	}

	return builder
}

func (self *mapBuilder) setUserRoom(room types.Room) {
	self.userRoom = room
}

func (self *mapBuilder) addRoom(room types.Room, x int, y int, z int) {
	x = x * 2
	y = y * 2

	addIfExists := func(dir types.Direction, x int, y int) {
		if x < 0 || y < 0 {
			return
		}

		if room.HasExit(dir) {
			self.data[z][y][x].addExit(dir)
		}
	}

	if self.userRoom.GetId() == room.GetId() {
		self.data[z][y][x].char = '*'
		self.data[z][y][x].color = types.ColorRed
	} else {
		self.data[z][y][x].color = types.ColorMagenta
		if room.HasExit(types.DirectionUp) && room.HasExit(types.DirectionDown) {
			self.data[z][y][x].char = '+'
		} else if room.HasExit(types.DirectionUp) {
			self.data[z][y][x].char = '^'
		} else if room.HasExit(types.DirectionDown) {
			self.data[z][y][x].char = 'v'
		} else {
			char := '#'

			/*
				count := len(model.CharactersIn(room.GetId()))
				if count < 10 {
					char = rune(strconv.Itoa(count)[0])
				}
			*/

			self.data[z][y][x].char = char
			self.data[z][y][x].color = types.ColorWhite
		}
	}

	addIfExists(types.DirectionNorth, x, y-1)
	addIfExists(types.DirectionNorthEast, x+1, y-1)
	addIfExists(types.DirectionEast, x+1, y)
	addIfExists(types.DirectionSouthEast, x+1, y+1)
	addIfExists(types.DirectionSouth, x, y+1)
	addIfExists(types.DirectionSouthWest, x-1, y+1)
	addIfExists(types.DirectionWest, x-1, y)
	addIfExists(types.DirectionNorthWest, x-1, y-1)
}

func (self *mapBuilder) toString() string {
	str := ""

	for z := 0; z < self.depth; z++ {
		var rows []string
		for y := 0; y < self.height; y++ {
			row := ""
			for x := 0; x < self.width; x++ {
				tile := self.data[z][y][x].toString()
				row = row + tile
			}
			rows = append(rows, row)
		}

		rows = utils.TrimLowerRows(rows)

		if self.depth > 1 {
			divider := types.Colorize(types.ColorWhite, "================================================================================\r\n")
			rows = append(rows, divider)
		}

		for _, row := range rows {
			str = str + row + "\r\n"
		}
	}

	return str
}

func (self *mapTile) addExit(dir types.Direction) {
	combineChars := func(r1 rune, r2 rune, r3 rune) {
		if self.char == r1 {
			self.char = r2
		} else {
			self.char = r3
		}
	}

	self.color = types.ColorBlue

	switch dir {
	case types.DirectionNorth:
		combineChars('|', '|', '|')
	case types.DirectionNorthEast:
		combineChars('\\', 'X', '/')
	case types.DirectionEast:
		combineChars('-', '-', '-')
	case types.DirectionSouthEast:
		combineChars('/', 'X', '\\')
	case types.DirectionSouth:
		combineChars('|', '|', '|')
	case types.DirectionSouthWest:
		combineChars('\\', 'X', '/')
	case types.DirectionWest:
		combineChars('-', '-', '-')
	case types.DirectionNorthWest:
		combineChars('/', 'X', '\\')
	default:
		panic("Unexpected direction given to mapTile::addExit()")
	}
}


text:
using System;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;
using MargieBot.ExampleResponders.Models;
using MargieBot.Models;
using MargieBot.Responders;

namespace MargieBot.ExampleResponders.Responders
{
    public class ScoreboardRequestResponder : IResponder
    {
        public bool CanRespond(SlackMessage context)
        {
            return (context.Message.MentionsBot || context.Message.ChatHub.Type == SlackChatHubType.DM) && Regex.IsMatch(context.Message.Text, @"\bscore\b", RegexOptions.IgnoreCase);
        }

        public BotMessage GetResponse(SlackMessage context)
        {
            IReadOnlyDictionary<string, int> scores = context.Get<Scorebook>().GetScores();

            if (scores.Count > 0) {
                StringBuilder builder = new StringBuilder(context.Get<Phrasebook>().GetScoreboardHype());
                builder.Append("```");

                // add the scores to a list for sorting. while we do, figure out who has the longest name for the pseudo table formatting
                List<KeyValuePair<string, int>> sortedScores = new List<KeyValuePair<string, int>>();
                string longestName = string.Empty;

                foreach (string key in scores.Keys) {
                    KeyValuePair<string, int> newScore = new KeyValuePair<string, int>(context.UserNameCache[key], scores[key]);

                    if(newScore.Key.Length > longestName.Length) {
                        longestName = newScore.Key;
                    }

                    sortedScores.Add(newScore);
                }
                sortedScores.Sort((x, y) => { return y.Value.CompareTo(x.Value); });

                foreach(KeyValuePair<string, int> userScore in sortedScores)  {
                    StringBuilder nameString = new StringBuilder(userScore.Key);
                    while(nameString.Length < longestName.Length) {
                        nameString.Append(" ");
                    }

                    builder.Append(nameString.ToString() + " | " + userScore.Value.ToString() + "\n");
                }

                builder.Append("```");

                return new BotMessage() {
                    Text = builder.ToString()
                };
            }
            else { return new BotMessage() { Text = "Not a one-of-ya has scored yet. Come on, sleepyheads!" }; }
        }
    }
}


text:
package org.david.algorithms.codewars;

/**
 * Created by David Marques on 21/05/2017.
 */

/**
 * Some of you might remember spending afternoons playing Street Fighter 2 in some Arcade back in the 90s or emulating it nowadays with the numerous emulators for retro consoles.
 *

 * Can you solve this kata? Suuure-You-Can!
 *

 * UPDATE: a new kata's harder version is available here.
 *

 * The Kata
 *

 * You'll have to simulate the video game's character selection screen behaviour, more specifically the selection grid. Such screen looks like this:
 * Selection Grid Layout in text:
 *

 * | Ryu  | E.Honda | Blanka  | Guile   | Balrog | Vega    |
 * | Ken  | Chun Li | Zangief | Dhalsim | Sagat  | M.Bison |
 * Input
 *

 * the list of game characters in a 2x6 grid;
 * the initial position of the selection cursor (top-left is (0,0));
 * a list of moves of the selection cursor (which are up, down, left, right);
 * Output
 *

 * the list of characters who have been hovered by the selection cursor after all the moves (ordered and with repetition, all the ones after a move, wether successful or not, see tests);
 * Rules
 *

 * Selection cursor is circular horizontally but not vertically!
 *

 * As you might remember from the game, the selection cursor rotates horizontally but not vertically; that means that if I'm in the leftmost and I try to go left again I'll get to the rightmost (examples: from Ryu to Vega, from Ken to M.Bison) and vice versa from rightmost to leftmost.
 *

 * Instead, if I try to go further up from the upmost or further down from the downmost, I'll just stay where I am located (examples: you can't go lower than lowest row: Ken, Chun Li, Zangief, Dhalsim, Sagat and M.Bison in the above image; you can't go upper than highest row: Ryu, E.Honda, Blanka, Guile, Balrog and Vega in the above image).
 *

 * Test
 *

 * For this easy version the fighters grid layout and the initial position will always be the same in all tests, only the list of moves change.
 *

 * Notice : changing some of the input data might not help you.
 *

 * Examples
 *

 * 1.
 *

 * fighters = [
 * ["Ryu", "E.Honda", "Blanka", "Guile", "Balrog", "Vega"],
 * ["Ken", "Chun Li", "Zangief", "Dhalsim", "Sagat", "M.Bison"]
 * ]
 * initial_position = (0,0)
 * moves = ['up', 'left', 'right', 'left', 'left']
 * then I should get:
 *

 * ['Ryu', 'Vega', 'Ryu', 'Vega', 'Balrog']
 * as the characters I've been hovering with the selection cursor during my moves. Notice: Ryu is the first just because it "fails" the first up See test cases for more examples.
 *

 * 2.
 *

 * fighters = [
 * ["Ryu", "E.Honda", "Blanka", "Guile", "Balrog", "Vega"],
 * ["Ken", "Chun Li", "Zangief", "Dhalsim", "Sagat", "M.Bison"]
 * ]
 * initial_position = (0,0)
 * moves = ['right', 'down', 'left', 'left', 'left', 'left', 'right']
 * Result:
 *

 * ['E.Honda', 'Chun Li', 'Ken', 'M.Bison', 'Sagat', 'Dhalsim', 'Sagat']
 */
public class StreetFighter {

    public static String[] streetFighterSelection(String[][] fighters, int[] position, String[] moves) {

        String[] selection = new String[moves.length];
        int x = position[1];
        int y = position[0];
        int index = 0;
        for (String move : moves) {
            if (move.equalsIgnoreCase("down")) {
                y = (y + 1) == fighters.length ? y : y + 1;
            } else if (move.equalsIgnoreCase("up")) {
                y = (y - 1) == -1 ? y : y - 1;
            } else if (move.equalsIgnoreCase("left")) {
                x = (x + fighters[y].length - 1) % fighters[y].length;
            } else if (move.equalsIgnoreCase("right")) {
                x = (x + 1) % fighters[y].length;
            }
            selection[index] = fighters[y][x];
            index++;
        }

        return selection;
    }
}


text:
import Ember from 'ember';
import {
  moduleForComponent,
  test
} from 'ember-qunit';
import makeSubject from '../../helpers/make-subject';

var resolve = Ember.RSVP.resolve;
var run = Ember.run;

moduleForComponent('lazy-video', 'LazyVideoComponent', {
  subject: makeSubject({
    providers: {
      getThumbnailUrl: function() {
        return resolve('http://example.com');
      }
    }
  })
});

test('it renders with correct style attribute', function() {
  expect(1);

  var component = this.subject({
    url: 'https://www.youtube.com/watch?v=gvdf5n-zI14'
  });

  run(function() {
    component.append();
  });

  var componentStyle = component.$().attr('style');
  ok(/url\(http:\/\/example\.com\)/.test(componentStyle));
});


text:
exports.merge = function (sourceExports, destExports) {
    for (var key in sourceExports) {
        destExports[key] = sourceExports[key];
    }
};


text:
package de.unioninvestment.eai.portal.portlet.crud.domain.model.container;

import static java.util.Arrays.asList;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
import static org.mockito.Mockito.when;

import java.util.Map;

import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;

public class StreamItemValuesRowTest {

	@Mock
	private StreamItem itemMock;

	@Before
	public void setUp() {
		MockitoAnnotations.initMocks(this);
	}

	@Test
	public void shouldProvideItemValuesAsHashMap() {
		when(itemMock.getValue("A")).thenReturn("AValue");
		when(itemMock.getValue("B")).thenReturn("BValue");
		StreamItemValuesRow row = new StreamItemValuesRow(asList("A", "B"), itemMock);

		Map<String, Object> values = row.getValues();
		assertThat(values.size(), is(2));
		assertThat(values.get("A"), is((Object)"AValue"));
		assertThat(values.get("B"), is((Object)"BValue"));
	}
}


text:
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

// require: event_target.js

cr.define('cr.ui', function() {
  /** @const */ const Menu = cr.ui.Menu;

  /**
   * Handles context menus.
   * @implements {EventListener}
   */
  class ContextMenuHandler extends cr.EventTarget {
    constructor() {
      super();
      /** @private {!EventTracker} */
      this.showingEvents_ = new EventTracker();

      /**
       * The menu that we are currently showing.
       * @private {?cr.ui.Menu}
       */
      this.menu_ = null;

      /** @private {?number} */
      this.hideTimestamp_ = null;

      /** @private {boolean} */
      this.keyIsDown_ = false;
    }

    get menu() {
      return this.menu_;
    }

    /**
     * Shows a menu as a context menu.
     * @param {!Event} e The event triggering the show (usually a contextmenu
     *     event).
     * @param {!cr.ui.Menu} menu The menu to show.
     */
    showMenu(e, menu) {
      menu.updateCommands(assertInstanceof(e.currentTarget, Node));
      if (!menu.hasVisibleItems()) {
        return;
      }

      this.menu_ = menu;
      menu.classList.remove('hide-delayed');
      menu.show({x: e.screenX, y: e.screenY});
      menu.contextElement = e.currentTarget;

      // When the menu is shown we steal a lot of events.
      const doc = menu.ownerDocument;
      const win = /** @type {!Window} */ (doc.defaultView);
      this.showingEvents_.add(doc, 'keydown', this, true);
      this.showingEvents_.add(doc, 'mousedown', this, true);
      this.showingEvents_.add(doc, 'touchstart', this, true);
      this.showingEvents_.add(doc, 'focus', this);
      this.showingEvents_.add(win, 'popstate', this);
      this.showingEvents_.add(win, 'resize', this);
      this.showingEvents_.add(win, 'blur', this);
      this.showingEvents_.add(menu, 'contextmenu', this);
      this.showingEvents_.add(menu, 'activate', this);
      this.positionMenu_(e, menu);

      const ev = new Event('show');
      ev.element = menu.contextElement;
      ev.menu = menu;
      this.dispatchEvent(ev);
    }

    /**
     * Hide the currently shown menu.
     * @param {cr.ui.HideType=} opt_hideType Type of hide.
     *     default: cr.ui.HideType.INSTANT.
     */
    hideMenu(opt_hideType) {
      const menu = this.menu;
      if (!menu) {
        return;
      }

      if (opt_hideType === cr.ui.HideType.DELAYED) {
        menu.classList.add('hide-delayed');
      } else {
        menu.classList.remove('hide-delayed');
      }
      menu.hide();
      const originalContextElement = menu.contextElement;
      menu.contextElement = null;
      this.showingEvents_.removeAll();
      menu.selectedIndex = -1;
      this.menu_ = null;

      // On windows we might hide the menu in a right mouse button up and if
      // that is the case we wait some short period before we allow the menu
      // to be shown again.
      this.hideTimestamp_ = cr.isWindows ? Date.now() : 0;

      const ev = new Event('hide');
      ev.element = originalContextElement;
      ev.menu = menu;
      this.dispatchEvent(ev);
    }

    /**
     * Positions the menu
     * @param {!Event} e The event object triggering the showing.
     * @param {!cr.ui.Menu} menu The menu to position.
     * @private
     */
    positionMenu_(e, menu) {
      // TODO(arv): Handle scrolled documents when needed.

      const element = e.currentTarget;
      let x, y;
      // When the user presses the context menu key (on the keyboard) we need
      // to detect this.
      if (this.keyIsDown_) {
        const rect = element.getRectForContextMenu ?
            element.getRectForContextMenu() :
            element.getBoundingClientRect();
        const offset = Math.min(rect.width, rect.height) / 2;
        x = rect.left + offset;
        y = rect.top + offset;
      } else {
        x = e.clientX;
        y = e.clientY;
      }

      cr.ui.positionPopupAtPoint(x, y, menu);
    }

    /**
     * Handles event callbacks.
     * @param {!Event} e The event object.
     */
    handleEvent(e) {
      // Keep track of keydown state so that we can use that to determine the
      // reason for the contextmenu event.
      switch (e.type) {
        case 'keydown':
          this.keyIsDown_ = !e.ctrlKey && !e.altKey &&
              // context menu key or Shift-F10
              (e.keyCode === 93 && !e.shiftKey ||
               e.key === 'F10' && e.shiftKey);
          break;

        case 'keyup':
          this.keyIsDown_ = false;
          break;
      }

      // Context menu is handled even when we have no menu.
      if (e.type !== 'contextmenu' && !this.menu) {
        return;
      }

      switch (e.type) {
        case 'mousedown':
          if (!this.menu.contains(e.target)) {
            this.hideMenu();
            if (e.button === 0 /* Left button */ && (cr.isLinux || cr.isMac)) {
              // Emulate Mac and Linux, which swallow native 'mousedown' events
              // that close menus.
              e.preventDefault();
              e.stopPropagation();
            }
          } else {
            e.preventDefault();
          }
          break;

        case 'touchstart':
          if (!this.menu.contains(e.target)) {
            this.hideMenu();
          }
          break;

        case 'keydown':
          if (e.key === 'Escape') {
            this.hideMenu();
            e.stopPropagation();
            e.preventDefault();

            // If the menu is visible we let it handle all the keyboard events.
          } else if (this.menu) {
            this.menu.handleKeyDown(e);
            e.preventDefault();
            e.stopPropagation();
          }
          break;

        case 'activate':
          const hideDelayed =
              e.target instanceof cr.ui.MenuItem && e.target.checkable;
          this.hideMenu(
              hideDelayed ? cr.ui.HideType.DELAYED : cr.ui.HideType.INSTANT);
          break;

        case 'focus':
          if (!this.menu.contains(e.target)) {
            this.hideMenu();
          }
          break;

        case 'blur':
          this.hideMenu();
          break;

        case 'popstate':
        case 'resize':
          this.hideMenu();
          break;

        case 'contextmenu':
          if ((!this.menu || !this.menu.contains(e.target)) &&
              (!this.hideTimestamp_ || Date.now() - this.hideTimestamp_ > 50)) {
            this.showMenu(e, e.currentTarget.contextMenu);
          }
          e.preventDefault();
          // Don't allow elements further up in the DOM to show their menus.
          e.stopPropagation();
          break;
      }
    }

    /**
     * Adds a contextMenu property to an element or element class.
     * @param {!Element|!Function} elementOrClass The element or class to add
     *     the contextMenu property to.
     */
    addContextMenuProperty(elementOrClass) {
      const target = typeof elementOrClass === 'function' ?
          elementOrClass.prototype :
          elementOrClass;

      // eslint-disable-next-line no-restricted-properties
      target.__defineGetter__('contextMenu', function() {
        return this.contextMenu_;
      });
      // eslint-disable-next-line no-restricted-properties
      target.__defineSetter__('contextMenu', function(menu) {
        const oldContextMenu = this.contextMenu;

        if (typeof menu === 'string' && menu[0] === '#') {
          menu = this.ownerDocument.getElementById(menu.slice(1));
          cr.ui.decorate(menu, Menu);
        }

        if (menu === oldContextMenu) {
          return;
        }

        if (oldContextMenu && !menu) {
          this.removeEventListener('contextmenu', contextMenuHandler);
          this.removeEventListener('keydown', contextMenuHandler);
          this.removeEventListener('keyup', contextMenuHandler);
        }
        if (menu && !oldContextMenu) {
          this.addEventListener('contextmenu', contextMenuHandler);
          this.addEventListener('keydown', contextMenuHandler);
          this.addEventListener('keyup', contextMenuHandler);
        }

        this.contextMenu_ = menu;

        if (menu && menu.id) {
          this.setAttribute('contextmenu', '#' + menu.id);
        }

        cr.dispatchPropertyChange(this, 'contextMenu', menu, oldContextMenu);
      });

      if (!target.getRectForContextMenu) {
        /**
         * @return {!ClientRect} The rect to use for positioning the context
         *     menu when the context menu is not opened using a mouse position.
         */
        target.getRectForContextMenu = function() {
          return this.getBoundingClientRect();
        };
      }
    }

    /**
     * Sets the given contextMenu to the given element. A contextMenu property
     * would be added if necessary.
     * @param {!Element} element The element or class to set the contextMenu to.
     * @param {!cr.ui.Menu} contextMenu The contextMenu property to be set.
     */
    setContextMenu(element, contextMenu) {
      if (!element.contextMenu) {
        this.addContextMenuProperty(element);
      }
      element.contextMenu = contextMenu;
    }
  }

  /**
   * The singleton context menu handler.
   * @type {!ContextMenuHandler}
   */
  const contextMenuHandler = new ContextMenuHandler;

  // Export
  return {
    contextMenuHandler: contextMenuHandler,
  };
});


text:
[![AppVeyor](https://img.shields.io/appveyor/ci/JoyMoe/qcloudsharp.svg)](https://ci.appveyor.com/project/JoyMoe/qcloudsharp)
[![GitHub license](https://img.shields.io/badge/license-MIT-blue.svg)](https://raw.githubusercontent.com/JoyMoe/QcloudSmsSharp/master/LICENSE)
[![NuGet](https://img.shields.io/nuget/v/QcloudSharp.svg)](https://www.nuget.org/packages/QcloudSharp)
[![NuGet](https://img.shields.io/nuget/vpre/QcloudSharp.svg)](https://www.nuget.org/packages/QcloudSharp/absoluteLatest)
![netstandard1.6](https://img.shields.io/badge/.Net-netstandard1.6-brightgreen.svg)
![netstandard2.0](https://img.shields.io/badge/.Net-netstandard2.0-brightgreen.svg)
![netstandard2.1](https://img.shields.io/badge/.Net-netstandard2.1-brightgreen.svg)

[中文说明](README.zh.md)

## Installation

To install QcloudSharp, run the following command in the Package Manager Console

```powershell
PM> Install-Package QcloudSharp
```

## Example

```csharp
using QcloudSharp;
using Newtonsoft.Json;

dynamic client = new QcloudClient
{
    SecretId = "Your_Secret_Id",
    SecretKey = "Your_Secret_Key",
    Endpoint = Constants.Endpoint.Trade, // Endpoint can be used as the first argument of Dynamic Methods
    Region = Constants.Region.CAN, // Region can be used as the first or second argument of Dynamic Methods
};

var resultString = client.DescribeUserInfo();
// e.g. {"code":0,"message": "","userInfo":{"name":"compName","isOwner":1,"mailStatus":1,"mail":"112233@qq.com","phone":"13811112222"}}

dynamic result = JsonConvert.DeserializeObject<ApiResult>(resultString);

try
{
    Console.WriteLine(result.Code);
    Console.WriteLine(result.userInfo.name);
    Console.WriteLine(result.notExist);
}
catch(Exception ex)
{
    Console.WriteLine(ex.message);
}
```

Or you can have a look at [sample](sample).

## Constants

All Constants are provided by class `QcloudSharp.Constants`.

```csharp
public static class Endpoint // Abbreviation for endpoint domain
```

Members

* Account
* Batch
* Bgpip
* Bill
* Bm
* Bmeip
* Bmlb
* Bmvpc
* Cbs
* Cdb
* Cdn
* Cmem
* CmqQueue
* CmqTopic
* Cns
* Csec
* Cvm
* Dayu
* Dfw
* Eip
* Image
* Iot
* Kms
* Lb
* Live
* Market
* Mongodb
* Monitor
* Partners
* Redis
* Scaling
* Snapshot
* Sqlserver
* Tdsql
* Tmt
* Trade
* Vod
* Vod2
* Vpc
* Wenzhi
* Wss
* Yunsou

```csharp
public static class Region // IATA code for Region city
```

Members

* BJS `bj`
* CAN `gz`
* CAN1 `gzopen`
* CKG `cq`
* CTU `cd`
* FRA `de`
* HKG `hk`
* SEL `kr`
* SHA `sh`
* SHA2 `shjr`
* SIN `sg`
* SJC `usw`
* SZX2 `szjr`
* YTO `ca`

## Classes

### QcloudClient

```csharp
public class QcloudClient : DynamicObject
```

Constructors

* `QcloudClient()`
* `QcloudClient(SecretId, SecretKey)`

Properties

* string `SecretId`
* string `SecretKey`
* string `Region`
* string `Endpoint`

Methods

* `void AddParameter(KeyValuePair<string, string>)`
* `void AddParameter(IEnumerable<KeyValuePair<string, string>>)`
* `void ClearParameter()`
* `Submit(string, string, string)`
* `Submit(string, string)`
* `Submit(string)`

Dynamic Methods

* `{Action}([string][, string][, IEnumerable<KeyValuePair<string, string>>])`
* `{Action}([string][, string][, KeyValuePair<string, string> ...])`

### ApiResult

```csharp
public class ApiResult : DynamicObject
```

Constructors

* `ApiResult()`

Properties

* int `Code`
* string `Message`

Dynamic Properties

* object Any { Get; Set; }

## License

The MIT License

More info see [LICENSE](LICENSE)