text:
<?php

/**
 * PluginOp2Entry
 *
 * This class has been auto-generated by the Doctrine ORM Framework
 *
 * @package    opMTViewerPlugin
 * @subpackage model
 * @author     Kimura Youichi <kim.upsilon@gmail.com>
 */
abstract class PluginOp2Entry extends BaseOp2Entry
{
  public function setFromArray(array $entry)
  {
    $this->title = $entry['TITLE'];
    $this->created_at = date('Y-m-d H:i:s', strtotime($entry['DATE']));

    $this->setBodyArray($this->splitBody($entry['BODY']));

    $member = new Op2Member();
    $member->name = $entry['AUTHOR'];
    $this->Op2Member = $member;
  }

  protected function setBodyArray(array $body)
  {
    $this->body = $this->br2nl($body['body']);

    if (isset($body['images']))
    {
      $this->has_images = true;

      foreach ($body['images'] as $num => $imageUrl)
      {
        $this->addImage($imageUrl, $num);
      }
    }
  }

  protected function br2nl($html)
  {
    $html = preg_replace("/[\r\n]+/", '', $html);
    $html = preg_replace('/
/', "\n", $html);
    return $html;
  }

  protected function addImage($imageUrl, $idx)
  {
  }

  public function getCommentsCount()
  {
    return -1;
  }

  public function getCommentTable()
  {
    $tableName = get_class($this).'Comment';
    return Doctrine::getTable($tableName);
  }

  protected function splitBody($body)
  {
    if (0 !== strpos($body, '
'))
    {
      return array('body' => $body);
    }

    $result = array();

    $body = split('
', $body, 2);
    $result['body'] = $body[1];

    $meta = split("\n", str_replace('
', '', $body[0]));
    foreach ($meta as $line)
    {
      $line = ltrim($line);
      if (false !== strpos($line, '<img'))
      {
        $result['images'][] = preg_replace('/^\s*$/', '$1', $line);
      }
      else
      {
        $line = split(' : ', $line, 2);
        $result[$line[0]] = $line[1];
      }
    }

    return $result;
  }

  public function getBody()
  {
    return opTagConverter::convertTag($this->_get('body'));
  }
}


text:
/*Write a program to convert decimal numbers to their binary representation.*/

using System;

class ConvertDecimalToBinary
{
    static void Main()
    {
        Console.Write("Enter a decimal number: ");
        int decimNum = int.Parse(Console.ReadLine());
        string tempBinNum = null;
        string binNum = null;
        while (decimNum > 0)
        {
            tempBinNum += decimNum % 2;
            decimNum /= 2;
        }
        for (int i = tempBinNum.Length - 1; i >= 0; i--)
        {
            binNum += tempBinNum[i];
        }
        Console.WriteLine();
        Console.WriteLine("The number {0} in decimal numberal system is number {1} in binary numeral system.", decimNum, binNum);

    }
}

redpajama_set_name: RedPajamaGithub


text:
Usage Manual
============

.. toctree::

   terminology
   python-slimta
   slimta


text:
#include "ofxHotKeys.h"

#ifdef TARGET_WIN32

// not tested yet

bool ofGetModifierSelection(){
	return ofGetModifierShiftPressed();
}

//COMMAND on OS X, CTRL on Windows
//----------------------------------------
bool ofGetModifierShortcutKeyPressed(){
	return ofGetModifierPressed(OF_MODIFIER_KEY_CTRL);
}
bool ofGetModifierPressed(ofxModifierKey mod)
{
	unsigned int t = 0;

	if ((OF_MODIFIER_KEY_CTRL & mod) == OF_MODIFIER_KEY_CTRL)
		return (GetKeyState( VK_CONTROL ) & 0x80) > 0;

	else if ((OF_MODIFIER_KEY_ALT & mod) == OF_MODIFIER_KEY_ALT)
		return (GetKeyState( VK_MENU ) & 0x80) > 0;

	else if ((OF_MODIFIER_KEY_SHIFT & mod) == OF_MODIFIER_KEY_SHIFT)
		return (GetKeyState( VK_SHIFT ) & 0x80) > 0;

	else if ((OF_MODIFIER_KEY_SPECIAL & mod) == OF_MODIFIER_KEY_SPECIAL)
		return (GetKeyState( VK_LWIN ) & 0x80) > 0 || (GetKeyState( VK_RWIN ) & 0x80) > 0;

	return false;
}

#endif


text:
using CarManiacs.Business.Models.Projects;
using CarManiacs.Business.Models.Users;
using CarManiacs.Business.Services.Contracts;
using CarManiacs.WebClient.Models;
using Moq;
using NUnit.Framework;
using System;
using TestStack.FluentMVCTesting;

namespace CarManiacs.WebClient.UnitTests.ProjectsController
{
    [TestFixture]
    public class Details_Should
    {
        [Test]
        public void ReturnHttpNotFound_WhenUserFromRepoIsNull()
        {
            // Arrange
            var regularUserServiceMock = new Mock<IRegularUserService>();
            var projectServiceMock = new Mock<IProjectService>();
            var projectsController = new WebClient.Controllers.ProjectsController(projectServiceMock.Object, regularUserServiceMock.Object);
            Project projectFromService = null;
            var projectId = Guid.NewGuid();
            projectServiceMock.Setup(m => m.GetById(projectId)).Returns(projectFromService);

            //Act & Assert
            projectsController
                .WithCallTo(c => c.Details(projectId))
                .ShouldGiveHttpStatus(404);
        }
    }
}


text:
body { background-color: #1a1a1a; margin:0; padding:0; overflow: hidden; height:100%; width: 100%; }
	@font-face {
        font-family: 'ConsolasRegular';
        src: url('../font/consolas/consolas-webfont.eot');
        src: url('../font/consolas/consolas-webfont.eot?#iefix') format('embedded-opentype'),
             url('../font/consolas/consolas-webfont.woff') format('woff'),
             url('../font/consolas/consolas-webfont.ttf') format('truetype'),
             url('../font/consolas/consolas-webfont.svg#ConsolasRegular') format('svg');
        font-weight: normal;
        font-style: normal;
    }
	a { text-decoration:none; }


text:
import evdev

def list_devices():
    yield "foo"
    yield "badge_scanner"

class InputDevice(object):
    """Behaves (slightly) like an evdev device for testing other code."""

    def __init__(self, name):
        self.name = name

    def grab(self):
        pass

    def read_loop(self):
        """Always yields events that should type '8:8<ENTER>'."""
        # TODO: Make this more easily customizable, and catch where it would hang
        # because there are no events [either reading the wrong device, or reading a
        # second time]
        if self.name == "badge_scanner":
            for ev in self.type_eight():
                yield ev
            for ev in self.type_colon():
                yield ev
            for ev in self.type_eight():
                yield ev
            for ev in self.type_enter():
                yield ev

    # These were all found by logging what evdev does on Ubuntu; the timestamps
    # have been replaced with zeroes to make this more readable since we currently
    # don't use them for anything.
    def type_eight(self):
        yield evdev.events.InputEvent(0, 0, 4, 4, 458789)
        yield evdev.events.InputEvent(0, 0, 1, 9, 1)
        yield evdev.events.InputEvent(0, 0, 0, 0, 0)
        yield evdev.events.InputEvent(0, 0, 4, 4, 458789)
        yield evdev.events.InputEvent(0, 0, 1, 9, 0)
        yield evdev.events.InputEvent(0, 0, 0, 0, 0)

    def type_colon(self):
        yield evdev.events.InputEvent(0, 0, 4, 4, 458977)
        yield evdev.events.InputEvent(0, 0, 1, 42, 1)
        yield evdev.events.InputEvent(0, 0, 4, 4, 458803)
        yield evdev.events.InputEvent(0, 0, 1, 39, 1)
        yield evdev.events.InputEvent(0, 0, 0, 0, 0)
        yield evdev.events.InputEvent(0, 0, 4, 4, 458977)
        yield evdev.events.InputEvent(0, 0, 1, 42, 0)
        yield evdev.events.InputEvent(0, 0, 4, 4, 458803)
        yield evdev.events.InputEvent(0, 0, 1, 39, 0)
        yield evdev.events.InputEvent(0, 0, 0, 0, 0)

    def type_enter(self):
        yield evdev.events.InputEvent(0, 0, 4, 4, 458792)
        yield evdev.events.InputEvent(0, 0, 1, 28, 1)
        yield evdev.events.InputEvent(0, 0, 0, 0, 0)
        yield evdev.events.InputEvent(0, 0, 4, 4, 458792)
        yield evdev.events.InputEvent(0, 0, 1, 28, 0)
        yield evdev.events.InputEvent(0, 0, 0, 0, 0)


text:
#include "networklistmodel.h"
#include "debug.h"

const QString NetworkListModel::availTechs("AvailableTechnologies");
const QString NetworkListModel::enablTechs("EnabledTechnologies");
const QString NetworkListModel::connTechs("ConnectedTechnologies");
const QString NetworkListModel::OfflineMode("OfflineMode");
const QString NetworkListModel::DefaultTechnology("DefaultTechnology");
const QString NetworkListModel::State("State");

NetworkListModel* NetworkListModel::instance()
{
  static NetworkListModel *that = NULL;

  if (!that) {
    that = new NetworkListModel();
  }
  return that;
}

NetworkListModel::NetworkListModel()
  : QAbstractTableModel(),
    m_manager(NULL),
    m_getPropertiesWatcher(NULL),
    m_connectServiceWatcher(NULL)
{
  m_headerData.append("NetworkItemModel");
  m_headerData.append("Type");
  connectToConnman();
  startTimer(60000);
}

NetworkListModel::~NetworkListModel()
{
}

int NetworkListModel::rowCount(const QModelIndex &parent) const
{
  Q_UNUSED(parent);
  return m_networks.size();
}

int NetworkListModel::columnCount(const QModelIndex &parent) const
{
  Q_UNUSED(parent);
  return m_headerData.size();
}

QVariant NetworkListModel::headerData(int section, Qt::Orientation orientation, int role) const
{
  Q_UNUSED(orientation);
  if (role == Qt::DisplayRole) {
    if (section < m_headerData.size()) {
      return QVariant(m_headerData.at(section));
    }
  }
  return QVariant();
}

QVariant NetworkListModel::data(const QModelIndex &index, int role) const
{
  //MDEBUG("NetworkListModel::data");
  if (role == Qt::DisplayRole) {
    //MDEBUG("index is at: %d, %d", index.row(), index.column());
    if(index.isValid() && index.row() < m_networks.size()) {
      Q_ASSERT(m_networks[index.row()]);
      if (0 == index.column()) {
	return qVariantFromValue(qobject_cast<QObject*>(m_networks[index.row()]));
      } else if (1 == index.column()) {
	m_networks[index.row()]->dump();
	return QVariant(m_networks[index.row()]->type());
      } else {
	MDEBUG("column %d is out of range", index.column());
      }
    } else {
      MDEBUG("row is out of range, but index is valid");
    }
  } else {
    MDEBUG("role is not display role");
  }
  return QVariant();
}

void NetworkListModel::enableTechnology(const QString &technology)
{
  MDEBUG("enabling technology \"%s\"", STR(technology));
  m_manager->EnableTechnology(technology);
}

void NetworkListModel::disableTechnology(const QString &technology)
{
  m_manager->DisableTechnology(technology);
}

void NetworkListModel::connectService(const QString &name, const QString &security,
				      const QString &passphrase)
{
  Q_ASSERT(m_manager);

  MDEBUG("name: %s", STR(name));
  MDEBUG("security: %s", STR(security));
  MDEBUG("passphrase: %s", STR(passphrase));

  QVariantMap dict;
  dict.insert(QString("Type"), QVariant(QString("wifi")));
  dict.insert(QString("SSID"), QVariant(name));
  dict.insert(QString("Mode"), QVariant(QString("managed")));
  dict.insert(QString("Security"), QVariant(security));
  if (security != QString("none")) {
    dict.insert(QString("Passphrase"), QVariant(passphrase));
  }

  QDBusPendingReply<QDBusObjectPath> reply = m_manager->ConnectService(dict);
  m_connectServiceWatcher = new QDBusPendingCallWatcher(reply, m_manager);
  connect(m_connectServiceWatcher, SIGNAL(finished(QDBusPendingCallWatcher*)),
	  this,
	  SLOT(connectServiceReply(QDBusPendingCallWatcher*)));
}

const QStringList NetworkListModel::availableTechnologies() const
{
  return qdbus_cast<QStringList>
    (m_propertiesCache[NetworkListModel::availTechs]);
}

const QStringList NetworkListModel::enabledTechnologies() const
{
  return qdbus_cast<QStringList>
      (m_propertiesCache[NetworkListModel::enablTechs]);
}

const QStringList NetworkListModel::connectedTechnologies() const
{
  return qdbus_cast<QStringList>
      (m_propertiesCache[NetworkListModel::connTechs]);
}

void NetworkListModel::connectToConnman()
{
  disconnectFromConnman();
  m_manager = new Manager("org.moblin.connman", "/",
			  QDBusConnection::systemBus(),
			  this);
  if (!m_manager->isValid()) {
    //This shouldn't happen
  //  DCP_CRITICAL("manager is invalid");
    delete m_manager;
  } else {
    QDBusPendingReply<QVariantMap> reply = m_manager->GetProperties();
    m_getPropertiesWatcher = new QDBusPendingCallWatcher(reply, m_manager);
    connect(m_getPropertiesWatcher,
	    SIGNAL(finished(QDBusPendingCallWatcher*)),
	    this,
	    SLOT(getPropertiesReply(QDBusPendingCallWatcher*)));

  }
}

void NetworkListModel::disconnectFromConnman()
{
  if (m_manager) {
    delete m_manager; //we think that m_getPropertiesWatcher will be
		      //deleted due to m_manager getting deleted
    beginResetModel();
    m_manager = NULL;
    foreach(NetworkItemModel *pNIM, m_networks) {
      pNIM->decreaseReferenceCount();
    }
    m_networks.clear();
    endResetModel();
  }
}

void NetworkListModel::getPropertiesReply(QDBusPendingCallWatcher *call)
{
  Q_ASSERT(call);
  QDBusPendingReply<QVariantMap> reply = *call;
  if (reply.isError()) {
    disconnectFromConnman();
    //TODO set up timer to reconnect in a bit
  } else {
    m_propertiesCache = reply.value();
    QList<QDBusObjectPath> services =
      qdbus_cast<QList<QDBusObjectPath> >(m_propertiesCache["Services"]);
    beginInsertRows(QModelIndex(), 0, services.count());
    foreach (QDBusObjectPath p, services) {
   //   DCP_CRITICAL( QString("service path:\t%1").arg(p.path()).toAscii());
      NetworkItemModel *pNIM = new NetworkItemModel(p.path(), this);
      connect(pNIM, SIGNAL(modified(const QList<const char *>&)),
	      this, SLOT(networkItemModified(const QList<const char *>&)));
      pNIM->increaseReferenceCount();
      m_networks.append(pNIM);
    }
    endInsertRows();
    connect(m_manager,
	    SIGNAL(PropertyChanged(const QString&, const QDBusVariant&)),
	    this,
	    SLOT(propertyChanged(const QString&, const QDBusVariant&)));
    emitTechnologiesChanged();
    emit defaultTechnologyChanged(m_propertiesCache[DefaultTechnology].toString());
    emit stateChanged(m_propertiesCache[State].toString());
  }
}

void NetworkListModel::connectServiceReply(QDBusPendingCallWatcher *call)
{
  Q_ASSERT(call);
  QDBusPendingReply<QDBusObjectPath> reply = *call;
  if (reply.isError()) {
    QDBusError error = reply.error();
    MDEBUG("ERROR!");
    MDEBUG("message: %s", STR(error.message()));
    MDEBUG("name: %s", STR(error.name()));
    MDEBUG("error type: %s", STR(QDBusError::errorString(error.type())));
  } else {
    QDBusObjectPath p = reply.value();
    MDEBUG("object path: %s", STR(p.path()));
  }
}

void NetworkListModel::propertyChanged(const QString &name,
				       const QDBusVariant &value)
{
  MDEBUG("Property \"%s\" changed", STR(name));
  m_propertiesCache[name] = value.variant();
  if (name == NetworkListModel::availTechs ||
      name == NetworkListModel::enablTechs ||
      name == NetworkListModel::connTechs) {
    emitTechnologiesChanged();
  } else if (name == DefaultTechnology) {
    emit defaultTechnologyChanged(m_propertiesCache[DefaultTechnology].toString());
  } else if (name == State) {
    emit stateChanged(m_propertiesCache[State].toString());
  }else if (name == "Services") {
    QList<QDBusObjectPath> new_services =
      qdbus_cast<QList<QDBusObjectPath> >(value.variant());
    int num_new = new_services.count();
    for (int i = 0; i < num_new; i++) {
      QDBusObjectPath path(new_services[i]);
      int j = findNetworkItemModel(path);
      //DCP_CRITICAL(QString("i=%1 j=%2").arg(i).arg(j).toAscii());
      if (-1 == j) {
	//DCP_CRITICAL(QString("couldn't find service %1 in existing networks").arg(path.path()).toAscii());
	beginInsertRows(QModelIndex(), i, i+1);

	NetworkItemModel *pNIM = new NetworkItemModel(path.path());
	pNIM->increaseReferenceCount();
	m_networks.insert(i, pNIM);

	endInsertRows();
      } else {
	if (i != j) { //only move if from and to aren't the same
	  beginMoveRows(QModelIndex(), j, j, QModelIndex(), i);

	  //DCP_CRITICAL(QString("%1 (position %2) appears in the list of old networks at position %3").arg(path.path()).arg(i).arg(j).toAscii());
	  NetworkItemModel *pNIM = m_networks[j];
	  Q_ASSERT(pNIM);
	  m_networks.remove(j);
	  m_networks.insert(i, pNIM);
	  endMoveRows();
	}
      }
    }
    int num_old = m_networks.count();
    if (num_old > num_new) {
      //DCP_CRITICAL(QString("num old: %1  num new: %2").arg(num_old).arg(num_new).toAscii());
      //DCP_CRITICAL(QString("we have %1 networks to remove").arg(num_old - num_new).toAscii());
      beginRemoveRows(QModelIndex(), num_new, num_old - 1);

      for (int i = num_new; i < num_old; i++) {
	//DCP_CRITICAL(QString("removing network %1").arg(m_networks[i]->servicePath()).toAscii());
	m_networks[i]->decreaseReferenceCount();
      }
      m_networks.remove(num_new, num_old - num_new);

      endRemoveRows();
    }
  } else if (name == OfflineMode) {
    m_propertiesCache[OfflineMode] = value.variant();
    emit offlineModeChanged(m_propertiesCache[OfflineMode].toBool());
  }
}

 void NetworkListModel::networkItemModified(const QList<const char *> &members)
 {
   //this is a gross hack to keep from doing things again and again we
   //only really care for the sake of the model when the type changes
   //the type changes as a result from the initial getProperties call
   //on the service object after we get the service object paths from
   //the Manager in getProperties
   if (members.contains(NetworkItemModel::Type))
     {
       int row = m_networks.indexOf(static_cast<NetworkItemModel*>(sender()));
       Q_ASSERT(row != -1);
       emit dataChanged(createIndex(row, 0), createIndex(row, 1));
     }
 }

int NetworkListModel::findNetworkItemModel(const QDBusObjectPath &path) const
{
  for (int i= 0; i < m_networks.count(); i++) {
    if (m_networks[i]->servicePath() == path.path()) return i;
  }
  return -1;
}

 void NetworkListModel::emitTechnologiesChanged()
 {
   const QStringList availableTechnologies = qdbus_cast<QStringList>
     (m_propertiesCache[NetworkListModel::availTechs]);
   const QStringList enabledTechnologies = qdbus_cast<QStringList>
     (m_propertiesCache[NetworkListModel::enablTechs]);
   const QStringList connectedTechnologies = qdbus_cast<QStringList>
     (m_propertiesCache[NetworkListModel::connTechs]);
   qDebug() << availTechs << ": " << m_propertiesCache[NetworkListModel::availTechs];
   qDebug() << enablTechs << ": " << m_propertiesCache[NetworkListModel::enablTechs];
   qDebug() << connTechs << ": " << m_propertiesCache[NetworkListModel::connTechs];
   emit technologiesChanged(availableTechnologies,
			    enabledTechnologies,
			    connectedTechnologies);
 }

void NetworkListModel::timerEvent(QTimerEvent *event)
{
  Q_UNUSED(event);
//  DCP_CRITICAL("Dumping list of networks");
  foreach(NetworkItemModel* pNIM, m_networks) {
    pNIM->dump();
  }
}

void NetworkListModel::requestScan()
{
  const QString wifi("wifi");
  m_manager->RequestScan(wifi);
  //FIXME: error returns, etc
}

void NetworkListModel::setOfflineMode(const bool &offlineMode)
{
  Q_ASSERT(m_manager);

    QDBusPendingReply<void> reply =
      m_manager->SetProperty(OfflineMode, QDBusVariant(QVariant(offlineMode)));

#if 0 //It is fundamentally broken to wait here and it doesn't even do
      //anything but crash the app
    reply.waitForFinished();
    if (reply.isError()) {
      MDEBUG("got error from setProperty");
      throw -1;
    }
#endif
}

bool NetworkListModel::offlineMode() const
{
  return m_propertiesCache[OfflineMode].toBool();
}

QString NetworkListModel::defaultTechnology() const
{
  return m_propertiesCache[DefaultTechnology].toString();
}

QString NetworkListModel::state() const
{
  return m_propertiesCache[State].toString();
}


text:
<?php

namespace Google\Cloud\Translate\Connection;

use Google\Cloud\Core\RequestBuilder;
use Google\Cloud\Core\RequestWrapper;
use Google\Cloud\Core\RestTrait;
use Google\Cloud\Core\UriTrait;
use Google\Cloud\Translate\TranslateClient;

/**
 * Implementation of the
 * [Google Cloud Translation REST API](https://cloud.google.com/translation/docs/how-to).
 */
class Rest implements ConnectionInterface
{
    use RestTrait;
    use UriTrait;

    const BASE_URI = 'https://translation.googleapis.com/language/translate/';

    /**
     * @param array $config
     */
    public function __construct(array $config = [])
    {
        $config += [
            'serviceDefinitionPath' => __DIR__ . '/ServiceDefinition/translate-v2.json',
            'componentVersion' => TranslateClient::VERSION
        ];

        $this->setRequestWrapper(new RequestWrapper($config));
        $this->setRequestBuilder(new RequestBuilder(
            $config['serviceDefinitionPath'],
            self::BASE_URI
        ));
    }

    /**
     * @param array $args
     * @return array
     */
    public function listDetections(array $args = [])
    {
        return $this->send('detections', 'list', $args);
    }

    /**
     * @param array $args
     * @return array
     */
    public function listLanguages(array $args = [])
    {
        return $this->send('languages', 'list', $args);
    }

    /**
     * @param array $args
     * @return array
     */
    public function listTranslations(array $args = [])
    {
        return $this->send('translations', 'list', $args);
    }
}


text:
<<<<<<< HEAD
=======
// # Task automation for Ghost
//
// Run various tasks when developing for and working with Ghost.
//
// **Usage instructions:** can be found in the [Custom Tasks](#custom%20tasks) section or by running `grunt --help`.
//
// **Debug tip:** If you have any problems with any Grunt tasks, try running them with the `--verbose` command
>>>>>>> 09e03f4d78d17b2d1b1b3f452aff6933cd7cf1f6
var path           = require('path'),
    colors         = require('colors'),
    fs             = require('fs'),
<<<<<<< HEAD
    _              = require('underscore'),
    spawn          = require('child_process').spawn,
    buildDirectory = path.resolve(process.cwd(), '.build'),
    distDirectory  = path.resolve(process.cwd(), '.dist'),
    configLoader   = require('./core/config-loader.js'),
=======
    _              = require('lodash'),
    buildDirectory = path.resolve(process.cwd(), '.build'),
    distDirectory  = path.resolve(process.cwd(), '.dist'),
    bootstrap      = require('./core/bootstrap'),
>>>>>>> 09e03f4d78d17b2d1b1b3f452aff6933cd7cf1f6

    // ## Build File Patterns
    // A list of files and patterns to include when creating a release zip.
    // This is read from the `.npmignore` file and all patterns are inverted as the `.npmignore`
    // file defines what to ignore, whereas we want to define what to include.
    buildGlob = (function () {
        /*jslint stupid:true */
        return fs.readFileSync('.npmignore', {encoding: 'utf8'}).split('\n').map(function (pattern) {
            if (pattern[0] === '!') {
                return pattern.substr(1);
            }
            return '!' + pattern;
        });
    }()),

    configureGrunt = function (grunt) {

<<<<<<< HEAD
        // load all grunt tasks
        require('matchdep').filterDev('grunt-*').forEach(grunt.loadNpmTasks);
=======
        // *This is not useful but required for jshint*
        colors.setTheme({silly: 'rainbow'});

        // #### Load all grunt tasks
        //
        // Find all of the task which start with `grunt-` and load them, rather than explicitly declaring them all
        require('matchdep').filterDev(['grunt-*', '!grunt-cli']).forEach(grunt.loadNpmTasks);
>>>>>>> 09e03f4d78d17b2d1b1b3f452aff6933cd7cf1f6

        var cfg = {
            // #### Common paths used by tasks
            paths: {
                build: buildDirectory,
                nightlyBuild: path.join(buildDirectory, 'nightly'),
                weeklyBuild: path.join(buildDirectory, 'weekly'),
                buildBuild: path.join(buildDirectory, 'build'),
                dist: distDirectory,
                nightlyDist: path.join(distDirectory, 'nightly'),
                weeklyDist: path.join(distDirectory, 'weekly'),
                buildDist: path.join(distDirectory, 'build'),
                releaseDist: path.join(distDirectory, 'release')
            },
            // Standard build type, for when we have nightlies again.
            buildType: 'Build',
            // Load package.json so that we can create correctly versioned releases.
            pkg: grunt.file.readJSON('package.json'),

<<<<<<< HEAD
            // Watch files and livereload in the browser during development
=======
            // ### grunt-contrib-watch
            // Watch files and livereload in the browser during development.
            // See the [grunt dev](#live%20reload) task for how this is used.
>>>>>>> 09e03f4d78d17b2d1b1b3f452aff6933cd7cf1f6
            watch: {
                shared: {
                    files: ['core/shared/**/*.js'],
                    tasks: ['concat:dev']
                },
                'emberTemplates': {
                    files: ['core/client/**/*.hbs'],
                    tasks: ['emberTemplates:dev']
                },
                ember: {
                    files: ['core/client/**/*.js'],
                    tasks: ['clean:tmp', 'transpile', 'concat_sourcemap']
                },
                'ghost-ui': {
                    files: [
                        'bower_components/ghost-ui/dist/css/*.css'
                    ],
                    tasks: ['copy:dev']
                },
                livereload: {
                    files: [
                        'content/themes/casper/css/*.css',
                        'content/themes/casper/js/*.js',
                        'core/client/assets/css/*.css',
                        'core/built/scripts/*.js'
                    ],
                    options: {
                        livereload: true
                    }
                },
                express: {
                    files:  ['core/server.js', 'core/server/**/*.js'],
                    tasks:  ['express:dev'],
                    options: {
                        // **Note:** Without this option specified express won't be reloaded
                        nospawn: true
                    }
                }
            },

<<<<<<< HEAD
            // Start our server in development
=======
            // ### grunt-express-server
            // Start a Ghost expess server for use in development and testing
>>>>>>> 09e03f4d78d17b2d1b1b3f452aff6933cd7cf1f6
            express: {
                options: {
                    script: 'index.js'
                },

                dev: {
                    options: {}
                },
                test: {
                    options: {
                        node_env: 'testing'
                    }
                }
            },

            // ### grunt-contrib-jshint
            // Linting rules, run as part of `grunt validate`. See [grunt validate](#validate) and its subtasks for
            // more information.
            jshint: {
                // Linting rules for server side or shared javascript code
                server: {
                    options: {
                        jshintrc: '.jshintrc'
                    },
                    files: {
                        src: [
                            '*.js',
                            'core/*.js',
                            'core/server/**/*.js',
                            'core/shared/**/*.js',
                            '!core/shared/vendor/**/*.js',
                            '!core/shared/lib/**/*.js'
                        ]
                    }
                },
                // Linting rules for client side javascript code
                client: {
                    options: {
                        jshintrc: 'core/client/.jshintrc'
                    },
                    files: {
                        src: [
                            'core/client/**/*.js',
                            '!core/client/assets/vendor/**/*.js',
                            '!core/client/tpl/**/*.js'
                        ]
                    }
                }
            },

<<<<<<< HEAD
=======
            // ### grunt-mocha-cli
            // Configuration for the mocha test runner, used to run unit, integration and route tests as part of
            // `grunt validate`. See [grunt validate](#validate) and its sub tasks for more information.
>>>>>>> 09e03f4d78d17b2d1b1b3f452aff6933cd7cf1f6
            mochacli: {
                options: {
                    ui: 'bdd',
                    reporter: 'spec',
                    timeout: '15000'
                },

<<<<<<< HEAD
                all: {
                    src: ['core/test/unit/**/*_spec.js']
                },

                api: {
                    src: ['core/test/unit/**/api*_spec.js']
                },

                client: {
                    src: ['core/test/unit/**/client*_spec.js']
                },

=======
                // #### All Unit tests
                unit: {
                    src: ['core/test/unit/**/*_spec.js']
                },

                // ##### Groups of unit tests
>>>>>>> 09e03f4d78d17b2d1b1b3f452aff6933cd7cf1f6
                server: {
                    src: ['core/test/unit/**/server*_spec.js']
                },

                showdown: {
                    src: ['core/test/unit/**/showdown*_spec.js']
                },

                perm: {
                    src: ['core/test/unit/**/permissions_spec.js']
                },

                migrate: {
                    src: [
                        'core/test/unit/**/export_spec.js',
                        'core/test/unit/**/import_spec.js'
                    ]
                },

                storage: {
                    src: ['core/test/unit/**/storage*_spec.js']
                },

                // #### All Integration tests
                integration: {
                    src: [
                        'core/test/integration/**/model*_spec.js',
                        'core/test/integration/**/api*_spec.js',
                        'core/test/integration/*_spec.js'
                    ]
                },

                // ##### Model integration tests
                model: {
                    src: ['core/test/integration/**/model*_spec.js']
                },

                // ##### API integration tests
                api: {
                    src: ['core/test/integration/**/api*_spec.js']
                },

                // #### All Route tests
                routes: {
                    src: ['core/test/functional/routes/**/*_test.js']
                }
            },

<<<<<<< HEAD

=======
            // ### grunt-shell
            // Command line tools where it's easier to run a command directly than configure a grunt plugin
>>>>>>> 09e03f4d78d17b2d1b1b3f452aff6933cd7cf1f6
            shell: {
                // #### Run bower install
                // Used as part of `grunt init`. See the section on [Building Assets](#building%20assets) for more
                // information.
                bower: {
                    command: path.resolve(__dirname.replace(' ', '\\ ') + '/node_modules/.bin/bower install'),
                    options: {
                        stdout: true
                    }
                },
                // #### Generate coverage report
                // See the `grunt test-coverage` task in the section on [Testing](#testing) for more information.
                coverage: {
                    command: function () {
                        // **Note:** will only work on windows if mocha is globally installed
                        var cmd = !!process.platform.match(/^win/) ? 'mocha' : './node_modules/mocha/bin/mocha';
                        return cmd +
                            ' --timeout 15000 --reporter html-cov > coverage.html ./core/test/blanket_coverage.js';
                    },
                    execOptions: {
                        env: 'NODE_ENV=' + process.env.NODE_ENV
                    }
                }
            },

<<<<<<< HEAD
            handlebars: {
                core: {
=======
            // ### grunt-ember-templates
            // Compiles handlebar templates for ember
            emberTemplates: {
                dev: {
>>>>>>> 09e03f4d78d17b2d1b1b3f452aff6933cd7cf1f6
                    options: {
                        templateBasePath: /core\/client\//,
                        templateFileExtensions: /\.hbs/,
                        templateRegistration: function (name, template) {
                            return grunt.config.process('define(\'ghost/') +
                                name + '\', [\'exports\'], function(__exports__){ __exports__[\'default\'] = ' +
                                template + '; });';
                        }
                    },
                    files: {
                        'core/built/scripts/templates-ember.js': 'core/client/templates/**/*.hbs'
                    }
                }
            },

            // ### grunt-es6-module-transpiler
            // Compiles Ember es6 modules
            transpile: {
                client: {
                    type: 'amd',
                    moduleName: function (path) {
                        return 'ghost/' + path;
                    },
                    files: [{
                        expand: true,
                        cwd: 'core/client/',
                        src: ['**/*.js'],
                        dest: '.tmp/ember-transpiled/'
                    }]
                }
            },

            // ### grunt-es6-module-transpiler
            // Compiles Ember es6 modules
            concat_sourcemap: {
                client: {
                    src: ['.tmp/ember-transpiled/**/*.js'],
                    dest: 'core/built/scripts/ghost-dev-ember.js',
                    options: {
                        sourcesContent: true
                    }
                }
            },

<<<<<<< HEAD
            groc: {
=======
            // ### grunt-docker
            // Generate documentation from code
            docker: {
>>>>>>> 09e03f4d78d17b2d1b1b3f452aff6933cd7cf1f6
                docs: {
                    dest: 'docs',
                    src: ['.'],
                    options: {
                        onlyUpdated: true,
                        exclude: 'node_modules,.git,.tmp,bower_components,content,*built,*test,*doc*,*vendor,' +
                            'config.js,coverage.html,.travis.yml,*.min.css,screen.css',
                        extras: ['fileSearch']
                    }
                }
            },

<<<<<<< HEAD
            clean: {
                build: {
                    src: ['<%= paths.buildBuild %>/**']
=======
            // ### grunt-contrib-clean
            // Clean up files as part of other tasks
            clean: {
                built: {
                    src: ['core/built/**']
                },
                release: {
                    src: ['<%= paths.releaseBuild %>/**']
>>>>>>> 09e03f4d78d17b2d1b1b3f452aff6933cd7cf1f6
                },
                test: {
                    src: ['content/data/ghost-test.db']
                },
                tmp: {
                    src: ['.tmp/**']
                }
            },

<<<<<<< HEAD
=======
            // ### grunt-contrib-copy
            // Copy files into their correct locations as part of building assets, or creating release zips
>>>>>>> 09e03f4d78d17b2d1b1b3f452aff6933cd7cf1f6
            copy: {
                dev: {
                    files: [{
                        cwd: 'bower_components/jquery/dist/',
                        src: 'jquery.js',
                        dest: 'core/built/public/',
                        expand: true
                    }, {
                        cwd: 'bower_components/ghost-ui/dist/',
                        src: ['**'],
                        dest: 'core/client/assets/',
                        expand: true
                    }]
                },
                prod: {
                    files: [{
                        cwd: 'bower_components/jquery/dist/',
                        src: 'jquery.js',
                        dest: 'core/built/public/',
                        expand: true
                    }, {
                        cwd: 'bower_components/ghost-ui/dist/',
                        src: ['**'],
                        dest: 'core/client/assets/',
                        expand: true
                    }]
                },
                release: {
                    files: [{
                        cwd: 'bower_components/jquery/dist/',
                        src: 'jquery.js',
                        dest: 'core/built/public/',
                        expand: true
                    }, {
                        cwd: 'bower_components/ghost-ui/dist/',
                        src: ['**'],
                        dest: 'core/client/assets/',
                        expand: true
                    }, {
                        expand: true,
                        src: buildGlob,
                        dest: '<%= paths.buildBuild %>/'
                    }]
                }
            },

<<<<<<< HEAD
=======
            // ### grunt-contrib-compress
            // Zip up files for builds / releases
>>>>>>> 09e03f4d78d17b2d1b1b3f452aff6933cd7cf1f6
            compress: {
                nightly: {
                    options: {
                        archive: '<%= paths.nightlyDist %>/Ghost-Nightly-<%= pkg.version %>.zip'
                    },
                    expand: true,
                    cwd: '<%= paths.nightlyBuild %>/<%= pkg.version %>/',
                    src: ['**']
                },
                weekly: {
                    options: {
                        archive: '<%= paths.weeklyDist %>/Ghost-Weekly-<%= pkg.version %>.zip'
                    },
                    expand: true,
                    cwd: '<%= paths.weeklyBuild %>/<%= pkg.version %>/',
                    src: ['**']
                },
                build: {
                    options: {
                        archive: '<%= paths.buildDist %>/Ghost-Build.zip'
                    },
                    expand: true,
                    cwd: '<%= paths.buildBuild %>/',
                    src: ['**']
                },
                release: {
                    options: {
                        archive: '<%= paths.releaseDist %>/Ghost-<%= pkg.version %>.zip'
                    },
                    expand: true,
                    cwd: '<%= paths.buildBuild %>/',
                    src: ['**']
                }
            },

<<<<<<< HEAD
            bump: {
                options: {
                    tagName: '%VERSION%',
                    commitMessage: '<%= buildType %> Release %VERSION%',
                    tagMessage: '<%= buildType %> Release %VERSION%',
                    pushTo: 'origin build'
                }
            },

=======
            // ### grunt-contrib-concat
            // concatenate multiple JS files into a single file ready for use
>>>>>>> 09e03f4d78d17b2d1b1b3f452aff6933cd7cf1f6
            concat: {
                'dev': {
                    nonull: true,
                    dest: 'core/built/scripts/vendor-ember.js',
                    src: [
                        'bower_components/loader.js/loader.js',
                        'bower_components/jquery/dist/jquery.js',
                        'bower_components/lodash/dist/lodash.js',
                        'bower_components/handlebars/handlebars.js',
                        'bower_components/ember/ember.js',
                        'bower_components/ember-data/ember-data.js',
                        'bower_components/ember-resolver/dist/ember-resolver.js',
                        'bower_components/ic-ajax/dist/globals/main.js',
                        'bower_components/ember-load-initializers/ember-load-initializers.js',
                        'bower_components/validator-js/validator.js',
                        'bower_components/codemirror/lib/codemirror.js',
                        'bower_components/codemirror/addon/mode/overlay.js',
                        'bower_components/codemirror/mode/markdown/markdown.js',
                        'bower_components/codemirror/mode/gfm/gfm.js',
                        'bower_components/showdown/src/showdown.js',
                        'bower_components/moment/moment.js',
                        'bower_components/keymaster/keymaster.js',
                        'bower_components/device/lib/device.js',
                        'bower_components/jquery-ui/ui/jquery-ui.js',
                        'bower_components/jquery-file-upload/js/jquery.fileupload.js',
                        'bower_components/fastclick/lib/fastclick.js',
                        'bower_components/nprogress/nprogress.js',
                        'bower_components/ember-simple-auth/ember-simple-auth.js',
                        'bower_components/ember-simple-auth/ember-simple-auth-oauth2.js',

                        'core/shared/lib/showdown/extensions/ghostimagepreview.js',
                        'core/shared/lib/showdown/extensions/ghostgfm.js'
                    ]
                }
            },

<<<<<<< HEAD
=======
            // ### grunt-contrib-uglify
            // Minify concatenated javascript files ready for production
>>>>>>> 09e03f4d78d17b2d1b1b3f452aff6933cd7cf1f6
            uglify: {
                prod: {
                    files: {
                        'core/built/public/jquery.min.js': 'core/built/public/jquery.js'
                    }
                }
            },

            // ### grunt-update-submodules
            // Grunt task to update git submodules
            'update_submodules': {
                default: {
                    options: {
                        params: '--init'
                    }
                }
            }
        };

        // Load the configuration
        grunt.initConfig(cfg);

<<<<<<< HEAD
        grunt.registerTask('setTestEnv', 'Use "testing" Ghost config; unless we are running on travis (then show queries for debugging)', function () {
            process.env.NODE_ENV = process.env.TRAVIS ? 'travis' : 'testing';
        });

        grunt.registerTask('loadConfig', function () {
            var done = this.async();
            configLoader.loadConfig().then(function () {
                done();
            });
        });

        grunt.registerTask('updateCurrentPackageInfo', 'Update the package information after changes', function () {
            cfg.pkg = grunt.file.readJSON('package.json');
        });

        grunt.registerTask('setCurrentBuildType', function (type) {
            cfg.buildType = type;
        });

        grunt.registerTask('spawn-casperjs', function () {
=======
        // ## Utilities
        //
        // ### Spawn Casper.js
        // Custom test runner for our Casper.js functional tests
        // This really ought to be refactored into a separate grunt task module
        grunt.registerTask('spawnCasperJS', function (target) {

            target = _.contains(['client', 'frontend'], target) ? target + '/' : undefined;

>>>>>>> 09e03f4d78d17b2d1b1b3f452aff6933cd7cf1f6
            var done = this.async(),
                options = ['host', 'noPort', 'port', 'email', 'password'],
                args = ['test']
                    .concat(grunt.option('target') || target || ['client/', 'frontend/'])
                    .concat(['--includes=base.js', '--log-level=debug', '--port=2369']);

            // Forward parameters from grunt to casperjs
            _.each(options, function processOption(option) {
                if (grunt.option(option)) {
                    args.push('--' + option + '=' + grunt.option(option));
                }
            });

            if (grunt.option('fail-fast')) {
                args.push('--fail-fast');
            }

            // Show concise logs in Travis as ours are getting too long
            if (grunt.option('concise') || process.env.TRAVIS) {
                args.push('--concise');
            } else {
                args.push('--verbose');
            }

            grunt.util.spawn({
                cmd: 'casperjs',
                args: args,
                opts: {
                    cwd: path.resolve('core/test/functional'),
                    stdio: 'inherit'
                }
            }, function (error, result, code) {
                /*jshint unused:false*/
                if (error) {
                    grunt.fail.fatal(result.stdout);
                }
                grunt.log.writeln(result.stdout);
                done();
            });
        });

        // # Custom Tasks

        // Ghost has a number of useful tasks that we use every day in development. Tasks marked as *Utility* are used
        // by grunt to perform current actions, but isn't useful to developers.
        //
        // Skip ahead to the section on:
        //
        // * [Building assets](#building%20assets):
        //     `grunt init`, `grunt` & `grunt prod` or live reload with `grunt dev`
        // * [Testing](#testing):
        //     `grunt validate`, the `grunt test-*` sub-tasks or generate a coverage report with `grunt test-coverage`.

        // ### Help
        // Run `grunt help` on the commandline to get a print out of the available tasks and details of
        // what each one does along with any available options. This is an alias for `grunt --help`
        grunt.registerTask('help',
            'Outputs help information if you type `grunt help` instead of `grunt --help`',
            function () {
                console.log('Type `grunt --help` to get the details of available grunt tasks, ' +
                    'or alternatively visit https://github.com/TryGhost/Ghost/wiki/Grunt-Toolkit');
            });

        // ### Documentation
        // Run `grunt docs` to generate annotated source code using the documentation described in the code comments.
        grunt.registerTask('docs', 'Generate Docs', ['docker']);

        // ## Testing

        // Ghost has an extensive set of test suites. The following section documents the various types of tests
        // and how to run them.
        //
        // TLDR; run `grunt validate`

        // #### Set Test Env *(Utility Task)*
        // Set the NODE_ENV to 'testing' unless the environment is already set to TRAVIS.
        // This ensures that the tests get run under the correct environment, using the correct database, and
        // that they work as expected. Trying to run tests with no ENV set will throw an error to do with `client`.
        grunt.registerTask('setTestEnv',
            'Use "testing" Ghost config; unless we are running on travis (then show queries for debugging)',
            function () {
                process.env.NODE_ENV = process.env.TRAVIS ? process.env.NODE_ENV : 'testing';
                cfg.express.test.options.node_env = process.env.NODE_ENV;
            });

        // #### Load Config *(Utility Task)*
        // Make sure that we have a `config.js` file when running tests
        // Ghost requires a `config.js` file to specify the database settings etc. Ghost comes with an example file:
        // `config.example.js` which is copied and renamed to `config.js` by the bootstrap process
        grunt.registerTask('loadConfig', function () {
            var done = this.async();
            bootstrap().then(function () {
                done();
            }).catch(function (err) {
                grunt.fail.fatal(err.stack);
            });
        });

        // ### Validate
        // **Main testing task**
        //
        // `grunt validate` will build, lint and test your local Ghost codebase.
        //
        // `grunt validate` is one of the most important and useful grunt tasks that we have available to use. It
        // manages the build of your environment and then calls `grunt test`
        //
        // `grunt validate` is called by `npm test` and is used by Travis.
        grunt.registerTask('validate', 'Run tests and lint code',
            ['init', 'test']);

        // ### Test
        // **Main testing task**
        //
        // `grunt test` will lint and test your pre-built local Ghost codebase.
        //
        // `grunt test` runs jshint as well as the 4 test suites. See the individual sub tasks below for details of
        // each of the test suites.
        //
        grunt.registerTask('test', 'Run tests and lint code',
            ['jshint', 'test-routes', 'test-unit', 'test-integration', 'test-functional']);

        // ### Unit Tests *(sub task)*
        // `grunt test-unit` will run just the unit tests
        //
        // Provided you already have a `config.js` file, you can run individual sections from
        // [mochacli](#grunt-mocha-cli) by running:
        //
        // `NODE_ENV=testing grunt mochacli:section`
        //
        // If you need to run an individual unit test file, you can do so, providing you have mocha installed globally
        // by using a command in the form:
        //
        // `NODE_ENV=testing mocha --timeout=15000 --ui=bdd --reporter=spec core/test/unit/config_spec.js`
        //
        // Unit tests are run with [mocha](http://visionmedia.github.io/mocha/) using
        // [should](https://github.com/visionmedia/should.js) to describe the tests in a highly readable style.
        // Unit tests do **not** touch the database.
        // A coverage report can be generated for these tests using the `grunt test-coverage` task.
        grunt.registerTask('test-unit', 'Run unit tests (mocha)',
            ['clean:test', 'setTestEnv', 'loadConfig', 'mochacli:unit']);

        // ### Integration tests *(sub task)*
        // `grunt test-integration` will run just the integration tests
        //
        // Provided you already have a `config.js` file, you can run just the model integration tests by running:
        //
        // `NODE_ENV=testing grunt mochacli:model`
        //
        // Or just the api integration tests by running:
        //
        // `NODE_ENV=testing grunt mochacli:api`
        //
        // Integration tests are run with [mocha](http://visionmedia.github.io/mocha/) using
        // [should](https://github.com/visionmedia/should.js) to describe the tests in a highly readable style.
        // Integration tests are different to the unit tests because they make requests to the database.
        //
        // Their purpose is to test that both the api and models behave as expected when the database layer is involved.
        // These tests are run against sqlite3, mysql and pg on travis and ensure that differences between the databases
        // don't cause bugs. At present, pg often fails and is not officially supported.
        //
        // A coverage report can be generated for these tests using the `grunt test-coverage` task.
        grunt.registerTask('test-integration', 'Run integration tests (mocha + db access)',
            ['clean:test', 'setTestEnv', 'loadConfig', 'mochacli:integration']);

        // ### Route tests *(sub task)*
        // `grunt test-routes` will run just the route tests
        //
        // If you need to run an individual route test file, you can do so, providing you have a `config.js` file and
        // mocha installed globally by using a command in the form:
        //
        // `NODE_ENV=testing mocha --timeout=15000 --ui=bdd --reporter=spec core/test/functional/routes/admin_test.js`
        //
        // Route tests are run with [mocha](http://visionmedia.github.io/mocha/) using
        // [should](https://github.com/visionmedia/should.js) and [supertest](https://github.com/visionmedia/supertest)
        // to describe and create the tests.
        //
        // Supertest enables us to describe requests that we want to make, and also describe the response we expect to
        // receive back. It works directly with express, so we don't have to run a server to run the tests.
        //
        // The purpose of the route tests is to ensure that all of the routes (pages, and API requests) in Ghost
        // are working as expected, including checking the headers and status codes received. It is very easy and
        // quick to test many permutations of routes / urls in the system.
        grunt.registerTask('test-routes', 'Run functional route tests (mocha)',
            ['clean:test', 'setTestEnv', 'loadConfig', 'mochacli:routes']);

        // ### Functional tests *(sub task)*
        // `grunt test-functional` will run just the functional tests
        //
        // You can use the `--target` argument to run any individual test file, or the admin or frontend tests:
        //
        // `grunt test-functional --target=admin/editor_test.js` - run just the editor tests
        //
        // `grunt test-functional --target=admin/` - run all of the tests in the admin directory
        //
        // Functional tests are run with [phantom.js](http://phantomjs.org/) and defined using the testing api from
        // [casper.js](http://docs.casperjs.org/en/latest/testing.html).
        //
        // An express server is started with the testing environment set, and then a headless phantom.js browser is
        // used to make requests to that server. The Casper.js API then allows us to describe the elements and
        // interactions we expect to appear on the page.
        //
        // The purpose of the functional tests is to ensure that Ghost is working as is expected from a user perspective
        // including buttons and other important interactions in the admin UI.
        grunt.registerTask('test-functional', 'Run functional interface tests (CasperJS)',
            ['clean:test', 'setTestEnv', 'loadConfig', 'express:test', 'spawnCasperJS', 'express:test:stop']
        );

        // ### Coverage
        // `grunt test-coverage` will generate a report for the Unit and Integration Tests.
        //
        // This is not currently done as part of CI or any build, but is a tool we have available to keep an eye on how
        // well the unit and integration tests are covering the code base.
        // Ghost does not have a minimum coverage level - we're more interested in ensuring important and useful areas
        // of the codebase are covered, than that the whole codebase is covered to a particular level.
        //
        // Key areas for coverage are: helpers and theme elements, apps / GDK, the api and model layers.
        grunt.registerTask('test-coverage', 'Generate unit and integration (mocha) tests coverage report',
            ['clean:test', 'setTestEnv', 'loadConfig', 'shell:coverage']);

        // ## Building assets
        //
        // Ghost's GitHub repository contains the un-built source code for Ghost. If you're looking for the already
        // built release zips, you can get these from the [release page](https://github.com/TryGhost/Ghost/releases) on
        // GitHub or from https://ghost.org/download. These zip files are created using the [grunt release](#release)
        // task.
        //
        // If you want to work on Ghost core, or you want to use the source files from GitHub, then you have to build
        // the Ghost assets in order to make them work.
        //
        // There are a number of grunt tasks available to help with this. Firstly after fetching an updated version of
        // the Ghost codebase, after running `npm install`, you will need to run [grunt init](#init%20assets).
        //
        // For production blogs you will need to run [grunt prod](#production%20assets).
        //
        // For updating assets during development, the tasks [grunt](#default%20asset%20build) and
        // [grunt dev](#live%20reload) are available.
        //

        // #### Master Warning *(Utility Task)*
        // Warns git users not ot use the `master` branch in production.
        // `master` is an unstable branch and shouldn't be used in production as you run the risk of ending up with a
        // database in an unrecoverable state. Instead there is a branch called `stable` which is the equivalent of the
        // release zip for git users.
        grunt.registerTask('master-warn',
            'Outputs a warning to runners of grunt prod, that master shouldn\'t be used for live blogs',
            function () {
                console.log('>', 'Always two there are, no more, no less. A master and a'.red,
                        'stable'.red.bold + '.'.red);
                console.log('Use the', 'stable'.bold, 'branch for live blogs.', 'Never'.bold, 'master!');
            });

        // ### Ember Build *(Utility Task)*
        // All tasks related to building the Ember client code including transpiling ES6 modules and building templates
        grunt.registerTask('emberBuild', 'Build Ember JS & templates for development',
            ['clean:tmp', 'emberTemplates:dev', 'transpile', 'concat_sourcemap']);

        // ### Init assets
        // `grunt init` - will run an initial asset build for you
        //
        // Grunt init runs `bower install` as well as the standard asset build tasks which occur when you run just
        // `grunt`. This fetches the latest client side dependencies, and moves them into their proper homes.
        //
        // This task is very important, and should always be run and when fetching down an updated code base just after
        // running `npm install`.
        //
        // `bower` does have some quirks, such as not running as root. If you have problems please try running
        // `grunt init --verbose` to see if there are any errors.
        grunt.registerTask('init', 'Prepare the project for development',
            ['shell:bower', 'update_submodules', 'default']);

        // ### Production assets
        // `grunt prod` - will build the minified assets used in production.
        //
        // It is otherwise the same as running `grunt`, but is only used when running Ghost in the `production` env.
        grunt.registerTask('prod', 'Build JS & templates for production',
            ['concat', 'uglify', 'copy:prod', 'master-warn']);

        // ### Default asset build
        // `grunt` - default grunt task
        //
        // Compiles concatenates javascript files for the admin UI into a handful of files instead
        // of many files, and makes sure the bower dependencies are in the right place.
        grunt.registerTask('default', 'Build JS & templates for development',
            ['concat', 'copy:dev', 'emberBuild']);

        // ### Live reload
        // `grunt dev` - build assets on the fly whilst developing
        //
        // If you want Ghost to live reload for you whilst you're developing, you can do this by running `grunt dev`.
        // This works hand-in-hand with the [livereload](http://livereload.com/) chrome extension.
        //
        // `grunt dev` manages starting an express server and restarting the server whenever core files change (which
        // require a server restart for the changes to take effect) and also manage reloading the browser whenever
        // frontend code changes.
        //
        // Note that the current implementation of watch only works with casper, not other themes.
        grunt.registerTask('dev', 'Dev Mode; watch files and restart server on changes',
           ['concat', 'copy:dev', 'emberBuild', 'express:dev', 'watch']);

        // ### Release
        // Run `grunt release` to create a Ghost release zip file.
        // Uses the files specified by `.npmignore` to know what should and should not be included.
        // Runs the asset generation tasks for both development and production so that the release can be used in
        // either environment, and packages all the files up into a zip.
        grunt.registerTask('release',
            'Release task - creates a final built zip\n' +
<<<<<<< HEAD
            ' - Do our standard build steps (handlebars, etc)\n' +
            ' - Generate changelog for the past 14 releases\n' +
            ' - Copy files to build-folder/#/#{version} directory\n' +
            ' - Clean out unnecessary files (travis, .git*, .af*, .groc*)\n' +
            ' - Zip files in build folder to dist-folder/#{version} directory',
            [
                'shell:bower',
                'handlebars',
                'concat',
                'uglify',
                'bump:build',
                'updateCurrentPackageInfo',
                'changelog',
                'copy:nightly',
                'compress:nightly'
            ]);

        grunt.registerTask('weekly', [
            'setCurrentBuildType:Weekly',
            'shell:bourbon',
            'sass:compress',
            'handlebars',
            'concat',
            'uglify',
            'bump:build',
            'updateCurrentPackageInfo',
            'changelog',
            'copy:weekly',
            'compress:weekly'
        ]);

        grunt.registerTask('build', [
            'shell:bourbon',
            'sass:compress',
            'handlebars',
            'concat',
            'uglify',
            'changelog',
            'clean:build',
            'copy:build',
            'compress:build'
        ]);

        grunt.registerTask('release', [
            'shell:bourbon',
            'sass:admin',
            'handlebars',
            'concat',
            'uglify',
            'changelog',
            'clean:build',
            'copy:build',
            'compress:release'
        ]);

        grunt.registerTask('dev',
            'Dev Mode; watch files and restart server on changes',
            [
                'handlebars',
                'concat',
                'copy:dev',
                'express:dev',
                'open',
                'watch'
            ]);

        // TODO: Git submodule init/update (https://github.com/jaubourg/grunt-update-submodules)?
        grunt.registerTask('init', 'Prepare the project for development', ['shell:bourbon', 'default']);

        grunt.registerTask('test-functional', 'Run functional interface tests (CasperJS)', ['clean:test', 'setTestEnv', 'loadConfig', 'copy:dev', 'express:test', 'spawn-casperjs', 'express:test:stop']);

        grunt.registerTask('test-functional', 'Run casperjs tests only', ['clean:test', 'setTestEnv', 'express:test', 'spawn-casperjs']);

        grunt.registerTask('test-routes', 'Run functional route tests (mocha)', ['clean:test', 'setTestEnv', 'loadConfig', 'express:test', 'mochacli:routes', 'express:test:stop']);

        grunt.registerTask('validate', 'Run tests and lint code', ['jshint', 'test-routes', 'test-unit', 'test-api', 'test-integration', 'test-functional']);

        // ### Coverage report for Unit and Integration Tests

        grunt.registerTask('test-coverage', 'Generate unit and integration (mocha) tests coverage report', ['clean:test', 'setTestEnv', 'loadConfig', 'shell:coverage']);

        // ### Documentation

        grunt.registerTask('docs', 'Generate Docs', ['groc']);

        // ### Tools for building assets

        grunt.registerTask('init', 'Prepare the project for development', ['shell:bower', 'default']);

        // Before running in production mode
        grunt.registerTask('prod', 'Build JS & templates for production', ['handlebars', 'concat', 'uglify', 'copy:prod']);

        // When you just say 'grunt'
        grunt.registerTask('default', 'Build JS & templates for development', ['update_submodules', 'handlebars', 'concat', 'copy:dev']);
=======
            ' - Do our standard build steps \n' +
            ' - Copy files to release-folder/#/#{version} directory\n' +
            ' - Clean out unnecessary files (travis, .git*, etc)\n' +
            ' - Zip files in release-folder to dist-folder/#{version} directory',
            ['shell:bower', 'update_submodules', 'concat', 'uglify', 'clean:release', 'copy:release', 'compress:release']);
>>>>>>> 09e03f4d78d17b2d1b1b3f452aff6933cd7cf1f6
    };

// Export the configuration
module.exports = configureGrunt;


text:
/*
 * Developer: Swaroop <durgaswaroop@gmail.com>
 * Date: March 2017
 */

package delorean
package commands

import delorean.FileOps._
import delorean.commands.OutputFormat.OutputFormat

/**
  * Class for the command 'show-timeline'.
  *
  */
case class ShowTimeLine(outputFormat: OutputFormat = OutputFormat.SHORT) {

  // Either the pitstop hash or an empty string
  val currentPitstop: String = getCurrentPitstop()

  // If current pitstop is empty it means there are no pitstops shown yet.
  if (currentPitstop.isEmpty) {
    println("delorean: No pitstops present on the current timeline")
    System.exit(1)
  }

  printTimeLine(currentPitstop, outputFormat)
  var parentPitstop: String = parent(currentPitstop)
  while (parentPitstop nonEmpty) {
    printTimeLine(parentPitstop, outputFormat)
    parentPitstop = parent(parentPitstop)
  }

  /**
    * Prints the timeline information in ethe given 'format'.
    *
    * If format is SHORT, we will just see the pitstop hash and the rider log
    * If the format is Long, we will see that pitstop's metadata as well.
    *
    * @param pitstop : pitstop to print
    * @param format  : OutputFormat. Can be SHORT or LONG
    */
  def printTimeLine(pitstop: String, format: OutputFormat): Unit = {
    val metadata = Metadata(pitstop)
    if (format == OutputFormat.SHORT)
      println("* " + pitstop.take(6) + " " + metadata.riderLog.take(60))
    else println(s"""pitstop ${pitstop.take(25)}
               |Rider: ${metadata.rider}
               |Time:  ${metadata.time}
               |
                    |Rider log: ${metadata.riderLog}
                """.stripMargin)
  }
}

object OutputFormat extends Enumeration {
  type OutputFormat = Value
  val SHORT: commands.OutputFormat.Value = Value(0)
  val LONG: commands.OutputFormat.Value = Value(1)
}


text:
using UnityEngine;
using UnityEditor;
using System;
using System.Collections;
using System.Collections.Generic;
using Random = UnityEngine.Random;

namespace StrayTech
{
    /// <summary>
    /// A custom property drawer for ThirdPersonCameraStateSettings.
    /// </summary>
    [CustomPropertyDrawer(typeof(ThirdPersonCameraStateSettings))]
    public class ThirdPersonCameraStateSettingsPropertyDrawer : PropertyDrawer
    {
        #region members
            private SerializedProperty _mouseOrbitField;
            private SerializedProperty _targetOffsetField;
            private SerializedProperty _mouseOrbitDistanceField;
            private SerializedProperty _mousePitchRangeField;
            private SerializedProperty _mouseSensitivityField;
            private SerializedProperty _mouseInvertYField;
            private SerializedProperty _motionSmoothingField;
            private SerializedProperty _useCameraCollisionField;
        #endregion members

        #region methods
            public override void OnGUI(Rect canvas, SerializedProperty property, GUIContent label)
            {
                // fail gracefully if CacheFields throws an exception.
                if (this.CacheFields(property, label) == false)
                {
                    this.DrawCacheFieldsFailureMessage(canvas, label);
                    return;
                }

                DrawCustomGUI(canvas, property, label);
            }

            private bool CacheFields(SerializedProperty property, GUIContent label)
            {
                // if you refactor a class, it's field names might change but that won't be reflected here.
                // fail gracefully by returning false instead of emitting hundreds of hard exceptions.
                try
                {
                    this._mouseOrbitField = property.FindPropertyRelativeExplosive("_mouseOrbit");
                    this._targetOffsetField = property.FindPropertyRelativeExplosive("_targetOffset");
                    this._mouseOrbitDistanceField = property.FindPropertyRelativeExplosive("_mouseOrbitDistance");
                    this._mousePitchRangeField = property.FindPropertyRelativeExplosive("_mousePitchRange");
                    this._mouseSensitivityField = property.FindPropertyRelativeExplosive("_mouseSensitivity");
                    this._mouseInvertYField = property.FindPropertyRelativeExplosive("_mouseInvertY");
                    this._motionSmoothingField = property.FindPropertyRelativeExplosive("_motionSmoothing");
                    this._useCameraCollisionField = property.FindPropertyRelativeExplosive("_useCameraCollision");
                }
                catch (Exception e)
                {
                    this._cacheFieldsFailureMessage = e.Message;
                    return false;
                }

                return true;
            }

            /// <summary>
            /// Render our custom GUI.
            /// </summary>
            private void DrawCustomGUI(Rect canvas, SerializedProperty property, GUIContent label)
            {
                EditorExtensions.RenderBackgroundRect(canvas, GetPropertyHeight(property, label), property.name);

                //Extract space to make up for the title!
                EditorExtensions.ExtractSpace(ref canvas, 19f);

                EditorGUI.BeginChangeCheck();
                {
                    EditorGUI.PropertyField(EditorExtensions.ExtractSpace(ref canvas, EditorGUI.GetPropertyHeight(this._mouseOrbitField)), this._mouseOrbitField);
                }
                if (EditorGUI.EndChangeCheck())
                {
                    property.serializedObject.ApplyModifiedProperties();
                }

                EditorGUI.BeginChangeCheck();
                {
                    if (this._mouseOrbitField.boolValue == true)
                    {
                        EditorGUI.PropertyField(EditorExtensions.ExtractSpace(ref canvas, EditorGUI.GetPropertyHeight(this._mouseOrbitDistanceField)), this._mouseOrbitDistanceField);
                        EditorGUI.PropertyField(EditorExtensions.ExtractSpace(ref canvas, EditorGUI.GetPropertyHeight(this._mousePitchRangeField)), this._mousePitchRangeField);
                        EditorGUI.PropertyField(EditorExtensions.ExtractSpace(ref canvas, EditorGUI.GetPropertyHeight(this._mouseSensitivityField)), this._mouseSensitivityField);
                        EditorGUI.PropertyField(EditorExtensions.ExtractSpace(ref canvas, EditorGUI.GetPropertyHeight(this._mouseInvertYField)), this._mouseInvertYField);
                    }
                    else
                    {
                        EditorGUI.PropertyField(EditorExtensions.ExtractSpace(ref canvas, EditorGUI.GetPropertyHeight(this._targetOffsetField)), this._targetOffsetField);
                    }

                    EditorGUI.PropertyField(EditorExtensions.ExtractSpace(ref canvas, EditorGUI.GetPropertyHeight(this._motionSmoothingField)), this._motionSmoothingField);
                    EditorGUI.PropertyField(EditorExtensions.ExtractSpace(ref canvas, EditorGUI.GetPropertyHeight(this._useCameraCollisionField)), this._useCameraCollisionField);
                }
                if (EditorGUI.EndChangeCheck())
                {
                    property.serializedObject.ApplyModifiedProperties();
                }
            }

            /// <summary>
            /// Return the property height
            /// </summary>
            public override float GetPropertyHeight(SerializedProperty property, GUIContent label)
            {
                if (this.CacheFields(property, label) == false)
                {
                    return EditorGUIUtility.singleLineHeight;
                }

                var runningHeight = 25f;

                runningHeight += EditorGUI.GetPropertyHeight(this._mouseOrbitField);
                if (this._mouseOrbitField.boolValue == true)
                {
                    runningHeight += EditorGUI.GetPropertyHeight(this._mouseOrbitDistanceField);
                    runningHeight += EditorGUI.GetPropertyHeight(this._mousePitchRangeField);
                    runningHeight += EditorGUI.GetPropertyHeight(this._mouseSensitivityField);
                    runningHeight += EditorGUI.GetPropertyHeight(this._mouseInvertYField);
                }
                else
                {
                    runningHeight += EditorGUI.GetPropertyHeight(this._targetOffsetField);
                }

                runningHeight += EditorGUI.GetPropertyHeight(this._motionSmoothingField);
                runningHeight += EditorGUI.GetPropertyHeight(this._useCameraCollisionField);

                return runningHeight;
            }
        #endregion methods

        #region template members
            /// <summary>
            /// An error message shown in the inspector when CacheFields throws an exception.
            /// </summary>
            private string _cacheFieldsFailureMessage = string.Empty;

            /// <summary>
            /// Display an error message caused by CacheFields throwing an exception.
            /// </summary>
            private void DrawCacheFieldsFailureMessage(Rect canvas, GUIContent label)
            {
                GUIColorHelper.DoWithColor(Color.red,
                    () =>
                    {
                        EditorGUI.LabelField(canvas, label.text, string.Format("{0}.CacheFields threw an exception: {1}", this.GetType().Name, this._cacheFieldsFailureMessage ?? string.Empty));
                    }
                );
            }
        #endregion template members
    }
}


text:
define(['jquery', 'knockout', 'Level'], function($, ko, Level) {
    return function(fac) {
        /* Parameters:
         *   fac: factor object, returned from API, w/ the following properties:
         *     id: factor id
         *     name: factor name
         *     type: type should be within self.factor_types
         *     levels: unique levels of the factor
         */

        var self = this;

        /*
         * Basic information of a factor object: id, name, type and levels if
         * provided
         */
        self.id = fac.id ? fac.id : 0;
        self.name = ko.observable(fac.name ? fac.name : '');
        self.type = ko.observable(fac.type ? fac.type : null);

        lvls = fac.levels ? fac.levels : [];
        if (typeof lvls === 'object') {
            var arr = []
            $.map(Object.keys(lvls).sort(), function(k){
                arr.push(lvls[k]);
            });
            lvls = arr;
        }
        self.levels = ko.observableArray(
            $.map(lvls, function(lvl){ return new Level(lvl); })
        );

        // Make sure input factor type is valid
        self.factor_types = ['Category', 'Integer', 'Decimal', null];
        if (self.factor_types.indexOf(self.type()) == -1){
            throw new Error(self.type() + ' is not allowed!');
        }

        /*
         * Helper function to select levels in factor
         */
        //TODO keep the selection status while hidden
        self.query = ko.observable();
        self.query.subscribe(function(val){
            // check if string is empty
            if (val){
                for (g in self.levels()){
                    if (self.levels()[g].name.search(val) === -1){
                        self.levels()[g]._destroy = true;
                    } else {
                        self.levels()[g]._destroy = false;
                    }
                }
            } else {
                for (g in self.levels()){
                    self.levels()[g]._destroy = false;
                }
            }
            self.levels.valueHasMutated();
        }, self);
        self.chosen_levels = ko.observableArray();

        self.get_chosen_levels = function(){
            return $.map(self.chosen_levels(), function(l){return l.name})
        }

    };
});


text:
<?php

// autoload.php generated by Composer

require_once __DIR__ . '/composer' . '/autoload_real.php';

return ComposerAutoloaderInit8a0d2c8944092dbc7c5163c3b2637e2d::getLoader();


text:
package com.googlecode.jmxtrans.model.output;

import com.google.common.collect.ImmutableList;
import com.googlecode.jmxtrans.model.output.support.WriterPoolOutputWriter;
import com.googlecode.jmxtrans.test.IntegrationTest;
import com.googlecode.jmxtrans.test.RequiresIO;
import com.googlecode.jmxtrans.test.UdpLoggingServer;
import org.junit.Rule;
import org.junit.Test;
import org.junit.experimental.categories.Category;

import java.util.concurrent.Callable;

import static com.google.common.base.Charsets.UTF_8;
import static com.googlecode.jmxtrans.model.QueryFixtures.dummyQuery;
import static com.googlecode.jmxtrans.model.ResultFixtures.dummyResults;
import static com.googlecode.jmxtrans.model.ServerFixtures.dummyServer;
import static com.jayway.awaitility.Awaitility.await;
import static java.util.concurrent.TimeUnit.MILLISECONDS;

@Category({IntegrationTest.class, RequiresIO.class})
public class StatsDWriterFactoryIT {

	@Rule
	public UdpLoggingServer udpLoggingServer = new UdpLoggingServer(UTF_8);

	@Test
	public void messageIsSent() throws Exception {
		WriterPoolOutputWriter<StatsDWriter2> statsDWriter = new StatsDWriterFactory(
			ImmutableList.<String>of(),
				null, null, false, null,
				udpLoggingServer.getLocalSocketAddress().getHostName(),
				udpLoggingServer.getLocalSocketAddress().getPort(),
				null, null, null, null
		).create();

		statsDWriter.doWrite(dummyServer(), dummyQuery(), dummyResults());
		statsDWriter.close();

		await().atMost(200, MILLISECONDS)
				.until(messageReceived("servers.host_example_net_4321.MemoryAlias.ObjectPendingFinalizationCount:10|c\n"));
	}

	private Callable<Boolean> messageReceived(final String message) {
		return new Callable<Boolean>() {
			@Override
			public Boolean call() throws Exception {
				return udpLoggingServer.messageReceived(message);
			}
		};
	}

}


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>com.github.thomasfischl.aihome.controller</groupId>
  <artifactId>com.github.thomasfischl.aihome.controller</artifactId>
  <url>https://github.com/thomasfischl/ai-home</url>
  <name>AI-Home Controller</name>

  <developers>
    <developer>
      <email>fischl.thomas@gmail.com</email>
      <name>Thomas Fischl</name>
    </developer>
  </developers>

  <parent>
    <groupId>com.github.thomasfischl.aihome</groupId>
    <artifactId>com.github.thomasfischl.aihome</artifactId>
    <version>0.0.1</version>
    <relativePath>../com.github.thomasfischl.aihome/pom.xml</relativePath>
  </parent>

  <dependencies>
    <dependency>
      <groupId>com.github.thomasfischl.aihome.controller.pi</groupId>
      <artifactId>com.github.thomasfischl.aihome.controller.pi</artifactId>
      <version>0.0.1</version>
    </dependency>
    <dependency>
      <groupId>com.google.guava</groupId>
      <artifactId>guava</artifactId>
      <version>17.0</version>
    </dependency>
    <dependency>
      <groupId>com.google.code.gson</groupId>
      <artifactId>gson</artifactId>
      <version>2.2.4</version>
    </dependency>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.11</version>
    </dependency>
  </dependencies>

  <build>
    <plugins>
      <plugin>
        <artifactId>maven-compiler-plugin</artifactId>
        <configuration>
          <source>1.7</source>
          <target>1.7</target>
        </configuration>
      </plugin>

      <plugin>
        <artifactId>maven-assembly-plugin</artifactId>
        <version>2.4</version>
        <configuration>
          <archive>
            <manifest>
              <mainClass>com.github.thomasfischl.aihome.controller.Application</mainClass>
            </manifest>
          </archive>
          <descriptorRefs>
            <descriptorRef>jar-with-dependencies</descriptorRef>
          </descriptorRefs>
        </configuration>
      </plugin>
    </plugins>
  </build>

</project>


text:
tool-manager
============

Simple PHP web-app for mana


text:
learning_git
============

This repository is a test.  I am learning how to use git for my school projects.


text:
package com.jamierf.maestro.api;

import com.google.common.base.Optional;

// TODO: Device product IDs
public enum Product {
    MICRO6(8187, 137, 6, 1024),
    MINI12(8187, 0, 12, 8192),

    MINI18(8187, 0, 18, 8192),
    MINI24(8187, 0, 24, 8192);

    public static Optional<Product> fromId(int vendorId, int productId) {
        for (Product product : Product.values()) {
            if (vendorId != product.getVendorId())
                continue;

            if (productId != product.getProductId())
                continue;

            return Optional.of(product);
        }

        return Optional.absent();
    }

    private final int vendorId;
    private final int productId;
    private final int ports;
    private final int maxScriptLength;

    Product(int vendorId, int productId, int ports, int maxScriptLength) {
        this.vendorId = vendorId;
        this.productId = productId;
        this.ports = ports;
        this.maxScriptLength = maxScriptLength;
    }

    public int getVendorId() {
        return vendorId;
    }

    public int getProductId() {
        return productId;
    }

    public int getPorts() {
        return ports;
    }

    public int getMaxScriptLength() {
        return maxScriptLength;
    }
}


text:
@interface SamuraiHtmlDocument : SamuraiDocument

@prop_strong( SamuraiHtmlDomNode *,		domTree );
@prop_strong( SamuraiCSSStyleSheet *,	styleTree );
@prop_strong( SamuraiRenderObject *,	renderTree );

@prop_strong( NSString *,	rootTag );
@prop_strong( NSString *,	headTag );
@prop_strong( NSString *,	bodyTag );

- (SamuraiHtmlDomNode *)getRootDomNode;
- (SamuraiHtmlDomNode *)getHeadDomNode;
- (SamuraiHtmlDomNode *)getBodyDomNode;

@end

#endif	// #if (TARGET_OS_IPHONE || TARGET_IPHONE_SIMULATOR)


text:
MD=drivefs
# Full go import path of the project
MDPath=github.com/eliothedeman/${MD}

# Build the binary for the current platform
make:
	go build -o bin/${MD}

# Remove the bin folder
clean:
	rm -rf bin/

all:
	make darwin_amd64
	make linux_amd64
	make linux_arm

darwin_amd64:
	GOOS="darwin" GOARCH="amd64" go build -o bin/${MD}_darwin_amd64

linux_amd64:
	GOOS="linux" GOARCH="amd64" go build -o bin/${MD}_linux_amd64

linux_arm:
	GOOS="linux" GOARCH="arm" go build -o bin/${MD}_linux_arm


text:
module ActsRateable
  class Rating  < ActsRateable::ArRating

    belongs_to :resource, polymorphic: true

    validates :resource, :total, :sum, :average, :estimate, presence: true
    validates_numericality_of :total, :sum, :average, :estimate

    unless (Rails::VERSION::STRING.to_f >= 4)
      attr_accessible :resource_id, :resource_type, :total, :sum, :average, :estimate, :type
    end

  	before_save :update_ratings

  	#  RETURNS = { "total_ratings"=>"", "rating_sum"=>"", "rating_avg"=>"", "rated_count"=>"", "avg_num_ratings"=>"" }
    def self.get_totals(resource)
      sql = "SELECT COUNT(*) total_ratings, SUM(value) rating_sum, AVG(value) rating_avg, "+
            "(SELECT COUNT(DISTINCT resource_id) FROM ar_rates WHERE resource_type = '#{resource.class.base_class.name}') rated_count, "+
            "((SELECT COUNT(*) from ar_rates WHERE resource_type = '#{resource.class.base_class.name}') / (SELECT COUNT(DISTINCT resource_id) FROM ar_rates WHERE resource_type = '#{resource.class.base_class.name}')) avg_num_ratings "+
            "FROM ar_rates WHERE resource_type = '#{resource.class.base_class.name}'"
      ActsRateable::Rate.connection.execute(sql).first
    end

    # RETURNS = {"total_ratings"=>"", "rating_sum"=>"", "rating_avg"=>""}
    def self.values_for(resource)
      sql =   "SELECT COUNT(*) total_ratings, COALESCE(SUM(value),0) rating_sum, COALESCE(AVG(value),0) rating_avg "+
              "FROM ar_rates WHERE resource_type = '#{resource.class.base_class.name}' and resource_id = '#{resource.id}'"
      ActsRateable::Rate.connection.execute(sql).first
    end

    def self.data_for(resource)
      local     = values_for(resource)
      global    = get_totals(resource)
      estimate  = (local['total_ratings'].to_f / (local['total_ratings'].to_f+global['avg_num_ratings'].to_f)) * local['rating_avg'].to_f + (global['avg_num_ratings'].to_f / (local['total_ratings'].to_f+global['avg_num_ratings'].to_f)) *global['rating_avg'].to_f
      return    { 'global' => global, 'local' => local.merge!({ 'estimate' => estimate }) }
    end

    protected

    def update_ratings
      if resource && !resource.rates.empty?
        result   = self.class.data_for(resource)
        self.total    = result['local']['total_ratings']
        self.average  = result['local']['rating_avg']
        self.sum      = result['local']['rating_sum']
        self.estimate = result['local']['estimate']
      end
    end
  end
end


text:
package com.intellij.openapi.wm.impl;

import com.intellij.openapi.actionSystem.DataContext;
import com.intellij.openapi.util.ActionCallback;
import com.intellij.openapi.util.Expirable;
import com.intellij.openapi.util.ExpirableRunnable;
import com.intellij.openapi.wm.FocusCommand;
import com.intellij.openapi.wm.FocusRequestor;
import com.intellij.openapi.wm.IdeFocusManager;
import com.intellij.openapi.wm.IdeFrame;
import org.jetbrains.annotations.NotNull;

import javax.swing.*;
import java.awt.*;
import java.awt.event.KeyEvent;

public class IdeFocusManagerHeadless extends IdeFocusManager {

  public static final IdeFocusManagerHeadless INSTANCE = new IdeFocusManagerHeadless();

  @Override
  @NotNull
  public ActionCallback requestFocus(@NotNull final Component c, final boolean forced) {
    return new ActionCallback.Done();
  }

  @Override
  @NotNull
  public ActionCallback requestFocus(@NotNull final FocusCommand command, final boolean forced) {
    return new ActionCallback.Done();
  }

  @Override
  public JComponent getFocusTargetFor(@NotNull final JComponent comp) {
    return null;
  }

  @Override
  public void doWhenFocusSettlesDown(@NotNull final Runnable runnable) {
    runnable.run();
  }

  @Override
  public void doWhenFocusSettlesDown(@NotNull ExpirableRunnable runnable) {
    if (!runnable.isExpired()) {
      runnable.run();
    }
  }

  @Override
  public Component getFocusedDescendantFor(final Component c) {
    return null;
  }

  @Override
  public boolean dispatch(@NotNull KeyEvent e) {
    return false;
  }

  @Override
  public void typeAheadUntil(ActionCallback done) {
  }

  @Override
  public boolean isFocusBeingTransferred() {
    return false;
  }

  @Override
  @NotNull
  public ActionCallback requestDefaultFocus(boolean forced) {
    return new ActionCallback.Done();
  }

  @Override
  public boolean isFocusTransferEnabled() {
    return true;
  }

  @NotNull
  @Override
  public Expirable getTimestamp(boolean trackOnlyForcedCommands) {
    return new Expirable() {
      @Override
      public boolean isExpired() {
        return false;
      }
    };
  }

  @NotNull
  @Override
  public FocusRequestor getFurtherRequestor() {
    return this;
  }

  @Override
  public void revalidateFocus(@NotNull ExpirableRunnable runnable) {
  }

  @Override
  public void setTypeaheadEnabled(boolean enabled) {
  }

  @Override
  public Component getFocusOwner() {
    return null;
  }

  @Override
  public void runOnOwnContext(@NotNull DataContext context, @NotNull Runnable runnable) {
    runnable.run();
  }

  @Override
  public Component getLastFocusedFor(IdeFrame frame) {
    return null;
  }

  @Override
  public IdeFrame getLastFocusedFrame() {
    return null;
  }

  @Override
  public void toFront(JComponent c) {
  }

  @Override
  public void dispose() {
  }
}


text:
package stringoperation;

public class Interleaving {
    // little similar to parenthesis generation
    public static void printIlsRecur(String str1, String str2,
                                     StringBuilder sb, int m, int n, int i) {
        // Base case: If all characters of str1 and str2 have been included in
        // output string, then print the output string
        if (m == 0 && n == 0) {
            System.out.println(sb);
        }
        // System.out.println("m = " + m + " n = " + n);
        // If some characters of str1 are left to be included, then include the
        // first character from the remaining characters and recur for rest
        if (m != 0) {
            sb.setCharAt(i, str1.charAt(0));
            printIlsRecur(str1.substring(1), str2, sb, m - 1, n, i + 1);
        }

        // If some characters of str2 are left to be included, then include the
        // first character from the remaining characters and recur for rest
        if (n != 0) {
            sb.setCharAt(i, str2.charAt(0));
            printIlsRecur(str1, str2.substring(1), sb, m, n - 1, i + 1);
        }
    }

    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        StringBuilder sb = new StringBuilder("       ");
        printIlsRecur("abcd", "efg", sb, 4, 3, 0);
    }

}


text:
Contact Us

GIVE US A SHOUT

				<form name="sentMessage" id="contactForm" novalidate>

							Name
							<input type="text" class="form-control" placeholder="Name" id="name" required data-validation-required-message="Please enter your name.">

							Email Address
							<input type="email" class="form-control" placeholder="Email Address" id="email" required data-validation-required-message="Please enter your email address.">

							Phone Number
							<input type="tel" class="form-control" placeholder="Phone Number" id="phone" required data-validation-required-message="Please enter your phone number.">

							Message
							<textarea rows="5" class="form-control" placeholder="Message" id="message" required data-validation-required-message="Please enter a message."></textarea>

							<button type="submit" class="btn btn-success btn-lg">Send</button>

				</form>

				<img src="<?php echo base_url() ?>assets/img/social-icons/Facebook-Icon.png">
				<img src="<?php echo base_url() ?>assets/img/social-icons/Twitter-Icon.png">
				<img src="<?php echo base_url() ?>assets/img/social-icons/Instagram-Icon.png">
				<img src="<?php echo base_url() ?>assets/img/social-icons/YouTube-Icon.png">


text:
local d = require "distribution"

-- A system to use for instance for ammo:
-- Roll your current ammo die any time you use ammo
-- If you roll a 1, switch to the next die in the sequence
-- If you roll a 1 on the last die, you are out of ammo

-- The average number of rolls you get is simply the total number
-- of faces on all the dice of the sequence, so you can vary the
-- sequence for different average numbers of successful rolls.

-- Using the simple sequence of "all" RPG dice from high to low makes
-- it easy to remember and to track down, with the added effect of
-- impending risk when reaching the lower ones.

-- The randomness represents the chance of recovering ammo, or bad
-- quality ammo, etc.

function cascading_dice(sequence, limit)

	local memo = {}

	local function rec(die_index, level)

		local key = die_index .. ":" .. level

		if memo[key] then
			return memo[key]
		end

		if level == limit then
			return level
		end

		local die = sequence[die_index]
		local result = die:apply(function(x)

			if x == 1 then
				if die_index == #sequence then
					return level
				else
					return rec(die_index + 1, level + 1)
				end

			else
				return rec(die_index, level + 1)
			end
		end)

		memo[key] = result
		return result
	end

	return rec(1,1)
end

local d20 = d.uniform(20)
local d12 = d.uniform(12)
local d10 = d.uniform(10)
local d8 = d.uniform(8)
local d6 = d.uniform(6)
local d4 = d.uniform(4)

local sequence = {d20, d12, d10, d8, d6, d4}

print(cascading_dice(sequence, 300))


text:
<title>minimal demo</title>

		<button type="button" ng-click="start()">start</button>
		<button type="button" ng-click="select()">click</button>
		<button type="button" ng-click="stop()">stop</button>

Accurate:

Count:

Value:

Actual: , Guess:. Result:{{y===guess}}

D: {{arrayToString(layer.out_act.w)}}

Dw: {{arrayToString(layer.out_act.dw)}}


text:
DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
BASE_DIR=$DIR/..
TEST_DIR=$1

if test -z "$TEST_DIR"; then
  echo
  echo "  USAGE:"
  echo
  echo "    ${BASH_SOURCE[0]##*/} \"<dirname to run tests in>\" [zopkio args...]"
  echo
  exit 0
fi

# always use absolute paths for ABS_TEST_DIR
ABS_TEST_DIR=$(cd $(dirname $TEST_DIR); pwd)/$(basename $TEST_DIR)
SCRIPTS_DIR=$ABS_TEST_DIR/scripts

# safety check for virtualenv
if [ -f $HOME/.pydistutils.cfg ]; then
  echo "Virtualenv can't run while $HOME/.pydistutils.cfg exists."
  echo "Please remove $HOME/.pydistutils.cfg, and try again."
  exit 0
fi

# build integration test tarball
./gradlew releaseTestJobs

# create integration test directory
mkdir -p $ABS_TEST_DIR
rm -rf $SCRIPTS_DIR
cp -r samza-test/src/main/python/ $SCRIPTS_DIR
cp ./samza-test/build/distributions/samza-test*.tgz $ABS_TEST_DIR
cd $ABS_TEST_DIR

# setup virtualenv locally if it's not already there
VIRTUAL_ENV=virtualenv-15.0.1
if [[ ! -d "${ABS_TEST_DIR}/${VIRTUAL_ENV}" ]] ; then
  # using --location to follow any redirects
  curl -O --location https://pypi.python.org/packages/source/v/virtualenv/$VIRTUAL_ENV.tar.gz
  tar xvfz $VIRTUAL_ENV.tar.gz
fi

# build a clean virtual environment
SAMZA_INTEGRATION_TESTS_DIR=$ABS_TEST_DIR/samza-integration-tests
if [[ ! -d "${SAMZA_INTEGRATION_TESTS_DIR}" ]] ; then
  python $VIRTUAL_ENV/virtualenv.py $SAMZA_INTEGRATION_TESTS_DIR
fi

# activate the virtual environment
source $SAMZA_INTEGRATION_TESTS_DIR/bin/activate

# install zopkio and requests
pip install -r $SCRIPTS_DIR/requirements.txt

# treat all trailing parameters (after dirname) as zopkio switches
shift
SWITCHES="$*"

# default to info-level debugging if not specified
if [[ $SWITCHES != *"console-log-level"* ]]; then
  SWITCHES="$SWITCHES --console-log-level INFO"
fi

# run the tests
zopkio --config-overrides remote_install_path=$ABS_TEST_DIR $SWITCHES $SCRIPTS_DIR/integration_tests.py

# go back to execution directory
deactivate
cd $DIR


text:
package io.electrum.prepaidutility.api;

import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.container.AsyncResponse;
import javax.ws.rs.container.Suspended;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.HttpHeaders;
import javax.ws.rs.core.Request;
import javax.ws.rs.core.SecurityContext;
import javax.ws.rs.core.UriInfo;

import io.electrum.prepaidutility.model.ErrorDetail;
import io.electrum.prepaidutility.model.FaultReportRequest;
import io.electrum.prepaidutility.model.FaultReportResponse;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import io.swagger.annotations.Authorization;

@Path(FaultReportsResource.PATH)
@Api(description = "the faultReports API", authorizations = { @Authorization("httpBasic") })
public abstract class FaultReportsResource {

   protected abstract IFaultReportsResource getResourceImplementation();

   public static final String PATH = "/faultReports";

   public class CreateFaultReport {
      public static final String CREATE_FAULT_REPORT = "createFaultReport";
      public static final int SUCCESS = 201;
      public static final String RELATIVE_PATH = "/{" + PathParameters.REQUEST_ID + "}";
      public static final String PATH = FaultReportsResource.PATH + RELATIVE_PATH;

      public class PathParameters {
         public static final String REQUEST_ID = "requestId";
      }
   }

   @POST
   @Path(CreateFaultReport.RELATIVE_PATH)
   @Consumes({ "application/json" })
   @Produces({ "application/json" })
   @ApiOperation(nickname = CreateFaultReport.CREATE_FAULT_REPORT, value = "Report a fault on a meter", notes = "Reports a technical fault on a specified meter. This resource is used when a customer wishes to report a technical fault to the utility with whom the meter is reqistered.")
   @ApiResponses(value = {
         @ApiResponse(code = CreateFaultReport.SUCCESS, message = "Created", response = FaultReportResponse.class),
         @ApiResponse(code = 400, message = "Bad request", response = ErrorDetail.class),
         @ApiResponse(code = 500, message = "Internal Server Error", response = ErrorDetail.class),
         @ApiResponse(code = 501, message = "Not implemented", response = ErrorDetail.class),
         @ApiResponse(code = 503, message = "Service Unavailable", response = ErrorDetail.class),
         @ApiResponse(code = 504, message = "Gateway Timeout", response = ErrorDetail.class) })
   public void createFaultReport(
         @ApiParam(value = "The randomly generated UUID of this request.", required = true) @PathParam(CreateFaultReport.PathParameters.REQUEST_ID) String requestId,
         @ApiParam(value = "A fault report", required = true) FaultReportRequest body,
         @Context SecurityContext securityContext,
         @Suspended AsyncResponse asyncResponse,
         @Context Request request,
         @Context HttpServletRequest httpServletRequest,
         @Context HttpHeaders httpHeaders,
         @Context UriInfo uriInfo) {

      getResourceImplementation().createFaultReport(
            requestId,
            body,
            securityContext,
            asyncResponse,
            request,
            httpServletRequest,
            httpHeaders,
            uriInfo);
   }

}