text:
layout: post
title:  "Fests"
date:   2015-06-26 12:28:01
categories: [jekyll, update, section]
excerpt: Surprise struck to the junta in the autumn of 2013 when Thomso'13 unexpectedly kicked-ass in each and every goddamn domain. Undoubtedly, the days of Thomso are probably the best time at the campus of IIT-R.
class: ch-img-3
cover: fests_cover.jpg
---
--------------------------------
###Cognizance

Although it is the largest technical festival of Asia, calling it the 2nd largest technical festival of
Asia is simply IIT-R being humble. Cognizance takes place in the Spring semester: just after the
curse of mid-terms gets lifted from the lives of people. It invites eminent personalities from all
over the world for guest lectures, workshops and stage-shows pertaining to the world to
technology. The organizing team comprises of the students of IITR themselves. For both
Thomso and Cogni, a modest structure of hierarchy exists while working. A typical freshman
involved/pretending-to-be involved in the work can be identified by the following:

1. Begging his facebook friends to like the Cogni page.

2. Putting up posters in Bhawans.

3. Undying devotion for any kind of Chapo from a senior.

###Thomso

The annual cultural festival of IIT-R, Thomso is the time of year when the uneven sex-ratio in
the campus becomes hardly noticeable. It will be important to mention how bravely this festival
survived before the unfortunate disaster of 2010 which led to its banning in 2011. However, it
was re -launched with rigor in 2012 and people actually hoped that it was better to forget
about the heavenly days again on campus.

Surprise struck to the junta in the autumn of 2013 when Thomso'13 unexpectedly kicked-ass in
each and every goddamn domain. Undoubtedly, the days of Thomso are probably the best time
at the campus of IIT-R.

###Sankalp

Sankalp kicks off the trinity of fests in the spring semester. Sankalp is the socio technical fest,
organized by NSS. Though in its nascent stages, it is replete with multiple events like panel
discussions, case studies and guest lectures, underlining the message of social conscience.

If you are a faccha in NSS, you will be hounded by your seniors to attend the aforementioned
guest lectures and panel discussions, with dire threats of attendance hanging over your
shoulders.

It is mostly ignored by the rest of the campus.

###Sangram

The official sports fest of IITR, Sangram offers the sports fraternity of IITR a reason to keep their
spirits up after the InterIIT season ends. High spirited matches are marked by intense jeering
and inventive name calling from the abundant IITR crowd granting you the illusory sense of
fulfillment that you have done your part for the institute. It sees a healthy turnout from many
north Indian colleges, IITs included and is utilized to give freshmen some much needed game
time. Needless to say, regularity a month or two before the fest can land you a spot in one of
the B teams and maybe give you your 15 minutes of fame.


text:
package org.apache.spark.sql.execution.datasources.oap.utils

import java.io.OutputStream

import org.apache.spark.sql.catalyst.InternalRow
import org.apache.spark.sql.execution.datasources.OapException
import org.apache.spark.sql.execution.datasources.oap.filecache.FiberCache
import org.apache.spark.sql.execution.datasources.oap.index.IndexUtils
import org.apache.spark.sql.types._
import org.apache.spark.unsafe.types.UTF8String

/**
 * Initialize only once for every task for a static schema, to avoid pattern matching and
 * branching when directly use `writeBasedOnSchema` and `writeBasedOnDataType`.
 */
private[oap] class NonNullKeyWriter(schema: StructType) {
  private lazy val internalWriters: Seq[(OutputStream, Any) => Unit] =
    schema.toSeq.map(_.dataType).map(getWriterFunctionBasedOnType)

  private def getWriterFunctionBasedOnType(
      dt: DataType): (OutputStream, Any) => Unit = dt match {
    case BooleanType =>
      (out: OutputStream, b: Any) => IndexUtils.writeBoolean(out, b.asInstanceOf[Boolean])
    case ByteType =>
      (out: OutputStream, b: Any) => IndexUtils.writeByte(out, b.asInstanceOf[Byte])
    case ShortType =>
      (out: OutputStream, sh: Any) => IndexUtils.writeShort(out, sh.asInstanceOf[Short])
    case IntegerType =>
      (out: OutputStream, i: Any) => IndexUtils.writeInt(out, i.asInstanceOf[Int])
    case LongType =>
      (out: OutputStream, l: Any) => IndexUtils.writeLong(out, l.asInstanceOf[Long])
    case FloatType =>
      (out: OutputStream, f: Any) => IndexUtils.writeFloat(out, f.asInstanceOf[Float])
    case DoubleType =>
      (out: OutputStream, d: Any) => IndexUtils.writeDouble(out, d.asInstanceOf[Double])
    case StringType =>
      (out: OutputStream, s: Any) =>
        val bytes = s.asInstanceOf[UTF8String].getBytes
        IndexUtils.writeInt(out, bytes.length)
        out.write(bytes)
    case BinaryType =>
      (out: OutputStream, b: Any) =>
        val binary = b.asInstanceOf[Array[Byte]]
        IndexUtils.writeInt(out, binary.length)
        out.write(binary)
    case other => throw new OapException(s"OAP index currently doesn't support data type $other")
  }

  def writeKey(out: OutputStream, key: InternalRow): Unit = {
    internalWriters.zipWithIndex.foreach { wi =>
      val idx = wi._2
      val writer: (OutputStream, Any) => Unit = wi._1
      val value = key.get(idx, schema(idx).dataType)
      writer(out, value)
    }
  }
}

private[oap] class NonNullKeyReader(schema: StructType) {
  private lazy val internalReaders: Seq[(FiberCache, Int) => (Any, Int)] =
    schema.toSeq.map(_.dataType).map(getReaderFunctionBasedOnType)
  private def getReaderFunctionBasedOnType(dt: DataType): (FiberCache, Int) => (Any, Int) =
    (fiberCache: FiberCache, offset: Int) => dt match {
      case BooleanType => (fiberCache.getBoolean(offset), BooleanType.defaultSize)
      case ByteType => (fiberCache.getByte(offset), ByteType.defaultSize)
      case ShortType => (fiberCache.getShort(offset), ShortType.defaultSize)
      case IntegerType => (fiberCache.getInt(offset), IntegerType.defaultSize)
      case LongType => (fiberCache.getLong(offset), LongType.defaultSize)
      case FloatType => (fiberCache.getFloat(offset), FloatType.defaultSize)
      case DoubleType => (fiberCache.getDouble(offset), DoubleType.defaultSize)
      case DateType => (fiberCache.getInt(offset), DateType.defaultSize)
      case StringType =>
        val length = fiberCache.getInt(offset)
        val string = fiberCache.getUTF8String(offset + IndexUtils.INT_SIZE, length)
        (string, IndexUtils.INT_SIZE + length)
      case BinaryType =>
        val length = fiberCache.getInt(offset)
        val bytes = fiberCache.getBytes(offset + IndexUtils.INT_SIZE, length)
        (bytes, IndexUtils.INT_SIZE + bytes.length)
      case other => throw new OapException(s"OAP index currently doesn't support data type $other")
    }

  def readKey(fiberCache: FiberCache, offset: Int): (InternalRow, Int) = {
    var pos = offset
    val values = internalReaders.map { reader =>
      val (value, length) = reader(fiberCache, pos)
      pos += length
      value
    }
    (InternalRow.fromSeq(values), pos - offset)
  }
}

redpajama_set_name: RedPajamaGithub


text:
import Validator from '../Validator';
import { isArray } from '../internal/utils';

Validator.registerRule('array', (value: any) => isArray(value));


text:
/**
 *
 * Check if an app is installed.
 *
 * <example>
    :isAppInstalledSync.js
    browser.isAppInstalled('com.example.android.apis');
 * </example>
 *
 * @param {String} bundleId  ID of bundled app
 *
 * @see  https://github.com/appium/appium/blob/master/docs/en/writing-running-appium/appium-bindings.md#is-installed
 * @type mobile
 * @for android
 *
 */

import { ProtocolError } from '../utils/ErrorHandler'

let isAppInstalled = function (bundleId) {
    if (typeof appPath !== 'string') {
        throw new ProtocolError('isAppInstalled command requires bundleId parameter from type string')
    }

    return this.unify(this.requestHandler.create({
        path: '/session/:sessionId/appium/device/app_installed',
        method: 'POST'
    }, { bundleId }))
}

export default isAppInstalled


text:
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

<canvas width="550" height="800" id="canvas"></canvas>
<script src="app.js"></script>
</body>
</html>


text:
REGISTER_SINGLETON_REGISTRY("file system", sling::FileSystem);

namespace sling {
namespace {

// The file systems need to be initialized at most once.
pthread_once_t file_systems_initialized = PTHREAD_ONCE_INIT;

// Registered file systems.
std::unordered_map<string, FileSystem *> file_systems;
FileSystem *default_file_system = nullptr;

// Initialize all registered file systems.
void InitializeFileSystems() {
  auto *registry = FileSystem::registry();
  for (auto *fs = registry->components; fs != nullptr; fs = fs->next()) {
    VLOG(2) << "Initializing " << fs->type() << " file system";
    fs->object()->Init();
    if (fs->object()->IsDefaultFileSystem()) {
      default_file_system = fs->object();
    } else {
      file_systems[fs->type()] = fs->object();
    }
  }
}

// Find file system for file name. If no matching file system is found, the
// default file system is returned.
FileSystem *FindFileSystem(const string &filename, string *rest) {
  // Initialize file systems if not already done.
  if (default_file_system == nullptr) File::Init();

  // Match the first component in the path.
  if (!filename.empty() && filename[0] == '/') {
    int slash = filename.find('/', 1);
    if (slash != -1) {
      auto f = file_systems.find(filename.substr(1, slash - 1));
      if (f != file_systems.end()) {
        *rest = filename.substr(slash + 1);
        return f->second;
      }
    }
  }

  // Fall back on the default file system.
  *rest = filename;
  return default_file_system;
}

Status NoFileSystem(const string &filename) {
  return Status(1, "No file system", filename);
}

}  // namespace

void File::Init() {
  // Allow this method to be called multiple times.
  pthread_once(&file_systems_initialized, InitializeFileSystems);
}

Status File::Open(const string &name, const char *mode, File **f) {
  // Find file system.
  string rest;
  FileSystem *fs = FindFileSystem(name, &rest);
  if (fs == nullptr) return NoFileSystem(name);

  // Open new file.
  return fs->Open(rest, mode, f);
}

File *File::Open(const string &name, const char *mode) {
  File *f;
  if (!Open(name, mode, &f).ok()) return nullptr;
  return f;
}

File *File::OpenOrDie(const string &name, const char *mode) {
  File *f;
  CHECK(Open(name, mode, &f));
  return f;
}

Status File::Delete(const string &name) {
  // Find file system.
  string rest;
  FileSystem *fs = FindFileSystem(name, &rest);
  if (fs == nullptr) return NoFileSystem(name);

  // Delete file.
  return fs->DeleteFile(rest);
}

bool File::Exists(const string &name) {
  // Find file system.
  string rest;
  FileSystem *fs = FindFileSystem(name, &rest);
  if (fs == nullptr) return false;

  // Check if file exists.
  return fs->FileExists(rest);
}

Status File::GetSize(const string &name, uint64 *size) {
  // Find file system.
  string rest;
  FileSystem *fs = FindFileSystem(name, &rest);
  if (fs == nullptr) return NoFileSystem(name);

  // Get file size.
  return fs->GetFileSize(rest, size);
}

Status File::Stat(const string &name, FileStat *stat) {
  // Find file system.
  string rest;
  FileSystem *fs = FindFileSystem(name, &rest);
  if (fs == nullptr) return NoFileSystem(name);

  // Get file size.
  return fs->Stat(rest, stat);
}

Status File::Rename(const string &source, const string &target) {
  // Find file system.
  string src;
  string tgt;
  FileSystem *srcfs = FindFileSystem(source, &src);
  FileSystem *tgtfs = FindFileSystem(target, &tgt);
  if (srcfs == nullptr) return NoFileSystem(source);
  if (tgtfs == nullptr) return NoFileSystem(target);
  if (srcfs != tgtfs) return Status(1, "Cross file system rename", source);

  // Rename file.
  return srcfs->RenameFile(src, tgt);
}

Status File::Mkdir(const string &dir) {
  // Find file system.
  string rest;
  FileSystem *fs = FindFileSystem(dir, &rest);
  if (fs == nullptr) return NoFileSystem(dir);

  // Create directory.
  return fs->CreateDir(rest);
}

Status File::Rmdir(const string &dir) {
  // Find file system.
  string rest;
  FileSystem *fs = FindFileSystem(dir, &rest);
  if (fs == nullptr) return NoFileSystem(dir);

  // Create directory.
  return fs->DeleteDir(rest);
}

File *File::TempFile() {
  CHECK(default_file_system != nullptr);
  File *f;
  CHECK(default_file_system->CreateTempFile(&f));
  return f;
}

Status File::CreateTempDir(string *dir) {
  if (default_file_system == nullptr) return NoFileSystem("tmpdir");
  return default_file_system->CreateTempDir(dir);
}

Status File::Match(const string &pattern, std::vector<string> *filenames) {
  // Find file system.
  string rest;
  FileSystem *fs = FindFileSystem(pattern, &rest);
  if (fs == nullptr) return NoFileSystem(pattern);

  // Convert sharded file pattern.
  int at = rest.find('@');
  if (at != string::npos) {
    string shards = rest.substr(at + 1);
    int dot = shards.find('.');
    string ext;
    if (dot != string::npos) {
      ext = shards.substr(dot);
      shards.resize(dot);
    }
    rest.resize(at);
    rest.append("-\?\?\?\?\?-of-");
    rest.append(5 - shards.size(), '0');
    rest.append(shards);
    rest.append(ext);
  }

  // Find files.
  Status st = fs->Match(rest, filenames);
  if (!st.ok()) return st;

  // Sort file names.
  std::sort(filenames->begin(), filenames->end());

  return Status::OK;
}

Status File::ReadContents(const string &filename, string *data) {
  // Open file for reading.
  File *f;
  Status st = Open(filename, "r", &f);
  if (!st.ok()) return st;

  // Read contents.
  st = f->ReadToString(data);
  if (!st.ok()) {
    f->Close();
    return st;
  }

  // Close file.
  return f->Close();
}

Status File::WriteContents(const string &filename,
                           const void *data,
                           size_t size) {
  // Open file for writing.
  File *f;
  Status st = Open(filename, "w", &f);
  if (!st.ok()) return st;

  // Write contents.
  st = f->Write(data, size);
  if (!st.ok()) {
    f->Close();
    return st;
  }

  // Close file.
  return f->Close();
}

Status File::Read(void *buffer, size_t size) {
  // Keep reading partial data until all data has been read. Return error if
  // then end of the file is reached or a read error occurred.
  while (size > 0) {
    uint64 bytes;
    Status st = Read(buffer, size, &bytes);
    if (!st.ok()) return st;
    if (bytes == 0) return Status(1, "Truncated", filename());
    size -= bytes;
  }
  return Status::OK;
}

void File::ReadOrDie(void *buffer, size_t size) {
  uint64 read;
  CHECK(Read(buffer, size, &read));
  CHECK_EQ(read, size) << "Read " << read << " bytes, expected " << size;
}

void File::WriteOrDie(const void *buffer, size_t size) {
  CHECK(Write(buffer, size));
}

Status File::ReadToString(string *contents) {
  // Get current position and size.
  uint64 pos, size;
  Status st = GetPosition(&pos);
  if (!st.ok()) return st;
  st = GetSize(&size);
  if (!st.ok()) return st;
  size -= pos;

  // Read file data into string buffer.
  contents->resize(size);
  char *data = &(*contents)[0];
  uint64 read;
  st = Read(data, size, &read);
  if (st.ok() && read < contents->size()) contents->resize(read);
  return st;
}

Status File::WriteString(const string &str) {
  return Write(str.data(), str.size());
}

Status File::WriteLine(const string &line) {
  Status st = WriteString(line);
  if (st.ok()) st = Write("\n", 1);
  return st;
}

uint64 File::Tell() {
  uint64 pos;
  if (!GetPosition(&pos).ok()) return -1;
  return pos;
}

uint64 File::Size() {
  uint64 size;
  if (!GetSize(&size).ok()) return -1;
  return size;
}

size_t File::PageSize() {
  return sysconf(_SC_PAGESIZE);
}

void *File::MapMemory(uint64 pos, size_t size, bool writable) {
  return nullptr;
}

Status File::FlushMappedMemory(void *data, size_t size) {
  if (default_file_system == nullptr) return NoFileSystem("mmunmap");
  return default_file_system->FlushMappedMemory(data, size);
}

Status File::FreeMappedMemory(void *data, size_t size) {
  if (default_file_system == nullptr) return NoFileSystem("mmunmap");
  return default_file_system->FreeMappedMemory(data, size);
}

Status FileSystem::FlushMappedMemory(void *data, size_t size) {
  return Status(ENOSYS, "Memory-mapped files not supported");
}

Status FileSystem::FreeMappedMemory(void *data, size_t size) {
  return Status(ENOSYS, "Memory-mapped files not supported");
}

REGISTER_INITIALIZER(filesystem, {
  File::Init();
});

}  // namespace sling


text:
package swim

import (
	"testing"
)

func TestBroadcastQueue(t *testing.T) {
	bqueue := NewBroadcastQueue()

	// peek on empty queue
	if bqueue.Len() != 0 {
		t.Fatalf("Expected length of 0")
	}

	prune := func(b *Broadcast) func(b *Broadcast) bool {
		return func(that *Broadcast) bool {
			return b == nil || b == that
		}
	}

	// class 0 broadcast
	done := make(chan struct{}, 1)
	event0 := &SuspectEvent{From: 1, Id: 2, Incarnation: Seq(3)}
	bcast0 := &Broadcast{Class: 0, Event: event0, Done: done}
	bqueue.Push(bcast0)
	if bqueue.Len() != 1 {
		t.Fatalf("Expected length of 1")
	} else if bqueue.List()[0] != bcast0 {
		t.Fatalf("Expected list of broadcast 0")
	}

	bqueue.Prune(prune(bcast0))
	if l := bqueue.Len(); l != 0 {
		t.Fatalf("Expected length of 0 got %v", l)
	}

	// go test will detect deadlock if we were not signalled
	<-done

	// class 1 broadcast
	event1 := &SuspectEvent{From: 2, Id: 3, Incarnation: Seq(4)}
	bcast1 := &Broadcast{Class: 1, Event: event1}
	bqueue.Push(bcast1)
	if bqueue.List()[0] != bcast1 {
		t.Fatalf("Expected list of broadcast 1")
	} else if bqueue.Len() != 1 {
		t.Fatalf("Expected length of 1")
	}

	bqueue.Prune(prune(bcast1))
	if l := bqueue.Len(); l != 0 {
		t.Fatalf("Expected length of 0 got %v", l)
	}

	// class 0 and 1 broadcasts w/ stable sort
	bqueue.Push(bcast0)
	bqueue.Push(bcast1)
	if bqueue.Len() != 2 {
		t.Fatalf("Expected length of 2")
	} else if bqueue.List()[0] != bcast0 || bqueue.List()[1] != bcast1 {
		t.Fatalf("Expected list of broadcast 0 and 1 got %v", bqueue.List())
	}

	bqueue.Prune(prune(bcast1))
	if l := bqueue.Len(); l != 1 {
		t.Fatalf("Expected length of 1 got %v", l)
	} else if bqueue.List()[0] != bcast0 {
		t.Fatalf("Expected list of broadcast 0")
	}

	bqueue.Prune(prune(bcast0))
	if l := bqueue.Len(); l != 0 {
		t.Fatalf("Expected length of 0 got %v", l)
	}

	// go test will detect deadlock if we were not signalled
	<-done

	// class 0 and 1 broadcasts w/ attempts after insertion
	bqueue.Push(bcast0)
	bqueue.Push(bcast1)
	if bqueue.Len() != 2 {
		t.Fatalf("Expected length of 2")
	} else if bs := bqueue.List(); bs[0] != bcast0 || bs[1] != bcast1 {
		t.Fatalf("Expected list of broadcast 0 and 1 got %v and %v", bs[0], bs[1])
	}

	bqueue = NewBroadcastQueue()

	// class 0 and 1 broadcasts w/ attempts before insertion
	bqueue.Push(bcast0)
	bqueue.Push(bcast1)
	if bqueue.Len() != 2 {
		t.Fatalf("Expected length of 2")
	} else if bqueue.List()[0] != bcast0 || bqueue.List()[1] != bcast1 {
		t.Fatalf("Expected list of broadcast 0 and 1 got %v", bqueue.List())
	}

	bqueue = NewBroadcastQueue()

	// invalidation
	event1p := &SuspectEvent{From: 2, Id: 3, Incarnation: Seq(5)}
	bcast1p := &Broadcast{Class: 1, Event: event1p}
	bqueue.Push(bcast0)
	bqueue.Push(bcast1)
	bqueue.Push(bcast1p)
	if bqueue.Len() != 2 {
		t.Fatalf("Expected length of 2 got %v", bqueue.Len())
	} else if bs := bqueue.List(); bs[0] != bcast0 || bs[1] != bcast1p {
		t.Fatalf("Expected list of broadcast 0 and 1")
	}

	bqueue = NewBroadcastQueue()

	// three events
	bcast1.Attempts = 11
	event2 := &SuspectEvent{From: 3, Id: 4, Incarnation: Seq(5)}
	bcast2 := &Broadcast{Class: 1, Event: event2, Attempts: 10}
	bqueue.Push(bcast0)
	bqueue.Push(bcast1)
	bqueue.Push(bcast2)
	if bqueue.Len() != 3 {
		t.Fatalf("Expected length of 3")
	} else if bs := bqueue.List(); bs[0] != bcast0 || bs[1] != bcast2 || bs[2] != bcast1 {
		t.Logf("%v %v %v", bs[0], bs[1], bs[2])
		t.Fatalf("Expected list of broadcast 0, 2, 1")
	}

	bqueue = NewBroadcastQueue()

	// test prune
	bqueue.Push(bcast1)
	bqueue.Push(bcast0)
	bqueue.Push(bcast2)
	bqueue.Prune(func(b *Broadcast) bool {
		return b == bcast0
	})
	if l := bqueue.Len(); l != 2 {
		t.Fatalf("Expected length of 2 got %v", l)
	}
}


text:
from __future__ import unicode_literals

from .resort import Resort

from django.db import models
from django.contrib.postgres.fields import ArrayField

from dynamic_scraper.models import Scraper, SchedulerRuntime
from scrapy_djangoitem import DjangoItem

import datetime

# Past and forecasted conditions for a resort
class Conditions(models.Model):

    # Hard-coded attributes needed for scraping
    resort = models.ForeignKey(Resort, null = True, default=6)
    conditions_page_url = models.URLField(blank = True)
    checker_runtime = models.ForeignKey(SchedulerRuntime, blank = True, null = True, on_delete = models.SET_NULL)

    # Attributes collected during scraping
    date = models.DateField(default = datetime.date.today)
    base_temp = models.DecimalField(max_digits = 6, decimal_places = 2, default = 0)
    summit_temp = models.DecimalField(max_digits = 6, decimal_places = 2, default = 0)
    wind_speed = models.DecimalField(max_digits = 6, decimal_places = 2, default = 0)
    base_depth = models.DecimalField(max_digits = 6, decimal_places = 2, default = 0)
    num_trails_open = models.IntegerField(default = 0)
    new_snow_24_hr = models.IntegerField(default = 0)
    #past_n_day_snowfall = ArrayField(models.DecimalField(max_digits = 6, decimal_places = 2, default = 0), size = 15)
    #past_n_day_wind_speed = ArrayField(models.DecimalField(max_digits = 6, decimal_places = 2, default = 0), size = 15)
    #future_n_day_snowfall = ArrayField(models.DecimalField(max_digits = 6, decimal_places = 2, default = 0), size = 15)
    #future_n_day_wind_speed = ArrayField(models.DecimalField(max_digits = 6, decimal_places = 2, default = 0), size = 15)

    # For database querying
    unique_id = models.CharField(default='', max_length = 200)

    def __init__(self, *args, **kwargs):
        super(Conditions, self).__init__(*args, **kwargs)
        if not self.id:
            day = datetime.date.today
            self.conditions_page_url = self.resort.conditions_page_url
            self.unique_id = self.resort.name+str(datetime.date.today())

    def __unicode__(self):
        return self.resort.name+": "+str(self.date)

    def __str__(self):
        return self.resort.name+": "+str(self.date)

    class Meta:
        verbose_name_plural = "Conditions"

class ConditionsItem(DjangoItem):
    django_model = Conditions


text:
<?php
namespace Respect\Validation\Exceptions;

class MinimumAgeException extends ValidationException
{
    public static $defaultTemplates = array(
        self::MODE_DEFAULT => array(
            self::STANDARD => 'The age must be {{age}} years or more.',
        ),
        self::MODE_NEGATIVE => array(
            self::STANDARD => 'The age must not be {{age}} years or more.',
        )
    );
}


text:
mwc
===

Minetest Website Competition entry

Features
========

* Uses Bootstrap 3.3.5, jQuery 2.1.4.
* Uses FastClick for removing tap delay on mobile devices.
* Smooth scrolling to sections.
* Dynamic "back to top" button.
* Resposnive site and favicon.

Workflow
========

This site uses the [Jekyll](http://jekyllrb.com) static site generator as well
as the [Stylus](http://learnboost.github.io/stylus/) CSS preprocessor.

* Use `jekyll serve` to automatically build the Jekyll site.
* Use `grunt watch` to compile Stylus files automatically. The Stylus files are
  located in `css/stylus`.

License
=======

Copyright (c) 2015 Calinou

Code is under the MIT license, media and content under CC BY-SA 3.0 Unported.


text:
package com.netflix.spinnaker.clouddriver.kubernetes.description.manifest;

import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.entry;

import com.google.common.collect.ImmutableMap;
import com.netflix.spinnaker.clouddriver.kubernetes.description.manifest.KubernetesManifestStrategy.DeployStrategy;
import com.netflix.spinnaker.clouddriver.kubernetes.description.manifest.KubernetesManifestStrategy.Versioned;
import java.util.HashMap;
import java.util.Map;
import java.util.OptionalInt;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.EnumSource;
import org.junit.platform.runner.JUnitPlatform;
import org.junit.runner.RunWith;

@RunWith(JUnitPlatform.class)
final class KubernetesManifestStrategyTest {
  @Test
  void deployStrategyDefaultsToApply() {
    KubernetesManifestStrategy.DeployStrategy strategy =
        KubernetesManifestStrategy.DeployStrategy.fromAnnotations(ImmutableMap.of());
    assertThat(strategy).isEqualTo(DeployStrategy.APPLY);
  }

  @Test
  void otherStrategiesFalse() {
    KubernetesManifestStrategy.DeployStrategy strategy =
        KubernetesManifestStrategy.DeployStrategy.fromAnnotations(
            ImmutableMap.of(
                "strategy.spinnaker.io/recreate", "false",
                "strategy.spinnaker.io/replace", "false"));
    assertThat(strategy).isEqualTo(DeployStrategy.APPLY);
  }

  @Test
  void recreateStrategy() {
    KubernetesManifestStrategy.DeployStrategy strategy =
        KubernetesManifestStrategy.DeployStrategy.fromAnnotations(
            ImmutableMap.of("strategy.spinnaker.io/recreate", "true"));
    assertThat(strategy).isEqualTo(DeployStrategy.RECREATE);
  }

  @Test
  void replaceStrategy() {
    KubernetesManifestStrategy.DeployStrategy strategy =
        KubernetesManifestStrategy.DeployStrategy.fromAnnotations(
            ImmutableMap.of("strategy.spinnaker.io/replace", "true"));
    assertThat(strategy).isEqualTo(DeployStrategy.REPLACE);
  }

  @Test
  void nonBooleanValue() {
    KubernetesManifestStrategy.DeployStrategy strategy =
        KubernetesManifestStrategy.DeployStrategy.fromAnnotations(
            ImmutableMap.of("strategy.spinnaker.io/replace", "zzzz"));
    assertThat(strategy).isEqualTo(DeployStrategy.APPLY);
  }

  @Test
  void recreatePreferredOverReplace() {
    KubernetesManifestStrategy.DeployStrategy strategy =
        KubernetesManifestStrategy.DeployStrategy.fromAnnotations(
            ImmutableMap.of(
                "strategy.spinnaker.io/replace", "true",
                "strategy.spinnaker.io/recreate", "true"));
    assertThat(strategy).isEqualTo(DeployStrategy.RECREATE);
  }

  @Test
  void applyToAnnotations() {
    Map<String, String> annotations = DeployStrategy.APPLY.toAnnotations();
    assertThat(annotations).isEmpty();
  }

  @Test
  void recreateToAnnotations() {
    Map<String, String> annotations = DeployStrategy.RECREATE.toAnnotations();
    assertThat(annotations).containsOnly(entry("strategy.spinnaker.io/recreate", "true"));
  }

  @Test
  void replaceToAnnotations() {
    Map<String, String> annotations = DeployStrategy.REPLACE.toAnnotations();
    assertThat(annotations).containsOnly(entry("strategy.spinnaker.io/replace", "true"));
  }

  @Test
  void versionedDefaultsToDefault() {
    KubernetesManifestStrategy.Versioned versioned =
        KubernetesManifestStrategy.Versioned.fromAnnotations(ImmutableMap.of());
    assertThat(versioned).isEqualTo(Versioned.DEFAULT);
  }

  @Test
  void versionedTrue() {
    KubernetesManifestStrategy.Versioned versioned =
        KubernetesManifestStrategy.Versioned.fromAnnotations(
            ImmutableMap.of("strategy.spinnaker.io/versioned", "true"));
    assertThat(versioned).isEqualTo(Versioned.TRUE);
  }

  @Test
  void versionedFalse() {
    KubernetesManifestStrategy.Versioned versioned =
        KubernetesManifestStrategy.Versioned.fromAnnotations(
            ImmutableMap.of("strategy.spinnaker.io/versioned", "false"));
    assertThat(versioned).isEqualTo(Versioned.FALSE);
  }

  @Test
  void versionedNonsense() {
    KubernetesManifestStrategy.Versioned versioned =
        KubernetesManifestStrategy.Versioned.fromAnnotations(
            ImmutableMap.of("strategy.spinnaker.io/versioned", "zzz"));
    assertThat(versioned).isEqualTo(Versioned.FALSE);
  }

  @Test
  void versionedDefaultToAnnotations() {
    Map<String, String> annotations = Versioned.DEFAULT.toAnnotations();
    assertThat(annotations).isEmpty();
  }

  @Test
  void versionedTrueToAnnotations() {
    Map<String, String> annotations = Versioned.TRUE.toAnnotations();
    assertThat(annotations).containsOnly(entry("strategy.spinnaker.io/versioned", "true"));
  }

  @Test
  void versionedFalseToAnnotations() {
    Map<String, String> annotations = Versioned.FALSE.toAnnotations();
    assertThat(annotations).containsOnly(entry("strategy.spinnaker.io/versioned", "false"));
  }

  @Test
  void fromEmptyAnnotations() {
    KubernetesManifestStrategy strategy =
        KubernetesManifestStrategy.fromAnnotations(ImmutableMap.of());
    assertThat(strategy.getDeployStrategy()).isEqualTo(DeployStrategy.APPLY);
    assertThat(strategy.getVersioned()).isEqualTo(Versioned.DEFAULT);
    assertThat(strategy.getMaxVersionHistory()).isEqualTo(OptionalInt.empty());
    assertThat(strategy.isUseSourceCapacity()).isFalse();
  }

  @Test
  void fromDeployStrategyAnnotation() {
    KubernetesManifestStrategy strategy =
        KubernetesManifestStrategy.fromAnnotations(
            ImmutableMap.of("strategy.spinnaker.io/replace", "true"));
    assertThat(strategy.getDeployStrategy()).isEqualTo(DeployStrategy.REPLACE);
  }

  @Test
  void fromVersionedAnnotation() {
    KubernetesManifestStrategy strategy =
        KubernetesManifestStrategy.fromAnnotations(
            ImmutableMap.of("strategy.spinnaker.io/versioned", "true"));
    assertThat(strategy.getVersioned()).isEqualTo(Versioned.TRUE);
  }

  @Test
  void fromMaxVersionHistoryAnnotation() {
    KubernetesManifestStrategy strategy =
        KubernetesManifestStrategy.fromAnnotations(
            ImmutableMap.of("strategy.spinnaker.io/max-version-history", "10"));
    assertThat(strategy.getMaxVersionHistory()).isEqualTo(OptionalInt.of(10));
  }

  @Test
  void fromNonIntegerMaxVersionHistoryAnnotation() {
    KubernetesManifestStrategy strategy =
        KubernetesManifestStrategy.fromAnnotations(
            ImmutableMap.of("strategy.spinnaker.io/max-version-history", "zz"));
    assertThat(strategy.getMaxVersionHistory()).isEqualTo(OptionalInt.empty());
  }

  @Test
  void fromUseSourceCapacityAnnotation() {
    KubernetesManifestStrategy strategy =
        KubernetesManifestStrategy.fromAnnotations(
            ImmutableMap.of("strategy.spinnaker.io/use-source-capacity", "true"));
    assertThat(strategy.isUseSourceCapacity()).isTrue();
  }

  @Test
  void fromUseSourceCapacityAnnotationFalse() {
    KubernetesManifestStrategy strategy =
        KubernetesManifestStrategy.fromAnnotations(
            ImmutableMap.of("strategy.spinnaker.io/use-source-capacity", "false"));
    assertThat(strategy.isUseSourceCapacity()).isFalse();
  }

  @Test
  void fromUseSourceCapacityAnnotationNonsense() {
    KubernetesManifestStrategy strategy =
        KubernetesManifestStrategy.fromAnnotations(
            ImmutableMap.of("strategy.spinnaker.io/use-source-capacity", "zzz"));
    assertThat(strategy.isUseSourceCapacity()).isFalse();
  }

  @Test
  void allAnnotationsPresent() {
    KubernetesManifestStrategy strategy =
        KubernetesManifestStrategy.fromAnnotations(
            ImmutableMap.of(
                "strategy.spinnaker.io/replace", "true",
                "strategy.spinnaker.io/versioned", "true",
                "strategy.spinnaker.io/max-version-history", "20",
                "strategy.spinnaker.io/use-source-capacity", "true",
                "strategy.spinnaker.io/random-annotation", "abc"));

    assertThat(strategy.getDeployStrategy()).isEqualTo(DeployStrategy.REPLACE);
    assertThat(strategy.getVersioned()).isEqualTo(Versioned.TRUE);
    assertThat(strategy.getMaxVersionHistory()).isEqualTo(OptionalInt.of(20));
    assertThat(strategy.isUseSourceCapacity()).isTrue();
  }

  @Test
  void builderDefaults() {
    KubernetesManifestStrategy strategy = KubernetesManifestStrategy.builder().build();
    assertThat(strategy.getDeployStrategy()).isEqualTo(DeployStrategy.APPLY);
    assertThat(strategy.getVersioned()).isEqualTo(Versioned.DEFAULT);
    assertThat(strategy.getMaxVersionHistory()).isEqualTo(OptionalInt.empty());
    assertThat(strategy.isUseSourceCapacity()).isFalse();
  }

  @Test
  void emptyAnnotations() {
    Map<String, String> annotations = KubernetesManifestStrategy.builder().build().toAnnotations();
    assertThat(annotations).isEmpty();
  }

  @Test
  void deployStrategyRecreateToAnnotations() {
    Map<String, String> annotations =
        KubernetesManifestStrategy.builder()
            .deployStrategy(DeployStrategy.RECREATE)
            .build()
            .toAnnotations();
    assertThat(annotations).containsOnly(entry("strategy.spinnaker.io/recreate", "true"));
  }

  @Test
  void deployStrategyReplaceToAnnotations() {
    Map<String, String> annotations =
        KubernetesManifestStrategy.builder()
            .deployStrategy(DeployStrategy.REPLACE)
            .build()
            .toAnnotations();
    assertThat(annotations).containsOnly(entry("strategy.spinnaker.io/replace", "true"));
  }

  @Test
  void versionedToAnnotations() {
    Map<String, String> annotations =
        KubernetesManifestStrategy.builder().versioned(Versioned.FALSE).build().toAnnotations();
    assertThat(annotations).containsOnly(entry("strategy.spinnaker.io/versioned", "false"));
  }

  @Test
  void maxVersionHistoryToAnnotations() {
    Map<String, String> annotations =
        KubernetesManifestStrategy.builder().maxVersionHistory(10).build().toAnnotations();
    assertThat(annotations).containsOnly(entry("strategy.spinnaker.io/max-version-history", "10"));
  }

  @Test
  void useSourceCapacityToAnnotations() {
    Map<String, String> annotations =
        KubernetesManifestStrategy.builder().useSourceCapacity(true).build().toAnnotations();
    assertThat(annotations)
        .containsOnly(entry("strategy.spinnaker.io/use-source-capacity", "true"));
  }

  @ParameterizedTest
  @EnumSource(DeployStrategy.class)
  void deploymentStrategySetsAnnotations(DeployStrategy deployStrategy) {
    Map<String, String> annotations = new HashMap<>();
    deployStrategy.setAnnotations(annotations);
    assertThat(annotations).isEqualTo(deployStrategy.toAnnotations());
  }

  @ParameterizedTest
  @EnumSource(DeployStrategy.class)
  void deploymentStrategyOverwritesAnnotations(DeployStrategy deployStrategy) {
    Map<String, String> annotations = new HashMap<>(DeployStrategy.RECREATE.toAnnotations());
    deployStrategy.setAnnotations(annotations);
    assertThat(annotations).isEqualTo(deployStrategy.toAnnotations());
  }

  @ParameterizedTest
  @EnumSource(DeployStrategy.class)
  void deploymentStrategyIgnoresIrrelevantAnnotations(DeployStrategy deployStrategy) {
    ImmutableMap<String, String> irrelevantAnnotations =
        ImmutableMap.of(
            "strategy.spinnaker.io/versioned", "false",
            "artifact.spinnaker.io/version", "v001",
            "my-custom-annotation", "my-custom-value");
    Map<String, String> annotations = new HashMap<>(irrelevantAnnotations);
    deployStrategy.setAnnotations(annotations);
    assertThat(annotations).containsAllEntriesOf(irrelevantAnnotations);
  }

  @Test
  void toAnnotationsMultipleAnnotations() {
    Map<String, String> annotations =
        KubernetesManifestStrategy.builder()
            .deployStrategy(DeployStrategy.RECREATE)
            .versioned(Versioned.TRUE)
            .maxVersionHistory(30)
            .useSourceCapacity(true)
            .build()
            .toAnnotations();
    assertThat(annotations)
        .containsOnly(
            entry("strategy.spinnaker.io/recreate", "true"),
            entry("strategy.spinnaker.io/versioned", "true"),
            entry("strategy.spinnaker.io/max-version-history", "30"),
            entry("strategy.spinnaker.io/use-source-capacity", "true"));
  }
}


text:
package pubsub

import (
	"fmt"
	"os"

	"cloud.google.com/go/pubsub"
)

// Option is the function signature required to be considered an pubsub.Option.
type Option func(*Protocol) error

const (
	DefaultProjectEnvKey         = "GOOGLE_CLOUD_PROJECT"
	DefaultTopicEnvKey           = "PUBSUB_TOPIC"
	DefaultSubscriptionEnvKey    = "PUBSUB_SUBSCRIPTION"
	DefaultMessageOrderingEnvKey = "PUBSUB_MESSAGE_ORDERING"
)

// WithClient sets the pubsub client for pubsub transport. Use this for explicit
// auth setup. Otherwise the env var 'GOOGLE_APPLICATION_CREDENTIALS' is used.
// See https://cloud.google.com/docs/authentication/production for more details.
func WithClient(client *pubsub.Client) Option {
	return func(t *Protocol) error {
		t.client = client
		return nil
	}
}

// WithProjectID sets the project ID for pubsub transport.
func WithProjectID(projectID string) Option {
	return func(t *Protocol) error {
		t.projectID = projectID
		return nil
	}
}

// WithProjectIDFromEnv sets the project ID for pubsub transport from a
// given environment variable name.
func WithProjectIDFromEnv(key string) Option {
	return func(t *Protocol) error {
		v := os.Getenv(key)
		if v == "" {
			return fmt.Errorf("unable to load project id, %q environment variable not set", key)
		}
		t.projectID = v
		return nil
	}
}

// WithProjectIDFromDefaultEnv sets the project ID for pubsub transport from
// the environment variable named 'GOOGLE_CLOUD_PROJECT'.
func WithProjectIDFromDefaultEnv() Option {
	return WithProjectIDFromEnv(DefaultProjectEnvKey)
}

// WithTopicID sets the topic ID for pubsub transport.
func WithTopicID(topicID string) Option {
	return func(t *Protocol) error {
		t.topicID = topicID
		return nil
	}
}

// WithTopicIDFromEnv sets the topic ID for pubsub transport from a given
// environment variable name.
func WithTopicIDFromEnv(key string) Option {
	return func(t *Protocol) error {
		v := os.Getenv(key)
		if v == "" {
			return fmt.Errorf("unable to load topic id, %q environment variable not set", key)
		}
		t.topicID = v
		return nil
	}
}

// WithTopicIDFromDefaultEnv sets the topic ID for pubsub transport from the
// environment variable named 'PUBSUB_TOPIC'.
func WithTopicIDFromDefaultEnv() Option {
	return WithTopicIDFromEnv(DefaultTopicEnvKey)
}

// WithSubscriptionID sets the subscription ID for pubsub transport.
// This option can be used multiple times.
func WithSubscriptionID(subscriptionID string) Option {
	return func(t *Protocol) error {
		if t.subscriptions == nil {
			t.subscriptions = make([]subscriptionWithTopic, 0)
		}
		t.subscriptions = append(t.subscriptions, subscriptionWithTopic{
			subscriptionID: subscriptionID,
		})
		return nil
	}
}

// WithSubscriptionAndTopicID sets the subscription and topic IDs for pubsub transport.
// This option can be used multiple times.
func WithSubscriptionAndTopicID(subscriptionID, topicID string) Option {
	return func(t *Protocol) error {
		if t.subscriptions == nil {
			t.subscriptions = make([]subscriptionWithTopic, 0)
		}
		t.subscriptions = append(t.subscriptions, subscriptionWithTopic{
			subscriptionID: subscriptionID,
			topicID:        topicID,
		})
		return nil
	}
}

// WithSubscriptionIDAndFilter sets the subscription and topic IDs for pubsub transport.
// This option can be used multiple times.
func WithSubscriptionIDAndFilter(subscriptionID, filter string) Option {
	return func(t *Protocol) error {
		if t.subscriptions == nil {
			t.subscriptions = make([]subscriptionWithTopic, 0)
		}
		t.subscriptions = append(t.subscriptions, subscriptionWithTopic{
			subscriptionID: subscriptionID,
			filter:         filter,
		})
		return nil
	}
}

// WithSubscriptionTopicIDAndFilter sets the subscription with filter option and topic IDs for pubsub transport.
// This option can be used multiple times.
func WithSubscriptionTopicIDAndFilter(subscriptionID, topicID, filter string) Option {
	return func(t *Protocol) error {
		if t.subscriptions == nil {
			t.subscriptions = make([]subscriptionWithTopic, 0)
		}
		t.subscriptions = append(t.subscriptions, subscriptionWithTopic{
			subscriptionID: subscriptionID,
			topicID:        topicID,
			filter:         filter,
		})
		return nil
	}
}

// WithSubscriptionIDFromEnv sets the subscription ID for pubsub transport from
// a given environment variable name.
func WithSubscriptionIDFromEnv(key string) Option {
	return func(t *Protocol) error {
		v := os.Getenv(key)
		if v == "" {
			return fmt.Errorf("unable to load subscription id, %q environment variable not set", key)
		}

		opt := WithSubscriptionID(v)
		return opt(t)
	}
}

// WithSubscriptionIDFromDefaultEnv sets the subscription ID for pubsub
// transport from the environment variable named 'PUBSUB_SUBSCRIPTION'.
func WithSubscriptionIDFromDefaultEnv() Option {
	return WithSubscriptionIDFromEnv(DefaultSubscriptionEnvKey)
}

// WithFilter sets the subscription filter for pubsub transport.
func WithFilter(filter string) Option {
	return func(t *Protocol) error {
		if t.subscriptions == nil {
			t.subscriptions = make([]subscriptionWithTopic, 0)
		}
		t.subscriptions = append(t.subscriptions, subscriptionWithTopic{
			filter: filter,
		})
		return nil
	}
}

// WithFilterFromEnv sets the subscription filter for pubsub transport from
// a given environment variable name.
func WithFilterFromEnv(key string) Option {
	return func(t *Protocol) error {
		v := os.Getenv(key)
		if v == "" {
			return fmt.Errorf("unable to load subscription filter, %q environment variable not set", key)
		}

		opt := WithFilter(v)
		return opt(t)
	}
}

// AllowCreateTopic sets if the transport can create a topic if it does not
// exist.
func AllowCreateTopic(allow bool) Option {
	return func(t *Protocol) error {
		t.AllowCreateTopic = allow
		return nil
	}
}

// AllowCreateSubscription sets if the transport can create a subscription if
// it does not exist.
func AllowCreateSubscription(allow bool) Option {
	return func(t *Protocol) error {
		t.AllowCreateSubscription = allow
		return nil
	}
}

// WithReceiveSettings sets the Pubsub ReceiveSettings for pull subscriptions.
func WithReceiveSettings(rs *pubsub.ReceiveSettings) Option {
	return func(t *Protocol) error {
		t.ReceiveSettings = rs
		return nil
	}
}

// WithMessageOrdering enables message ordering for all topics and subscriptions.
func WithMessageOrdering() Option {
	return func(t *Protocol) error {
		t.MessageOrdering = true
		return nil
	}
}

// WithMessageOrderingFromEnv enables message ordering for all topics and
// subscriptions from a given environment variable name.
func WithMessageOrderingFromEnv(key string) Option {
	return func(t *Protocol) error {
		if v := os.Getenv(key); v != "" {
			t.MessageOrdering = true
		}
		return nil
	}
}

// WithMessageOrderingFromDefaultEnv enables message ordering for all topics and
// subscriptions from the environment variable named 'PUBSUB_MESSAGE_ORDERING'.
func WithMessageOrderingFromDefaultEnv() Option {
	return WithMessageOrderingFromEnv(DefaultMessageOrderingEnvKey)
}


text:
package pl.java.scalatech.entity.user;

import javax.persistence.Entity;
import javax.persistence.Table;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Pattern;
import javax.validation.constraints.Size;
import javax.xml.bind.annotation.XmlRootElement;

import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.NonNull;
import lombok.RequiredArgsConstructor;
import lombok.Setter;
import pl.java.scalatech.entity.common.EntityCommon;

/**
 * @author Sławomir Borowiec
 * Module name : basicEntity
 * Creating time :  21 lut 2014 16:17:38

 */
@Entity
@Table(name = "roles")
@RequiredArgsConstructor(staticName = "of")
@NoArgsConstructor
@XmlRootElement(name = "userRole")
public class UserRole extends EntityCommon {

    private static final long serialVersionUID = 4217735871414498766L;

	@NotNull
    @Size(min = 2, max = 20)
    @Pattern(regexp = "^[A-Z_]+$")
    @Setter @Getter
	@NonNull
	private String role;

}


text:
#ifndef __OTL_TABLE_H__
#define __OTL_TABLE_H__

#include "otlayout.h"

OTL_BEGIN_HEADER

  typedef struct OTL_TableRec_*    OTL_Table;

  typedef enum
  {
    OTL_TABLE_TYPE_GDEF = 1,
    OTL_TABLE_TYPE_GSUB,
    OTL_TABLE_TYPE_GPOS,
    OTL_TABLE_TYPE_BASE,
    OTL_TABLE_TYPE_JSTF

  } OTL_TableType;

 /* this may become a private structure later */
  typedef struct OTL_TableRec_
  {
    OTL_TableType  type;
    OTL_Bytes      base;
    OTL_Bytes      limit;

    OTL_Tag        script_tag;
    OTL_Tag        lang_tag;

    OTL_UInt       lookup_count;
    OTL_Byte*      lookup_flags;

    OTL_UInt       feature_count;
    OTL_Tag        feature_tags;
    OTL_Byte*      feature_flags;

  } OTL_TableRec;

  OTL_API( OTL_Error )
  otl_table_validate( OTL_Bytes      table,
                      OTL_Size       size,
                      OTL_TableType  type,
                      OTL_Size      *abyte_size );

  OTL_API( void )
  otl_table_init( OTL_Table      table,
                  OTL_TableType  type,
                  OTL_Bytes      base,
                  OTL_Size       size );

  OTL_API( void )
  otl_table_set_script( OTL_Table      table,
                        OTL_ScriptTag  script,
                        OTL_LangTag    language );

OTL_END_HEADER

#endif /* __OTL_TABLE_H__ */


text:
import pygame, sys, math, random

class Enemy():
    def __init__(self, speed=0, pos=[0,0], size=64):
        self.size = size
        self.imagesLeft = [pygame.transform.scale(pygame.image.load("Resources/Enemy/Enemy-Pew Left.png"), [self.size,self.size]),
                           pygame.transform.scale(pygame.image.load("Resources/Enemy/Enemy-Pew Left2.png"), [self.size,self.size])]
        self.imagesRight = [pygame.transform.scale(pygame.image.load("Resources/Enemy/Enemy-Pew Right.png"), [self.size,self.size]),
                           pygame.transform.scale(pygame.image.load("Resources/Enemy/Enemy-Pew Right2.png"), [self.size,self.size])]
        self.imagesUp = [pygame.transform.scale(pygame.image.load("Resources/Enemy/Enemy-Pew Up.png"), [self.size,self.size]),
                           pygame.transform.scale(pygame.image.load("Resources/Enemy/Enemy-Pew Up2.png"), [self.size,self.size])]
        self.imagesDown = [pygame.transform.scale(pygame.image.load("Resources/Enemy/Enemy-Pew Down.png"), [self.size,self.size]),
                           pygame.transform.scale(pygame.image.load("Resources/Enemy/Enemy-Pew Down2.png"), [self.size,self.size])]
        self.blankImage = pygame.image.load("Resources/Player/blank.png")

        self.maxSpeed = speed

        self.kind = "normal"

        self.didBounceX = False
        self.didBounceY = False
        self.inflationTime = 0
        self.inflationLevel = 0
        self.inflationMaxLevel = 9
        self.inflationMaxTime = 2

        self.state = "right"
        self.prevState = "right"

        self.frame = 0
        self.blinkFrame = 0

        self.animationTimer = 0
        self.animationTimerMax = .3 * 60 #seconds * 60 fps

        self.images = self.imagesRight
        self.image = self.images[self.frame]
        self.rect = self.image.get_rect(center = pos)
        self.maxFrame = len(self.images) - 1

        self.decideDirection()

        self.hit = False

    def move(self):
        self.didBounceX = False
        self.didBounceY = False
        self.speed = [self.speedx, self.speedy]
        self.rect = self.rect.move(self.speed)
        if self.speedx != 0:     #moving left/right
            if self.rect.left % self.size == 0:
                self.decideDirection()
        else:     #moving up/down
            if self.rect.top % self.size == 0:
                self.decideDirection()
        self.animate()

    def decideDirection(self):
        d = random.randint(0,3)
        if d == 0:
            self.speedx = 0
            self.speedy = -self.maxSpeed
            self.state = "up"
        elif d == 1:
            self.speedx = self.maxSpeed
            self.speedy = 0
            self.state = "right"
        elif d == 2:
            self.speedx = 0
            self.speedy = self.maxSpeed
            self.state = "down"
        elif d == 3:
            self.speedx = -self.maxSpeed
            self.speedy = 0
            self.state = "left"

    def animate(self):
        if self.prevState != self.state:
            self.prevState = self.state
            if self.state == "right":
                self.images = self.imagesRight
            elif self.state == "left":
                self.images = self.imagesLeft
            elif self.state == "up":
                self.images = self.imagesUp
            elif self.state == "down":
                self.images = self.imagesDown
            self.frame = 0
            self.maxFrame = len(self.images) - 1
            self.animationTimer = self.animationTimerMax

        if self.animationTimer < self.animationTimerMax:
            self.animationTimer += 1
        else:
            self.animationTimer = 0
            if self.frame < self.maxFrame:
                self.frame += 1
            else:
                self.frame = 0
            self.image = self.images[self.frame]

    def blinkImage(self):
        if self.blinkFrame == 0:
            self.prevImage = self.image
            self.blinkFrame = 1

        self.blinkFrame1 = self.prevImage
        self.blinkFrame2 = self.blankImage

        if self.blinkFrame > 0:
            if self.blinkFrame % 2 == 0:
                self.image = self.blinkFrame2
            if self.blinkFrame % 2 != 0:
                self.image = self.blinkFrame1
            self.blinkFrame += 1

    def dirtCollide(self, other):
        if self.rect.right > other.rect.left and self.rect.left < other.rect.right:
            if self.rect.bottom > other.rect.top and self.rect.top < other.rect.bottom:
                self.speedx = -self.speedx
                self.speedy = -self.speedy
                self.didBounceX = True
                self.didBounceY = True
                self.move()

    def screenCollide(self, screenSize):
        screenWidth = screenSize[0]
        screenHeight = screenSize[1]
        if self.rect.top < 0 or self.rect.bottom > screenHeight:
            self.speedy = -self.speedy
        if self.rect.center[0] > screenWidth:
            self.rect.center = [0, self.rect.center[1]]
        elif self.rect.center[0] < 0:
            self.rect.center = [screenWidth, self.rect.center[1]]

    def playerCollide(self, other):
        if self.rect.right > other.rect.left and self.rect.left < other.rect.right:
                if self.rect.bottom > other.rect.top and self.rect.top < other.rect.bottom:
                    self.speedx = -self.speedx
                    self.speedy = -self.speedy
                    self.move()
                    other.hit = True

    #def playerCollide(self, other):
        #if self.rect.right > other.rect.left and self.rect.left < other.rect.right:
                #if self.rect.bottom > other.rect.top and self.rect.top < other.rect.bottom:
                    #diffX = self.rect.centerx - other.rect.centerx
                    #diffY = self.rect.centery - other.rect.centery
                    #if abs(diffX) > abs(diffY): #left right collide
                        #if diffX > 0: #left
                            #self.rect.left = other.rect.right + 1
                        #else:
                            #self.rect.right = other.rect.left - 1
                        #self.speedx = 0
                        #other.hit = True
                    #else:
                        #if diffY > 0: #below
                            #self.rect.top = other.rect.bottom + 1
                        #else:
                            #self.rect.bottom = other.rect.top - 1
                        #self.speedy = 0
                        #other.hit = True

    def dist(self, pt):
        x = pt[0] - self.rect.right
        y = pt[1] - self.rect.bottom
        if x < 0:
            x += -64
            x += x
        if y < 0:
            y += -64
            y += y
        return [x, y]
        return math.sqrt(xDiff**2 + yDiff**2)

#if __name__ == "__main__":
    #pygame.init()

    #clock = pygame.time.Clock()

    #width = 768
    #height = 640
    #size = width, height
    #screen = pygame.display.set_mode(size)

    #e = Enemy(0, [200,200])
    #down = False
    #while True:
        #for event in pygame.event.get():
            #if event.type == pygame.QUIT: sys.exit()
            #if event.type == pygame.MOUSEBUTTONDOWN:
                #down = True
            #if event.type == pygame.MOUSEBUTTONUP:
                #down = False

            #if down:
                #bgColor = 0,0,255

                #screen.fill(bgColor)
                #screen.blit(e.imageSLeft, e.rect)
            #else:
                #bgColor = 255,0,0

                #screen.fill(bgColor)
                #screen.blit(e.imageLeft, e.rect)

            #pygame.display.flip()
            #clock.tick(60)


text:
package com.planet_ink.coffee_mud.core;

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

import com.planet_ink.coffee_mud.Items.interfaces.SpaceShip;
import com.planet_ink.coffee_mud.Libraries.interfaces.LanguageLibrary;
import com.planet_ink.coffee_mud.Locales.interfaces.Room;

public class Directions
{
	/**
	 * Constructs a new Directions object for the current thread group.
	 */
	public Directions()
	{
		super();
		final char c=Thread.currentThread().getThreadGroup().getName().charAt(0);
		if(dirs[c]==null)
			dirs[c]=this;
	}

	/**
	 * Returns the Directions object for the current threadgroup, or null if unassigned.
	 * @return the Directions object, or null
	 */
	private static Directions d()
	{
		return dirs[Thread.currentThread().getThreadGroup().getName().charAt(0)];
	}

	/**
	 * Returns the Directions instance tied to the given thread group, or null if not yet created.
	 * @param c the code for the thread group to return (0-255)
	 * @return the Directions instance tied to the given thread group, or null if not yet created.
	 */
	public static Directions d(char c)
	{
		return dirs[c];
	}

	/**
	 * Returns the Directions object that applies to the callers thread group.
	 * @return the Directions object that applies to the callers thread group.
	 */
	public static Directions instance()
	{
		final Directions d=d();
		if(d==null)
			return new Directions();
		return d;
	}

	private static final Directions[] dirs=new Directions[256];

	public static final int	NORTH		= 0;
	public static final int	SOUTH		= 1;
	public static final int	EAST		= 2;
	public static final int	WEST		= 3;
	public static final int	UP			= 4;
	public static final int	DOWN		= 5;

	public static final int	GATE		= 6;

	public static final int	NORTHEAST	= 7;
	public static final int	NORTHWEST	= 8;
	public static final int	SOUTHEAST	= 9;
	public static final int	SOUTHWEST	= 10;

	private final static String	DEFAULT_DIRECTION_7_LETTERS		= "N, S, E, W, U, D, or V";
	private final static String	DEFAULT_DIRECTION_11_LETTERS	= "N, S, E, W, NE, NW, SE, SW, U, D, or V";
	private final static String	DEFAULT_DIRECTION_7_NAMES		= "North, South, East, West, Up, or Down";
	private final static String	DEFAULT_DIRECTION_11_NAMES		= "North, South, East, West, Northeast, Northwest, Southeast, Southwest, Up, or Down";
	private final static String	DEFAULT_DIRECTION_7_SHIPNAMES	= "Foreward, Aft, Starboard, Port, Above, or Below";
	private final static String	DEFAULT_DIRECTION_11_SHIPNAMES	= "Foreward, Aft, Starboard, Port, Foreward Starboard, Foreward Port, "
																+ "Aft Starboard, Aft Port, Above, or Below";
	private final static String DEFAULT_DIRECTIONS_LIST_COMPASS	= "North,South,East,West,Up,Down,There,Northeast,Northwest,Southeast,Southwest";
	private final static String DEFAULT_DIRECTIONS_LIST_SHIP	= "Foreward,Aft,Starboard,Portside,Above,Below,There,Fore Starboard,Fore Portside,Aft Starboard,Aft Portside";
	private final static String DEFAULT_FROM_DIR_LIST_COMPASS	= "the north,the south,the east,the west,above,below,out of nowhere,the northeast,the northwest,the southeast,the southwest";
	private final static String DEFAULT_FROM_DIR_LIST_SHIP		= "foreward,aft,starboard,portside,above,below,out of nowhere,forward starboard,forward portside,aft starboard,aft portside";
	private final static String DEFAULT_OF_DIR_LIST_COMPASS		= "north of,south of,east of,west of,above,below,,northeast of,northwest of,southeast of,southwest of";
	private final static String DEFAULT_TO_DIR_LIST_COMPASS		= "to the north,to the south,to the east,to the west,above you,below,there,to the northeast,to the northwest,to the southeast,to the southwest";
	private final static String DEFAULT_TO_DIR_LIST_SHIP		= "to foreward,to aft,to starboard,to portside,above you,below,there,to forward starboard,to forward port,to aft starboard,to aft portside";
	private static final String DEFAULT_DIRECTION_CHARS			= "N,S,E,W,U,D,V,NE,NW,SE,SW";

	/* Display order directions.  Include up, down, and gate.  Include -1 to insert the other 4/8 */
	private final static int[]	DIRECTIONS_DISP_ORDER	= { UP, -1, DOWN, GATE };
	private final static int[]	DIRECTIONS_7_BASE		= { NORTH, SOUTH, EAST, WEST };
	private final static int[]	DIRECTIONS_11_BASE		= { NORTH, SOUTH, EAST, WEST, NORTHEAST, NORTHWEST, SOUTHEAST, SOUTHWEST };

	private String	 DIRECTION_7_LETTERS				= DEFAULT_DIRECTION_7_LETTERS;
	private String	 DIRECTION_11_LETTERS				= DEFAULT_DIRECTION_11_LETTERS;
	private String	 DIRECTION_7_NAMES					= DEFAULT_DIRECTION_7_NAMES;
	private String	 DIRECTION_11_NAMES					= DEFAULT_DIRECTION_11_NAMES;
	private String	 DIRECTION_7_SHIPNAMES				= DEFAULT_DIRECTION_7_SHIPNAMES;
	private String	 DIRECTION_11_SHIPNAMES				= DEFAULT_DIRECTION_11_SHIPNAMES;
	private String[] DIRECTIONS_COMPASS_UPPER_INDEXED	= DEFAULT_DIRECTIONS_LIST_COMPASS.toUpperCase().split(",");
	private String[] DIRECTIONS_SHIP_UPPER_INDEXED		= DEFAULT_DIRECTIONS_LIST_SHIP.toUpperCase().split(",");
	private String[] DIRECTIONS_COMPASS_INDEXED			= DEFAULT_DIRECTIONS_LIST_COMPASS.split(",");
	private String[] DIRECTIONS_SHIP_INDEXED			= DEFAULT_DIRECTIONS_LIST_SHIP.split(",");
	private String[] DIRECTIONS_COMPASS_FROM_INDEXED	= DEFAULT_FROM_DIR_LIST_COMPASS.split(",");
	private String[] DIRECTIONS_SHIP_FROM_INDEXED		= DEFAULT_FROM_DIR_LIST_SHIP.split(",");
	private String[] DIRECTIONS_COMPASS_OF_INDEXED		= DEFAULT_OF_DIR_LIST_COMPASS.split(",");
	private String[] DIRECTIONS_COMPASS_TO_INDEXED		= DEFAULT_TO_DIR_LIST_COMPASS.split(",");
	private String[] DIRECTIONS_SHIP_TO_INDEXED			= DEFAULT_TO_DIR_LIST_SHIP.split(",");
	private String[] DIRECTION_CHARS					= DEFAULT_DIRECTION_CHARS.split(",");

	private int[]	DIRECTIONS_CODES	= { NORTH, SOUTH, EAST, WEST };
	private int[]	DIRECTIONS_DISPLAY	= { UP, DOWN, NORTH, SOUTH, EAST, WEST, GATE };
	private String	DIRECTION_LETTERS	= DIRECTION_7_LETTERS;
	private String	DIRECTION_NAMES		= DIRECTION_7_NAMES;
	private String	DIRECTION_SHIPNAMES	= DIRECTION_7_SHIPNAMES;

	private int NUM_DIRECTIONS=7;

	private Object[][] DIRECTIONS_COMPASS_CHART=
	{
		{"UP",Integer.valueOf(UP)},
		{"ABOVE",Integer.valueOf(UP)},
		{"NORTH",Integer.valueOf(NORTH)},
		{"SOUTH",Integer.valueOf(SOUTH)},
		{"EAST",Integer.valueOf(EAST)},
		{"WEST",Integer.valueOf(WEST)},
		{"NORTHEAST",Integer.valueOf(NORTHEAST)},
		{"NORTHWEST",Integer.valueOf(NORTHWEST)},
		{"SOUTHWEST",Integer.valueOf(SOUTHWEST)},
		{"SOUTHEAST",Integer.valueOf(SOUTHEAST)},
		{"NW",Integer.valueOf(NORTHWEST)},
		{"NE",Integer.valueOf(NORTHEAST)},
		{"SW",Integer.valueOf(SOUTHWEST)},
		{"SE",Integer.valueOf(SOUTHEAST)},
		{"DOWN",Integer.valueOf(DOWN)},
		{"BELOW",Integer.valueOf(DOWN)},
		{"NOWHERE",Integer.valueOf(GATE)},
		{"HERE",Integer.valueOf(GATE)},
		{"THERE",Integer.valueOf(GATE)},
		{"VORTEX",Integer.valueOf(GATE)},
	};

	private Object[][] DIRECTIONS_SHIP_CHART=
	{
		{"ABOVE",Integer.valueOf(UP)},
		{"FOREWARD",Integer.valueOf(NORTH)},
		{"STARBOARD",Integer.valueOf(EAST)},
		{"PORTSIDE",Integer.valueOf(WEST)},
		{"AFT",Integer.valueOf(SOUTH)},
		{"FORESTARBOARD",Integer.valueOf(NORTHEAST)},
		{"FOREPORT",Integer.valueOf(NORTHWEST)},
		{"AFTPORT",Integer.valueOf(SOUTHWEST)},
		{"AFTSTARBOARD",Integer.valueOf(SOUTHEAST)},
		{"FP",Integer.valueOf(NORTHWEST)},
		{"FS",Integer.valueOf(NORTHEAST)},
		{"AP",Integer.valueOf(SOUTHWEST)},
		{"AS",Integer.valueOf(SOUTHEAST)},
		{"BELOW",Integer.valueOf(DOWN)},
		{"NOWHERE",Integer.valueOf(GATE)},
		{"HERE",Integer.valueOf(GATE)},
		{"THERE",Integer.valueOf(GATE)},
		{"VORTEX",Integer.valueOf(GATE)}
	};

	private static <T> T[] concat(T[] first, T[] second)
	{
		final T[] result = Arrays.copyOf(first, first.length + second.length);
		System.arraycopy(second, 0, result, first.length, second.length);
		return result;
	}

	private Object[][] DIRECTIONS_FULL_CHART=concat(DIRECTIONS_COMPASS_CHART, DIRECTIONS_SHIP_CHART);

	/**
	 * Returns the total number of permitted exit directions, either 7 or 11
	 * @return the total number of permitted exit directions, either 7 or 11
	 */
	public static final int NUM_DIRECTIONS()
	{
		return d().NUM_DIRECTIONS;
	}

	/**
	 * The BASE direction code numbers, in numeric order.  Typically 4 or 8
	 * @return BASE direction code numbers, in numeric order
	 */
	public static final int[] CODES()
	{
		return d().DIRECTIONS_CODES;
	}

	/**
	 * The direction code numbers in preferred display order.  Typically 7 or 11.
	 * @return direction code numbers in preferred display order.  Typically 7 or 11.
	 */
	public static final int[] DISPLAY_CODES()
	{
		return d().DIRECTIONS_DISPLAY;
	}

	/**
	 * Returns a string list of all of the permitted direction letters. Either 7 or 11.
	 * @return a string list of all of the permitted direction letters. Either 7 or 11.
	 */
	public static final String LETTERS()
	{
		return d().DIRECTION_LETTERS;
	}

	/**
	 * Returns a string list of all of the permitted direction names. Either 6 or 10.
	 * @return a string list of all of the permitted direction names. Either 6 or 10.
	 */
	public static final String NAMES_LIST()
	{
		return d().DIRECTION_NAMES;
	}

	/**
	 * Returns a string list of all of the permitted direction names, in ship-talk. Either 6 or 10.
	 * @return a string list of all of the permitted direction names, in ship-talk. Either 6 or 10.
	 */
	public static final String SHIP_NAMES_LIST()
	{
		return d().DIRECTION_SHIPNAMES;
	}

	/**
	 * Returns the formal direction name of the partial direction given.
	 * @param theDir the partial direction name, case insensitive
	 * @return the formal direction name
	 */
	public String getDirectionName(final String theDir)
	{
		return getDirectionName(getDirectionCode(theDir));
	}

	/**
	 * An interface to a translator for the direction words in this class
	 * @author Bo Zimmerman
	 *
	 */
	public static interface DirectionWordTranslator
	{
		public String translate(String string);
	}

	/**
	 * Reinitializes this direction object with a new number-of-directions.
	 * @param dirs the number of directions, either 7 or 11
	 */
	public final void reInitialize(final int dirs, final DirectionWordTranslator translator)
	{
		NUM_DIRECTIONS=dirs;
		if(dirs<11)
		{
			DIRECTIONS_CODES=DIRECTIONS_7_BASE;
			DIRECTION_LETTERS=DIRECTION_7_LETTERS;
			DIRECTION_NAMES=DIRECTION_7_NAMES;
			DIRECTION_SHIPNAMES=DIRECTION_7_SHIPNAMES;
		}
		else
		{
			DIRECTIONS_CODES=DIRECTIONS_11_BASE;
			DIRECTION_LETTERS=DIRECTION_11_LETTERS;
			DIRECTION_NAMES=DIRECTION_11_NAMES;
			DIRECTION_SHIPNAMES=DIRECTION_11_SHIPNAMES;
		}
		DIRECTIONS_DISPLAY = new int[100];
		int index=0;
		for(int i=0;i<Directions.DIRECTIONS_DISP_ORDER.length;i++)
		{
			if(Directions.DIRECTIONS_DISP_ORDER[i] >= 0)
			{
				DIRECTIONS_DISPLAY[index++] = Directions.DIRECTIONS_DISP_ORDER[i];
			}
			else
			{
				for(int dir : DIRECTIONS_CODES)
				{
					DIRECTIONS_DISPLAY[index++]= dir;
				}
			}
		}
		DIRECTIONS_DISPLAY = Arrays.copyOf(DIRECTIONS_DISPLAY, index);

		try
		{
			DIRECTION_7_LETTERS=translator.translate(DEFAULT_DIRECTION_7_LETTERS);
			DIRECTION_11_LETTERS=translator.translate(DEFAULT_DIRECTION_11_LETTERS);
			DIRECTION_7_NAMES=translator.translate(DEFAULT_DIRECTION_7_NAMES);
			DIRECTION_11_NAMES=translator.translate(DEFAULT_DIRECTION_11_NAMES);
			DIRECTION_7_SHIPNAMES=translator.translate(DEFAULT_DIRECTION_7_SHIPNAMES);
			DIRECTION_11_SHIPNAMES=translator.translate(DEFAULT_DIRECTION_11_SHIPNAMES);
			DIRECTIONS_COMPASS_UPPER_INDEXED=translator.translate(DEFAULT_DIRECTIONS_LIST_COMPASS).toUpperCase().split(",");
			DIRECTIONS_SHIP_UPPER_INDEXED=translator.translate(DEFAULT_DIRECTIONS_LIST_SHIP).toUpperCase().split(",");
			DIRECTIONS_COMPASS_INDEXED=translator.translate(DEFAULT_DIRECTIONS_LIST_COMPASS).split(",");
			DIRECTIONS_SHIP_INDEXED=translator.translate(DEFAULT_DIRECTIONS_LIST_SHIP).split(",");
			DIRECTIONS_COMPASS_FROM_INDEXED	= translator.translate(DEFAULT_FROM_DIR_LIST_COMPASS).split(",");
			DIRECTIONS_SHIP_FROM_INDEXED = translator.translate(DEFAULT_FROM_DIR_LIST_SHIP).split(",");
			DIRECTIONS_COMPASS_OF_INDEXED = translator.translate(DEFAULT_OF_DIR_LIST_COMPASS).split(",");
			DIRECTIONS_COMPASS_TO_INDEXED = translator.translate(DEFAULT_TO_DIR_LIST_COMPASS).split(",");
			DIRECTIONS_SHIP_TO_INDEXED = translator.translate(DEFAULT_TO_DIR_LIST_SHIP).split(",");
			DIRECTION_CHARS = translator.translate(DEFAULT_DIRECTION_CHARS).split(",");
			List<Object[]> newChart = new ArrayList<Object[]>();
			newChart.add(new Object[]{DIRECTIONS_COMPASS_UPPER_INDEXED[UP],Integer.valueOf(UP)});
			newChart.add(new Object[]{DIRECTIONS_SHIP_UPPER_INDEXED[UP],Integer.valueOf(UP)});
			newChart.add(new Object[]{DIRECTIONS_COMPASS_UPPER_INDEXED[NORTH],Integer.valueOf(NORTH)});
			newChart.add(new Object[]{DIRECTIONS_COMPASS_UPPER_INDEXED[SOUTH],Integer.valueOf(SOUTH)});
			newChart.add(new Object[]{DIRECTIONS_COMPASS_UPPER_INDEXED[EAST],Integer.valueOf(EAST)});
			newChart.add(new Object[]{DIRECTIONS_COMPASS_UPPER_INDEXED[WEST],Integer.valueOf(WEST)});
			newChart.add(new Object[]{DIRECTIONS_COMPASS_UPPER_INDEXED[NORTHEAST],Integer.valueOf(NORTHEAST)});
			newChart.add(new Object[]{DIRECTIONS_COMPASS_UPPER_INDEXED[NORTHWEST],Integer.valueOf(NORTHWEST)});
			newChart.add(new Object[]{DIRECTIONS_COMPASS_UPPER_INDEXED[SOUTHWEST],Integer.valueOf(SOUTHWEST)});
			newChart.add(new Object[]{DIRECTIONS_COMPASS_UPPER_INDEXED[SOUTHEAST],Integer.valueOf(SOUTHEAST)});
			newChart.add(new Object[]{DIRECTION_CHARS[NORTHEAST],Integer.valueOf(NORTHEAST)});
			newChart.add(new Object[]{DIRECTION_CHARS[NORTHWEST],Integer.valueOf(NORTHWEST)});
			newChart.add(new Object[]{DIRECTION_CHARS[SOUTHWEST],Integer.valueOf(SOUTHWEST)});
			newChart.add(new Object[]{DIRECTION_CHARS[SOUTHEAST],Integer.valueOf(SOUTHEAST)});
			newChart.add(new Object[]{DIRECTIONS_COMPASS_UPPER_INDEXED[DOWN],Integer.valueOf(DOWN)});
			newChart.add(new Object[]{DIRECTIONS_SHIP_UPPER_INDEXED[DOWN],Integer.valueOf(DOWN)});
			newChart.add(new Object[]{translator.translate("NOWHERE"),Integer.valueOf(GATE)});
			newChart.add(new Object[]{translator.translate("HERE"),Integer.valueOf(GATE)});
			newChart.add(new Object[]{translator.translate("THERE"),Integer.valueOf(GATE)});
			newChart.add(new Object[]{translator.translate("VORTEX"),Integer.valueOf(GATE)});
			DIRECTIONS_COMPASS_CHART = newChart.toArray(new Object[0][]);
			newChart.clear();
			newChart.add(new Object[]{DIRECTIONS_SHIP_UPPER_INDEXED[UP],Integer.valueOf(UP)});
			newChart.add(new Object[]{DIRECTIONS_SHIP_UPPER_INDEXED[NORTH],Integer.valueOf(NORTH)});
			newChart.add(new Object[]{DIRECTIONS_SHIP_UPPER_INDEXED[SOUTH],Integer.valueOf(SOUTH)});
			newChart.add(new Object[]{DIRECTIONS_SHIP_UPPER_INDEXED[EAST],Integer.valueOf(EAST)});
			newChart.add(new Object[]{DIRECTIONS_SHIP_UPPER_INDEXED[WEST],Integer.valueOf(WEST)});
			newChart.add(new Object[]{CMStrings.replaceAll(DIRECTIONS_SHIP_UPPER_INDEXED[NORTHEAST]," ",""),Integer.valueOf(NORTHEAST)});
			newChart.add(new Object[]{CMStrings.replaceAll(DIRECTIONS_SHIP_UPPER_INDEXED[NORTHWEST]," ",""),Integer.valueOf(NORTHWEST)});
			newChart.add(new Object[]{CMStrings.replaceAll(DIRECTIONS_SHIP_UPPER_INDEXED[SOUTHWEST]," ",""),Integer.valueOf(SOUTHWEST)});
			newChart.add(new Object[]{CMStrings.replaceAll(DIRECTIONS_SHIP_UPPER_INDEXED[SOUTHEAST]," ",""),Integer.valueOf(SOUTHEAST)});
			newChart.add(new Object[]{translator.translate("FP"),Integer.valueOf(NORTHWEST)});
			newChart.add(new Object[]{translator.translate("FS"),Integer.valueOf(NORTHEAST)});
			newChart.add(new Object[]{translator.translate("AP"),Integer.valueOf(SOUTHWEST)});
			newChart.add(new Object[]{translator.translate("AS"),Integer.valueOf(SOUTHEAST)});
			newChart.add(new Object[]{DIRECTIONS_SHIP_UPPER_INDEXED[DOWN],Integer.valueOf(DOWN)});
			newChart.add(new Object[]{translator.translate("NOWHERE"),Integer.valueOf(GATE)});
			newChart.add(new Object[]{translator.translate("HERE"),Integer.valueOf(GATE)});
			newChart.add(new Object[]{translator.translate("THERE"),Integer.valueOf(GATE)});
			newChart.add(new Object[]{translator.translate("VORTEX"),Integer.valueOf(GATE)});
			DIRECTIONS_SHIP_CHART = newChart.toArray(new Object[0][]);

			DIRECTIONS_FULL_CHART=concat(DIRECTIONS_COMPASS_CHART, DIRECTIONS_SHIP_CHART);
		}
		catch(Exception e)
		{
		}
	}

	/**
	 * Given the direction code, returns the formal name of that direction, capitalized.
	 * @param code the direction code
	 * @return the name of that direction, capitalized
	 */
	public String getDirectionName(final int code)
	{
		if((code>=0)&&(code < this.DIRECTIONS_COMPASS_INDEXED.length))
			return this.DIRECTIONS_COMPASS_INDEXED[code];
		return "";
	}

	/**
	 * Given the direction code, returns the formal name of that direction, capitalized.
	 * @param code the direction code
	 * @return the name of that direction, capitalized
	 */
	public String getUpperDirectionName(final int code, boolean useShip)
	{
		if((code>=0)&&(code<NUM_DIRECTIONS()))
		{
			if(useShip)
				return DIRECTIONS_COMPASS_UPPER_INDEXED[code];
			else
				return DIRECTIONS_SHIP_UPPER_INDEXED[code];
		}
		return "";
	}

	/**
	 * Given the direction code, returns the ship-talk name of that direction, capitalized.
	 * @param code the direction code
	 * @return the ship-talk name of that direction, capitalized
	 */
	public String getShipDirectionName(final int code)
	{
		if((code>=0)&&(code < DIRECTIONS_SHIP_INDEXED.length))
			return DIRECTIONS_SHIP_INDEXED[code];
		return "";
	}

	/**
	 * Given the numeric direction code, this method returns the 1 or 2 char
	 * "code" that represents that direction, such as N, S, E, W, NW, SW, etc..
	 * @param code the direction code
	 * @return the direction character or characters
	 */
	public String getDirectionChar(final int code)
	{
		if(code<NUM_DIRECTIONS())
			return DIRECTION_CHARS[code];
		return " ";
	}

	/**
	 * Given a string which is supposed to be a direction name of any type,
	 * this method will make a case-insensitive check against the given
	 * string and return the direction it probably represents.  It gives
	 * preference to actual direction names, such as north, aft, below, up, but
	 * if all fail, it will try prefixes, such as nor, por, or just N, S, etc.
	 * @param theDir the direction search string
	 * @return the direction code it represents, or -1 if no match at ALL
	 */
	public int getDirectionCode(final String theDir)
	{
		final int code=getGoodDirectionCode(theDir);
		if(code<0)
		{
			final String upDir=theDir.toUpperCase();
			for(int i=0;i<NUM_DIRECTIONS();i++)
			{
				if(upDir.startsWith(DIRECTION_CHARS[i]))
					return i;
			}
		}
		return code;
	}

	/**
	 * Given a string which is technically supposed to be a ship-talk direction name,
	 * this method will make a case-insensitive check against the given
	 * string and return the direction it probably represents.  It gives
	 * preference to actual direction names, such as port and aft, but
	 * if all fail, it will try prefixes, such as por, for, etc.
	 * @param theDir the ship-talk direction search string
	 * @return the direction code it represents, or -1 if no match at ALL
	 */
	public int getShipDirectionCode(final String theDir)
	{
		return getGoodShipDirectionCode(theDir);
	}

	/**
	 * Given a string which is supposed to be a compass direction name,
	 * this method will make a case-insensitive check against the given
	 * string and return the direction it probably represents.  It gives
	 * preference to actual direction names, such as north, south, etc, but
	 * if all fail, it will try prefixes, such as nor, sou, or just N, S, etc.
	 * @param theDir the direction search string
	 * @return the direction code it represents, or -1 if no match at ALL
	 */
	public int getCompassDirectionCode(final String theDir)
	{
		final int code=getGoodCompassDirectionCode(theDir);
		if(code<0)
		{
			final String upDir=theDir.toUpperCase();
			for(int i=0;i<NUM_DIRECTIONS();i++)
			{
				if(upDir.startsWith(DIRECTION_CHARS[i]))
					return i;
			}
		}
		return code;
	}

	/**
	 * Given a string which is supposed to be a direction name of any type,
	 * this method will make a case-insensitive check against the given
	 * string and return the direction it probably represents.  It gives
	 * preference to actual direction names, such as north, aft, below, up, but
	 * if all fail, it will try prefixes, such as nor, por, etc.
	 * @param theDir the direction search string
	 * @return the direction code it represents, or -1 if no match at ALL
	 */
	public int getGoodDirectionCode(final String theDir)
	{
		if(theDir.length()==0)
			return -1;
		final String upDir=theDir.toUpperCase();
		for (final Object[] element : DIRECTIONS_FULL_CHART)
		{
			if((element[0].toString().startsWith(upDir))
			&&(((Integer)element[1]).intValue()<NUM_DIRECTIONS()))
				return ((Integer)element[1]).intValue();
		}
		return -1;
	}

	/**
	 * Given a string which is supposed to be a direction name of any type,
	 * this method will make a case-insensitive check against the given
	 * string and return the direction it probably represents.  It
	 * requires strict actual direction names, such as north, aft, below, up.
	 * @param theDir the direction search string
	 * @return the direction code it represents, or -1 if no match at ALL
	 */
	public int getStrictDirectionCode(final String theDir)
	{
		if(theDir.length()==0)
			return -1;
		final String upDir=theDir.toUpperCase();
		for (final Object[] element : DIRECTIONS_FULL_CHART)
		{
			if((element[0].toString().equals(upDir))
			&&(((Integer)element[1]).intValue()<NUM_DIRECTIONS()))
				return ((Integer)element[1]).intValue();
		}
		for(int i=0;i<NUM_DIRECTIONS();i++)
		{
			if(upDir.equals(DIRECTION_CHARS[i]))
				return i;
		}
		return -1;
	}

	/**
	 * Given a string which is supposed to be a compass direction name,
	 * this method will make a case-insensitive check against the given
	 * string and return the direction it probably represents.  It gives
	 * preference to actual direction names, such as north, south, etc, but
	 * if all fail, it will try prefixes, such as nor, sou, etc.
	 * @param theDir the direction search string
	 * @return the direction code it represents, or -1 if no match at ALL
	 */
	public int getGoodCompassDirectionCode(final String theDir)
	{
		if(theDir.length()==0)
			return -1;
		final String upDir=theDir.toUpperCase();
		for (final Object[] element : DIRECTIONS_COMPASS_CHART)
		{
			if((element[0].toString().startsWith(upDir))
			&&(((Integer)element[1]).intValue()<NUM_DIRECTIONS()))
				return ((Integer)element[1]).intValue();
		}
		return -1;
	}

	/**
	 * Given a string which is supposed to be a compass direction name,
	 * this method will make a case-insensitive check against the given
	 * string and return the direction it probably represents.  It
	 * requires actual direction names, such as north, south, etc, but
	 * if all fail, it will try short letters, such as n, ne, etc.
	 * @param theDir the direction search string
	 * @return the direction code it represents, or -1 if no match at ALL
	 */
	public int getStrictCompassDirectionCode(final String theDir)
	{
		if(theDir.length()==0)
			return -1;
		final String upDir=theDir.toUpperCase();
		for (final Object[] element : DIRECTIONS_COMPASS_CHART)
		{
			if((element[0].toString().equals(upDir))
			&&(((Integer)element[1]).intValue()<NUM_DIRECTIONS()))
				return ((Integer)element[1]).intValue();
		}
		for(int i=0;i<NUM_DIRECTIONS();i++)
		{
			if(upDir.equals(DIRECTION_CHARS[i]))
				return i;
		}
		return -1;
	}

	/**
	 * Given a string which is technically supposed to be a ship-talk direction name,
	 * this method will make a case-insensitive check against the given
	 * string and return the direction it probably represents.  It gives
	 * preference to actual direction names, such as port and aft, but
	 * if all fail, it will try prefixes, such as por, for, etc.
	 * @param theDir the ship-talk direction search string
	 * @return the direction code it represents, or -1 if no match at ALL
	 */
	public int getGoodShipDirectionCode(final String theDir)
	{
		if(theDir.length()==0)
			return -1;
		final String upDir=theDir.toUpperCase();
		for (final Object[] element : DIRECTIONS_SHIP_CHART)
		{
			if((element[0].toString().startsWith(upDir))
			&&(((Integer)element[1]).intValue()<NUM_DIRECTIONS()))
				return ((Integer)element[1]).intValue();
		}
		return -1;
	}

	/**
	 * Given a string which is technically supposed to be a ship-talk direction name,
	 * this method will make a case-insensitive check against the given
	 * string and return the direction it represents.  It requires
	 * actual direction names, such as port and aft.
	 * @param theDir the ship-talk direction search string
	 * @return the direction code it represents, or -1 if no match at ALL
	 */
	public int getStrictShipDirectionCode(final String theDir)
	{
		if(theDir.length()==0)
			return -1;
		final String upDir=theDir.toUpperCase();
		for (final Object[] element : DIRECTIONS_SHIP_CHART)
		{
			if((element[0].toString().equals(upDir))
			&&(((Integer)element[1]).intValue()<NUM_DIRECTIONS()))
				return ((Integer)element[1]).intValue();
		}
		return -1;
	}

	/**
	 * Given an x and y coordinate, and a direction code, this method will return
	 * an int array with 2 entries x, and y, representing the changes to the given
	 * x and y after moving in that direction.
	 * @param x the x coordinate
	 * @param y the y coordinate
	 * @param direction the direction code being travelled
	 * @return the 2 dimensional int array with the new x and y
	 */
	public static final int[] adjustXYByDirections(int x, int y, final int direction)
	{
		switch(direction)
		{
		case Directions.NORTH:
			y--;
			break;
		case Directions.SOUTH:
			y++;
			break;
		case Directions.EAST:
			x++;
			break;
		case Directions.WEST:
			x--;
			break;
		case Directions.NORTHEAST:
			x++;
			y--;
			break;
		case Directions.NORTHWEST:
			x--;
			y--;
			break;
		case Directions.SOUTHEAST:
			x++;
			y++;
			break;
		case Directions.SOUTHWEST:
			x--;
			y++;
			break;
		}
		final int[] xy=new int[2];
		xy[0]=x;
		xy[1]=y;
		return xy;
	}

	/**
	 * Given an x and y and z coordinate, and a direction code, this method will return
	 * an int array with 2 entries x, y, and z representing the changes to the given
	 * x, y, and z after moving in that direction.
	 * @param x the x coordinate
	 * @param y the y coordinate
	 * @param z the z coordinate
	 * @param direction the direction code being travelled
	 * @return the 3 dimensional int array with the new x, y, z
	 */
	public static final int[] adjustXYZByDirections(int x, int y, int z, final int direction)
	{
		switch(direction)
		{
		case Directions.NORTH:
			y--;
			break;
		case Directions.SOUTH:
			y++;
			break;
		case Directions.EAST:
			x++;
			break;
		case Directions.WEST:
			x--;
			break;
		case Directions.NORTHEAST:
			x++;
			y--;
			break;
		case Directions.NORTHWEST:
			x--;
			y--;
			break;
		case Directions.SOUTHEAST:
			x++;
			y++;
			break;
		case Directions.SOUTHWEST:
			x--;
			y++;
			break;
		case Directions.UP:
			z--;
			break;
		case Directions.DOWN:
			z++;
			break;
		}
		final int[] xy=new int[3];
		xy[0]=x;
		xy[1]=y;
		xy[2]=z;
		return xy;
	}

	/**
	 * Returns the proper english compass direction name to follow the preposition
	 * "from" when talking about something or someone coming FROM the given direction
	 * code.  Completes the following sentence: "Joe arrived from ..."
	 * @param code the direction code
	 * @return the name of the direction phrase
	 */
	public String getFromCompassDirectionName(final int code)
	{
		if((code>=0)&&(code < DIRECTIONS_COMPASS_FROM_INDEXED.length))
			return DIRECTIONS_COMPASS_FROM_INDEXED[code];
		return "";
	}

	/**
	 * Returns the proper english compass direction name to relative to somewhere else.
	 * @param code the direction code
	 * @return the name of the direction phrase
	 */
	public String getRelativeCompassDirectionName(final int code)
	{
		if((code>=0)&&(code < DIRECTIONS_COMPASS_OF_INDEXED.length))
			return DIRECTIONS_COMPASS_OF_INDEXED[code];
		return "";
	}
	/**
	 * Returns the proper english ship direction name to follow the preposition
	 * "from" when talking about something or someone coming FROM the given direction
	 * code on a ship.  Completes the following sentence: "Joe arrived from ..."
	 * @param code the direction code
	 * @return the name of the direction phrase
	 */
	public  String getFromShipDirectionName(final int code)
	{
		if((code>=0)&&(code < DIRECTIONS_SHIP_FROM_INDEXED.length))
			return DIRECTIONS_SHIP_FROM_INDEXED[code];
		return "";
	}

	/**
	 * Returns the proper english compass direction name to follow the preposition
	 * "happens" when talking about something happening in the given direction
	 * code.  Completes the following sentence: "You hear something happen ..."
	 * Usually begins with "to the", such as "to the north", "to the northeast", etc.
	 * @param code the direction code the direction the thing is happening in
	 * @return the name of the direction completion phrase
	 */
	public String getInDirectionName(final int code)
	{
		if((code>=0)&&(code < DIRECTIONS_COMPASS_TO_INDEXED.length))
			return DIRECTIONS_COMPASS_TO_INDEXED[code];
		return "";
	}

	/**
	 * Returns the proper english ship-talk direction name to follow the preposition
	 * "happens" when talking about something happening in the given direction
	 * code on a ship.  Completes the following sentence: "You hear something happen ..."
	 * Usually begins with "to", such as "to foreward", "to portside", etc.
	 * @param code the direction code the direction the thing is happening in
	 * @return the name of the direction completion phrase
	 */
	public String getShipInDirectionName(final int code)
	{
		if((code>=0)&&(code < DIRECTIONS_SHIP_TO_INDEXED.length))
			return DIRECTIONS_SHIP_TO_INDEXED[code];
		return "";
	}

	/**
	 * Returns the direction code opposite to the given code.
	 * E.G. Returns North for South, Northwest for Southeast, etc.
	 * @param code the direction code
	 * @return the opposite direction code
	 */
	public static final int getOpDirectionCode(final int code)
	{
		switch(code)
		{
		case NORTH:
			return SOUTH;
		case SOUTH:
			return NORTH;
		case WEST:
			return EAST;
		case EAST:
			return WEST;
		case NORTHEAST:
			return SOUTHWEST;
		case NORTHWEST:
			return SOUTHEAST;
		case SOUTHEAST:
			return NORTHWEST;
		case SOUTHWEST:
			return NORTHEAST;
		case UP:
			return DOWN;
		case DOWN:
			return UP;
		case GATE:
			return GATE;
		}
		return -1;
	}

	/**
	 * Returns the direction code next to the given curentCode that
	 * moves towards the target direction code
	 * @param curentCode the current direction code
	 * @param targetCode the target direction code
	 * @return the next direction code
	 */
	public static final int getGradualDirectionCode(final int curentCode, final int targetCode)
	{
		final boolean elevenDirections = Directions.NUM_DIRECTIONS() == 11;
		switch(curentCode)
		{
		case NORTH:
			switch(targetCode)
			{
			case NORTH:
				return NORTH;
			case SOUTH:
				return elevenDirections ? NORTHEAST : EAST;
			case WEST:
				return elevenDirections ? NORTHWEST : WEST;
			case EAST:
				return elevenDirections ? NORTHEAST : EAST;
			case NORTHEAST:
				return NORTHEAST;
			case NORTHWEST:
				return NORTHWEST;
			case SOUTHEAST:
				return NORTHEAST;
			case SOUTHWEST:
				return NORTHWEST;
			default:
				break;
			}
			return targetCode;
		case SOUTH:
			switch(targetCode)
			{
			case NORTH:
				return elevenDirections ? SOUTHWEST : WEST;
			case SOUTH:
				return SOUTH;
			case WEST:
				return elevenDirections ? SOUTHWEST : WEST;
			case EAST:
				return elevenDirections ? SOUTHEAST : EAST;
			case NORTHEAST:
				return SOUTHEAST;
			case NORTHWEST:
				return SOUTHWEST;
			case SOUTHEAST:
				return SOUTHEAST;
			case SOUTHWEST:
				return SOUTHWEST;
			default:
				break;
			}
			return targetCode;
		case WEST:
			switch(targetCode)
			{
			case NORTH:
				return elevenDirections ? NORTHWEST : NORTH;
			case SOUTH:
				return elevenDirections ? SOUTHWEST : SOUTH;
			case WEST:
				return WEST;
			case EAST:
				return elevenDirections ? NORTHWEST : NORTH;
			case NORTHEAST:
				return elevenDirections ? NORTHWEST : NORTH;
			case NORTHWEST:
				return NORTHWEST;
			case SOUTHEAST:
				return elevenDirections ? SOUTHWEST : SOUTH;
			case SOUTHWEST:
				return SOUTHWEST;
			default:
				break;
			}
			return targetCode;
		case EAST:
			switch(targetCode)
			{
			case NORTH:
				return elevenDirections ? NORTHEAST : NORTH;
			case SOUTH:
				return elevenDirections ? SOUTHEAST : SOUTH;
			case WEST:
				return elevenDirections ? SOUTHEAST : SOUTH;
			case EAST:
				return EAST;
			case NORTHEAST:
				return NORTHEAST;
			case NORTHWEST:
				return elevenDirections ? NORTHEAST : NORTH;
			case SOUTHEAST:
				return SOUTHEAST;
			case SOUTHWEST:
				return elevenDirections ? SOUTHEAST : SOUTH;
			default:
				break;
			}
			return targetCode;
		case NORTHEAST:
			switch(targetCode)
			{
			case NORTH:
				return NORTH;
			case SOUTH:
				return EAST;
			case WEST:
				return NORTH;
			case EAST:
				return EAST;
			case NORTHEAST:
				return NORTHEAST;
			case NORTHWEST:
				return NORTH;
			case SOUTHEAST:
				return EAST;
			case SOUTHWEST:
				return EAST;
			default:
				break;
			}
			return targetCode;
		case NORTHWEST:
			switch(targetCode)
			{
			case NORTH:
				return NORTH;
			case SOUTH:
				return WEST;
			case WEST:
				return WEST;
			case EAST:
				return NORTH;
			case NORTHEAST:
				return NORTH;
			case NORTHWEST:
				return NORTHWEST;
			case SOUTHEAST:
				return NORTH;
			case SOUTHWEST:
				return EAST;
			default:
				break;
			}
			return targetCode;
		case SOUTHEAST:
			switch(targetCode)
			{
			case NORTH:
				return EAST;
			case SOUTH:
				return SOUTH;
			case WEST:
				return SOUTH;
			case EAST:
				return EAST;
			case NORTHEAST:
				return EAST;
			case NORTHWEST:
				return NORTH;
			case SOUTHEAST:
				return SOUTHEAST;
			case SOUTHWEST:
				return SOUTH;
			default:
				break;
			}
			return targetCode;
		case SOUTHWEST:
			switch(targetCode)
			{
			case NORTH:
				return WEST;
			case SOUTH:
				return SOUTH;
			case WEST:
				return WEST;
			case EAST:
				return SOUTH;
			case NORTHEAST:
				return WEST;
			case NORTHWEST:
				return WEST;
			case SOUTHEAST:
				return SOUTH;
			case SOUTHWEST:
				return SOUTHWEST;
			default:
				break;
			}
			return targetCode;
		case UP:
			return targetCode;
		case DOWN:
			return targetCode;
		case GATE:
			return targetCode;
		}
		return -1;
	}

	/**
	 * Given a string which is supposed to be a direction name of any type,
	 * this method will make a case-insensitive check against the given
	 * string and return the direction opposite to what it probably represents.  It gives
	 * preference to actual direction names, such as north, aft, below, up, but
	 * if all fail, it will try prefixes, such as nor, por, or just N, S, etc.
	 * @param theDir the direction search string
	 * @return the direction code opposite to the one it represents, or -1 if no match at ALL
	 */
	public int getOpDirectionCode(final String theDir)
	{
		final int code=getDirectionCode(theDir);
		return getOpDirectionCode(code);
	}

	/**
	 * Returns the cardinal direction from the FROM point on a graph to the
	 * TO point, where the points are X, then Y, with the northwest corner
	 * being 0,0.
	 * @param xyFrom the starting point
	 * @param xyTo the target point
	 * @return the direction from the start to target
	 */
	public static final int getRelativeDirection(int[] xyFrom, int[] xyTo)
	{
		return getRelativeDirection(xyFrom,xyTo,Directions.NUM_DIRECTIONS()!=11);
	}

	/**
	 * Returns the cardinal direction from the FROM point on a graph to the
	 * TO point, where the points are X, then Y, with the northwest corner
	 * being 0,0.  This always return 11 direction codes.
	 * @param xyFrom the starting point
	 * @param xyTo the target point
	 * @return the direction from the start to target
	 */
	public static final int getRelative11Directions(int[] xyFrom, int[] xyTo)
	{
		return getRelativeDirection(xyFrom,xyTo,false);
	}

	/**
	 * Returns the cardinal direction from the FROM point on a graph to the
	 * TO point, where the points are X, then Y, with the northwest corner
	 * being 0,0.
	 * @param xyFrom the starting point
	 * @param xyTo the target point
	 * @param useBase4 true to use NSEW, false to use NORTHEAST, etc.
	 * @return the direction from the start to target
	 */
	public static final int getRelativeDirection(int[] xyFrom, int[] xyTo, boolean useBase4)
	{
		double x =  xyTo[0] - xyFrom[0];
		double y =  xyTo[1] - xyFrom[1];
		double rads = Math.atan2(x,y);
		int dir= (int)Math.round(rads * 180.0 / Math.PI);
		if(useBase4)
		{
			if((dir < -135)||(dir > 135))
				return Directions.NORTH;
			else
			if(dir < -45)
				return Directions.WEST;
			else
			if(dir > 45)
				return Directions.EAST;
			else
				return Directions.SOUTH;
		}
		else
		{
			if((dir < -157)||(dir > 157))
				return Directions.NORTH;
			else
			if(dir < -112)
				return Directions.NORTHWEST;
			else
			if(dir < -67)
				return Directions.WEST;
			else
			if(dir < -22)
				return Directions.SOUTHWEST;
			else
			if(dir > 112)
				return Directions.NORTHEAST;
			else
			if(dir > 67)
				return Directions.EAST;
			else
			if(dir > 22)
				return Directions.SOUTHEAST;
			else
				return Directions.SOUTH;
		}
	}
}


text:
var gui = require('nw.gui');

angular.module("app").controller("MainController", [
  "$scope",
  "$window",
  "BookshelfService",
  "KindleGenService",
  "LogService",
  "SystemService",
  function(
    $scope,
    $window,
    BookshelfService,
    KindleGenService,
    LogService,
    SystemService
  ) {

  $scope.hardRefresh = function() {
    $window.location.reload();
  };

  $scope.refresh = function() {
    SystemService.commandExists('ebook-convert', function(exists) {
      $scope.showCalibreWarning = !exists;
      $scope.$apply();
    });

    $scope.accounts = [];
    $scope.currentAccount = "";

    $scope.books = [];

    $scope.locateBookshelf();
  };

  $scope.locateBookshelf = function() {
    var bookshelf = BookshelfService.pathToBookshelf;

    $scope.accounts = [];
    $scope.currentAccount = "";
    $scope.books = [];
    $scope.message = '';

    BookshelfService.bookshelfExists(function(bookshelfFound) {
      $scope.bookshelfFound = bookshelfFound;

      if ($scope.bookshelfFound) {
        $scope.message = "Select your Bookshelf account from the dropdown menu above.";
        BookshelfService.getAccounts(function(accounts) {
          $scope.accounts = accounts;
          $scope.$apply();
        });
      } else {
        $scope.message = "We couldn't find the Bookshelf folder on your desktop.";
        $scope.$apply();
      }
    });
  };

  $scope.refreshBooks = function() {
    var account = $scope.currentAccount;
    BookshelfService.getBooks(account, function(books) {
      $scope.books = books;
      $scope.message = "";
      $scope.$apply();
    });
  };

  $scope.downloadCalibre = function() {
    gui.Shell.openExternal('http://calibre-ebook.com/');
    $scope.showCalibreWarning = false;
  };

  $scope.noBookshelf = function() {
    if ($scope.currentBookshelf === "") {
      return false;
    }

    return !$scope.bookshelfFound;
  };

  $scope.selectAccount = function() {
    if ($scope.noBookshelf()) {
      return false;
    }

    return $scope.accounts.length > 0;
  };

  $scope.message = "This program needs Amazon's KindleGen tool to work properly, we're downloading it now. This shouldn't take more than a couple of minutes.";

  KindleGenService.verifyInstall(function(err, results) {
    $scope.refresh();
  });

}]);


text:
package de.uni.freiburg.iig.telematik.swat.misc.timecontext.distributions;

import java.util.Arrays;
import java.util.Random;

import org.apache.commons.math3.distribution.AbstractRealDistribution;

public class MeasuredDistributionView extends AbstractDistributionView {

	double[] bins;
	double[] frequency;
	double[] cummulated;
	double step;
	private Random r;

	public static void main(String[] args) {
		double[] occurence = { 1, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 4, 4.1 };
		MeasuredDistributionView view = new MeasuredDistributionView(occurence, 4);
		for (int i = 0; i < 10; i++)
			System.out.print(view.getNeededTime() + ", ");

	}

	public MeasuredDistributionView(double[] occurences, int numberOfBins) {
		Arrays.sort(occurences);
		initializeBins(occurences, numberOfBins);
		frequency = fillBins(occurences, bins);

		printDetails();

		//normalize
		normalize(frequency);

		//transform frequency to inverse
		cummulated = cummulate(frequency);

		r = new Random();
		type = DistributionType.MEASURED;

	}

	public void printDetails() {
		System.out.println("Step: " + step);
		System.out.println("Occurences: ");
		for (int i = 0; i < bins.length; i++) {
			System.out.println(bins[i] + "->" + (bins[i] + step) + ": " + frequency[i]);
		}
		System.out.println("-----");

	}

	/** make cummulative histogram. last entry will be one **/
	private double[] cummulate(double[] frequency) {
		double[] cummulated = new double[frequency.length];
		double sum = 0;
		for (int i = 0; i < frequency.length; i++) {
			sum += frequency[i];
			cummulated[i] = sum;
		}
		return cummulated;
	}

	/** normalize: divide frequency so they sum up to 1 **/
	private void normalize(double[] frequency) {
		double sum = 0.0;
		for (double d : frequency) {
			sum += d;
		}
		for (int i = 0; i < frequency.length; i++) {
			frequency[i] = frequency[i] / sum;
		}
	}

	/**
	 * create histogram out of occurences with given bins. occurences must be
	 * sorted
	 **/
	private double[] fillBins(double[] occurences, double[] bins) {
		double[] frequency = new double[bins.length];
		int startFrom = 0;
		//sweep through bins
		for (int i = 0; i < bins.length; i++) {
			int count = 0;
			while (startFrom < occurences.length) { //sweep through measeaured occurences
				if (occurences[startFrom] <= bins[i]) {
					count++; //add occurence into current bin
					startFrom++; //go on with next occurence
				} else
					break; //bin full. Go to next bin
			}
			frequency[i] = count; //put into bin: number of matching occurences
		}
		return frequency;

	}

	@Override
	/** use inverse method to draw a random sample out of occurences**/
	public double getNeededTime() {
		double random = r.nextDouble();
		int index = Arrays.binarySearch(cummulated, random);
		if (index < 0)
			index = Math.abs(index) - 1;//not a direct hit. use next neighbor

		return bins[index];
	}

	/**
	 * create bin-limits for histogram with
	 *
	 * @param occurences
	 *            values that will be inserted within bins
	 * @param numberOfBins
	 *            how many bins wanted
	 */
	public void initializeBins(double[] occurences, int numberOfBins) {
		bins = new double[numberOfBins];
		double min = occurences[0]; //value for first bin
		double max = Math.ceil(occurences[occurences.length - 1]); //value for last bin
		step = (max - min) / (((double) numberOfBins - 1)); //width of each bin
		bins[0] = min;
		for (int i = 1; i < numberOfBins; i++) {
			bins[i] = bins[i - 1] + step; //value for each bin
		}
	}

	@Override
	public AbstractRealDistribution getDistribution() {
		// TODO Auto-generated method stub
		return null;
	}

}


text:
char *copyTidyNodeValue(TidyNode tnode, TidyDoc tdoc);
DFNode *fromTidyNode(DFDocument *htmlDoc, TidyDoc tdoc, TidyNode tnode);


text:
package jena;

public class rset {
    public static void main(String... args) {
        arq.rset.main(args);
    }
}


text:
/*
 * Common Modal Views
 *
 * js/app/common/modal_views.js
 */

"use strict";

class NotificationModalView extends MicromodalBaseView {

  get el() { return $("#" + this.tag); }

  get events() {
    return {
      'click div[data-micromodal-close]': 'cancel',
      'click button[name=notify-cancel]': 'cancel',
      'click button[name=notify-success]': 'success',
      'keydown': 'keydownHandler'
    };
  }

  get template() {
    return App.templates.notify_template(this.model.toJSON());
  }

  constructor(options) {
    super(options);
    this.tag = 'notify-modal';
  }

  cancelCB() {
    console.log('Cancel');
  }

  successCB() {
    console.log('Success');
  }
};

class AlertModalView extends MicromodalBaseView {

  get el() { return $("#" + this.tag); }

  get events() {
    return {
      'click div[data-micromodal-close]': 'cancel'
    };
  }

  get template() {
    return App.templates.alert_template(this.model.toJSON());
  }

  constructor(options) {
    super(options);
    this.tag = 'alert-modal';
  }
};

// Test Modal View
class TestNotifyModalView extends MicromodalBaseView {

  get el() { return $("#" + this.tag); }

  get events() {
    return {
      'click div[data-micromodal-close]': 'cancel',
      'click button[name=notify-cancel]': 'cancel',
      'click button[name=notify-success]': 'success',
      'keydown': 'keydownHandler'
    };
  }

  get template() {
    return App.templates.test_notify_template(this.model.toJSON());
  }

  constructor(options) {
    super(options);
    this.tag = 'test-notify-modal';
  }

  cancelCB() {
    console.log('Cancel');
  }

  successCB() {
    console.log('Success');
  }
};